diff --git "a/5043.jsonl" "b/5043.jsonl" new file mode 100644--- /dev/null +++ "b/5043.jsonl" @@ -0,0 +1,706 @@ +{"seq_id":"41171247405","text":"import numpy as np\nfrom sklearn.cluster import MeanShift, estimate_bandwidth\n#from sklearn.datasets import make_blob\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimport imageio\nimport time\n\npath_1440frames = 'C:/Users/bob\\Documents/build-RadarVisualizer-Desktop_Qt_6_4_2_MinGW_64_bit-Release/release/parse_script/ParsedData/parsOut_5.4__22_12_5.csv'\npath_1199frames = 'C:/Users/bob\\Documents/build-RadarVisualizer-Desktop_Qt_6_4_2_MinGW_64_bit-Release/release/parse_script/ParsedData/parsOut_16.3__19_5_43.csv'\ndata = np.genfromtxt(path_1199frames,delimiter=',',skip_header=1)\ndata_all = np.genfromtxt(path_1199frames,delimiter=',',skip_header=1)\nfocusedFrame = 0\n\n#selection on focusedFrame data\nindices = np.argwhere(data[:,0] == focusedFrame)\nindices = np.squeeze(indices)\ndata_posX_focusedFrame = np.array(data[indices[0]:indices[-1]+1,2])\ndata_posY_focusedFrame = np.array(data[indices[0]:indices[-1]+1,3])\nx = data_posX_focusedFrame\ny = data_posY_focusedFrame\ndata = np.hstack((x.reshape(-1,1),y.reshape(-1,1)))\n\nlenOfFocusedData = indices[-1]-indices[0]\n#print(\"%d - %d\" %(indices[-1],indices[0]))\nprint(\"focData/indic: %d/%d\" %(data.shape[0]-1,lenOfFocusedData))\n\n\n#lastFrame = data_all[-1,0]\nlastFrame = 100\n# Define the fixed length of the images list\n# create a list of images\n # Initialize the images list with None values\n#images = [None for _ in range(lastFrame+1)]\nimages = []\n#print(\"size: %d\" %len(images))\n\ni=0\nstartTime_total = time.process_time()\nwhile(i 0:\n #create a random number between 1 to 6 \n rolled_dice = random.randint(1,6)\n arr_times.append(rolled_dice)\n times += 1\n else:\n break\n #assign the array to a tuple \n tuple_times = tuple(arr_times)\n return tuple_times\n \n def play():\n pass\n\n\n def calculate_score(roll_dice):\n sum = 0\n count_result = Counter(roll_dice)\n #define a most common that = to common value for the rolling dice to return sorted array as a list of tuples \n most_common = count_result.most_common() \n # print(most_common)\n #if the length of array for most conmon values = 6 then a 2000 will be add to sum\n if len(most_common) == 6:\n sum += 2000\n return sum\n #else if length of most common = 3 and each key’s value = 2 then add 1500 to sum\n elif len(most_common) == 3 and all(count == 2 for _, count in most_common):\n sum += 1500\n return sum\n #else iterate the item in the common value array using a loop:\n else:\n for item in most_common:\n if item[0] == 1 and item[1] < 3:\n sum += 100 * item[1]\n if item[0] == 1 and item[1] == 3:\n sum += 1000\n if item[0] == 1 and item[1] == 4:\n sum += 2000\n if item[0] == 1 and item[1] == 5:\n sum += 4000\n if item == (1, 6):\n sum += 8000\n if item[0] == 5 and item[1] < 3:\n sum += 50 * item[1]\n if item[1] == 2:\n sum += 0\n if item[1] == 3 and item[0] != 1:\n sum += 100 * item[0]\n if item[1] == 4 and item[0] != 1:\n sum += 200 * item[0]\n if item[1] == 5 and item[0] != 1:\n sum += 400 * item[0]\n if item[1] == 6 and item[0] != 1:\n sum += 800 * item[0]\n return sum\n \n def run_dice(number):\n GameLogic.roll_dice(number)\n GameLogic.calculate_score()\n \n\n def validate_keepers(roll, keepers):\n roll = roll.counter(roll)\n keepers = keepers.counter(keepers)\n result = roll - keepers\n\n# after_input_ofdice = GameLogic.roll_dice(4)\n# after_calculating_score = GameLogic.calculate_score((1,2,5,5,5,6))\n# print(after_input_ofdice)\n# print(after_calculating_score) ","repo_name":"SahmAbuHashish/ten-thousand","sub_path":"ten_thousand/game_logic.py","file_name":"game_logic.py","file_ext":"py","file_size_in_byte":2873,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14992083950","text":"import bl\n\nmenu = \"\"\"\n0. exit\n1. get all themes names\n2. get all themes info\n3. add a new theme\n4. read a theme\n5. search for a theme\n6. add a new comment\n\"\"\"\n\ndef get_all_names():\n print(bl.get_all_names())\n\ndef get_all_info():\n print(bl.get_all())\n \ndef add_theme():\n name = input(\"Input a theme name:\\n\")\n descr = input(\"And a description:\\n\")\n print(bl.add_theme(name, descr))\n\ndef read_theme():\n name = input(\"Input a name:\\n\")\n print(bl.read_theme(name))\n\ndef search():\n term = input(\"Input a search term:\\n\")\n print(bl.search(term))\n\ndef add_comment():\n name = input(\"Input a theme name:\\n\")\n comment = input(\"Write your comment:\\n\")\n print(bl.add_comment(name, comment))\n\n\ndef main_cycle():\n while True:\n print(\"choose a point from the menu:\")\n print(menu)\n choice = input()\n if choice == '0':\n break\n elif choice == '1':\n get_all_names()\n elif choice == '2':\n get_all_info()\n elif choice == '3':\n add_theme()\n elif choice == '4':\n read_theme()\n elif choice == '5':\n search()\n elif choice == '6':\n add_comment() \n else:\n print(\"Invalid menu item, please try again\")\n\n\nmain_cycle()","repo_name":"MikitaTsiarentsyeu/Md-PT1-59-22","sub_path":"Tasks/Yakovenko/Task7/forum/ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":1298,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"69835681427","text":"import cv2\nimport numpy as np\n\nim = cv2.imread('bordered3.jpg')\n\ndepth = im.shape\n\n\n#if len(depth) == 3:\nblur = cv2.blur(im,(5,5))\nimg_sharp = cv2.addWeighted(im, 1.5, blur, -0.5, 0)\n#if len(depth) == 2:\n\t\n\ncv2.imshow(\"original\" , im)\ncv2.imshow(\"contrast\" , img_sharp)\n\nk = cv2.waitKey(0)\n#if k == 27:\n#\tbreak\n\ncv2.destroyAllWindows()\n","repo_name":"xjoshramos/border","sub_path":"sharpen.py","file_name":"sharpen.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5671174915","text":"#\n# @lc app=leetcode id=332 lang=python3\n#\n# [332] Reconstruct Itinerary\n#\n\n# @lc code=start\n\n\nfrom collections import defaultdict, deque\nfrom bisect import insort\n\n\nclass Solution:\n def findItinerary(self, tickets: list[list[str]]) -> list[str]:\n choices: dict[str, list] = defaultdict(list)\n for ticket in tickets:\n insort(choices[ticket[0]], ticket[1])\n if ticket[1] not in choices:\n choices[ticket[1]] = list()\n def dfs(path: list[str]) -> list[str]:\n if len(path) == len(tickets) + 1:\n return path\n\n for i, choice in enumerate(choices[path[-1]]):\n removed = choices[path[-1]].pop(i)\n itinerary_str = dfs(path + [choice])\n choices[path[-1]].insert(i, removed)\n if itinerary_str:\n return itinerary_str\n return []\n \n return dfs([\"JFK\"])\n\n\n# @lc code=end\nprint(Solution().findItinerary(\n [[\"JFK\",\"KUL\"],[\"JFK\",\"NRT\"],[\"NRT\",\"JFK\"]]\n));\n","repo_name":"felivalencia3/Leetcode","sub_path":"332.reconstruct-itinerary.py","file_name":"332.reconstruct-itinerary.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28404068871","text":"import cv2\r\nfrom ultralytics import YOLO\r\nimport os\r\n\r\nmodel = YOLO('yolov8n.pt')\r\n\r\nvideo_path = r'D:\\yoloproject\\demo.avi'\r\noutput_dir = r'C:\\Users\\warzo\\OneDrive\\Desktop\\demo\\photos'\r\nmax_frames = 10\r\n\r\n\r\ncap = cv2.VideoCapture(video_path)\r\n\r\nframe_count = 0\r\n\r\nwhile frame_count < max_frames:\r\n \r\n ret, frame = cap.read()\r\n\r\n if not ret:\r\n break\r\n\r\n results = model(frame)\r\n annotated_frame = results[0].plot()\r\n\r\n \r\n annotated_frame_filename = os.path.join(output_dir, f'annotated_frame_{frame_count:04d}.jpg')\r\n cv2.imwrite(annotated_frame_filename, annotated_frame)\r\n\r\n frame_count += 1\r\n\r\n\r\ncap.release()\r\nprint(\"completed\")\r\n","repo_name":"drude087/object_detection","sub_path":"practiceideas.py","file_name":"practiceideas.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73897372627","text":"'''\nCreated on Jul 15, 2013\n@author: Yubin Bai\n'''\nimport time\nfrom multiprocessing.pool import Pool\nfrom collections import Counter\nparallelSolve = False\nINF = 1 << 31\n\n\ndef solve(par):\n N, K, array = par\n\n def valid(n1):\n currN = 0\n count = 0\n for i in range(N):\n if array[i] > currN:\n count += 1\n currN = n1\n currN -= array[i]\n return count <= K\n\n low = array[0]\n high = sum(array)\n while low < high:\n mid = (low + high) >> 1\n if valid(mid):\n high = mid\n else:\n low = mid + 1\n result = []\n currN = high\n for i in range(N - 1, -1, -1):\n if array[i] > currN:\n result.append('/')\n currN = high\n currN -= array[i]\n result.append(str(array[i]))\n result.reverse()\n c = Counter(result)\n if c['/'] < K - 1:\n for i in range(K - 1 - c['/']):\n for j in range(len(result)):\n if result[j] != '/' and result[j + 1] != '/':\n result.insert(j + 1, '/')\n break\n\n print(high)\n return ' '.join(result)\n\n\nclass Solver:\n\n def getInput(self):\n self.numOfTests = int(self.fIn.readline())\n self.input = []\n for itertest in range(self.numOfTests):\n N, K = map(int, self.fIn.readline().strip().split())\n array = map(int, self.fIn.readline().split())\n self.input.append((N, K, array))\n\n def __init__(self):\n self.fIn = open('input.txt')\n self.fOut = open('output.txt', 'w')\n self.results = []\n\n def parallel(self):\n self.getInput()\n p = Pool(4)\n millis1 = int(round(time.time() * 1000))\n self.results = p.map(solve, self.input)\n millis2 = int(round(time.time() * 1000))\n print(\"Time in milliseconds: %d \" % (millis2 - millis1))\n self.makeOutput()\n\n def sequential(self):\n self.getInput()\n millis1 = int(round(time.time() * 1000))\n for i in self.input:\n self.results.append(solve(i))\n millis2 = int(round(time.time() * 1000))\n print(\"Time in milliseconds: %d \" % (millis2 - millis1))\n self.makeOutput()\n\n def makeOutput(self):\n for test in range(self.numOfTests):\n self.fOut.write(\"%s\\n\" % self.results[test])\n self.fIn.close()\n self.fOut.close()\n\nif __name__ == '__main__':\n solver = Solver()\n if parallelSolve:\n solver.parallel()\n else:\n solver.sequential()\n","repo_name":"yubinbai/pcuva-problems","sub_path":"UVa 714 - Copying Books/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2557,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"48"} +{"seq_id":"19502022275","text":"# 函数的名称空间:\n# 1.内置空间 -- 存放python自带的一些函数\n# 2.全局空间 -- 当前py文件定格编写代码开辟的空间\n# 3.局部空间 -- 函数体\n\n# 程序加载顺序(从外向内):内置空间 > 全局空间 > 局部空间\n# 程序取值顺序(从内向外):局部空间 > 全局空间 > 内置空间\n# a = 10\n# b = 10\n# def func():\n# a = 6\n# print(a)\n# print(b)\n# func()\n\n# 作用域:\n# 1.全局作用域:内置 + 全局 globals() 查看全局作用域\n# 1.局部作用域:局部 locals() 查看当前作用域(建议查看局部)\n\na = 10\nb = 15\ndef func():\n b = 5\n print(locals())\nfunc()\nprint(locals())\nd = 10\nprint(locals())","repo_name":"myin1994/mylearn","sub_path":"Python基础/day010/06 函数的名称空间.py","file_name":"06 函数的名称空间.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"16295684909","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 22 19:02:51 2015\n\n@author: simonfredon\n\"\"\"\n\nimport string\n\na = string.ascii_lowercase\n\nb = 1\nfor i in range(0, 25):\n for j in range(b, 26):\n print(a[i] + a[j])\n b = b + 1\n","repo_name":"simonfredon/hackinscience","sub_path":"exercises/080/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"345972822","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nMIT License\r\n\r\nCopyright (c) 2018 sarah-murray\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining a copy\r\nof this software and associated documentation files (the \"Software\"), to deal\r\nin the Software without restriction, including without limitation the rights\r\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\ncopies of the Software, and to permit persons to whom the Software is\r\nfurnished to do so, subject to the following conditions:\r\n\r\nThe above copyright notice and this permission notice shall be included in all\r\ncopies or substantial portions of the Software.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\nSOFTWARE.\r\n\"\"\"\r\n\r\n\r\nimport numpy as np\r\nimport csv\r\n\r\nclass Cross_section():\r\n \"\"\"\r\n Provide methods to build and slice 3D surfaces.\r\n \r\n Build 3D surfaces within a matplotlib figure. Take in user-specified\r\n X, Y, and Z coordinates and slice the data along upper and lower \r\n limits.\tAssign NaN to any data outside of these limits.\r\n \"\"\"\r\n\r\n def __init__(self,ax):\r\n \"\"\"\r\n Define the model.\r\n \r\n Args:\r\n ax -- Matplotlib object, \r\n matplotlib.pyplot.figure().gca(projection='3d')\r\n \"\"\"\r\n self.ax = ax\r\n \r\n def create_data(self, directory, data_list):\r\n \"\"\"\r\n Converts .csv data into a 2D list of values.\r\n \r\n Args:\r\n directory (str) -- .csv filename.\r\n data_list (list) -- Empty list to contain data.\r\n \r\n Returns:\r\n data_list (list) -- 2D list containing values from .csv.\r\n \"\"\"\r\n f = open(directory, newline=\"\")\r\n reader = csv.reader(f, quoting=csv.QUOTE_NONNUMERIC)\r\n for row in reader:\r\n rowlist = []\r\n for value in row:\r\n rowlist.append(float(value))\r\n data_list.append(rowlist)\r\n f.close()\r\n \r\n def set_extents(self, raw_data, x_data, y_data):\r\n \"\"\"\r\n Create 2D lists to define the X and Y extents.\r\n \r\n Create 2D lists to correspond with the input data to define the\r\n X and Y coordinate for each cell.\r\n \r\n Args:\r\n raw_data (list) -- input data of Z values.\r\n x_data (list) -- Empty list.\r\n y_data (list) -- Empty list.\r\n \r\n Returns:\r\n x_data (list) -- 2D list of X values.\r\n y_data (list) -- 2D list of Y values.\r\n \"\"\"\r\n ypoint = 1\r\n while ypoint <= len(raw_data[0]):\r\n ypoints = 1\r\n ylist = []\r\n while ypoints <= len(raw_data[0]):\r\n ylist.append(ypoint)\r\n ypoints += 1\r\n y_data.append(ylist)\r\n ypoint += 1\r\n \r\n xpoint = 1\r\n xlist = []\r\n while xpoint <= len(raw_data):\r\n xlist.append(xpoint)\r\n xpoint += 1\r\n xpoints = 1\r\n while xpoints <= len(raw_data):\r\n x_data.append(xlist)\r\n xpoints += 1\r\n\r\n def limit_surface(self, surface, new_surface, upper_limit, lower_limit):\r\n \"\"\"\r\n Set 2D list value to NaN where outside of specified values.\r\n \r\n Args:\r\n surface (list) -- 2D list.\r\n new_surface (list) -- Empty 2D list.\r\n upper_limit (float) -- Maximum value to keep within data.\r\n lower_limit (float) -- Minimum value to keep within data.\r\n \r\n Returns:\r\n new_surface (list) -- 2D list of the same dimensions as \r\n input data. Replace values not between lower_limit and \r\n upper_limit with \"nan\".\r\n \"\"\"\r\n #recreate surfaces replaces limited values with nan\r\n for i in surface:\r\n list = []\r\n for j in i:\r\n if j >= upper_limit:\r\n j = np.nan\r\n if j <= lower_limit:\r\n j = np.nan\r\n list.append(j)\r\n new_surface.append(list)\r\n\r\n def set_axes(self, x, y, z):\r\n \"\"\"\r\n Set axes to the minimum and maximum X, Y, and Z values.\r\n \r\n Prevent axes from changing with the maximum and minimum of\r\n displayed data.\r\n \r\n Args:\r\n x (list) -- 1D list of X coordinates.\r\n y (list) -- 1D list of Y coordinates.\r\n z (list) -- 1D list of Z coordinates.\r\n \"\"\"\r\n self.ax.set_xlim(min(x), max(x))\r\n self.ax.set_ylim(min(y), max(y))\r\n self.ax.set_zlim(min(z), max(z))\r\n\r\n def define_limits(self, data, limits):\r\n \"\"\"\r\n Convert a 2D list to a 1D list.\r\n \r\n Args:\r\n data (list) -- 2D list.\r\n limits (list) -- Empty list.\r\n \r\n Returns:\r\n limits (list) -- 1D list containing all values from data.\r\n \"\"\"\r\n for i in data:\r\n for j in i:\r\n limits.append(j)","repo_name":"sarah-murray/3D-surface-model","sub_path":"model_functions.py","file_name":"model_functions.py","file_ext":"py","file_size_in_byte":5401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29539916133","text":"'''\n\tGiven a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.\n\n\tExample 1:\n\n\tInput: n = 12\n\tOutput: 3 \n\tExplanation: 12 = 4 + 4 + 4.\n\tExample 2:\n\n\tInput: n = 13\n\tOutput: 2\n\tExplanation: 13 = 4 + 9.\n'''\n\nclass Solution(object):\n def numSquares(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n mapping = {}\n squares = [num*num for num in range(1, int(pow(n, 0.5)) + 1)]\n for square in squares:\n \tmapping[square] = 1\n\n for val in range(1, n+1):\n \tif val not in mapping:\n \t\tmapping[val] = float('inf')\n \t\tfor square in squares:\n \t\t\tif square < val:\n \t\t\t\tmapping[val] = min(mapping[val], mapping[square] + mapping[val-square])\n return mapping[n]","repo_name":"Garvit244/Leetcode","sub_path":"200-300q/279.py","file_name":"279.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","stars":1245,"dataset":"github-code","pt":"48"} +{"seq_id":"21901994544","text":"#\n# (c) 2019 Lenovo.\n#\n# This file is part of Ansible\n#\n# Ansible is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Ansible is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Ansible. If not, see .\n#\nfrom __future__ import (absolute_import, division, print_function)\n__metaclass__ = type\n\nfrom ansible_collections.community.network.tests.unit.compat.mock import patch\nfrom ansible_collections.community.network.plugins.modules import cnos_vrf\nfrom ansible_collections.community.network.tests.unit.plugins.modules.utils import set_module_args\nfrom .cnos_module import TestCnosModule, load_fixture\n\n\nclass TestCnosVrfModule(TestCnosModule):\n\n module = cnos_vrf\n\n def setUp(self):\n super(TestCnosVrfModule, self).setUp()\n\n self.mock_load_config = patch('ansible_collections.community.network.plugins.modules.cnos_vrf.load_config')\n self.load_config = self.mock_load_config.start()\n\n self.mock_run_commands = patch('ansible_collections.community.network.plugins.modules.cnos_vrf.run_commands')\n self.run_commands = self.mock_run_commands.start()\n\n self._patch_is_switchport = patch(\n 'ansible_collections.community.network.plugins.modules.cnos_vrf.is_switchport'\n )\n self._is_switchport = self._patch_is_switchport.start()\n\n def tearDown(self):\n super(TestCnosVrfModule, self).tearDown()\n self.mock_load_config.stop()\n self.mock_run_commands.stop()\n self._patch_is_switchport.stop()\n\n def load_fixtures(self, commands=None):\n config_file = 'cnos_vrf_config.cfg'\n self.load_config.return_value = load_fixture(config_file)\n self.run_commands.return_value = load_fixture(config_file)\n self._is_switchport.return_value = False\n\n def test_cnos_vrf_present(self):\n set_module_args(dict(name='test1', state='present'))\n self.execute_module(changed=True, commands=['vrf context test1'])\n\n def test_cnos_vrf_present_management(self):\n set_module_args(dict(name='management', state='present'))\n self.execute_module(changed=True, commands=['vrf context management'])\n\n def test_cnos_vrf_absent_management(self):\n set_module_args(dict(name='management', state='absent'))\n result = self.execute_module(failed=True)\n self.assertEqual(result['msg'], 'Management VRF context cannot be deleted')\n\n def test_cnos_vrf_absent_no_change(self):\n set_module_args(dict(name='test1', state='absent'))\n self.execute_module(changed=False, commands=[])\n\n def test_cnos_vrf_default(self):\n set_module_args(dict(name='default', state='present'))\n result = self.execute_module(failed=True)\n self.assertEqual(result['msg'], 'VRF context default is reserved')\n","repo_name":"ansible-collections/community.network","sub_path":"tests/unit/plugins/modules/test_cnos_vrf.py","file_name":"test_cnos_vrf.py","file_ext":"py","file_size_in_byte":3234,"program_lang":"python","lang":"en","doc_type":"code","stars":108,"dataset":"github-code","pt":"48"} +{"seq_id":"19975005047","text":"from distutils.core import setup\nimport py2exe\n\npliki = [('.', ['splash.png', 'icon.ico'])]\n\nsetup(windows=[{\"script\": 'client.py', \"icon_resources\": [(1, 'icon.ico')]}],\ndata_files = pliki,\nzipfile = None,\noptions={\n \"py2exe\":{\n \"unbuffered\": True,\n \"optimize\": 2,\n \"bundle_files\": 1,\n\t\t\t\t\t\t\"includes\":[\"sip\", \"PyQt4.QtNetwork\"]\n }\n }\n\n)","repo_name":"qbajas/Forum-Tracker","sub_path":"client/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28018793682","text":"\"\"\"A script which exports the subset of this repository required for target(s).\n\nThis project is getting large. This has two major downsides:\n * Fresh checkouts of the git repository take longer and consume more space.\n * The large number of packages is confusing to newcomers.\n\nI feel like there's a 90-10 rule that applies to this repo: 90% of people who\ncheckout this repo only need 10% of the code contained within it.\nThis script provides a way to export that 10%.\n\"\"\"\n\nimport contextlib\nimport git\nimport github as github_lib\nimport pathlib\nimport tempfile\nimport sys\nimport typing\n\nimport getconfig\nfrom datasets.github import api\nfrom labm8 import app\nfrom tools.source_tree import phd_workspace\n\nFLAGS = app.FLAGS\n\napp.DEFINE_list('targets', [], 'The bazel target(s) to export.')\napp.DEFINE_list('excluded_targets', [],\n 'A list of bazel targets to exclude from export.')\napp.DEFINE_list(\n 'extra_files', [], 'A list of additional files to export. Each element in '\n 'the list is a relative path to export. E.g. `bar/baz.txt`.')\napp.DEFINE_list(\n 'mv_files', [],\n 'Each element in the list is a mapping of relative paths in the form '\n ':. E.g. `foo.py:bar/baz.txt` will move file `foo.py` to '\n 'destination `bar/baz.txt`.')\napp.DEFINE_string('github_repo', None, 'Name of a GitHub repo to export to.')\napp.DEFINE_boolean('github_create_repo', False,\n 'Whether to create the repo if it does not exist.')\napp.DEFINE_boolean('github_repo_create_private', True,\n 'Whether to create new GitHub repos as private.')\napp.DEFINE_boolean('export_source_tree_print_files', False,\n 'Print the files that will be exported and terminate.')\n\n\ndef GetOrCreateRepoOrDie(github: github_lib.Github,\n repo_name: str) -> github_lib.Repository:\n \"\"\"Get the github repository to export to. Create it if it doesn't exist.\"\"\"\n try:\n if FLAGS.github_create_repo:\n return api.GetOrCreateUserRepo(\n github,\n repo_name,\n description='PhD repo subtree export',\n homepage='https://github.com/ChrisCummins/phd',\n has_wiki=False,\n has_issues=False,\n private=FLAGS.github_repo_create_private)\n else:\n return api.GetUserRepo(github, repo_name)\n except (api.RepoNotFoundError, OSError) as e:\n app.FatalWithoutStackTrace(str(e))\n\n\n@contextlib.contextmanager\ndef DestinationDirectoryFromFlags() -> pathlib.Path:\n \"\"\"Get the export destination.\"\"\"\n if FLAGS.github_repo:\n with tempfile.TemporaryDirectory(prefix='phd_tools_source_tree_') as d:\n yield pathlib.Path(d)\n else:\n yield pathlib.Path(FLAGS.destination)\n\n\ndef EXPORT(github_repo: str,\n targets: typing.List[str],\n excluded_targets: typing.List[str] = None,\n extra_files: typing.List[str] = None,\n move_file_mapping: typing.Dict[str, str] = None) -> None:\n \"\"\"Custom entry-point to export source-tree.\n\n This should be called from a bare python script, before flags parsing.\n\n Args:\n github_repo: The name of the GitHub repo to export to.\n targets: A list of bazel targets to export. These targets, and their\n dependencies, will be exported. These arguments are passed unmodified to\n bazel query, so `/...` and `:all` labels are expanded, e.g.\n `//some/package/to/export/...`. All targets should be absolute, and\n prefixed with '//'.\n extra_files: A list of additional files to export.\n move_file_mapping: A dictionary of relative paths listing files\n which should be moved from their respective source location to the\n destination.\n \"\"\"\n excluded_targets = excluded_targets or []\n extra_files = extra_files or []\n move_file_mapping = move_file_mapping or {}\n\n def _DoExport():\n source_path = pathlib.Path(getconfig.GetGlobalConfig().paths.repo_root)\n source_workspace = phd_workspace.PhdWorkspace(source_path)\n\n with tempfile.TemporaryDirectory(prefix='phd_tools_source_tree_') as d:\n destination = pathlib.Path(d)\n credentials = api.ReadGitHubCredentials(\n pathlib.Path('~/.githubrc').expanduser())\n connection = github_lib.Github(credentials.username, credentials.password)\n repo = GetOrCreateRepoOrDie(connection, github_repo)\n api.CloneRepoToDestination(repo, destination)\n destination_repo = git.Repo(destination)\n\n src_files = source_workspace.GetAllSourceTreeFiles(\n targets, excluded_targets, extra_files, move_file_mapping)\n if FLAGS.export_source_tree_print_files:\n print('\\n'.join(src_files))\n sys.exit(0)\n\n source_workspace.ExportToRepo(destination_repo, targets, src_files,\n extra_files, move_file_mapping)\n app.Log(1, 'Pushing changes to remote')\n destination_repo.git.push('origin')\n\n app.Run(_DoExport)\n\n\ndef main(argv: typing.List[str]):\n \"\"\"Main entry point.\"\"\"\n if len(argv) > 1:\n raise app.UsageError(\"Unknown arguments: '{}'.\".format(' '.join(argv[1:])))\n\n if not FLAGS.targets:\n raise app.UsageError('--targets must be one-or-more bazel targets')\n targets = list(sorted(set(FLAGS.targets)))\n\n excluded_targets = set(FLAGS.excluded_targets)\n\n def _GetFileMapping(f: str):\n if len(f.split(':')) == 2:\n return f.split(':')\n else:\n return f, f\n\n extra_files = list(sorted(set(FLAGS.extra_files)))\n\n move_file_tuples = [\n _GetFileMapping(f) for f in list(sorted(set(FLAGS.mv_files)))\n ]\n move_file_mapping = {x[0]: x[1] for x in move_file_tuples}\n\n with DestinationDirectoryFromFlags() as destination:\n connection = api.GetGithubConectionFromFlagsOrDie()\n repo = GetOrCreateRepoOrDie(connection, FLAGS.github_repo)\n api.CloneRepoToDestination(repo, destination)\n destination_repo = git.Repo(destination)\n source_workspace.ExportToRepo(destination_repo, targets, excluded_targets,\n extra_files, move_file_mapping)\n destination_repo.git.push('origin')\n\n\nif __name__ == '__main__':\n app.RunWithArgs(main)\n","repo_name":"ChrisCummins/bazel_subtree_github_export","sub_path":"tools/source_tree/export_source_tree.py","file_name":"export_source_tree.py","file_ext":"py","file_size_in_byte":6094,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40113926762","text":"import random\n\nfrom penman import Graph\n\nfrom amrbank_analysis.find_rare_node_labels import load_corpus_from_folder\nfrom amrbank_analysis.vulcan_pickle_builder import VulcanPickleBuilder\n\n\ndef main():\n training_corpus = load_corpus_from_folder(\"../../../data/Edinburgh/amr3.0/data/amrs/split/training/\")\n print(len(training_corpus))\n test_corpus = load_corpus_from_folder(\"../../../data/Edinburgh/amr3.0/data/amrs/split/test/\")\n print(len(test_corpus))\n\n r = random.Random(391) # seed generated by random.org\n r.shuffle(test_corpus)\n\n seen_dates = set()\n seen_names = set()\n\n for graph in training_corpus:\n for instance in graph.instances():\n if instance.target == \"date-entity\":\n date_string = get_date_string_for_date_instance(graph, instance)\n seen_dates.add(date_string)\n elif instance.target == \"name\":\n name_string = get_name_string_for_name_instance(graph, instance)\n seen_names.add(name_string)\n\n vpb_unseen_dates = VulcanPickleBuilder()\n vpb_unseen_names = VulcanPickleBuilder()\n vpb_seen_dates = VulcanPickleBuilder()\n vpb_seen_names = VulcanPickleBuilder()\n\n with open(\"outputs/unseen_dates.txt\", \"w\") as f:\n with open(\"../corpus/unseen_dates.tsv\", \"w\") as g:\n with open(\"outputs/unseen_names.txt\", \"w\") as f2:\n with open(\"../corpus/unseen_names.tsv\", \"w\") as g2:\n with open(\"../corpus/seen_dates.tsv\", \"w\") as h:\n with open(\"../corpus/seen_names.tsv\", \"w\") as h2:\n for graph in test_corpus:\n for instance in graph.instances():\n if instance.target == \"date-entity\":\n date_string = get_date_string_for_date_instance(graph, instance)\n if date_string not in seen_dates:\n f.write(date_string + \"\\n\")\n g.write(f\"{graph.metadata['id']}\\t{date_string}\\n\")\n vpb_unseen_dates.add_graph(graph)\n vpb_unseen_dates.add_graph_highlight([instance.source])\n else:\n h.write(f\"{graph.metadata['id']}\\t{date_string}\\n\")\n vpb_seen_dates.add_graph(graph)\n vpb_seen_dates.add_graph_highlight([instance.source])\n elif is_name_node(graph, instance):\n name_string = get_name_string_for_name_instance(graph, instance)\n if name_string not in seen_names:\n f2.write(name_string + \"\\n\")\n g2.write(f\"{graph.metadata['id']}\\t{name_string}\\n\")\n vpb_unseen_names.add_graph(graph)\n vpb_unseen_names.add_graph_highlight([instance.source])\n else:\n h2.write(f\"{graph.metadata['id']}\\t{name_string}\\n\")\n vpb_seen_names.add_graph(graph)\n vpb_seen_names.add_graph_highlight([instance.source])\n\n vpb_unseen_dates.save_pickle(\"outputs/unseen_dates.pickle\")\n vpb_unseen_names.save_pickle(\"outputs/unseen_names.pickle\")\n vpb_seen_dates.save_pickle(\"outputs/seen_dates.pickle\")\n vpb_seen_names.save_pickle(\"outputs/seen_names.pickle\")\n\n\ndef is_name_node(graph: Graph, instance):\n if not instance.target == \"name\":\n return False\n incoming_name_edges = [edge for edge in graph.edges(target=instance.source, role=\":name\")]\n if len(incoming_name_edges) == 0:\n return False\n name_attributes = [attribute for attribute in graph.attributes(source=instance.source)\n if attribute.role.startswith(\":op\")]\n return len(name_attributes) > 0\n\n\ndef get_name_string_for_name_instance(graph, instance):\n \"\"\"\n given a graph and an instance in it, returns the \" \".join of its sorted target labels\n used only when instance is a name, so the targets are op_i. Sorting them gives the parts of the name in order.\n :param graph:\n :param instance:\n :return: str: e.g. \"Capitol Hill\"\n \"\"\"\n name_dict = []\n for attribute in graph.attributes(source=instance.source):\n name_dict.append((attribute.role, attribute.target))\n name_dict.sort() # in opi order\n name_string = \" \".join([t[1] for t in name_dict]).replace(\"\\\"\", \"\")\n return name_string\n\n\ndef get_date_string_for_date_instance(graph, instance):\n date_dict = []\n for attribute in graph.attributes(source=instance.source):\n date_dict.append((attribute.role, attribute.target))\n date_dict.sort()\n date_string = \" \".join([f\"{t[0]} {t[1]}\" for t in date_dict])\n return date_string\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"jgroschwitz/GrAPES","sub_path":"amrbank_analysis/get_unseen_names_and_dates.py","file_name":"get_unseen_names_and_dates.py","file_ext":"py","file_size_in_byte":5209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35296814723","text":"import torchvision\nimport torch\nimport os\n\n\ndef _load_net(use_checkpoint, checkpoint_path, checkpoints_name, n_class, device, backbone, is_pre_train):\n Nets = {\n 'alexnet': torchvision.models.alexnet(num_classes=n_class, pretrained=is_pre_train),\n 'vgg16': torchvision.models.vgg16(num_classes=n_class, pretrained=is_pre_train),\n 'resnet18': torchvision.models.resnet18(num_classes=n_class, pretrained=is_pre_train),\n 'resnet50': torchvision.models.resnet50(num_classes=n_class, pretrained=is_pre_train),\n 'resnetn_101': torchvision.models.resnet101(num_classes=n_class, pretrained=is_pre_train),\n 'densenet121': torchvision.models.densenet121(num_classes=n_class, pretrained=is_pre_train),\n 'inception_v3': torchvision.models.inception_v3(num_classes=n_class, pretrained=is_pre_train)\n }\n if (use_checkpoint == True):\n checkpoints_dir = os.path.join(checkpoint_path,\n '{:s}'.format(checkpoints_name))\n net = Nets[backbone]\n net.load_state_dict(torch.load(checkpoints_dir, map_location=device))\n # net.eval()\n net.to(device)\n else:\n net = Nets[backbone]\n net.to(device)\n\n return net","repo_name":"leijiezhang/Cifar10_CNN","sub_path":"load_net.py","file_name":"load_net.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"7052352577","text":"\ngraph={'A':['B','C'],\n 'B':['A','D'],\n 'C':['A','D','E'],\n 'E':['C','D'],\n 'F':[],\n 'H':[]}\n\ndef add_edges(graph):\n edges=[]\n for start in graph:\n for neighbour in graph[start]:\n edges.append((start,neighbour))\n return edges\n\ndef isolated_node(graph):\n isolatedNode=[]\n while(graph):\n for start in graph:\n #if(graph[start]== []):\n if not graph[start]:\n isolatedNode+=start\n return isolatedNode\n\nprint(add_edges(graph))\nprint(isolated_node(graph))\n\nclass Graph(object):\n def __init__(self,graph_dict={}):\n self._graphDict=graph_dict\n\n def vertices(self):\n return(list(self._graphDict.keys()))\n\n def edges(self):\n return self._generateEdges()\n\n def add_vertex(self,vertex):\n if vertex not in self._graphDict:\n self._graphDict[vertex]=[]\n\n def add_edge(self,edges):\n edge=set(edges)\n print(\"Print set of edges\",edge)\n (vertex1,vertex2)=tuple(edge)\n print((vertex1,vertex2))\n if vertex1 in self._graphDict:\n self._graphDict[vertex1].append(vertex2)\n else :\n self._graphDict[vertex1]=[vertex2]\n\n def _generateEdges(self):\n edges=[]\n for vertex in self._graphDict:\n for neighbour in self._graphDict[vertex]:\n if {neighbour, vertex} not in edges:\n edges.append({vertex, neighbour})\n return edges\n\n def findpath(self,vertex1,vertex2):\n path=[]\n graph=self._graphDict\n path=path+ [vertex1]\n if vertex1==vertex2:\n return path\n if vertex1 not in graph:\n return None\n for vertex in graph[vertex1]:\n if vertex not in path:\n extended_path=self.findpath(vertex1,vertex2)\n if extended_path:\n return extended_path\n return None\n\n\n if self._generateEdges():\n path+=self._generateEdges()\n return path\n else:\n print(\"No path\")\n\nif __name__ == \"__main__\":\n graph={'A':['B','C'],\n 'B':['A','D'],\n 'C':['A','D','E'],\n 'E':['C','D'],\n 'F':[],\n 'H':[]}\n\ngraph1=Graph(graph)\n\nprint(\"Vertices of graph:\")\nprint(graph1.vertices())\n\nprint(\"Edges of graph:\")\nprint(graph1.edges())\n\nprint(\"Add vertex:\")\ngraph1.add_vertex(\"z\")\n\nprint(\"Vertices of graph:\")\nprint(graph1.vertices())\n\nprint(\"Add an edge:\")\ngraph1.add_edge({\"a\",\"z\"})\n\nprint(\"Vertices of graph:\")\nprint(graph1.vertices())\n\nprint(\"Edges of graph:\")\nprint(graph1.edges())\n\nprint('Adding an edge {\"x\",\"y\"} with new vertices:')\ngraph1.add_edge({\"x\",\"y\"})\nprint(\"Vertices of graph:\")\nprint(graph1.vertices())\nprint(\"Edges of graph:\")\nprint(graph1.edges())\nprint(\"Find Path\")\nprint(graph1.findpath('A','B'))\n\n","repo_name":"Naina0412/Data-Structures-Algorithms","sub_path":"Graph_Implementation.py","file_name":"Graph_Implementation.py","file_ext":"py","file_size_in_byte":2822,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"19449830962","text":"import time\n\nfrom typing import Dict\nmemo: Dict[int, int] = { 0: 0, 1: 1 }\n\ndef fib3(n: int) -> int:\n if n not in memo:\n memo[n] = fib3(n-1) + fib3(n-2)\n return memo[n]\n\nif __name__ == \"__main__\":\n start_time = time.time()\n n = 40\n print(\"fib3(%d)=%d\"%(n, fib3(n)))\n print(\"execution time: %s [s]\"%(time.time()-start_time))\n\n ","repo_name":"novoru/CS","sub_path":"01/fib/fib3.py","file_name":"fib3.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"3356677309","text":"## plot day to day network connections for a common set of neurons\nfrom typing import Optional, Dict, List\nfrom os.path import join, expanduser\nimport numpy as np\nfrom scipy.cluster.hierarchy import linkage\nimport toml\nfrom noformat import File\nfrom algorithm.array import DataFrame, common_axis, search_ar\nfrom algorithm.time_series import fold_by\nfrom mplplot import network as corr_graph\nfrom lever.analysis import motion_corr, classify_cells, noise_autocorrelation, noise_correlation, reliability\nfrom lever.utils import load_mat, MotionParams\nfrom lever.plot import fancy_dendrogram\nfrom mplplot import Figure, stacked_bar\n\nmotion_params = {\"quiet_var\": 0.001, \"window_size\": 1000, \"event_thres\": 0.3, \"pre_time\": 0.1, \"post_time\": 0.9}\nproject_folder = expanduser(\"~/Sync/project/2017-leverpush\")\nimg_folder = join(project_folder, \"report\", \"img\")\nres_folder = join(project_folder, \"report\", \"measure\")\nCOLORS = [\"#dc322fff\", \"#268bd2ff\", \"#d33682ff\", \"#2aa198ff\", \"#859900ff\", \"#b58900ff\"]\nmice = toml.load(join(project_folder, \"data/recording.toml\"))\nfiles = {x['session']: File(join(project_folder, 'data', x['path'])) for x in mice['wt']['0304']['3']}\n\ndef _sem(x):\n return np.std(x) / np.sqrt(len(x))\n\n# Cell: classify cells from the last day\ndef draw_classify_neurons(data_file: File, neuron_ids: Optional[np.ndarray] = None):\n lever = load_mat(data_file['response'])\n neuron = DataFrame.load(data_file['spike'])\n if neuron_ids is not None:\n neuron = neuron[search_ar(neuron_ids, neuron.axes[0]), :]\n neuron_rate = data_file.attrs['frame_rate']\n corr = motion_corr(lever, neuron, neuron_rate, 16000, motion_params)\n good, bad, anti = [corr[x, 0] for x in classify_cells(corr, 0.001)]\n with Figure(join(img_folder, \"good_unrelated_cmp.svg\"), (4, 6)) as ax:\n ax[0].bar((0, 1), [good.mean(), np.r_[bad, anti].mean()], yerr=[_sem(good), _sem(np.r_[bad, anti])])\n\n# cell: network graph\ndef draw_network_graph(data_files: Dict[int, File], params: MotionParams, threshold: int = 16000):\n \"\"\"Draw neuron functional connection for each session, with neurons colored by the last session.\n Args:\n data_files: {day_id: int, data_file: File}\n params: classify_cells need [\"quiet_var\", \"window_size\", \"event_thres\", \"pre_time\"]\n threshold: threshold for motion_corr, single linked cluster distance\n \"\"\"\n last_day = data_files[max(data_files.keys())]\n neurons = common_axis([DataFrame.load(x['spike']) for x in data_files.values()])\n neuron_rate = last_day.attrs['frame_rate']\n final_corr_mat = noise_autocorrelation(load_mat(last_day['response']), neurons[-1], neuron_rate)\n categories = classify_cells(motion_corr(last_day, neurons[-1], neuron_rate, threshold, params), 0.001)\n layout = corr_graph.get_layout(final_corr_mat, neurons[-1].axes[0])\n for (day_id, data_file), neuron in zip(data_files.items(), neurons):\n corr_mat = noise_autocorrelation(load_mat(data_file['response']), neuron, neuron_rate)\n with Figure(join(img_folder, f\"network-day-{day_id:02d}.svg\")) as ax:\n corr_graph.corr_plot(ax[0], corr_mat, categories, neuron.axes[0], layout=layout)\n print('done')\n\n# Cell: cluster proportions\ndef draw_hierarchy(data_files: Dict[int, File]):\n neurons = common_axis([DataFrame.load(x['spike']) for x in files.values()])\n for (day_id, data_file), neuron in zip(files.items(), neurons):\n lever = load_mat(data_file['response'])\n corr_mat = noise_autocorrelation(lever, neuron, data_file.attrs['frame_rate'])\n with Figure() as (ax,):\n ax.set_title(f\"day-{day_id:02d}\")\n fancy_dendrogram(linkage(corr_mat, 'average'), ax=ax)\n\n# Cell: stacked bar from manually labeled files\nClusterFile = Dict[str, Dict[str, List[int]]]\n\ndef draw_stacked_bar(cluster_file: ClusterFile):\n days = ('5', '10', '13', '14')\n res = [[len(cluster_file[day].get(str(cluster_id), []))\n for cluster_id in range(1, 15)] for day in days]\n with Figure() as (ax,):\n stacked_bar(ax, res, COLORS)\n ax.set_xticks(range(len(days)), days)\n\n# Cell: noise correlation\ndef _take_triu(x):\n return x[np.triu_indices(x.shape[0], 1)]\n\ndef draw_noise(data_files: Dict[int, File], neuron_id: int, params: MotionParams):\n last_day = max(data_files.keys())\n lever = load_mat(data_files[last_day]['response'])\n neuron_rate = data_files[last_day].attrs['frame_rate']\n neurons = common_axis([DataFrame.load(x['spike']) for x in data_files.values()])\n good, bad, anti = classify_cells(motion_corr(\n lever, neurons[-1], neuron_rate, 16000, params), 0.001)\n amp = list()\n corrs: Dict[str, List[List[float]]] = {'good': [], 'unrelated': [], 'between': []}\n for (day_id, data_file), neuron in zip(data_files.items(), neurons):\n if day_id == last_day:\n continue\n lever = load_mat(data_file['response'])\n corrs['good'].append(_take_triu(noise_autocorrelation(lever, neuron[good], neuron_rate)))\n corrs['unrelated'].append(_take_triu(noise_autocorrelation(lever, neuron[bad | anti], neuron_rate)))\n corrs['between'].append(_take_triu(noise_correlation(lever, neuron[good], neuron[bad | anti], neuron_rate)))\n lever.center_on(\"motion\", **params)\n neuron_trials = fold_by(neuron, lever, neuron_rate, True)\n amp.append(neuron_trials.values[np.argwhere(neuron.axes[0] == neuron_id)[0, 0], :, :].max(axis=1))\n with Figure(join(project_folder, 'report', 'img', f'noise_corr_{neuron_id}.svg')) as (ax,):\n day_ids = [x for x in data_files.keys() if x != last_day]\n for idx, (group_str, group) in enumerate(corrs.items()):\n ax.errorbar(day_ids, [np.mean(x) for x in group],\n yerr=[_sem(x) for x in group], color=COLORS[idx], label=group_str)\n ax2 = ax.twinx()\n ax2.errorbar(day_ids, [np.mean(x) for x in amp], [_sem(x) for x in amp], color=COLORS[-1])\n ax.set_title(str(neuron_id))\n ax.legend()\n\n# Cell: Mesuare the inter-cell correlation between trials of typical pushes for single neurons on different days\ndef draw_neuron_corr(data_files: Dict[int, File], params: MotionParams, fov_id: str = None):\n neurons = common_axis([DataFrame.load(x['spike']) for x in data_files.values()])\n last_day = max(data_files.keys())\n lever = load_mat(data_files[last_day]['response'])\n neuron_rate = data_files[last_day].attrs['frame_rate']\n good, bad, anti = classify_cells(motion_corr(\n lever, neurons[-1], neuron_rate, 16000, params), 0.001)\n result_list = list()\n for (day, data_file), neuron in zip(data_files.items(), neurons):\n lever.center_on('motion') # type: ignore\n motion_neurons = fold_by(neuron, lever, neuron_rate, True)\n result_list.append([reliability(motion_neuron) for motion_neuron in motion_neurons.values])\n result = np.array(result_list)\n\n with Figure(join(img_folder, (\"neuron_corr.svg\" if fov_id is None else f\"{fov_id}.svg\"))) as ax:\n ax[0].plot(list(data_files.keys()), result[:, good])\n## actual running\ncommon_id = common_axis([DataFrame.load(x['spike']) for x in files.values()])[-1].axes[0]\ndraw_classify_neurons(files[14], common_id)\ndraw_hierarchy(files)\ndraw_stacked_bar(toml.load(join(res_folder, 'cluster.toml'))) # type: ignore\nneuron_ids = toml.load(join(res_folder, \"0304-neurons.toml\"))['neuron_id']\ndraw_noise(files, 27, motion_params)\ndraw_neuron_corr(files, motion_params)\n##\n","repo_name":"Palpatineli/lever","sub_path":"lever/script/testing/noise_corr.py","file_name":"noise_corr.py","file_ext":"py","file_size_in_byte":7484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"43642117310","text":"from django.contrib import admin\nfrom .models import Member, Attendance\n\n\n@admin.register(Member)\nclass MemberAdmin(admin.ModelAdmin):\n list_display = [\n # 'id',\n 'member_id',\n 'first_name',\n 'middle_name',\n 'last_name',\n 'gender',\n 'location',\n 'phone_number_1',\n 'phone_number_2',\n 'visitor',\n 'date_added',\n 'date_updated',\n ]\n\n fields = (#'member_id',\n 'first_name',\n 'last_name',\n 'middle_name',\n 'gender',\n 'phone_number_1',\n 'phone_number_2', \n 'location',\n 'visitor',)\n # readonly_fields = ('member_id',)\n\n date_hierarchy = 'date_added'\n # list_editable = ('first_name', 'middle_name', 'last_name', 'gender', 'phone_number_1',\n # 'phone_number_2',)\n # list_filter = ('member_id', 'first_name',\n # 'middle_name', 'last_name', 'date_added')\n search_fields = ('member_id', 'first_name',\n 'middle_name', 'last_name', 'gender', 'phone_number_1',)\n list_per_page = 200\n list_max_show_all = 500\n\n # def get_form(self, request, obj=None, **kwargs):\n # try:\n # form = super(MemberAdmin, self).get_form(request, obj, **kwargs)\n # form.base_fields['member_id'].initial = self.member_id = int(Member.objects.order_by(\n # 'member_id').last().member_id) + 1\n # form.base_fields['member_id'].editable = False\n # except Exception as identifier:\n # self.member_id = 1001\n\n # return form\n\n # readonly_fields = ('member_id',)\n # def save_model(self, request, obj, form, change):\n # super().save_model(request, obj, form, change)\n\n # try:\n # pass\n # except expression as identifier:\n # pass\n\n class Meta:\n model = Member\n\n\n@admin.register(Attendance)\nclass AttendanceAdmin(admin.ModelAdmin):\n autocomplete_fields = ['member']\n\n def member_id(self, obj):\n return f'{obj.member.member_id}'\n\n def member_name(self, obj):\n return f'{obj.member.last_name} {obj.member.first_name}'\n\n list_display = [\n 'id',\n 'date',\n 'member_id',\n 'member_name',\n # 'temp_tens',\n # 'temp_ones',\n # 'temp_decimals',\n 'service',\n 'temperature',\n 'present',\n 'child',\n 'date_added'\n ]\n\n fields = (\n 'date',\n 'service',\n 'member',\n 'temperature',\n # ('temp_tens', 'temp_ones', 'temp_decimals'),\n 'child',\n\n\n )\n\n # readonly_fields = ('temperature',)\n date_hierarchy = 'date'\n search_fields = ('member__member_id',\n 'member__first_name', 'member__last_name', 'member__middle_name')\n list_filter = ('date',)\n list_display_links = ['member_id', 'member_name']\n\n # def save_model(self, request, obj, form, change):\n # self.member_id = int(Member.objects.order_by(\n # 'member_id').last().member_id) + 1\n # super().save_model(request, obj, form, change)\n \n\n class Meta:\n model = Attendance\n\n\nclass AttendanceInline(admin.TabularInline):\n model = Attendance\n # exclude = ['short_description']\n","repo_name":"may-dev-core/church-app","sub_path":"apps_module/membership/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":3308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"3704488868","text":"# valueIterationAgents.py\n# -----------------------\n# Licensing Information: You are free to use or extend these projects for\n# educational purposes provided that (1) you do not distribute or publish\n# solutions, (2) you retain this notice, and (3) you provide clear\n# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.\n#\n# Attribution Information: The Pacman AI projects were developed at UC Berkeley.\n# The core projects and autograders were primarily created by John DeNero\n# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).\n# Student side autograding was added by Brad Miller, Nick Hay, and\n# Pieter Abbeel (pabbeel@cs.berkeley.edu).\n\n\n# valueIterationAgents.py\n# -----------------------\n# Licensing Information: You are free to use or extend these projects for\n# educational purposes provided that (1) you do not distribute or publish\n# solutions, (2) you retain this notice, and (3) you provide clear\n# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.\n#\n# Attribution Information: The Pacman AI projects were developed at UC Berkeley.\n# The core projects and autograders were primarily created by John DeNero\n# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).\n# Student side autograding was added by Brad Miller, Nick Hay, and\n# Pieter Abbeel (pabbeel@cs.berkeley.edu).\n\n\nimport mdp, util\n\nfrom learningAgents import ValueEstimationAgent\nimport collections\n\n\n\"\"\"\npart 2-1\n\"\"\"\n\nclass ValueIterationAgent(ValueEstimationAgent):\n \"\"\"\n * Please read learningAgents.py before reading this.*\n\n A ValueIterationAgent takes a Markov decision process\n (see mdp.py) on initialization and runs value iteration\n for a given number of iterations using the supplied\n discount factor.\n \"\"\"\n def __init__(self, mdp, discount = 0.9, iterations = 100):\n \"\"\"\n Your value iteration agent should take an mdp on\n construction, run the indicated number of iterations\n and then act according to the resulting policy.\n\n Some useful mdp methods you will use:\n mdp.getStates()\n mdp.getPossibleActions(state)\n mdp.getTransitionStatesAndProbs(state, action)\n mdp.getReward(state, action, nextState)\n mdp.isTerminal(state)\n \"\"\"\n self.mdp = mdp\n self.discount = discount\n self.iterations = iterations\n self.values = util.Counter() # A Counter is a dict with default 0\n self.runValueIteration()\n\n def runValueIteration(self):\n # Write value iteration code here\n \"*** YOUR CODE HERE ***\"\n # Begin your code\n\n \"\"\"\n V(s) = max_{a in actions} Q(s,a)\n policy(s) = arg_max_{a in actions} Q(s,a)\n \"\"\"\n for i in range(self.iterations):\n nextQValues = self.values.copy()\n for state in self.mdp.getStates():\n if self.mdp.isTerminal(state):\n continue\n bestAction = self.computeActionFromValues(state) # this is policy(s)\n bestValue = self.computeQValueFromValues(state, bestAction) # this is V(s)\n nextQValues[state] = bestValue\n self.values = nextQValues\n # End your code\n\n\n def getValue(self, state):\n \"\"\"\n Return the value of the state (computed in __init__).\n \"\"\"\n return self.values[state]\n\n\n def computeQValueFromValues(self, state, action):\n \"\"\"\n Compute the Q-value of action in state from the\n value function stored in self.values.\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n # Begin your code\n QValue = 0\n\n Transitions = self.mdp.getTransitionStatesAndProbs(state, action)\n for i in range(len(Transitions)):\n nextState, Prob = Transitions[i]\n nextReward = self.mdp.getReward(state, action, nextState)\n QValue += Prob * (nextReward + self.discount * self.getValue(nextState))\n return QValue\n # End your code\n\n def computeActionFromValues(self, state):\n \"\"\"\n The policy is the best action in the given state\n according to the values currently stored in self.values.\n\n You may break ties any way you see fit. Note that if\n there are no legal actions, which is the case at the\n terminal state, you should return None.\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n # Begin your code\n if self.mdp.isTerminal(state):\n return None\n\n QValues = util.Counter() # A dict(), but defalt value is 0.\n\n\n # We will iterate all possible actions to count the Qvalues.\n PossibleActions = self.mdp.getPossibleActions(state)\n for possibleAction in PossibleActions:\n QValues[possibleAction] = self.computeQValueFromValues(state, possibleAction)\n\n\n # Iterate all possible actions to get the best action which has max Qvalue.\n bestAction = None\n bestValue = -1000000000.0\n for possibleAction in PossibleActions:\n if QValues[possibleAction] > bestValue:\n bestValue = QValues[possibleAction]\n bestAction = possibleAction\n\n return bestAction\n # End your code\n\n def getPolicy(self, state):\n \"\"\"\n The policy is the best action in the given state\n according to the values computed by value iteration.\n You may break ties any way you see fit. Note that if\n there are no legal actions, which is the case at the\n terminal state, you should return None.\n \"\"\"\n return self.computeActionFromValues(state)\n\n def getAction(self, state):\n \"Returns the policy at the state (no exploration).\"\n return self.computeActionFromValues(state)\n\n def getQValue(self, state, action):\n \"\"\"\n The q-value of the state action pair\n (after the indicated number of value iteration\n passes). Note that value iteration does not\n necessarily create this quantity and you may have\n to derive it on the fly.\n \"\"\"\n return self.computeQValueFromValues(state, action)\n","repo_name":"HaKkaz/NYCU-Introduction-to-AI","sub_path":"hw3/Q-learning/valueIterationAgents.py","file_name":"valueIterationAgents.py","file_ext":"py","file_size_in_byte":6205,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"72534335507","text":"from flask import Flask, render_template\nimport RPi.GPIO as GPIO\n\napp = Flask(__name__)\napp.debug=True\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(18, GPIO.OUT)\npwm = GPIO.PWM(18, 50) # sets a reference to GPIO PWM pin 18, at 50Hz\n\n@app.route('/')\ndef index():\n return 'Try http://localhost:5000/on!'\n\n@app.route('/on')\ndef led_on():\n pwm.stop() # stops PWM if it's active, why not?\n GPIO.output(18, 1)\n return 'LED on!'\n\n@app.route('/off')\ndef led_off():\n pwm.stop() # stops PWM if it's active, why not?\n GPIO.output(18, 0)\n return 'LED off!'\n\n@app.route('/pwm/')\ndef var(var):\n pwm.stop() # stops PWM if it's active, why not?\n pwm.start(int(var)) # starts PWM with duty cycle equal to var\n # note, we could also use pwm.ChangeDutyCycle(var) instead of stopping and \n # starting the PWM pin\n return 'PWM duty cycle set to {}'.format(var)\n\nif __name__ == \"__main__\":\n app.run()\n","repo_name":"blamejoel/iot-workshop","sub_path":"iot-4-internet-connected-light/app2.py","file_name":"app2.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"74910093906","text":"#!/usr/bin/env python\n\nimport fire\nimport glob\nimport os\nimport yaml\nimport math\nimport pycoevolity as pe\nimport pandas as pd\nfrom check import check_output, check_eco_output\nimport dendropy as dp\nfrom statistics import mean, stdev\nfrom tqdm import tqdm\nfrom decimal import Decimal as D\nfrom decimal import getcontext\n\ndef calc_stats(method, rep, true, chains, interval=0.95):\n combined = [i for j in chains for i in j]\n \n # Determine upper and lower quantiles\n getcontext().prec = 3\n quant = (D(1.0) - D(interval)) / 2\n lower_quant = 0 + quant\n upper_quant = 1 - quant\n\n # Calculate credible interval and hpd\n lower_hpd, upper_hpd = pe.stats.get_hpd_interval(combined, \n interval_prob=interval)\n lower_ci = pe.stats.quantile(combined, lower_quant)\n upper_ci = pe.stats.quantile(combined, upper_quant)\n\n # Check if true value within hpd\n if lower_hpd < true < upper_hpd:\n hpd_covered = True \n else:\n hpd_covered = False\n\n # Check if true value within credible interval\n if lower_ci < true < upper_ci:\n ci_covered = True\n else: \n ci_covered = False\n\n # Calculate potential scale reduction factor\n if len(chains) > 1:\n red_fac = pe.stats.potential_scale_reduction_factor(chains)\n else:\n red_fac = None\n \n # Add stats to dictionary\n d = dict(\n method=method,\n replicate=rep,\n true=true,\n mean=mean(combined),\n red_fac=red_fac,\n ess=pe.stats.effective_sample_size(combined),\n interval=interval,\n ci_lower=lower_ci,\n ci_upper=upper_ci,\n ci_covered=ci_covered,\n hpd_lower=lower_hpd,\n hpd_upper=upper_hpd,\n hpd_covered=hpd_covered)\n\n return d\n\ndef summarize(dir, eco_burnin=501, star_burnin=201, method=\"all\", interval=0.95):\n dir = os.path.abspath(dir)\n config = yaml.safe_load(open(os.path.join(dir, \"config.yml\")))\n nreps = config[\"nreps\"]\n eco_chains = config[\"ecoevolity_chains\"]\n star_chains = config[\"starbeast_chains\"]\n theta_dicts = []\n time_dicts = []\n for rep in tqdm(range(0, nreps)):\n rep_dir = os.path.join(dir, \"rep-{}\".format(rep))\n\n # Get true simulated values\n sim_tree_path = os.path.join(rep_dir, \"species_tree.nex\")\n sim_tree = dp.Tree.get(path=sim_tree_path, schema=\"nexus\")\n true_thetas = {}\n true_times = {}\n for node in sim_tree:\n if node.taxon:\n label = node.taxon.label\n else:\n label = \"root\" \n true_thetas[label] = float(node.annotations[\"pop_size\"].value)\n true_times[label] = float(node.edge.length)\n\n if method in [\"all\", \"ecoevolity\"]:\n # Calculate and store stats for ecoevolity\n eco_theta_chains = dict(root=[], T1=[], T2=[])\n eco_time_chains = []\n for chain in range(1, eco_chains+1):\n chain_dir = os.path.join(rep_dir, \"ecoevo-chain-{}\".format(chain))\n # eco_pattern = os.path.join(chain_dir, \"ecoevo-{}-{}.o*\".format(rep, chain))\n eco_log = os.path.join(chain_dir, \"ecoevolity-config-state-run-1.log\")\n est_df = pd.read_csv(eco_log, sep='\\t').loc[eco_burnin:]\n eco_theta_chains[\"root\"].append(est_df[\"pop_size_root_T1\"].tolist())\n eco_theta_chains[\"T1\"].append(est_df[\"pop_size_T1\"].tolist())\n eco_theta_chains[\"T2\"].append(est_df[\"pop_size_T2\"].tolist())\n eco_time_chains.append(est_df[\"root_height_T1\"].tolist())\n for key in eco_theta_chains:\n theta_dict = calc_stats(\n method=\"ecoevolity\",\n rep=rep,\n true=true_thetas[key],\n chains=eco_theta_chains[key],\n interval=interval)\n theta_dict[\"taxon\"] = key\n theta_dicts.append(theta_dict)\n time_dicts.append(calc_stats(\n method=\"ecoevolity\",\n rep=rep,\n true=true_times[\"T1\"],\n chains=eco_time_chains, \n interval=interval))\n\n if method in [\"all\", \"starbeast\"]:\n # Calculate and store stats for starbeast\n star_theta_chains = dict(root=[], T1=[], T2=[])\n star_time_chains = []\n for chain in range(1, star_chains+1):\n chain_dir = os.path.join(\n rep_dir, \"starbeast-chain-{}\".format(chain))\n trees_path = os.path.join(chain_dir, \"species.trees\")\n trees = dp.TreeList.get(path=trees_path, schema='nexus')\n theta_chain = {key: [] for key in true_thetas}\n time_chain = []\n for tree in trees[star_burnin:]:\n for node in tree:\n if node.taxon:\n theta_chain[node.taxon.label].append(\n float(node.annotations[\"dmv\"].value[0]))\n if node.taxon.label == \"T1\":\n time_chain.append(node.edge.length)\n else:\n theta_chain[\"root\"].append(float(\n node.annotations[\"dmv\"].value[0]))\n for key in star_theta_chains:\n star_theta_chains[key].append(theta_chain[key])\n star_time_chains.append(time_chain)\n for key in star_theta_chains:\n theta_dict = calc_stats(\n method=\"starbeast\",\n rep=rep,\n true=true_thetas[key],\n chains=star_theta_chains[key],\n interval=interval)\n theta_dict[\"taxon\"] = key\n theta_dicts.append(theta_dict)\n time_dicts.append(calc_stats(\n method=\"starbeast\", \n rep=rep,\n true=true_times[\"T1\"], \n chains=star_time_chains,\n interval=interval))\n \n # Output stats to file\n theta_df = pd.DataFrame(theta_dicts)\n theta_df.to_csv(os.path.join(dir, \"summary-theta.csv\"), index=False)\n time_df = pd.DataFrame(time_dicts)\n time_df.to_csv(os.path.join(dir, \"summary-time.csv\"), index=False)\n\n # Here for testing, avoid recomputing all stats above\n # theta_df = pd.read_csv(os.path.join(dir, \"summary-theta.csv\"))\n # time_df = pd.read_csv(os.path.join(dir, \"summary-time.csv\"))\n\n # Get theta coverage\n theta_coverage = []\n theta_coverage_strs = [] \n for method, group in theta_df.groupby([\"method\"]):\n for taxon, g in group.groupby([\"taxon\"]):\n hpd_cover = g[\"hpd_covered\"].sum() / nreps\n ci_cover = g[\"ci_covered\"].sum() / nreps\n theta_coverage.append(dict(\n interval=\"hpd\",\n method=method,\n taxon=taxon,\n coverage=hpd_cover))\n theta_coverage.append(dict(\n interval=\"ci\",\n method=method,\n taxon=taxon,\n coverage=ci_cover))\n theta_coverage_strs.append(\n \"Theta-{}-{}-hpd= {}\".format(method, taxon, hpd_cover)) \n theta_coverage_strs.append(\n \"Theta-{}-{}-ci= {}\".format(method, taxon, ci_cover)) \n\n # Get time coverage\n time_coverage = []\n time_coverage_strs = [] \n for method, group in time_df.groupby([\"method\"]):\n hpd_cover = g[\"hpd_covered\"].sum() / nreps\n ci_cover = g[\"ci_covered\"].sum() / nreps\n time_coverage.append(dict(\n interval=\"hpd\",\n method=method,\n coverage=hpd_cover))\n time_coverage.append(dict(\n interval=\"ci\",\n method=method,\n coverage=ci_cover))\n time_coverage_strs.append(\n \"Time-{}-hpd= {}\".format(method, hpd_cover)) \n time_coverage_strs.append(\n \"Time-{}-ci= {}\".format(method, ci_cover)) \n\n # Store coverage in csv\n theta_coverage_df = pd.DataFrame(theta_coverage)\n theta_coverage_df.to_csv(os.path.join(dir, \"coverage-theta.csv\"), index=False)\n time_coverage_df = pd.DataFrame(time_coverage)\n time_coverage_df.to_csv(os.path.join(dir, \"coverage-time.csv\"), index=False)\n\n # Print coverage and write strings to text file\n for i in theta_coverage_strs:\n print(i)\n with open(os.path.join(dir, \"coverage-theta.txt\"), \"w\") as fh:\n fh.write('\\n'.join(theta_coverage_strs))\n\n for i in time_coverage_strs:\n print(i)\n with open(os.path.join(dir, \"coverage-time.txt\"), \"w\") as fh:\n fh.write('\\n'.join(time_coverage_strs))\n\n\n print(\"Summary Complete\")\n\nif __name__ == \"__main__\":\n fire.Fire(summarize)\n","repo_name":"kerrycobb/align-error-sp-tree-sim","sub_path":"sims/summarize.py","file_name":"summarize.py","file_ext":"py","file_size_in_byte":8811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13806447679","text":"# Imports\nfrom machine import Pin\nimport time\n\n# set up buttons on GPIO pins and set 3.3v pin to 0v with PULL DOWN\nbutton1 = Pin(3, Pin.IN, Pin.PULL_DOWN)\n\n# set up LEDs\nred = Pin(18, Pin.OUT)\namber = Pin(19, Pin.OUT)\ngreen = Pin(20, Pin.OUT)\n\n\nwhile True:\n # prevent multiple firings with 1 button press\n time.sleep(0.2)\n \n # toggle LEDs on and off\n if button1.value() == 1:\n print(\"Button 1\tpressed\")\n red.toggle()\n amber.toggle()\n green.toggle()\n \n\n","repo_name":"ivnkris/raspberrypi-pico-projects","sub_path":"buttons/toggling_with_buttons.py","file_name":"toggling_with_buttons.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12367138969","text":"import os\nimport errno\n\n\ndef split_channels(playlist_file):\n\n playlist = []\n with open(playlist_file, \"r\", encoding=\"utf-8\") as f:\n for line in f:\n playlist.append(line)\n \n #chunk\n chunk_size = 3\n\n chunks = [playlist[i:i + chunk_size]\n for i in range(1, len(playlist), chunk_size)]\n result_list = []\n\n for chunk in chunks:\n result_list.append(chunk)\n #print (result_list)\n \n sd_channels = []\n hd_channels = []\n\n\n for i in result_list:\n channel = i[0]\n if \"HD\" in channel or \"4K\" in channel or \"4k\" in channel or \"1080p\" in channel:\n hd_channels.append(i)\n else:\n sd_channels.append(i)\n \n return sd_channels, hd_channels\n\n\ndef write_channels(channels, file_path):\n with open(file_path, \"w\", encoding=\"utf-8\") as f:\n f.write(\"#EXTM3U\\n\")\n for channel in channels:\n print(channel)\n for line in channel:\n f.write (line)\n\nif __name__ == \"__main__\":\n playlist_file = \"playlist (futbol club effekt).m3u8\"\n sd_channels, hd_channels = split_channels(playlist_file)\n\n try:\n os.makedirs(\"SD\")\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise\n\n try:\n os.makedirs(\"HD\")\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise\n\n write_channels(sd_channels, \"SD/SD.m3u\")\n write_channels(hd_channels, \"HD/HD.m3u\")\n print(f\"{len(sd_channels)} SD channels and {len(hd_channels)} HD created successfully!\")\n","repo_name":"ncniyazov/iptv-m3u-editor","sub_path":"other_versions/iptv.py","file_name":"iptv.py","file_ext":"py","file_size_in_byte":1562,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"4843286919","text":"#!/usr/bin/python3\n\"\"\" LIFO Caching\n\"\"\"\n\n\nfrom base_caching import BaseCaching\n\n\nclass LIFOCache(BaseCaching):\n \"\"\" aninherits caching system\n \"\"\"\n def __init__(self):\n \"\"\"inistate\"\"\"\n super().__init__()\n self.__key = []\n\n def put(self, key, item):\n \"\"\" put cahce\n Args:\n key ([type]): key of dictionary\n item ([type]): item to insert in dictionary\n \"\"\"\n if len(self.cache_data) == self.MAX_ITEMS and key not in self.__key:\n discard = self.__key.pop()\n del self.cache_data[discard]\n print('DISCARD: {}'.format(discard))\n if key and item:\n self.__key.append(key)\n self.cache_data[key] = item\n\n def get(self, key):\n \"\"\" get value\n \"\"\"\n if not key or key not in self.cache_data:\n return None\n return self.cache_data[key]\n","repo_name":"mardochee01/alx-backend","sub_path":"0x01-caching/2-lifo_cache.py","file_name":"2-lifo_cache.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18600910005","text":"import asyncio\r\n\r\nimport streamlit as st\r\nimport searchconsole\r\nimport pandas as pd\r\nfrom pathlib import Path\r\nimport json\r\nimport pandas as pd\r\n#from io import StringIO\r\n\r\n#Synode's code ###########################################\r\n\r\nfrom contextlib import contextmanager\r\nfrom io import StringIO\r\nfrom streamlit.report_thread import REPORT_CONTEXT_ATTR_NAME\r\nfrom threading import current_thread\r\nfrom time import sleep\r\nimport streamlit as st\r\nimport sys\r\n\r\n\r\n@contextmanager\r\ndef st_redirect(src, dst):\r\n old_write = src.write\r\n\r\n with StringIO() as buffer:\r\n def new_write(b):\r\n if getattr(current_thread(), REPORT_CONTEXT_ATTR_NAME, None):\r\n buffer.write(b)\r\n dst(buffer.getvalue())\r\n else:\r\n old_write(b)\r\n\r\n try:\r\n src.write = new_write\r\n yield\r\n finally:\r\n src.write = old_write\r\n\r\n\r\n@contextmanager\r\ndef st_stdout(dst):\r\n with st_redirect(sys.stdout, dst):\r\n yield\r\n\r\n\r\n@contextmanager\r\ndef st_stderr(dst):\r\n with st_redirect(sys.stderr, dst):\r\n yield\r\n\r\n\r\ndef main():\r\n out1 = st.empty()\r\n with st_stdout(out1.code):\r\n print(\"Hello\")\r\n sleep(1)\r\n print(\"World\")\r\n\r\n out2 = st.empty()\r\n with st_stdout(out2.info):\r\n print(\"Goodbye\")\r\n sleep(1)\r\n print(\"World\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n\r\n\r\n###########################################\r\n\r\nst.set_option('deprecation.showfileUploaderEncoding', False)\r\n\r\nst.title(\"Connect to GSC via Josh Carty code\")\r\n\r\nuploaded_file = st.file_uploader(\"Choose a file\")\r\n\r\nif not uploaded_file:\r\n st.warning('Upload your credentials first. ☝️')\r\n st.stop()\r\n\r\nif uploaded_file is not None:\r\n # To read file as bytes:\r\n bytes_data = uploaded_file.read()\r\n #st.write(type(bytes_data))\r\n #st.write(bytes_data)\r\n import json\r\n JsonFromString = json.loads(bytes_data)\r\n st.header(\"First JSON file!\")\r\n st.write(JsonFromString)\r\n\r\nsite = 'https://www.tatielou.co.uk/' # Property to extract\r\n\r\nnum_days = 5 # Number of Days, Months to Extract\r\n#creds = 'GSCTatieLouCredentialsNonLegacy.json'\r\noutput = 'gsc_data.csv'\r\n\r\nst.header(\"Proceed to Oauth\")\r\n\r\nmy_file = Path(\"credentials.json\")\r\n#if st.button('Proceed to Oauth'):\r\n\r\n\r\nif my_file.is_file():\r\n #account = searchconsole.authenticate(client_config=JsonFromString,credentials='credentials.json')\r\n account = searchconsole.authenticate(client_config=JsonFromString,credentials='credentials.json')\r\n webproperty = account['https://www.tatielou.co.uk/']\r\n report = webproperty.query.range('today', days=-7).dimension('query').get()\r\n df = pd.DataFrame(report.rows)\r\n st.write(df)\r\nelse:\r\n #account = searchconsole.authenticate(client_config=JsonFromString,serialize='credentials.json')\r\n #Synode's code ###############\r\n outputStdout = st.empty()\r\n with st_stdout(outputStdout.info):\r\n account = searchconsole.authenticate(client_config=JsonFromString,serialize='credentials.json', flow=\"console\")\r\n #searchconsole.authenticate(client_config=\"GSCTatieLouCredentials.json\", serialize='credentials.json', flow=\"console\")\r\n #st.write('No, credentials.json doesnt exist')\r\n\r\n\r\nif account:\r\n code = st.text_input(\"Authorization code\")\r\nelse:\r\n code = None\r\n \"Waiting client configuration...\"\r\n\r\n\"## Access token\"\r\n\r\nasync def write_access_token(code):\r\n token = await account.get_access_token(code, redirect_uri)\r\n st.write(token)\r\n\r\nif code:\r\n asyncio.run(write_access_token(code))\r\n st.write(type(code))\r\nelse:\r\n \"Waiting authorization code...\"\r\n\r\n\r\ntry:\r\n with open(\"credentials.json\", \"r\") as f:\r\n my_dict = json.load(f)\r\n st.header(\"2nd JSON file: credentials.json\")\r\n st.write(my_dict)\r\nexcept FileNotFoundError:\r\n st.warning('credentials.json NOT THERE')\r\n\r\nst.checkbox(\"checkboxTest\")\r\nst.stop()\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"CharlyWargnier/StreamlitGSCConnectorTests","sub_path":"GSCConnectMasterV2.py","file_name":"GSCConnectMasterV2.py","file_ext":"py","file_size_in_byte":3964,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74584396304","text":"from __future__ import absolute_import\n\nimport unittest\n\nfrom . import parse_version\nfrom digits import test_utils\n\n\ntest_utils.skipIfNotFramework('none')\n\n\nclass TestParseVersion():\n\n def test_equality(self):\n for v1, v2 in [\n ('11', '11'),\n ('11', 11),\n ('11', ('11',)),\n ('11', (11,)),\n ('11', '11.0'),\n ('11', '11.0.0'),\n ]:\n yield self.check_equal, v1, v2\n\n def check_equal(self, v1, v2):\n assert parse_version(v1) == parse_version(v2)\n\n def test_lt(self):\n # Each list should be in strictly increasing order\n example_lists = []\n\n # Some DIGITS versions\n example_lists.append(\n 'v1.0 v1.0.1 v1.0.2 v1.0.3 v1.1.0-rc1 v1.1.0-rc2 v1.1.0 v1.1.1 '\n 'v1.1.2 v1.1.3 v2.0.0-rc v2.0.0-rc2 v2.0.0-rc3 v2.0.0-preview '\n 'v2.0.0 v2.1.0 v2.2.0 v2.2.1'.split()\n )\n # Some NVcaffe versions\n example_lists.append('v0.13.0 v0.13.1 v0.13.2 v0.14.0-alpha '\n 'v0.14.0-beta v0.14.0-rc.1 v0.14.0-rc.2'.split())\n # Semver.org examples\n example_lists.append(\n '1.0.0-alpha 1.0.0-alpha.1 1.0.0-alpha.beta 1.0.0-beta '\n '1.0.0-beta.2 1.0.0-beta.11 1.0.0-rc.1 1.0.0'.split()\n )\n # PEP 440 examples\n example_lists.append('0.1 0.2 0.3 1.0 1.1'.split())\n example_lists.append('1.1.0 1.1.1 1.1.2 1.2.0'.split())\n example_lists.append('0.9 1.0a1 1.0a2 1.0b1 1.0rc1 1.0 1.1a1'.split())\n example_lists.append('0.9 1.0.dev1 1.0.dev2 1.0.dev3 1.0.dev4 1.0c1 1.0c2 1.0 1.0.post1 1.1.dev1'.split())\n example_lists.append('2012.1 2012.2 2012.3 2012.15 2013.1 2013.2'.split())\n\n for l in example_lists:\n for v1, v2 in zip(l[:-1], l[1:]):\n yield self.check_lt, v1, v2\n\n def check_lt(self, v1, v2):\n bad = (\n # pkg_resources handles this one differently\n '1.0.0-alpha.beta',\n # poor decision\n 'v2.0.0-preview')\n if v1 in bad or v2 in bad:\n raise unittest.case.SkipTest\n assert parse_version(v1) < parse_version(v2)\n","repo_name":"NVIDIA/DIGITS","sub_path":"digits/utils/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":2216,"program_lang":"python","lang":"en","doc_type":"code","stars":4106,"dataset":"github-code","pt":"48"} +{"seq_id":"21481203373","text":"# O(n) time, although it looks like O(n^2), the while loop only\n# runs for n iterations throughout the entire program, so\n# runtime is O(n+n) is still O(n)\n# O(n) space since we use the set for look-up table\nclass Solution:\n def longestConsecutive(self, nums: List[int]) -> int:\n if len(nums) == 0: return 0\n seen = set(nums)\n length = 1\n for num in seen:\n if num - 1 in seen:\n continue\n else:\n curr = num + 1\n curr_length = 1\n while curr in seen:\n curr_length += 1\n curr += 1\n length = max(curr_length, length)\n return length","repo_name":"Donny-Guo/Leetcode","sub_path":"128_Longest_Consecutive_Sequence/LongestConsecutiveSequence.py","file_name":"LongestConsecutiveSequence.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40243622506","text":"import numpy\nimport torch\n\nimport gym_MagicMan.envs.utils.MagicManDeck as deck\nfrom gym_MagicMan.envs.utils.MagicManPlayer import AdversaryPlayer\nfrom torch.distributions import Uniform, Categorical\n\n\nclass NaiveAdversary(AdversaryPlayer):\n \"\"\"\n My Name used to be Jules. :)\n \"\"\"\n \n \"\"\"\n player.round_obs = {_:\n {\n \"norm_bids\" : torch.zeros(self.n_players),\n \"all_bid_completion\" : torch.zeros(self.n_players),\n \"player_idx\" : torch.zeros(self.n_players),\n \"player_self_bid_completion\" : torch.zeros(1),\n \"n_cards\" : torch.zeros(self.max_rounds),\n \"played_cards\" : torch.zeros((self.n_players,60)),\n \"legal_cards_tensor\" : torch.zeros(60),\n \"current_suit\" : torch.zeros(6),\n } \n for _ in range(self.current_round)}\n \"\"\"\n\n def __init__(self):\n super().__init__()\n\n self.name = \"NaiveAdversary\"+str(self.random_id)\n \n self.mgm_factor = 1\n self.tmp_n_factor = .3\n self.tmp_val_factor = .07\n self.clr_n_factor = -.8\n self.clr_val_factor = .1\n self.foo_factor = -1\n \n \n \n \n def bid (self,obs):\n #bid as an integer and then divide by current round\n \n magic_man_bid = self.mgm_factor * sum(obs[\"legal_cards_tensor\"][-4:])\n tmp_cards = obs[\"legal_cards_tensor\"][::4][1:-1]\n trump_bid = self.tmp_n_factor * sum(tmp_cards) + self.tmp_val_factor * sum([tmp_card*(_+1) for _,tmp_card in enumerate(tmp_cards)])\n \n clr_bid_dict = {\"yellow_bid\":0,\"blue_bid\":0,\"green_bid\":0}\n for clr_idx,clr_name in enumerate(clr_bid_dict.keys()):\n clr_cards = obs[\"legal_cards_tensor\"][clr_idx+1:][::4][1:-1]\n clr_bid_dict[clr_name] = self.clr_n_factor * sum(clr_cards) + self.clr_val_factor * sum([clr_card*(_+1) for _,clr_card in enumerate(clr_cards)])\n \n fool_bid = self.foo_factor * sum(obs[\"legal_cards_tensor\"][:4])\n \n bid = magic_man_bid + trump_bid + sum(clr_bid_dict.values())\n \n \n return (bid / 4).item() \n\n \n def play (self,obs,action_mask):\n \n for round_obs in obs.values():\n if round_obs[\"round_active_flag\"]:\n obs = round_obs #very simple agent doesnt look into the past\n \n if obs[\"player_self_bid_completion\"]<0:\n self.mode=\"GET_SUITS\"\n elif obs[\"player_self_bid_completion\"]>=0:\n self.mode=\"STOP_SUITS\"\n else:\n raise UserWarning (f\"Adversary bid completion is faulty {obs['player_self_bid_completion']}\")\n \n \n played_cards_obj = [deck.deck[torch.argmax(turn_played_cards).item()] for turn_played_cards in obs[\"played_cards\"] if sum(turn_played_cards)>0]\n current_suit_idx = deck.legal(played_cards_obj,self.cards_obj)\n \n deck.turn_value(played_cards_obj,current_suit_idx)\n deck.hand_turn_value(torch.argmax(obs[\"player_idx\"]),self.cards_obj,current_suit_idx)\n \n \n \n cards_value_dict = {card:card.turn_value for card in self.cards_obj if card.legal}\n \n max_val_played=0\n if played_cards_obj:\n max_val_played = max([card.turn_value for card in played_cards_obj])\n \n can_take_suit = max([card.turn_value for card in self.cards_obj]) > max_val_played\n \n \n \n if self.mode == \"GET_SUITS\":\n if can_take_suit:\n maxval_card = max(cards_value_dict, key=cards_value_dict.get)\n return deck.deck.index(maxval_card)\n else:\n minval_card = min(cards_value_dict, key=cards_value_dict.get)\n return deck.deck.index(minval_card)\n \n elif self.mode == \"STOP_SUITS\":\n if max_val_played>0:\n win_cards = [key for key,val in cards_value_dict.items() if val>max_val_played]\n if len(win_cards)= 0 and j >= 0:\n s = ctoi[num1[i]] + ctoi[num2[j]] + c\n c = 0\n if s >= 10:\n c = 1\n s = s % 10\n rlt += itoc[s]\n i -= 1\n j -= 1\n while i >= 0:\n s = ctoi[num1[i]]+ c\n c = 0\n if s >= 10:\n c = 1\n s = s % 10\n rlt += itoc[s]\n i -= 1\n while j >= 0:\n s = ctoi[num2[j]] + c\n c = 0\n if s >= 10:\n c = 1\n s = s % 10\n rlt += itoc[s]\n j -= 1\n \n if c == 1:\n rlt += '1'\n return rlt[::-1]","repo_name":"GondorFu/Lintcode","sub_path":"665.Big_Integer_Addition/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"31592907909","text":"## The dependencies needed are : python3, numpy, matplotlib\n## To run the code type following command in terminal : python3 180123057_MOHAMMAD_HUMAM_KHAN_q2.py\n\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport random\nimport math\n\n\n#Function to generate sequence of numbers according to given formula\ndef Generator(theta,cum_freq,intervals,rounds,plot_name):\n\tx_values = []\n\tfor i in range (rounds):\n\t\tu = random.uniform(0,1)\n\t\txi = -1*theta*math.log(1-u)\n\t\tx_values.append(xi)\n\t\tu = 0.00\n\t\t#Calculating Cummulative Frequencies\n\t\tfor i in range(100):\n\t\t\tif (xi <= u):\n\t\t\t\tcum_freq[i] = cum_freq[i] + 1\n\t\t\tu = round(u + 0.05, 2)\t\t\n\n\t#Calculating mean and variance\t\t\n\tmean = round(np.mean(x_values), 5)\n\tvariance = round(np.var(x_values), 5)\t\n\n\t#Plotting the graphs\n\tplt.figure(figsize=(20,12))\n\tplt.title(\"Frequency Distribution Function of generated numbers \\n Sample Mean = %s ---- Actual Mean = 0.5 \\n Sample Variance = %s ---- Actual Variance = 0.25 \\n Number of Rounds in Simulation = %s\" % (mean, variance,rounds), fontsize=20)\n\tplt.xlabel(\"Range of Intervals of xi\", fontsize=20)\n\tplt.ylabel(\"Cummulative Frequencies of xi in given range\", fontsize=20)\n\tplt.plot(intervals, cum_freq, color='b')\n\tplt.savefig(plot_name)\n\tplt.clf()\t\n\t\n\t\n\n\n\n#Function to plot Actual CDF \ndef Actual_CDF(rounds, i):\n\tx = np.linspace(0, 5, rounds)\n\ty = -x/theta\n\ty = np.exp(y)\n\ty = 1-y\n\tplt.figure(figsize=(20,12))\n\tplt.title(\"Actual CDF of F(x) \\n Number of rounds in Simulation = %s\" % rounds, fontsize=20)\n\tplt.xlabel(\"x-values\", fontsize=20)\n\tplt.ylabel(\"F(x)-values\", fontsize=20)\n\tplt.scatter(x,y)\n\tplt.savefig(\"180123057_q2_Actual_CDF_%s\" % i)\n\tplt.clf()\n\n\n\n\n# Intervals contain 100 intervals of size 0.05 each\n# storing mid-point of the interval\n\nintervals = []\nfreq = [0]*100\nval = 0.00\nfor i in range(100):\n\tintervals.append(val)\n\tval += 0.05\n\ntheta = 0.5\n\nGenerator(theta,freq,intervals,1000,\"180123057_q2_Plot_1\")\nActual_CDF(1000, 1)\n\nGenerator(theta,freq,intervals,10000,\"180123057_q2_Plot_2\")\nActual_CDF(10000, 2)\n\nGenerator(theta,freq,intervals,100000,\"180123057_q2_Plot_3\")\nActual_CDF(100000, 3)\n\n\n","repo_name":"humamkhan2k/MA-323-Monte-Carlo-Simulation","sub_path":"LAB 2/q2/180123057_MOHAMMAD_HUMAM_KHAN_q2.py","file_name":"180123057_MOHAMMAD_HUMAM_KHAN_q2.py","file_ext":"py","file_size_in_byte":2127,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"30869596581","text":"class Human:\r\n\r\n def __init__(self, n , g, o):\r\n self.name = n\r\n self.gender = g\r\n self.occupation = o\r\n\r\n def kind(self):\r\n if self.gender == \"Female\":\r\n print(self.name, \"is a female\")\r\n elif self.gender == \"Male\":\r\n print(self.name, \"Is a Male\")\r\n\r\n def do_work(self):\r\n if self.occupation == \"Tennis Player\":\r\n print(self.name, \"Plays tennis\")\r\n elif self.occupation == \"actor\":\r\n print(self.name, \"Shoots film\")\r\n\r\n def speaks(self):\r\n print(self.name, \"Says how are you and is asking if you are enjoying your holliday\")\r\n\r\n def fight(self):\r\n print(self.name, \"Likes to fight for human rights\")\r\n\r\n\r\n\r\n \r\n\r\ntom = Human('Tom', \"Male\", \"actor\")\r\njane = Human('Jane', \"Female\", \"Tennis Player\")\r\n\r\ntom.kind()\r\ntom.do_work()\r\ntom.speaks()\r\nprint('\\n =====')\r\njane.kind()\r\njane.do_work()\r\njane.speaks()\r\njane.fight()\r\n","repo_name":"Ugocode/Python_OOP","sub_path":"PythonClasses_OOP/Tutorial-Python-Classes.py","file_name":"Tutorial-Python-Classes.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"12506381523","text":"import requests\nfrom bs4 import BeautifulSoup\n \n\ndef get_api(url):\n try: \n reqs = requests.get(url)\n soup = BeautifulSoup(reqs.text, 'html.parser')\n for link in soup.find_all('a'):\n print(link.get('href'))\n except:\n return (\"error\")\n\n\n","repo_name":"yavuzakyuz/secord","sub_path":"getapis.py","file_name":"getapis.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1368261530","text":"#\n# @lc app=leetcode id=280 lang=python3\n#\n# [280] Wiggle Sort\n#\n\n# @lc code=start\nclass Solution:\n # Solution 1 : sort and swap -- O(nlog(n))\n def sol1(self, nums) :\n if len(nums) < 2 : return \n nums.sort()\n idx = 1\n while idx + 1 < len(nums):\n nums[idx], nums[idx + 1] = nums[idx + 1], nums[idx]\n idx += 2\n\n # Solution 2 : O(n)\n def sol2(self, nums) :\n if len(nums) < 2 : return\n for i in range(1, len(nums)) :\n if (i % 2 == 0 and nums[i] > nums[i - 1]) or (i % 2 == 1 and nums[i] < nums[i - 1]) :\n nums[i], nums[i - 1] = nums[i - 1], nums[i]\n\n def wiggleSort(self, nums: List[int]) -> None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n \"\"\"\n self.sol2(nums)\n \n \n\n# @lc code=end\n\n","repo_name":"quixoteji/Leetcode","sub_path":"solutions/280.wiggle-sort.py","file_name":"280.wiggle-sort.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"22935089117","text":"import logging\nimport re\nfrom datetime import datetime\n\nimport telegram\nfrom pytz import timezone\nfrom telegram.ext.dispatcher import run_async\n\nimport profdumbledorebot.supportmethods as support\nfrom profdumbledorebot.sql.admin import set_admin_settings, set_ladmin_settings\nfrom profdumbledorebot.sql.group import get_group, commit_group\nfrom profdumbledorebot.sql.news import is_news_subscribed, rm_news_subscription, set_news_subscription\nfrom profdumbledorebot.sql.settings import set_max_members, set_general_settings, set_join_settings, set_nanny_settings, \\\n set_welcome_cooldown\nfrom profdumbledorebot.sql.support import are_banned\nfrom profdumbledorebot.sql.usergroup import remove_warn\nfrom profdumbledorebot.sql.user import is_staff\nfrom profdumbledorebot.sql.welcome import set_welc_preference, set_custom_welcome, set_welcome_settings\n\n\n@run_async\ndef settings(bot, update, args=None):\n chat_id, chat_type, user_id, text, message, message_type = support.extract_update_info(update)\n support.delete_message(chat_id, message.message_id, bot)\n\n if (not support.is_admin(chat_id, user_id, bot) or are_banned(user_id, chat_id)) and is_staff(user_id) is False:\n return\n\n group = get_group(chat_id)\n if group is None:\n bot.sendMessage(\n chat_id=chat_id,\n text=\"❌ No puedo reconocer este grupo. Si estaba funcionando hasta ahora, pregunta en @profesordumbledoreayuda.\",\n parse_mode=telegram.ParseMode.MARKDOWN\n )\n return\n\n message = bot.sendMessage(chat_id=chat_id, text=\"Oído cocina!...\")\n support.update_settings_message(chat_id, bot, message.message_id, keyboard=\"main\")\n\n\n@run_async\ndef set_welcome(bot, update):\n chat_id, chat_type, user_id, text, message, message_type = support.extract_update_info(update)\n text, data_type, content, buttons = support.get_welcome_type(message)\n\n if (not support.is_admin(chat_id, user_id, bot) or are_banned(user_id, chat_id)) and is_staff(user_id) is False:\n return\n\n group = get_group(chat_id)\n if group is None:\n bot.sendMessage(\n chat_id=chat_id,\n text=\"❌ No puedo reconocer este grupo. Si estaba funcionando hasta ahora, pregunta en @profesordumbledoreayuda.\",\n parse_mode=telegram.ParseMode.MARKDOWN\n )\n return\n\n if data_type is None:\n set_welc_preference(chat_id, False)\n bot.sendMessage(chat_id=chat_id, text=\"👌 Mensaje de bienvenida desactivado correctamente\")\n return\n\n set_welc_preference(chat_id, True)\n set_custom_welcome(chat_id, content or text, data_type, buttons)\n bot.sendMessage(chat_id=chat_id, text=\"👌 Mensaje de bienvenida guardado correctamente\")\n\n\n@run_async\ndef set_zone(bot, update, args=None):\n chat_id, chat_type, user_id, text, message, message_type = support.extract_update_info(update)\n support.delete_message(chat_id, message.message_id, bot)\n\n if (not support.is_admin(chat_id, user_id, bot) or are_banned(user_id, chat_id)) and is_staff(user_id) is False:\n return\n\n group = get_group(chat_id)\n if group is None:\n bot.sendMessage(\n chat_id=chat_id,\n text=\"❌ No puedo reconocer este grupo. Si estaba funcionando hasta ahora, pregunta en @profesordumbledoreayuda.\",\n parse_mode=telegram.ParseMode.MARKDOWN\n )\n return\n\n if args is None or len(args) != 1 or len(args[0]) < 3 or len(args[0]) > 60:\n bot.sendMessage(\n chat_id=chat_id,\n text=(\"❌ Me siento un poco perdido ahora mismo. Debes pasarme un nombre de zona horaria en inglés, por ejemplo, `America/Montevideo` o `Europe/Madrid`.\"),\n parse_mode=telegram.ParseMode.MARKDOWN\n )\n return\n\n tz = support.get_unified_timezone(args[0])\n\n if len(tz) == 1:\n commit_group(chat_id, timezone=tz[0])\n bot.sendMessage(\n chat_id=chat_id,\n text=\"👌 Perfecto! Zona horaria cambiada de *{0}* a *{1}*.\".format(group.timezone, tz[0]),\n parse_mode=telegram.ParseMode.MARKDOWN\n )\n now = datetime.now(timezone(tz[0])).strftime(\"%H:%M\")\n bot.sendMessage(\n chat_id=chat_id,\n text=\"🕒 Por favor, comprueba que la hora sea correcta: {}\".format(now))\n\n elif len(tz) == 0:\n bot.sendMessage(\n chat_id=chat_id,\n text=\"❌ Uy, no he encontrado ninguna zona horaria con ese nombre\")\n\n else:\n bot.sendMessage(\n chat_id=chat_id,\n text=\"❌ Has sido demasiado genérico con el nombre de la zona horaria. Intenta concretar más.\")\n\n\n@run_async\ndef set_maxmembers(bot, update, args=None):\n chat_id, chat_type, user_id, text, message, message_type = support.extract_update_info(update)\n support.delete_message(chat_id, message.message_id, bot)\n\n if (not support.is_admin(chat_id, user_id, bot) or are_banned(user_id, chat_id)) and is_staff(user_id) is False:\n return\n\n group = get_group(chat_id)\n if group is None:\n bot.sendMessage(\n chat_id=chat_id,\n text=\"❌ No puedo reconocer este grupo. Si estaba funcionando hasta ahora, pregunta en @profesordumbledoreayuda.\",\n parse_mode=telegram.ParseMode.MARKDOWN\n )\n return\n\n if args is None or len(args) != 1 or not args[0].isdigit() or int(args[0])<0:\n bot.sendMessage(\n chat_id=chat_id,\n text=\"❌ No he reconocido el parámetro introducido. Por favor, revisa el comando e intenta de nuevo.\")\n return\n\n if int(args[0]) is 0:\n set_max_members(chat_id, None)\n output = \"👌 Número máximo de miembros en el grupo desactivado correctamente.\"\n else:\n set_max_members(chat_id, int(args[0]))\n output = \"👌 Número máximo de miembros en el grupo establecido a {}\".format(args[0])\n bot.sendMessage(\n chat_id=chat_id,\n text=output,\n parse_mode=telegram.ParseMode.MARKDOWN)\n return\n\n\n@run_async\ndef set_cooldown(bot, update, args=None):\n chat_id, chat_type, user_id, text, message, message_type = support.extract_update_info(update)\n support.delete_message(chat_id, message.message_id, bot)\n\n if (not support.is_admin(chat_id, user_id, bot) or are_banned(user_id, chat_id)) and is_staff(user_id) is False:\n return\n\n group = get_group(chat_id)\n if group is None:\n bot.sendMessage(\n chat_id=chat_id,\n text=\"❌ No puedo reconocer este grupo. Si estaba funcionando hasta ahora, pregunta en @profesordumbledoreayuda.\",\n parse_mode=telegram.ParseMode.MARKDOWN\n )\n return\n\n if args is None or len(args) != 1 or not args[0].isdigit() or int(args[0])<0:\n bot.sendMessage(\n chat_id=chat_id,\n text=\"❌ No he reconocido el parámetro introducido. Por favor, revisa el comando e intenta de nuevo.\")\n return\n\n if int(args[0]) is 0:\n set_welcome_cooldown(chat_id, None)\n output = \"👌 El mensaje de bienvenida no se eliminará automáticamente.\"\n else:\n set_welcome_cooldown(chat_id, int(args[0]))\n output = \"👌 El mensaje de bienvenida se eliminará automáticamente en {} segundos\".format(args[0])\n bot.sendMessage(\n chat_id=chat_id,\n text=output,\n parse_mode=telegram.ParseMode.MARKDOWN)\n return\n\n\n@run_async\ndef settingsbutton(bot, update):\n logging.debug(\"%s %s\", bot, update)\n query = update.callback_query\n data = query.data\n user = update.effective_user\n user_id = query.from_user.id\n user_username = query.from_user.username\n chat_id = query.message.chat.id\n message_id = query.message.message_id\n\n are_banned(user_id, chat_id)\n\n settings_goto = {\n \"settings_goto_general\": \"general\",\n \"settings_goto_join\": \"join\",\n \"settings_goto_news\": \"news\",\n \"settings_goto_welcome\": \"welcome\",\n \"settings_goto_nanny\": \"nanny\",\n \"settings_goto_ladmin\": \"ladmin\",\n \"settings_goto_main\": \"main\"\n }\n settings_general = {\n \"settings_general_games\": \"games\",\n \"settings_general_hard\": \"hard\",\n \"settings_general_reply\": \"reply\",\n \"settings_general_warn\": \"warn\"\n }\n settings_join = {\n \"settings_join_mute\": \"silence\",\n \"settings_join_silence\": \"mute\",\n \"settings_join_val\": \"val\"\n }\n settings_welcome = {\n \"settings_welcome_welcome\": \"should_welcome\"\n }\n settings_nanny = {\n \"settings_nanny_command\": \"cmd\",\n \"settings_nanny_animation\": \"animation\",\n \"settings_nanny_contact\": \"contact\",\n \"settings_nanny_photo\": \"photo\",\n \"settings_nanny_games\": \"games\",\n \"settings_nanny_text\": \"text\",\n \"settings_nanny_sticker\": \"sticker\",\n \"settings_nanny_location\": \"location\",\n \"settings_nanny_url\": \"url\",\n \"settings_nanny_video\": \"video\",\n \"settings_nanny_warn\": \"warn\",\n \"settings_nanny_admin_too\": \"admin_too\",\n \"settings_nanny_voice\":\"voice\"\n }\n settings_ladmin = {\n \"settings_ladmin_welcome\": \"welcome\",\n \"settings_ladmin_admin\": \"admin\",\n \"settings_ladmin_ejections\": \"ejections\"\n }\n settings_admin = {\n \"settings_admin_welcome\": \"welcome\",\n \"settings_admin_goodbye\": \"goodbye\",\n \"settings_admin_admin\": \"admin\",\n \"settings_admin_ejections\": \"ejections\"\n }\n\n if re.match(\"^settings_.+$\", data) is not None:\n match = re.match(r\"settings_news_([-0-9]*)\", query.data)\n if not support.is_admin(chat_id, user_id, bot) and is_staff(user_id) is False:\n bot.answerCallbackQuery(\n text=\"Solo los administradores del grupo pueden configurar el bot.\",\n callback_query_id=update.callback_query.id,\n show_alert=\"true\"\n )\n return\n\n if data in settings_goto:\n support.update_settings_message(chat_id, bot, message_id, keyboard=settings_goto[data])\n elif data == \"settings_done\":\n support.delete_message(chat_id, message_id, bot)\n elif data in settings_general:\n set_general_settings(chat_id, settings_general[data])\n support.update_settings_message(chat_id, bot, message_id, keyboard=\"general\") \n elif data in settings_join:\n set_join_settings(chat_id, settings_join[data])\n support.update_settings_message(chat_id, bot, message_id, keyboard=\"join\")\n elif data in settings_welcome:\n set_welcome_settings(chat_id, settings_welcome[data])\n support.update_settings_message(chat_id, bot, message_id, keyboard=\"welcome\")\n elif data in settings_nanny:\n set_nanny_settings(chat_id, settings_nanny[data])\n support.update_settings_message(chat_id, bot, message_id, keyboard=\"nanny\")\n elif data in settings_admin:\n set_admin_settings(chat_id, settings_admin[data])\n support.update_settings_message(chat_id, bot, message_id, keyboard=\"admin\")\n elif data in settings_ladmin:\n set_ladmin_settings(chat_id, settings_ladmin[data])\n support.update_settings_message(chat_id, bot, message_id, keyboard=\"ladmin\")\n elif data == \"settings_admin_spy\":\n set_ladmin_settings(chat_id, \"admin_bot\")\n support.delete_message(chat_id, message_id, bot)\n output = \"Antes de nada administradores quiero daros las gracias. Debeis haber demostrado verdadera lealtad hacia mi en el grupo, y solo eso ha podido lograr que acuda Fawkes a vuestro grupo.\\nÉl no puede leer nada de lo que suceda en el grupo, simplemente enviará las alertas que hayais configurado. Si necesitais configurar de nuevo las alertas o quereis usar los comandos, invitadme de nuevo al grupo y cuando acabeis volved a activar a Fawkes.\"\n bot.sendMessage(chat_id=chat_id, text=output, parse_mode=telegram.ParseMode.MARKDOWN)\n bot.leaveChat(chat_id=chat_id)\n\n elif match:\n news_id = match.group(1)\n if is_news_subscribed(chat_id, news_id):\n rm_news_subscription(chat_id, news_id)\n else:\n set_news_subscription(chat_id, news_id)\n support.update_settings_message(chat_id, bot, message_id, keyboard=\"news\")\n\n return\n\n match = re.match(r\"rm_warn\\((.+?)\\)\", query.data)\n if match:\n if not support.is_admin(chat_id, user_id, bot) and is_staff(user_id) is False:\n bot.answerCallbackQuery(\n text=\"Solo los administradores del grupo pueden retirar warns.\",\n callback_query_id=update.callback_query.id,\n show_alert=\"true\"\n )\n return\n\n user_id = match.group(1)\n res = remove_warn(user_id, chat_id)\n if res:\n text = \"Aviso eliminado por @{}.\".format(user_username)\n bot.answerCallbackQuery(\n text=\"Has eliminado un warn.\", callback_query_id=update.callback_query.id, show_alert=\"true\")\n\n else:\n bot.answerCallbackQuery(\n text=\"En estos momentos no puedo eliminar el warn, prueba mas tarde.\",\n callback_query_id=update.callback_query.id,\n show_alert=\"true\"\n )\n return\n bot.edit_message_text(\n text=text,\n chat_id=chat_id,\n message_id=message_id,\n parse_mode=telegram.ParseMode.HTML,\n disable_web_page_preview=True\n )\n return\n\n match = re.match(r\"rm_ban\\((.+?)\\)\", query.data)\n if match:\n if not support.is_admin(chat_id, user_id, bot) and is_staff(user_id) is False:\n bot.answerCallbackQuery(\n text=\"Solo los administradores del grupo pueden retirar bans.\",\n callback_query_id=update.callback_query.id,\n show_alert=\"true\"\n )\n return\n us_id = match.group(1)\n bot.unbanChatMember(chat_id, us_id)\n bot.answerCallbackQuery(\n text=\"Has eliminado un ban.\", callback_query_id=update.callback_query.id, show_alert=\"true\")\n text=\"Ban retirado por @{}.\".format(user_username)\n bot.edit_message_text(\n text=text,\n chat_id=chat_id,\n message_id=message_id,\n parse_mode=telegram.ParseMode.HTML,\n disable_web_page_preview=True\n )\n return\n\n match = re.match(r\"rm_mute\\((.+?)\\)\", query.data)\n if match:\n if not support.is_admin(chat_id, user_id, bot) and is_staff(user_id) is False:\n bot.answerCallbackQuery(\n text=\"Solo los administradores del grupo pueden desmutear usuarios.\",\n callback_query_id=update.callback_query.id,\n show_alert=\"true\"\n )\n return\n us_id = match.group(1)\n bot.restrict_chat_member(chat_id, us_id, can_send_messages=True, can_send_media_messages=True, can_send_other_messages=True, can_add_web_page_previews=True)\n bot.answerCallbackQuery(\n text=\"El usuario ha sido desmuteado.\", callback_query_id=update.callback_query.id, show_alert=\"true\")\n text=\"Usuario desmuteado por @{}.\".format(user_username)\n bot.edit_message_text(\n text=text,\n chat_id=chat_id,\n message_id=message_id,\n parse_mode=telegram.ParseMode.HTML,\n disable_web_page_preview=True\n )\n return\n\n else:\n logging.error('settingsbutton:%s is not a expected settings command', data)\n\n","repo_name":"pikaping/ProfesorDumbledoreBot","sub_path":"profdumbledorebot/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":15641,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"73533329106","text":"#!/usr/bin/env python2\n\"\"\"\nThis script samples synthetic images according to various criteria from an OMERO\nserver running the syntheticsampler webapp.\n\"\"\"\n\n\nfrom __future__ import print_function\n\nimport argparse\nimport json\nimport os\nimport random\nimport sys\nimport urllib\nimport urllib2\n\n\nOMERO_ROOT = \"http://omero.compbio.cs.cmu.edu:8080/\"\nIDS_ENDPOINT = OMERO_ROOT + \"syntheticsampler/image_ids/\"\nIMAGES_ENDPOINT = OMERO_ROOT + \"syntheticsampler/images/\"\n\n\ndef get_args():\n \"\"\"\n Make an argparser and get the arguments from the command line. Exits on bad\n CLI args.\n \"\"\"\n parser = argparse.ArgumentParser(\n description=\"Download synthetic images from an OMERO server\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter\n )\n parser.add_argument(\"--dimensionality\", default=\"2D\", help=\"2D or 3D\")\n parser.add_argument(\"--cell-line\", default=\"HeLa\", help=\"type of cell line\")\n parser.add_argument(\"--downsampling-factor\",\n help=\"amount to downsample the images by using bicubic interpolation\")\n parser.add_argument(\"--number-of-images\", type=int, default=1,\n help=\"number of images to download\")\n parser.add_argument(\"--channel0-model-class\",\n help=\"model class for channel 0 (e.g. framework)\")\n parser.add_argument(\"--channel0-model-type\",\n help=\"model type for channel 0 (e.g. cylindrical, diffeomorphic)\")\n parser.add_argument(\"--channel1-model-class\",\n help=\"model class for channel 1 (e.g. framework)\")\n parser.add_argument(\"--channel1-model-type\",\n help=\"model type for channel 1 (e.g. ratio, diffeomorphic)\")\n parser.add_argument(\"--channel2-model-class\",\n help=\"model class for channel 2 (e.g. vesicles, microtubule)\")\n parser.add_argument(\"--channel2-model-type\",\n help=\"model type for channel 2 (e.g. gmm, network)\")\n parser.add_argument(\"--output-dir\", default=\".\",\n help=\"directory to save the images in\")\n return parser.parse_args()\n\ndef check_downsampling_factor(downsampling_factor_arg):\n \"\"\"\n Check that the provided downsampling factor is either None or a number greater\n than 1.\n \"\"\"\n if (downsampling_factor_arg is not None):\n try:\n downsampling_factor = float(downsampling_factor_arg)\n except:\n msg = \"Downsampling factor must be a floating point number (got {}).\"\n error_exit(msg.format(str(downsampling_factor_arg)))\n if downsampling_factor <= 1:\n msg = \"Downsampling factor must be greater than 1 (got {:f}).\"\n error_exit(msg.format(downsampling_factor))\n\ndef print_inline(s):\n \"\"\"\n Return the cursor to the beginning of the line after printing.\n \"\"\"\n print(s, end='\\r')\n sys.stdout.flush()\n\ndef get_matching_image_ids(\n dimensionality=None,\n cell_line=None,\n channel0_model_class=None,\n channel0_model_type=None,\n channel1_model_class=None,\n channel1_model_type=None,\n channel2_model_class=None,\n channel2_model_type=None\n ):\n \"\"\"\n Ask the OMERO server for all ids of images that match the given criteria\n (passed as query parameters).\n \"\"\"\n query_options = {\n 'dimensionality': dimensionality,\n 'cell_line': cell_line,\n 'channel0_model_class': channel0_model_class,\n 'channel0_model_type': channel0_model_type,\n 'channel1_model_class': channel1_model_class,\n 'channel1_model_type': channel1_model_type,\n 'channel2_model_class': channel2_model_class,\n 'channel2_model_type': channel2_model_type\n }\n none_keys = set()\n for key in query_options:\n if query_options[key] is None:\n none_keys.add(key)\n for none_key in none_keys:\n del query_options[none_key]\n query_string = urllib.urlencode(query_options)\n try:\n response = json.load(urllib2.urlopen(IDS_ENDPOINT + \"?\" + query_string))\n return response['data']\n except Exception as e:\n err_msg = \"Failed to retrieve the ids: {}\"\n error_exit(err_msg.format(e))\n\ndef error_exit(s):\n \"\"\"\n Print the message and exit with non-zero status.\n \"\"\"\n print(s)\n sys.exit(1)\n\ndef download_image(image_id, downsampling_factor, output_path,\n percentage_template):\n \"\"\"\n Download the image with the given id from the OMERO server, requesting that it\n be downsampled by the given amount (if any), and save to the provided output\n path.\n \"\"\"\n image_url = IMAGES_ENDPOINT + str(image_id)\n if downsampling_factor:\n image_url += \"?downsampling_factor=\" + downsampling_factor\n response = urllib2.urlopen(image_url)\n total_size = int(response.info().getheader('Content-Length').strip())\n so_far = 0\n chunk_read_size = 16 * 1024\n chunk = response.read(chunk_read_size)\n with open(output_path, 'wb') as f:\n while chunk:\n f.write(chunk)\n so_far += len(chunk)\n percentage = round((float(so_far) / total_size) * 100, 2)\n print_inline(percentage_template.format(percentage))\n chunk = response.read(chunk_read_size)\n\ndef get_synthetic_images(\n dimensionality='2D',\n cell_line='HeLa',\n downsampling_factor=None,\n number_of_images=1,\n channel0_model_class=None,\n channel0_model_type=None,\n channel1_model_class=None,\n channel1_model_type=None,\n channel2_model_class=None,\n channel2_model_type=None,\n output_dir='out'\n ):\n \"\"\"\n Sample from an image collection in omero.compbio.cs.cmu.edu and saves the\n image(s) to disk.\n\n For a full list of model classess and types visit www.cellorganizer.org\n\n :param dimensionality: image dimensionality\n :type dimensionality: string\n :param cell_line: image cell lines. Default is HeLa.\n :type cell_line: string\n :param downsampling_factor: amount to downsample the images (bicubic\n interpolation)\n :type downsampling_factor: float|None\n :param number_of_images: number of synthesized images\n :type number_of_images: int\n :param channel0_model_class: model class\n :type channel0_model_class: string\n :param channel0_model_type: model type\n :type channel0_model_type: string\n :param channel1_model_class: model class\n :type channel1_model_class: string\n :param channel1_model_type: model type\n :type channel1_model_type: string\n :param channel2_model_class: model class\n :type channel2_model_class: string\n :param channel2_model_type: model type\n :type channel2_model_type: string\n :param output_dir: directory for saving the images\n :type output_dir: string\n \"\"\"\n print_inline(\"Getting matching ids...\")\n all_matching_image_ids = get_matching_image_ids(\n dimensionality=dimensionality,\n cell_line=cell_line,\n channel0_model_class=channel0_model_class,\n channel0_model_type=channel0_model_type,\n channel1_model_class=channel1_model_class,\n channel1_model_type=channel1_model_type,\n channel2_model_class=channel2_model_class,\n channel2_model_type=channel2_model_type\n )\n if len(all_matching_image_ids) < number_of_images:\n err = \"{} ids requested; only {} ids matching the criteria were found.\"\n error_exit(err.format(number_of_images, len(all_matching_image_ids)))\n image_ids = random.sample(all_matching_image_ids, number_of_images)\n s = \"Downloading {{}}... {{{{:3.2f}}}}% [{{:{}}}/{}] \"\n status_template = s.format(len(str(number_of_images)), number_of_images)\n for (i, image_id) in enumerate(image_ids):\n output_path = os.path.join(output_dir, \"{}.tif\".format(i + 1))\n percentage_template = status_template.format(output_path, i + 1)\n download_image(\n image_id, downsampling_factor, output_path, percentage_template\n )\n pad = \" \" * len(status_template)\n print(\"Downloaded {} images.{}\".format(number_of_images, pad))\n\ndef main():\n \"\"\"\n Parse the command line options and call get_synthetic_images with the passed\n options.\n \"\"\"\n args = get_args()\n check_downsampling_factor(args.downsampling_factor)\n get_synthetic_images(\n dimensionality=args.dimensionality,\n cell_line=args.cell_line,\n downsampling_factor=args.downsampling_factor,\n number_of_images=args.number_of_images,\n channel0_model_class=args.channel0_model_class,\n channel0_model_type=args.channel0_model_type,\n channel1_model_class=args.channel1_model_class,\n channel1_model_type=args.channel1_model_type,\n channel2_model_class=args.channel2_model_class,\n channel2_model_type=args.channel2_model_type,\n output_dir=args.output_dir\n )\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"icaoberg/omepslid","sub_path":"sample_synthetic_images.py","file_name":"sample_synthetic_images.py","file_ext":"py","file_size_in_byte":8240,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"43900553683","text":"import os\n\nimport torch\n\nfrom models.base import BaseModel\nfrom models.conv_net.conv_net_model import ConvNetClassifier\n\n_PROJECT_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n_DEVICE = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n_CONV_MODEL_PATH = os.path.join(\n _PROJECT_PATH, 'models', 'conv_net', 'saved_models',\n 'ConvNet_embed_200_filters_num_256_kern_[5, 10, 15]_drop_0.4_lr_0.0002_wd_0.0003_max_words_256_rem_sw_True'\n '_lemm_False_smote_False_v2.pt'\n)\n\n\ndef get_model() -> BaseModel:\n cnn_model = _get_cnn_model()\n return cnn_model\n\n\ndef _get_cnn_model() -> ConvNetClassifier:\n conv_model = ConvNetClassifier(\n embedding_dim=200,\n output_dim=4,\n dropout=0.5,\n batch_size=128,\n learning_rate=1e-4,\n weight_decay=65e-4,\n filters_number=256,\n kernels_sizes=[5, 10, 15],\n max_num_words=256,\n removing_stop_words=True,\n lemmatization=False\n )\n conv_model.load_state_dict(torch.load(_CONV_MODEL_PATH, map_location=_DEVICE))\n conv_model.eval()\n return conv_model\n","repo_name":"wojtek11530/song_lyric_classification","sub_path":"backend_app/used_model.py","file_name":"used_model.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"} +{"seq_id":"18091375661","text":"import argparse\nimport json\nfrom pathlib import Path\nfrom types import SimpleNamespace\nimport torch\n\n\ndef ckpt_path(epoch=None):\n path = Path('checkpoint')\n path.mkdir(exist_ok=True)\n path = path / 'current.json'\n if epoch is None:\n if path.exists():\n with path.open() as fp:\n epoch = json.load(fp)['epoch']\n else:\n return\n else:\n with path.open('w') as fp:\n json.dump({'epoch': epoch}, fp)\n return path.parent / f'{epoch}.dat'\n\n\ndef save_ckpt(model, optimizer, epoch):\n def do_save(fp):\n torch.save({\n 'epoch': epoch,\n 'model': model,\n 'optimizer': optimizer.state_dict(),\n }, fp)\n # always save as single-GPU setting\n if torch.cuda.device_count() > 1:\n model = model.module\n do_save(ckpt_path(epoch))\n\n\ndef load_ckpt(filepath=None):\n \"\"\" Load checkpoint file\n\n Parameters:\n optimizer: load parameter into optimizer from checkpoint, if not null\n filepath: filepath of checkpoint(s), otherwise lookup checkpoint/current.json\n\n Returns:\n Raise error if specific checkpoint file not found\n Otherwise checkpoint as SimpleNamespace Object\n \"\"\"\n if filepath:\n filepath = Path(filepath)\n if not filepath.exists():\n print(\"Aborted: checkpoint not found!\", filepath)\n exit(-2)\n else:\n filepath = ckpt_path()\n if not filepath or not filepath.exists():\n return\n print(\"Loading checkpoint '{}'\".format(filepath))\n if torch.cuda.is_available():\n # Load all tensors onto previous state\n checkpoint = torch.load(filepath)\n else:\n # Load all tensors onto the CPU\n checkpoint = torch.load(filepath, map_location=lambda storage, loc: storage)\n return SimpleNamespace(**checkpoint)","repo_name":"winston-li/pytorch_playground","sub_path":"AttentionDeepMIL/ckpt.py","file_name":"ckpt.py","file_ext":"py","file_size_in_byte":1871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28158966973","text":"import cv2\nimport joblib\nimport torch\nimport torchvision.models as models\nimport torch.nn as nn\nfrom tqdm import tqdm\n\nimport netvlad\nimport cv2 as cv\nimport numpy as np\n# import res2net\nimport torchvision.transforms as transforms\nimport os\nimport time\nimport random\n\n\nfrom sklearn.decomposition import KernelPCA\n\nimport gc\nfrom KPCA import tools\n\nimport cupy as cp\n\n# resnet_netvlad\nencoder_dim = 1024\nnumber_cluster = 64\n# 存放的路径\n# model_path = \"/home/zhehan-yang/Desktop/Resnet_SEblock_NetVLAD/checkpoint.pth.tar\"\n# model_path = \"/media/zhehan-yang/yzh3/resnet/pytorch-NetVlad-master/runs/Jan06_11-58-03_resnet_netvlad/checkpoints/checkpoint.pth.tar\"\n# model_path = \"/media/zhehan-yang/yzh3/global/pitt_r50l3_netvlad_partial.pth\"\n# model_path = \"/media/zhehan-yang/yzh3/global/t1_msls_r50l3_netvlad.pth\"\nmodel_path = \"/media/zhehan-yang/yzh3/global/msls_r101l3_netvlad_partial.pth\"\n# model_path = \"/media/zhehan-yang/yzh3/global/pitt_r101l3_netvlad_partial.pth\"\n# 存放大量图片的地点,用来训练\nphoto_set_path = \"/media/zhehan-yang/yzh3/ubuntu/datasheet/TUM\"\n# 做前向处理的路径\nphoto_path = \"/media/zhehan-yang/yzh3/ubuntu/datasheet/TUM/Handheld_SLAM/rgbd_dataset_freiburg2_desk/rgb\"\n# 输出路径,在前向过程中存放全局描述子\n# output_path = \"/home/zhehan-yang/Desktop/Resnet_SEblock_NetVLAD/output\"\noutput_path = \"/media/zhehan-yang/yzh3/ubuntu/datasheet/TUM/Handheld_SLAM/rgbd_dataset_freiburg2_desk/feature_hfnet/way4_on_different_arch/glb_resnet101_msls\"\n# train_output_path = \"/home/zhehan-yang/Desktop/Resnet_SEblock_NetVLAD/train_output\"\n\n# 存放kpca中间处理结果的路径\nnumpy_work_path = '/media/zhehan-yang/yzh3/global/store_kpca/kpca_resnet101vlad_msls.npy'\n# kpca_path = \"/media/zhehan-yang/yzh3/global/store_kpca/kpca_resnet50vlad_pitts.npy\"\n# kpca_path = \"/media/zhehan-yang/yzh3/global/store_kpca/kpca_resnet50vlad_msls.npy\"\n# kpca_path = \"/media/zhehan-yang/yzh3/global/store_kpca/kpca_resnet101vlad_pitts.npy\"\nkpca_path = \"/media/zhehan-yang/yzh3/global/store_kpca/kpca_resnet101vlad_msls.npy\"\n\n# 切分的份数和每一份的长度\n\nmode = \"train\"\nmode = \"test\"\n\n# 👇👇👇👇👇👇👇这部分做了图片路径读取的任务👇👇👇👇👇👇👇\nif mode == \"train\":\n list_photo = []\n for root, dirs, files in os.walk(photo_set_path):\n for dir in dirs:\n if dir == \"rgb\":\n list_photo.extend([\"/\".join([root, \"rgb\", k]) for k in os.listdir(\"/\".join([root, \"rgb\"]))])\n print(\"Load photo directory finish!\")\n numArray = set()\n while len(numArray) < 10000:\n numArray.add(random.randint(0, len(list_photo) - 1))\n list_photo = [list_photo[k] for k in numArray]\nelif mode == \"test\":\n list_photo = os.listdir(photo_path)\n\n# 👇👇👇👇👇👇👇这部分做了模型定义和导入的任务👇👇👇👇👇👇👇\nencoder = models.resnet101(pretrained=False)\nlayers = list(encoder.children())[:-3]\nencoder = nn.Sequential(*layers)\nmodel = nn.Module()\n# model.add_module('encoder', encoder)\nmodel.add_module('backbone', encoder)\n\nnet_vlad = netvlad.NetVLAD(num_clusters=number_cluster, dim=encoder_dim, vladv2=False)\n# model.add_module(\"pool\", net_vlad)\nmodel.add_module(\"aggregation\", net_vlad)\n\nprint(\"Loading files...\")\ncheckpoint = torch.load(model_path, map_location=lambda storage, loc: storage)\n# model.load_state_dict(checkpoint[\"state_dict\"]) # 代坤的用这个\nmodel.load_state_dict(checkpoint) # 其他用这个\nprint(\"Loading finished\")\n\nprint(\"Moving mode to cuda\")\nmodel = model.to(\"cuda\")\nprint(\"Moving finished\")\n\nif mode == \"test\":\n # kpca = np.load(\"/\".join([numpy_work_path, \"kpca\", \"kpca.npy\"]))\n # kpca = np.load(kpca_path)\n kpca = cp.load(kpca_path)\n\n# 👇👇👇👇👇👇👇这部分做了利用模型做前向的过程👇👇👇👇👇👇👇\nif mode == \"test\":\n\n from cupy.core.dlpack import fromDlpack\n from torch.utils.dlpack import to_dlpack\n with torch.no_grad():\n trans = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225]),\n ])\n for photo_name in tqdm(list_photo, desc=\"photo inference\"):\n # begintime = time.time() # 开始计时\n\n photo_input = cv.imread(\"/\".join([photo_path, photo_name]))\n photo_input = cv.resize(photo_input, dsize=(224, 224), interpolation=cv.INTER_LINEAR)\n photo_input = trans(photo_input)\n photo_input = photo_input.unsqueeze(0).to(\"cuda\")\n # image_encoding = model.encoder(photo_input)\n # output_numpy = model.pool(image_encoding).cpu().numpy()\n image_encoding = model.backbone(photo_input)\n # output_numpy = model.aggregation(image_encoding).cpu().numpy()\n\n\n # output_numpy = model.aggregation(image_encoding).cpu().numpy()\n output_numpy = fromDlpack(to_dlpack(model.aggregation(image_encoding)))\n\n # 👇👇👇👇👇👇👇这部分做KPCA👇👇👇👇👇👇👇\n\n # output_numpy_kpca = np.matmul(output_numpy, kpca)\n # output_numpy_kpca = (output_numpy_kpca - np.min(output_numpy_kpca)) \\\n # / \\\n # (np.max(output_numpy_kpca) - np.min(output_numpy_kpca))\n output_numpy_kpca = cp.matmul(output_numpy, kpca)\n output_numpy_kpca = (output_numpy_kpca - cp.min(output_numpy_kpca)) \\\n / \\\n (cp.max(output_numpy_kpca) - cp.min(output_numpy_kpca))\n\n # 👇👇👇👇👇👇👇这部分输出👇👇👇👇👇👇👇\n # np.save(\"/\".join([output_path, photo_name.replace(\"png\", \"npy\")]), output_numpy_kpca)\n cp.save(\"/\".join([output_path, photo_name.replace(\"png\", \"npy\")]), output_numpy_kpca)\nelif mode == \"train\":\n model.eval()\n with torch.no_grad():\n trans = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225]),\n ])\n first_in = True\n for photo_name in tqdm(list_photo, desc=\"Training Process:\"):\n try:\n photo_input = cv.imread(photo_name)\n photo_input = cv.resize(photo_input, dsize=(224, 224), interpolation=cv2.INTER_LINEAR)\n photo_input = trans(photo_input)\n photo_input = photo_input.unsqueeze(0).to(\"cuda\")\n # image_encoding = model.encoder(photo_input)\n image_encoding = model.backbone(photo_input)\n # output_numpy = model.pool(image_encoding).cpu().numpy()\n output_numpy = model.aggregation(image_encoding).cpu().numpy()\n if first_in:\n output_numpys = [output_numpy]\n first_in = False\n else:\n # output_numpys = numpy.concatenate((output_numpys, output_numpy), axis=0)\n output_numpys.append(output_numpy)\n except Exception as e:\n print(f\"Some error happened in photo path: {photo_name}\")\n print(f\"Error named: {e}\")\n # 👇👇👇👇👇👇👇这部分做KPCA👇👇👇👇👇👇👇\n try:\n print(\"Concatenating the numpy array.....\")\n output_numpys = np.concatenate(tuple(output_numpys), axis=0)\n\n np.save(\"output_numpy.npy\", output_numpys)\n except Exception as e:\n print(\"Error happen in numpy save,Error named: \")\n print(e)\n\n # data_list = []\n print(\"Start to train KPCA\")\n # if not os.path.exists(\"/\".join([numpy_work_path, \"kpca\"])):\n # os.makedir(\"/\".join([numpy_work_path,\"kpca\"])) os.mkdir(\"/\".join([numpy_work_path, \"kpca\"]))\n # print(\"Check kpca file package finish!\")\n # for i in tqdm(range(1, copies + 1), desc=\"Training layer1 numpy\"):\n # data = np.load(\"/\".join([numpy_work_path, \"numpy_split\", \"output_numpy\" + str(i) + \".npy\"]))\n # numArray = set()\n # while len(numArray) < 20000:\n # numArray.add(random.randint(0, data.shape[0] - 1))\n # data = data[list(numArray), :]\n # kpca = KernelPCA(n_components=portion / 8)\n # # data_list.append(kpca.fit(data))\n # kpca.fit(data)\n # joblib.dump(kpca, numpy_work_path + f\"/kpca/kpca{str(i)}.m\")\n\n u, lams, mu = tools.pca(output_numpys, num_pcs=4096, subtract_mean=True)\n u = u[:, :4096]\n lams = lams[:4096]\n print('===> Add PCA Whiten')\n u = np.matmul(u, np.diag(np.divide(1., np.sqrt(lams + 1e-9))))\n np.save(numpy_work_path, u)\n a = 1\n","repo_name":"zhehan-yang/graduation_project_TYUT","sub_path":"hf-net/pth_use_tools.py","file_name":"pth_use_tools.py","file_ext":"py","file_size_in_byte":9064,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"135434531","text":"#!/usr/bin/python3\n\"\"\"\nCreating a view for State objects that handles all\ndefault RESTFul API actions\n\"\"\"\n\n\nfrom api.v1.views import app_views\nfrom flask import jsonify, abort, make_response, request\nfrom models import storage\nfrom models.state import State\nimport json\n\n\n@app_views.route(\"/states\", strict_slashes=False)\ndef states():\n \"\"\"\n Retrieves the list of all State objects\n \"\"\"\n all_states = storage.all(State).values()\n state_list = []\n for states in all_states:\n state_list.append(states.to_dict())\n return jsonify(state_list)\n\n\n@app_views.route(\"/states/\", strict_slashes=False)\ndef states_by_id(state_id):\n \"\"\"\n Retrieves a State object\n \"\"\"\n state = storage.get(State, state_id)\n if state:\n return jsonify(state.to_dict())\n else:\n abort(404)\n\n\n@app_views.route(\n \"/states/\", methods=[\"DELETE\"], strict_slashes=False\n )\ndef delete_state(state_id):\n \"\"\"\n Deletes a State object\n \"\"\"\n state = storage.get(State, state_id)\n if state:\n empty_dict = {}\n storage.delete(state)\n storage.save()\n response = make_response(jsonify(empty_dict), 200)\n return response\n else:\n abort(404)\n\n\n@app_views.route(\"/states\", methods=[\"POST\"], strict_slashes=False)\ndef create_state():\n \"\"\"\n Creates a State\n \"\"\"\n data = request.get_json()\n if not data:\n return jsonify('Not a JSON'), 400\n if \"name\" in data:\n new_state = State(**data)\n storage.new(new_state)\n storage.save()\n dict_ = new_state.to_dict()\n return jsonify(dict_), 201\n else:\n return jsonify(\"Missing name\"), 400\n\n\n@app_views.route(\"/states/\", methods=[\"PUT\"], strict_slashes=False)\ndef update_state(state_id):\n \"\"\"\n Updates a State\n \"\"\"\n state = storage.get(State, state_id)\n if state:\n data = request.get_json()\n if not data:\n return jsonify(\"Not a JSON\"), 400\n for key, value in data.items():\n list_ = [\"id\", \"created_at\", \"updated_at\"]\n if key not in list_:\n setattr(state, key, value)\n storage.save()\n dict_ = state.to_dict()\n response = make_response(jsonify(dict_), 200)\n return response\n else:\n abort(404)\n","repo_name":"Mahlet2123/AirBnB_clone_v3","sub_path":"api/v1/views/states.py","file_name":"states.py","file_ext":"py","file_size_in_byte":2326,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26338646587","text":"\"\"\"\r\n mbed CMSIS-DAP debugger\r\n Copyright (c) 2006-2015 ARM Limited\r\n\"\"\"\r\nimport time\r\nimport logging\r\n\r\nfrom ..pyDAPAccess import DAPAccess\r\n\r\n# CPUID ARCHITECTURE values\r\nARMv6M = 0xC\r\nARMv7M = 0xF\r\n\r\n# CPUID PARTNO values\r\nARM_CortexM0 = 0xC20\r\nARM_CortexM1 = 0xC21\r\nARM_CortexM3 = 0xC23\r\nARM_CortexM4 = 0xC24\r\nARM_CortexM0p = 0xC60\r\n\r\n# User-friendly names for core types.\r\nCORE_TYPE_NAME = {\r\n ARM_CortexM0 : \"Cortex-M0\",\r\n ARM_CortexM1 : \"Cortex-M1\",\r\n ARM_CortexM3 : \"Cortex-M3\",\r\n ARM_CortexM4 : \"Cortex-M4\",\r\n ARM_CortexM0p : \"Cortex-M0+\"\r\n}\r\n\r\n# Map from register name to DCRSR register index.\r\n#\r\n# The CONTROL, FAULTMASK, BASEPRI, and PRIMASK registers are special in that they share the\r\n# same DCRSR register index and are returned as a single value. In this dict, these registers\r\n# have negative values to signal to the register read/write functions that special handling\r\n# is necessary. The values are the byte number containing the register value, plus 1 and then\r\n# negated. So -1 means a mask of 0xff, -2 is 0xff00, and so on. The actual DCRSR register index\r\n# for these combined registers has the key of 'cfbp'.\r\nCORE_REGISTER = {\r\n 'r0' : 0,\r\n 'r1' : 1,\r\n 'r2' : 2,\r\n 'r3' : 3,\r\n 'r4' : 4,\r\n 'r5' : 5,\r\n 'r6' : 6,\r\n 'r7' : 7,\r\n 'r8' : 8,\r\n 'r9' : 9,\r\n 'r10' : 10,\r\n 'r11' : 11,\r\n 'r12' : 12,\r\n 'sp' : 13,\r\n 'r13' : 13,\r\n 'lr' : 14,\r\n 'r14' : 14,\r\n 'pc' : 15,\r\n 'r15' : 15,\r\n 'xpsr': 16,\r\n 'msp' : 17,\r\n 'psp' : 18,\r\n 'cfbp': 20,\r\n 'control' :-4,\r\n 'faultmask':-3,\r\n 'basepri' :-2,\r\n 'primask' :-1,\r\n 'fpscr': 33,\r\n 's0' : 0x40,\r\n 's1' : 0x41,\r\n 's2' : 0x42,\r\n 's3' : 0x43,\r\n 's4' : 0x44,\r\n 's5' : 0x45,\r\n 's6' : 0x46,\r\n 's7' : 0x47,\r\n 's8' : 0x48,\r\n 's9' : 0x49,\r\n 's10': 0x4a,\r\n 's11': 0x4b,\r\n 's12': 0x4c,\r\n 's13': 0x4d,\r\n 's14': 0x4e,\r\n 's15': 0x4f,\r\n 's16': 0x50,\r\n 's17': 0x51,\r\n 's18': 0x52,\r\n 's19': 0x53,\r\n 's20': 0x54,\r\n 's21': 0x55,\r\n 's22': 0x56,\r\n 's23': 0x57,\r\n 's24': 0x58,\r\n 's25': 0x59,\r\n 's26': 0x5a,\r\n 's27': 0x5b,\r\n 's28': 0x5c,\r\n 's29': 0x5d,\r\n 's30': 0x5e,\r\n 's31': 0x5f,\r\n}\r\n\r\nclass CortexM(object):\r\n \"\"\"\r\n This class has basic functions to access a Cortex M core:\r\n - init\r\n - read/write memory\r\n - read/write core registers\r\n \"\"\"\r\n TARGET_RUNNING = 1 # Core is executing code.\r\n TARGET_HALTED = 2 # Core is halted in debug mode.\r\n TARGET_RESET = 3 # Core is being held in reset.\r\n TARGET_SLEEPING = 4 # Core is sleeping due to a wfi or wfe instruction.\r\n TARGET_LOCKUP = 5 # Core is locked up.\r\n\r\n # CPUID Register\r\n CPUID = 0xE000ED00\r\n CPUID_IMPLEMENTER_MASK = 0xff000000\r\n CPUID_IMPLEMENTER_POS = 24\r\n CPUID_IMPLEMENTER_ARM = 0x41\r\n CPUID_VARIANT_MASK = 0x00f00000\r\n CPUID_VARIANT_POS = 20\r\n CPUID_ARCHITECTURE_MASK = 0x000f0000\r\n CPUID_ARCHITECTURE_POS = 16\r\n CPUID_PARTNO_MASK = 0x0000fff0\r\n CPUID_PARTNO_POS = 4\r\n CPUID_REVISION_MASK = 0x0000000f\r\n CPUID_REVISION_POS = 0\r\n\r\n NVIC_AIRCR = 0xE000ED0C\r\n NVIC_AIRCR_VECTKEY = (0x5FA << 16)\r\n NVIC_AIRCR_VECTRESET = (1 << 0)\r\n NVIC_AIRCR_SYSRESETREQ = (1 << 2)\r\n\r\n # Core Register Selector Register\r\n DCRSR = 0xE000EDF4\r\n DCRSR_REGWnR = (1 << 16)\r\n DCRSR_REGSEL = 0x1F\r\n\r\n # Core Register Data Register\r\n DCRDR = 0xE000EDF8\r\n \r\n # Debug Halting Control and Status Register\r\n DHCSR = 0xE000EDF0\r\n C_DEBUGEN = (1 << 0)\r\n C_HALT = (1 << 1)\r\n C_STEP = (1 << 2)\r\n C_MASKINTS = (1 << 3)\r\n C_SNAPSTALL = (1 << 5)\r\n S_REGRDY = (1 << 16)\r\n S_HALT = (1 << 17)\r\n S_SLEEP = (1 << 18)\r\n S_LOCKUP = (1 << 19)\r\n S_RETIRE_ST = (1 << 24)\r\n S_RESET_ST = (1 << 25)\r\n\r\n # Debug Exception and Monitor Control Register\r\n DEMCR = 0xE000EDFC\r\n DEMCR_TRCENA = (1 << 24)\r\n DEMCR_VC_HARDERR = (1 << 10)\r\n DEMCR_VC_BUSERR = (1 << 8)\r\n DEMCR_VC_CORERESET = (1 << 0)\r\n\r\n DBGKEY = (0xA05F << 16)\r\n\r\n def __init__(self, link, dp, ap):\r\n self.link = link\r\n self.dp = dp\r\n self.ap = ap\r\n\r\n self.arch = 0\r\n self.core = 0\r\n\r\n ## @brief Read the CPUID register and determine core type.\r\n def readCoreType(self):\r\n cpuid = self.ap.read32(CortexM.CPUID)\r\n\r\n if (cpuid & CortexM.CPUID_IMPLEMENTER_MASK) >> CortexM.CPUID_IMPLEMENTER_POS != CortexM.CPUID_IMPLEMENTER_ARM:\r\n logging.warning(\"CPU implementer is not ARM!\")\r\n\r\n self.arch = (cpuid & CortexM.CPUID_ARCHITECTURE_MASK) >> CortexM.CPUID_ARCHITECTURE_POS\r\n self.core = (cpuid & CortexM.CPUID_PARTNO_MASK) >> CortexM.CPUID_PARTNO_POS\r\n logging.info(\"CPU core is %s\", CORE_TYPE_NAME[self.core])\r\n\r\n def halt(self):\r\n self.ap.writeMemory(CortexM.DHCSR, CortexM.DBGKEY | CortexM.C_DEBUGEN | CortexM.C_HALT)\r\n self.dp.flush()\r\n\r\n def resume(self):\r\n if self.getState() != CortexM.TARGET_HALTED: return\r\n \r\n self.ap.writeMemory(CortexM.DHCSR, CortexM.DBGKEY | CortexM.C_DEBUGEN)\r\n self.dp.flush()\r\n\r\n def reset(self, software_reset=True):\r\n \"\"\"reset a core. After a call to this function, the core is running\"\"\"\r\n if software_reset:\r\n try:\r\n self.ap.writeMemory(CortexM.NVIC_AIRCR, CortexM.NVIC_AIRCR_VECTKEY | CortexM.NVIC_AIRCR_SYSRESETREQ)\r\n self.dp.flush() # Without a flush a transfer error can occur\r\n except DAPAccess.TransferError:\r\n self.dp.flush()\r\n else:\r\n self.dp.reset()\r\n\r\n # Now wait for the system to come out of reset. Keep reading the DHCSR until\r\n # we get a good response with S_RESET_ST cleared, or we time out.\r\n startTime = time.time()\r\n while time.time() - startTime < 2.0:\r\n try:\r\n dhcsr = self.ap.read32(CortexM.DHCSR)\r\n if (dhcsr & CortexM.S_RESET_ST) == 0: break\r\n except DAPAccess.TransferError:\r\n self.dp.flush()\r\n time.sleep(0.01)\r\n\r\n def getState(self):\r\n dhcsr = self.ap.readMemory(CortexM.DHCSR)\r\n if dhcsr & CortexM.S_RESET_ST:\r\n newDhcsr = self.ap.readMemory(CortexM.DHCSR)\r\n if (newDhcsr & CortexM.S_RESET_ST) and not (newDhcsr & CortexM.S_RETIRE_ST):\r\n return CortexM.TARGET_RESET\r\n if dhcsr & CortexM.S_LOCKUP:\r\n return CortexM.TARGET_LOCKUP\r\n elif dhcsr & CortexM.S_SLEEP:\r\n return CortexM.TARGET_SLEEPING\r\n elif dhcsr & CortexM.S_HALT:\r\n return CortexM.TARGET_HALTED\r\n else:\r\n return CortexM.TARGET_RUNNING\r\n\r\n def isRunning(self):\r\n return self.getState() == CortexM.TARGET_RUNNING\r\n\r\n def isHalted(self):\r\n return self.getState() == CortexM.TARGET_HALTED\r\n\r\n def registerNameToIndex(self, reg):\r\n if isinstance(reg, str):\r\n try:\r\n reg = CORE_REGISTER[reg.lower()]\r\n except KeyError:\r\n logging.error('cannot find %s core register', reg)\r\n return\r\n return reg\r\n\r\n def readCoreRegister(self, reg):\r\n regIndex = self.registerNameToIndex(reg)\r\n regValue = self.readCoreRegisterRaw(regIndex)\r\n # Convert int to float.\r\n if regIndex >= 0x40:\r\n regValue = conversion.u32BEToFloat32BE(regValue)\r\n return regValue\r\n\r\n def readCoreRegisterRaw(self, reg):\r\n vals = self.readCoreRegistersRaw([reg])\r\n return vals[0]\r\n\r\n def readCoreRegistersRaw(self, reg_list):\r\n reg_list = [self.registerNameToIndex(reg) for reg in reg_list]\r\n\r\n # Sanity check register values\r\n for reg in reg_list:\r\n if reg not in CORE_REGISTER.values():\r\n raise ValueError(\"unknown reg: %d\" % reg)\r\n elif ((reg >= 128) or (reg == 33)) and (not self.has_fpu):\r\n raise ValueError(\"attempt to read FPU register without FPU\")\r\n\r\n # Begin all reads and writes\r\n dhcsr_cb_list = []\r\n reg_cb_list = []\r\n for reg in reg_list:\r\n if (reg < 0) and (reg >= -4):\r\n reg = CORE_REGISTER['cfbp']\r\n\r\n self.ap.writeMemory(CortexM.DCRSR, reg)\r\n\r\n # Technically, we need to poll S_REGRDY in DHCSR here before reading DCRDR. But\r\n # we're running so slow compared to the target that it's not necessary.\r\n # Read it and assert that S_REGRDY is set\r\n\r\n dhcsr_cb = self.ap.readMemory(CortexM.DHCSR, now=False)\r\n reg_cb = self.ap.readMemory(CortexM.DCRDR, now=False)\r\n dhcsr_cb_list.append(dhcsr_cb)\r\n reg_cb_list.append(reg_cb)\r\n\r\n # Read all results\r\n reg_vals = []\r\n for reg, reg_cb, dhcsr_cb in zip(reg_list, reg_cb_list, dhcsr_cb_list):\r\n dhcsr_val = dhcsr_cb()\r\n assert dhcsr_val & CortexM.S_REGRDY\r\n val = reg_cb()\r\n\r\n # Special handling for registers that are combined into a single DCRSR number.\r\n if (reg < 0) and (reg >= -4):\r\n val = (val >> ((-reg - 1) * 8)) & 0xff\r\n\r\n reg_vals.append(val)\r\n\r\n return reg_vals\r\n\r\n def writeCoreRegister(self, reg, data):\r\n regIndex = self.registerNameToIndex(reg)\r\n # Convert float to int.\r\n if regIndex >= 0x40:\r\n data = conversion.float32beToU32be(data)\r\n self.writeCoreRegisterRaw(regIndex, data)\r\n\r\n def writeCoreRegisterRaw(self, reg, data):\r\n self.writeCoreRegistersRaw([reg], [data])\r\n\r\n def writeCoreRegistersRaw(self, reg_list, data_list):\r\n \"\"\"Write one or more core registers\"\"\"\r\n assert len(reg_list) == len(data_list)\r\n reg_list = [self.registerNameToIndex(reg) for reg in reg_list]\r\n\r\n # Sanity check register values\r\n for reg in reg_list:\r\n if reg not in CORE_REGISTER.values():\r\n raise ValueError(\"unknown reg: %d\" % reg)\r\n elif ((reg >= 128) or (reg == 33)) and (not self.has_fpu):\r\n raise ValueError(\"attempt to write FPU register without FPU\")\r\n\r\n # Read special register if it is present in the list\r\n for reg in reg_list:\r\n if (reg < 0) and (reg >= -4):\r\n specialRegValue = self.readCoreRegister(CORE_REGISTER['cfbp'])\r\n break\r\n\r\n # Write out registers\r\n dhcsr_cb_list = []\r\n for reg, data in zip(reg_list, data_list):\r\n if (reg < 0) and (reg >= -4):\r\n # Mask in the new special register value so we don't modify the other register\r\n # values that share the same DCRSR number.\r\n shift = (-reg - 1) * 8\r\n mask = 0xffffffff ^ (0xff << shift)\r\n data = (specialRegValue & mask) | ((data & 0xff) << shift)\r\n specialRegValue = data # update special register for other writes that might be in the list\r\n reg = CORE_REGISTER['cfbp']\r\n\r\n self.ap.writeMemory(CortexM.DCRDR, data)\r\n self.ap.writeMemory(CortexM.DCRSR, reg | CortexM.DCRSR_REGWnR) #start write transfer\r\n\r\n # Technically, we need to poll S_REGRDY in DHCSR here to ensure the\r\n # register write has completed.\r\n # Read it and assert that S_REGRDY is set\r\n dhcsr_cb = self.ap.readMemory(CortexM.DHCSR, now=False)\r\n dhcsr_cb_list.append(dhcsr_cb)\r\n\r\n # Make sure S_REGRDY was set for all register writes\r\n for dhcsr_cb in dhcsr_cb_list:\r\n dhcsr_val = dhcsr_cb()\r\n assert dhcsr_val & CortexM.S_REGRDY\r\n\r\n def setTargetState(self, state):\r\n if state == \"PROGRAM\":\r\n self.resetStopOnReset(True)\r\n # Write the thumb bit in case the reset handler points to an ARM address\r\n self.writeCoreRegister('xpsr', 0x1000000)\r\n\r\n def resetStopOnReset(self, software_reset=None):\r\n \"\"\"perform a reset and stop the core on the reset handler\"\"\"\r\n logging.debug(\"reset stop on Reset\")\r\n\r\n self.halt()\r\n\r\n demcr = self.ap.readMemory(CortexM.DEMCR)\r\n\r\n self.ap.writeMemory(CortexM.DEMCR, demcr | CortexM.DEMCR_VC_CORERESET) # enable the vector catch\r\n\r\n self.reset(software_reset)\r\n while self.isRunning(): pass\r\n\r\n self.ap.writeMemory(CortexM.DEMCR, demcr)","repo_name":"mfkiwl/MCUProgFast","sub_path":"daplink/coresight/cortex_m.py","file_name":"cortex_m.py","file_ext":"py","file_size_in_byte":12565,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"} +{"seq_id":"27091940732","text":"import webbrowser\nimport pyautogui\nimport time\nimport cv2\nimport pyperclip\nimport re\nfrom pyclick import HumanClicker\nimport random\nfrom pywinauto import keyboard\nimport win32api\nimport keyboard\n\n#simple colorbot for farming infernal eels\n\n\nr=0\ni=0\ninvCount = 0\nprint(\"starting infernalEelsBot v1.0.0 in 3 seconds...\\n\\n\\n\\n\\n\")\ntime.sleep(3)\nnoFindColor=[]\nres = {}\n\n#begin finding new fishing spot\ndef fishingSpot():\n q=0\n coordList=[]\n while not coordList:\n print(\"Failed colors: \")\n print(res)\n print(\"\\n\")\n \n \n print(\"Finding fishing spot color\")\n \n colorarray= [(145, 136, 86),(150, 157, 102),(123, 99, 58),(250, 211, 172),(140, 130, 80),(179, 162, 117),(148, 157, 105),(141, 155, 106),(143, 125, 83),(124, 100, 57),(183, 157, 115),(143, 152, 96),(132, 122, 75),(151, 158, 103),(146, 154, 99),(129, 104, 66),(148, 154, 105),(147, 149, 100),(143, 142, 94),(149, 152, 98),(150, 160, 111)\n\n]\n j=random.randrange(0,len(colorarray))\n color = colorarray[j]\n print(\"color selected: \" + str(color))\n #coordList=[]\n print(\"Getting Locations\")\n \n s = pyautogui.screenshot()\n for x in range(s.width):\n for y in range(s.height):\n if s.getpixel((x, y)) == color:\n #put all of these locations ^ into array\n \n coord = tuple([x,y])\n coordList.append(coord)\n\n \n \n\n #printing if location not found and restarting search\n print(\"Amount of locations found: \" + str(len(coordList)))\n print(\"number of times failing location finding: \" +str(q)+\"\\n\")\n q=q+1\n #has found color and picking random out of list of coords\n if coordList:\n f=random.randrange(0,len(coordList))\n print(\"Position in Array: \" + str(f) + \"\\n\") \n pyautogui.moveTo(coordList[f])\n time.sleep(.1)\n \n pyautogui.mouseDown()\n clickTime = random.uniform(.1,.5)\n time.sleep(clickTime)\n pyautogui.mouseUp()\n \n q=0\n else:\n \n noFindColor.append(color)\n for i in noFindColor:\n res[i] = noFindColor.count(i)\n \n #i=i+1\n #rint(\"Count: \" + str(i))\n\n#drop inventory sequence\ndef crushEels():\n inventNumber=0\n xgen=random.randint(-23,23)\n ygen=random.randint(-23,23)\n \n \n x=2216+xgen\n y=1142+ygen\n pyautogui.moveTo(x,y)\n pyautogui.mouseDown()\n clickTime = random.uniform(.10,.35)\n time.sleep(clickTime)\n pyautogui.mouseUp()\n \n waitTime = random.uniform(.1,1.3)\n \n time.sleep(waitTime)\n \n #re generating rand x and y additions\n xgen=random.randint(-23,23)\n ygen=random.randint(-23,23)\n #picking which invent slot\n slotNumber=random.randint(1,3)\n if slotNumber==1:\n x=2121+xgen\n y=1143+ygen\n pyautogui.moveTo(x,y)\n pyautogui.mouseDown()\n clickTime = random.uniform(.10,.35)\n time.sleep(clickTime)\n pyautogui.mouseUp()\n \n elif slotNumber==2:\n x=2118+xgen\n y=1061+ygen\n pyautogui.moveTo(x,y)\n pyautogui.mouseDown()\n clickTime = random.uniform(.10,.35)\n time.sleep(clickTime)\n pyautogui.mouseUp()\n \n else:\n x=2216+xgen\n y=1060+ygen\n pyautogui.moveTo(x,y)\n pyautogui.mouseDown()\n clickTime = random.uniform(.10,.35)\n time.sleep(clickTime)\n pyautogui.mouseUp()\n \n \n crushTime = random.uniform(38,48.5)\n time.sleep(crushTime)\n print(\"Crushing eel slot \" + str(slotNumber) + \" for \" + str(crushTime) + \" seconds.\")\n \n \nwhile invCount < 10: #number of inventories to catch\n #random number generator variables\n timex = random.uniform(30.3,62.7)\n \n print(\"Inventories completed: \" + str(invCount)+ \"\\n\")\n \n #feesh pictures to find\n fish1 = pyautogui.locateOnScreen('C:\\\\Users\\\\forry\\\\Pictures\\\\eel1.png', confidence=.8,region=(2086,1108,2153,1177))\n fish2 = pyautogui.locateOnScreen('C:\\\\Users\\\\forry\\\\Pictures\\\\eel2.png', confidence=.8,region=(2086,1108,2153,1177))\n fish3 = pyautogui.locateOnScreen('C:\\\\Users\\\\forry\\\\Pictures\\\\eel3.png', confidence=.8,region=(2086,1108,2153,1177))\n \n \n #if finds feesh in last invent slot, move to drop items\n if fish1 or fish2 or fish3:\n print(\"has found something in last slot, moving to crush eels\\n\")\n crushEels()\n invCount = invCount + 1\n \n #otherwise just finds new fishing spot \n else:\n print(\"didnt find anything in drop spot, moving to find new spot\\n\")\n\n\n #finding fishing spot and waiting until next invent check\n fishingSpot()\n print(\"fishing spot found, waiting for: \" + str(timex) + \"\\n\")\n time.sleep(timex)","repo_name":"empaw1/projectsDemo","sub_path":"otherPython/infernalEelsColorBot.py","file_name":"infernalEelsColorBot.py","file_ext":"py","file_size_in_byte":4943,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"540223184","text":"import numpy as np\r\nimport cv2\r\nimport os.path\r\n\r\nTraining_Data = 'F:\\Masters RIME\\Third Semester\\Deep learning\\Assignemnts\\Test_Images'\r\nTest_Data = 'F:\\Masters RIME\\Third Semester\\Deep learning\\Assignments\\Train_Images'\r\nOutput = [\"Balls\", \"Football\"]\r\n\r\ndef pre_processing(image_path):\r\n img = cv2.imread(image_path)\r\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n img_pred = cv2.resize(img, (100, 100), interpolation=cv2.INTER_AREA)\r\n \r\n img_pred = np.asarray(img_pred)\r\n \r\n img_pred = img_pred / 255\r\n return img_pred\r\n\r\ndef train(path):\r\n X = []\r\n for file in os.listdir(path):\r\n if (os.path.isfile(path + \"/\" + file)):\r\n image = pre_processing(path + \"/\" + file)\r\n image = np.reshape(image,(image.shape[0]*image.shape[1]))\r\n X.append(image)\r\n \r\n X_train = np.array(X)\r\n y_duck = np.zeros((10,1))\r\n y_horse = np.ones((10,1))\r\n Y_train = np.concatenate((y_duck,y_horse))\r\n \r\n return X_train,Y_train\r\n\r\ndef test(path):\r\n X = []\r\n for file in os.listdir(path):\r\n if (os.path.isfile(path + \"/\" + file)):\r\n image = pre_processing(path + \"/\" + file)\r\n image = np.reshape(image,(image.shape[0]*image.shape[1]))\r\n X.append(image)\r\n \r\n X_test = np.array(X)\r\n y_duck = np.zeros((5,1))\r\n y_horse = np.ones((5,1))\r\n Y_test = np.concatenate((y_duck,y_horse))\r\n return X_test,Y_test\r\n\r\nX_train,Y_train = train(Dataset_path)\r\nprint(X_train.shape)\r\nprint(Y_train.shape)\r\n ","repo_name":"Khubaib-Haider/Assignment-03-Deep-Learning-","sub_path":"Image.py","file_name":"Image.py","file_ext":"py","file_size_in_byte":1562,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37931478588","text":"import pytest\nfrom pyspark.sql import Row\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.dataframe import DataFrame\nfrom pyspark.sql.functions import avg\n\n\n@pytest.fixture(scope='session')\ndef spark():\n return SparkSession.builder.getOrCreate()\n\n\ndef evaluate_feature_avg_price_per_merchant(df: DataFrame) -> DataFrame:\n return df.groupBy('merchant').agg(avg('price').alias('avg_price'))\n\n\ndef test_evaluate_feature_avg_price_per_merchant(spark: SparkSession):\n df = spark.createDataFrame([\n Row(merchant=1, price=1.0),\n Row(merchant=1, price=2.0),\n Row(merchant=2, price=3.0),\n ]).orderBy('merchant')\n df_expected = spark.createDataFrame([\n Row(merchant=1, price=1.5),\n Row(merchant=2, price=3.0),\n ]).orderBy('merchant')\n\n df_out = evaluate_feature_avg_price_per_merchant(df)\n\n assert df_out.collect() == df_expected.collect()\n","repo_name":"mrk-andreev/medium_38f923dd659c","sub_path":"code/test_example.py","file_name":"test_example.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8453030345","text":"# Mode 4 : Buy when price is .3% under EMA. Sell when price is .2 over EMA\r\ndef under_over(model):\r\n length = model.ema_dataframe.shape[0]\r\n if length>26:\r\n price = model.ema_dataframe['price'].tail(1).reset_index(drop=True)\r\n EMA26 = model.ema_dataframe['EMA26'].tail(1).reset_index(drop=True)\r\n under = float(EMA26[0]) * .99 # 1% below EM26\r\n over = float(EMA26[0]) * 1.025 # 1.025% above EM26\r\n price = float(price[0])\r\n if (price - over > 0 ):\r\n signal = {'signal': True, 'value': 'sell'}\r\n elif (price - under < 0):\r\n signal = {'signal': True, 'value': 'buy'}\r\n else:\r\n signal = {'signal': False, 'value': None}\r\n model.ema_dataframe.loc[model.ema_dataframe.index[length-1], 'signal'] = signal['value']\r\n model.logPrice(True)\r\n return signal\r\n else:\r\n model.logPrice(True)","repo_name":"Malik807/Hekima","sub_path":"strategies/under_over.py","file_name":"under_over.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28296000809","text":"import pandas as pd\nimport numpy as np\nimport streamlit as st\nimport matplotlib.pyplot as plt\nimport pickle\nfrom sklearn.metrics import recall_score, precision_score, f1_score, accuracy_score, classification_report\n\n\nfile = open('to_show_df.pkl', 'rb')\nall_toshow_df = pickle.load(file)\nfile.close()\n\nst.set_page_config(layout=\"wide\")\n\nst.markdown(\"\"\"\n \n \"\"\", unsafe_allow_html=True)\n\n\nst.title(\"HealthCare Fraud Detection\")\n\n\nselectbox = st.selectbox(\n \"Select The Algorithm\",\n [\"Select Algorithm\", \"Logistic Regression\", \"Decision Tree\", \"Random Forest\", \"XG Boost\", \"Extra Tree\", \"Ada Boost\"]\n)\n\n\nif selectbox != \"Select Algorithm\":\n # st.write(f\"You selected the Algorithm: {selectbox}\")\n\n accuracy = accuracy_score(all_toshow_df[selectbox]['Real'],all_toshow_df[selectbox]['Pred'])\n precision = precision_score(all_toshow_df[selectbox]['Real'],all_toshow_df[selectbox]['Pred'])\n recall = recall_score(all_toshow_df[selectbox]['Real'],all_toshow_df[selectbox]['Pred'])\n f1 = f1_score(all_toshow_df[selectbox]['Real'],all_toshow_df[selectbox]['Pred'])\n\n st.markdown(\n f\"\"\"
MODEL Accuracy: {accuracy*100} %
\n MODEL Recall Score: {recall}
\n MODEL Precision Score: {precision}
\n MODEL f1 Score: {f1}
\"\"\", unsafe_allow_html=True\n )\n\n st.write(\"**Output DF for the Algorithm**\")\n # st.write(all_toshow_df[selectbox][['Real', 'Pred']])\n st.write(all_toshow_df[selectbox])\n\n #Plot Graph\n metrics = ['Accuracy', 'Recall', 'Precision', 'F1 Score']\n values = [accuracy, recall, precision, f1]\n\n fig = plt.figure(figsize = (8,2))\n\n # creating the bar plot\n plt.bar(metrics, values)\n\n plt.xlabel(\"-- Metrics -->\")\n plt.ylabel(\"-- Value -->\")\n plt.title(f\"Different Metrics of {selectbox} Model\")\n\n st.pyplot(fig)\n","repo_name":"lubnaumbc/lubna_data606","sub_path":"streamlit_application.py","file_name":"streamlit_application.py","file_ext":"py","file_size_in_byte":2624,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"29308046204","text":"import setuptools\n\nwith open(\"README.md\", \"r\", encoding=\"utf-8\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name=\"ylecomments\",\n version=\"1.0.1\",\n author=\"Juhani Astikainen\",\n author_email=\"juhani.astikainen@gmail.com\",\n description=\"A Python wrapper for Yle's Comments API\",\n long_description=long_description,\n license=\"MIT\",\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/juhanias/ylecomments\",\n project_urls={\n \"Bug Tracker\": \"https://github.com/juhanias/ylecomments/issues\",\n },\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n 'Topic :: Software Development :: Libraries',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n 'Programming Language :: Python :: 3.7',\n ],\n packages=[\"ylecomments\"],\n python_requires=\">=3.7\",\n install_requires=[\"requests<=2.28.2\"],\n)\n","repo_name":"juhanias/ylecomments","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28778828976","text":"'''\nGurkirat Singh: A11593827\nAnirudh Chava: A99415981\nJason Geneste: A11357496\n'''\nfrom problem21_1 import isGoal\nfrom helper import *\nimport Queue\n\ndef breadthFirstSearch(tup_node):\n\n\tqueue = Queue.Queue()\n\tqueue.put([tup_node,\"\"])\n\tallNodes = set()\n\n\twhile not queue.empty():\n\t\tnode = queue.get()\n\t\ttnode = node[0]\n\n\t\tres = isGoal(tnode,False)\n\t\tif res == 1:\n\t\t\treturn \"\".join(node[1])\n\t\telif res == -1:\n\t\t\treturn None\n\t\t\t\n\t\tif tnode not in allNodes:\n\t\t\tallNodes.add(tnode)\n\t\t\tfor idx, child in enumerate(getAllChildren(tnode, allNodes)):\n\t\t\t\tif child != None:\n\t\t\t\t\tqueue.put([child, node[1] + seq_one[idx]])\n\n\treturn \"None\"\n\nif __name__ == \"__main__\":\n\treadCallFuncs(breadthFirstSearch)","repo_name":"cseoreos/homework2","sub_path":"problem22_2.py","file_name":"problem22_2.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2374041913","text":"from navec import Navec\nfrom numpy import linalg as ln\nimport numpy as np\nimport time\nimport json\nimport tensorflow as tf\nfrom tensorflow.keras import layers\nimport matplotlib.pyplot as plt\nfrom random import random\nfrom slovnet.model.emb import NavecEmbedding\nimport torch\n\npath = 'navec_news_v1_1B_250K_300d_100q.tar'\nnavec = Navec.load(path)\n# emb = NavecEmbedding(navec)\n\n# print(ln.norm(navec['каспийский'] - navec['море']))\n# navec.vocab\n\n# path = 'navec_hudlit_v1_12B_500K_300d_100q.tar'\n# navec = Navec.load(path)\n\n# sentences1 = [\n# [[0.1, 0.3,0.7,0.8,0.9], [0.1, 0.12,0.15,0.21,0.24], \n# [0.1, 0.3,0.7,0.8,0.9], [0.1, 0.3,0.7,0.8,0.9],\n# [0.1, 0.3,0.7,0.8,0.9]],\n \n# [[0.01, 0.08,0.12,0.13,0.13], [0.58, 0.59,0.63,0.63,0.64], \n# [0.1, 0.3,0.7,0.8,0.9], \n# [0.2, 0.22,0.23,0.25,0.28]],\n \n# [[0.32, 0.34,0.35,0.38,0.39], [0.1, 0.12,0.15,0.21,0.24], \n# [0.78, 0.79,0.79,0.8,0.82]],\n \n# [[0.9, 0.7,0.7,0.6,0.4], [0.24, 0.21,0.15,0.12,0.12], \n# [0.9, 0.8,0.78,0.76,0.71], [0.5, 0.3,0.25,0.21,0.2],\n# [0.5, 0.35,0.32,0.31,0.31]],\n \n# [[0.21, 0.18,0.12,0.11,0.10], [0.58, 0.5,0.43,0.42,0.41], \n# [0.7, 0.65,0.62,0.6,0.58], \n# [0.3, 0.25,0.23,0.22,0.21]],\n \n \n# ]\n\n# sentences2 = [[[0.32, 0.34,0.35,0.38,0.39], [0.1, 0.12,0.15,0.21,0.24], \n# [0.78, 0.79,0.79,0.8,0.82]],\n# [[0.8, 0.79,0.78,0.76,0.75], [0.65, 0.63,0.6,0.58,0.56], \n# [0.78, 0.5,0.48,0.38,0.28]]\n# ]\n\n# answer1 = [\n# [1, 0], [1, 0], \n# [0, 1], [0, 1]\n# ]\n\n# answer2 = [\n# [1, 0], [0, 1]\n# ]\n\n# navec.vocab['b']\n# b = navec.pq.__getitem__(972)\n# navec.vocab['']\n# navec.vocab['']\n\n# def getNum():\n# r = int(random()*4)\n# return np.array(sentences1[r]), np.array(answer1[r])\n\n\n\n\n\n#%%\n\n\nxData = [\n ['овощь', \"ферма\", \"корова\", \"дача\"],\n [\"поле\", \"огород\", \"деревня\", \"свинья\"],\n [\"село\", \"трактор\", \"картофель\", \"петух\"],\n [\"чернозем\", \"ягода\"],\n [\"пшеница\", \"поле\", \"трава\", \"мясо\", \"говядина\", \"яйца\", \"сад\"],\n [\"дача\", \"огород\", \"комбайн\", \"элеватор\", \"колхоз\"],\n [\"сад\", \"фрукты\", \"жук\", \"трава\", \"лук\", \"укроп\", \"томат\"],\n \n [\"город\", \"фонтан\", \"парк\", \"здание\"],\n [\"администрация\", \"асфальт\", \"мост\"],\n [\"стена\", \"бордюр\", \"инфраструктура\", \"электричка\", \"троллейбус\"],\n [\"клуб\", \"офис\", \"город\", \"улица\", \"район\"],\n [\"бизнес\", \"центр\", \"памятник\", \"мэр\", \"проспект\"],\n [\"центр\", \"парк\", \"урбанист\"],\n [\"площадь\", \"сквер\", \"развязка\", \"перекрёсток\"]\n ]\n\nxTestData = [\n [\"небоскреб\", \"машина\", \"брусчатка\", \"трасса\"],\n [\"посев\", \"ячмень\", \"кукуруза\", \"гусь\"],\n [\"амбар\", \"загон\", \"скот\", \"чеснок\"],\n [\"район\", \"вокзал\", \"сквер\", \"мост\"],\n [\"зал\", \"микрорайон\", \"губернатор\"],\n ['морковь', \"саженец\", \"колхозник\", \"сарай\"]\n \n ]\n\nyTestData = [\n [0, 1],\n [1, 0],\n [1, 0],\n [0, 1],\n [0, 1],\n [1, 0]\n \n ]\n\nyData = [\n [1, 0],\n [1, 0],\n [1, 0],\n [1, 0],\n [1, 0],\n [1, 0],\n [1, 0],\n \n [0, 1],\n [0, 1],\n [0, 1],\n [0, 1],\n [0, 1],\n [0, 1],\n [0, 1]\n ]\n\n#%%\n\ndef getWordVec(embModel, word):\n if word in embModel:\n return embModel[word]\n else:\n return embModel['']\n\ndef textToVectors(embModel, tokenizedText):\n vectors = [getWordVec(embModel, word) for word in tokenizedText]\n return np.array(vectors)\n\ndef trimAndPadVectors(textVectors, embDimension:int, seqLen:int):\n output = np.zeros((seqLen, embDimension))\n trimmedVectors = textVectors[:seqLen]\n endOfPaddingIndex = seqLen - trimmedVectors.shape[0]\n output[endOfPaddingIndex:] = trimmedVectors\n return output.reshape((1, seqLen, embDimension, 1))\n\ndef embPreprocess(embModel, seqLen:int, tokenizedText):\n textVectors = textToVectors(embModel, tokenizedText)\n output = trimAndPadVectors(textVectors, embModel.pq.dim, seqLen)\n return output\n \n\n# text = ['абажур', \"журавль\", \"человек\", \"артист\", \"убийца\", \"кекс\"]\n# print(textToVectors(navec, text))\n# l = trimAndPadVectors(textToVectors(navec, text), 300, 30)\n# l3 = l.reshape((1, 300*30))\n\ndim = 300\nseq = 30\nbatch = 1\n\n#%%\nmodel = tf.keras.Sequential()\nmodel.add(layers.Conv2D(64, (3,3), input_shape=(seq, dim, 1)))\nmodel.add(layers.Activation(\"relu\"))\nmodel.add(layers.MaxPooling2D(pool_size=(2,2)))\n\nmodel.add(layers.Conv2D(64, (3,3)))\nmodel.add(layers.Activation(\"relu\"))\nmodel.add(layers.MaxPooling2D(pool_size=(2,2)))\n\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(64))\n\nmodel.add(layers.Dense(2, 'softmax'))\nmodel.compile(loss='categorical_crossentropy',\n optimizer='rmsprop')\nmodel.summary()\n\n\n#%%\nfor epoch in range(14):\n \n x = embPreprocess(navec, seq, xData[epoch])\n y = np.array(yData[epoch]).reshape(1,2)\n\n model.fit(x,y, epochs=1, batch_size=batch, verbose=2)\n \n#%%\nfor i in range(6):\n \n x = embPreprocess(navec, seq, xTestData[i])\n y = np.array(yTestData[i]).reshape(1,2)\n \n yhat = model.predict_classes(x)\n print(\"Expected: \", y, \" Predict: \", yhat)\n \n \n\nfor i in range(6):\n x = embPreprocess(navec, seq, xTestData[i])\n y = np.array(yTestData[i]).reshape(1,2)\n yhat = model.predict_classes(x)\n print(\"Expected: \", y, \" Predict: \", yhat)\n \n \n \n ","repo_name":"karuna-heks/python_nlp","sub_path":"wordEmbeddingsTest.py","file_name":"wordEmbeddingsTest.py","file_ext":"py","file_size_in_byte":6487,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"6613578753","text":"from delegates.base import SystemCalcDelegate\nfrom datetime import datetime\nfrom time import time\n\nts_to_str = lambda x: datetime.fromtimestamp(x).strftime('%Y-%m-%d %H:%M:%S')\n\nPREFIX = '/Ac/Genset'\n\n\nclass GensetStartStop(SystemCalcDelegate):\n\t\"\"\" Relay a unified view of what generator start/stop is doing. This\n\t clears up the distinction between relay/fisherpanda as well. \"\"\"\n\n\tdef get_input(self):\n\t\treturn [('com.victronenergy.generator', [\n\t\t\t\t'/RunningByConditionCode',\n\t\t\t\t'/Runtime',\n\t\t\t\t'/LastStartTime'])]\n\n\tdef get_output(self):\n\t\treturn [('{}/Runtime'.format(PREFIX), {'gettext': '%d'}),\n\t\t\t\t('{}/RunningByConditionCode'.format(PREFIX), {'gettext': '%d'}),\n\t\t]\n\n\tdef set_sources(self, dbusmonitor, settings, dbusservice):\n\t\tSystemCalcDelegate.set_sources(self, dbusmonitor, settings, dbusservice)\n\t\tself._dbusservice.add_path('{}/LastStartTime'.format(PREFIX), None,\n\t\t\tgettextcallback=lambda p, v: ts_to_str(v) if v is not None else '---')\n\n\t@property\n\tdef starttime(self):\n\t\ttry:\n\t\t\treturn self._dbusservice['{}/LastStartTime'.format(PREFIX)]\n\t\texcept KeyError:\n\t\t\treturn None\n\n\t@starttime.setter\n\tdef starttime(self, v):\n\t\tself._dbusservice['{}/LastStartTime'.format(PREFIX)] = v\n\n\tdef update_values(self, newvalues):\n\t\tfor service in sorted(self._dbusmonitor.get_service_list('com.victronenergy.generator')):\n\t\t\trbc = self._dbusmonitor.get_value(service, '/RunningByConditionCode')\n\t\t\tif rbc is not None:\n\t\t\t\tif self._dbusservice[PREFIX + '/RunningByConditionCode'] == 0 and rbc > 0:\n\t\t\t\t\t# Generator was started, update LastStartTime\n\t\t\t\t\tself.starttime = int(time())\n\n\t\t\t\tnewvalues[PREFIX + '/RunningByConditionCode'] = rbc\n\n\t\t\t\t# Update runtime in 10 second increments, we don't need more than that\n\t\t\t\trt = self._dbusmonitor.get_value(service, '/Runtime')\n\t\t\t\tnewvalues[PREFIX + '/Runtime'] = None if rt is None else 10 * (rt // 10)\n\t\t\t\tbreak\n","repo_name":"victronenergy/dbus-systemcalc-py","sub_path":"delegates/genset.py","file_name":"genset.py","file_ext":"py","file_size_in_byte":1870,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"9586464536","text":"from datetime import timedelta, date\n\nclass DateRangeIterable:\n def __init__(self, start_date, end_date):\n self.start_date = start_date\n self.end_date = end_date\n self._present_day = start_date\n\n def __iter__(self):\n return self\n\n def __next__(self):\n if self._present_day >= self.end_date:\n raise StopIteration\n today = self._present_day\n self._present_day += timedelta(days=1)\n return today\n\n# StopIteration 발생 시점까지 next 호출\nfor day in DateRangeIterable(date(2019, 1, 1), date(2019, 1, 5)):\n print(day)\n\nr1 = DateRangeIterable(date(2019, 1, 1), date(2019, 1, 5))\nprint(','.join(map(str, r1)))\n# print(max(r1))\n\nprint()\n\nclass DateRangeContainerIterable:\n def __init__(self, start_date, end_date):\n self.start_date = start_date\n self.end_date = end_date\n\n def __iter__(self):\n current_day = self.start_date\n while current_day < self.end_date:\n yield current_day\n current_day += timedelta(days=1)\n\nr1 = DateRangeContainerIterable(date(2019, 1, 1), date(2019, 1, 5))\nprint(','.join(map(str, r1)))\nprint(max(r1))","repo_name":"woo1/cleancode","sub_path":"02_pythonic_code/iterable_obj.py","file_name":"iterable_obj.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39461833104","text":"import socket\nimport threading\n\nHOST = ''\nPORT = 2222\n\ndef create_connection(conn, addr):\n print('Connected by', addr, ' active clients: ', threading.active_count()-1)\n while 1:\n data = conn.recv(1024)\n txt_data = data.decode(\"UTF-8\").strip()\n print(txt_data)\n if not data:\n break\n elif txt_data.lower() == 'close':\n conn.send('dosvidos \\n'.encode())\n break\n else:\n conn.send(data)\n conn.close()\n print(\"Connection from \", addr, \" was closed\")\n return\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.bind((HOST, PORT))\ns.listen(1)\n\n\nwhile threading.active_count() < 12:\n conn, addr = s.accept()\n th = threading.Thread(target=create_connection, args=(conn,addr))\n th.start()\n","repo_name":"tsmee/study","sub_path":"servak.py","file_name":"servak.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38192844365","text":"dicionario = {\"batatafrita\": \"frenchfries\", \"hambúrguer\": \"hamburguer\", \"cocacola\": \"coke\",\n \"eu\": \"I\", \"quero\": \"want\", \"e\": \"and\", \"com\": \"with\", \"carne\": \"meat\", \"queijo\": \"cheese\", \"para\": \"for\", \"hoje\": \"today\", \"comer\": \"eat\"}\n\nfrase = 'eu quero comer hambúrguer com queijo e carne para hoje'\nx = []\n\ndef traduz_para_ingles(frase):\n frase_arr = frase.split()\n for palavra in frase_arr:\n for i in dicionario.keys():\n if palavra.lower() == i.lower():\n x.append(dicionario[i])\n\n return \" \".join(x)\n\ntraducao = traduz_para_ingles(frase)\nprint(traducao)","repo_name":"gubarbosa/prg2","sub_path":"tradutor.py","file_name":"tradutor.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33321760149","text":"import pathlib\n\n# Define o caminho do diretório onde os dados serão armazenados\ndiretorio_raiz = pathlib.Path(__file__).parent.parent\n\ndiretorio_config = diretorio_raiz.joinpath('config')\narquivo_config = diretorio_config.joinpath('noticias_ner.cfg')\narquivo_config_cnpj = diretorio_config.joinpath('cnpj.cfg')\n\ndiretorio_dados = diretorio_raiz.joinpath('dados')\narquivo_gerado_final = diretorio_dados.joinpath('com_empresas.xlsx')\n\narquivo_noticias_rotulado = diretorio_dados.joinpath('labeled_4_labels.jsonl')\ndiretorio_raiz_modelos = diretorio_dados.joinpath('modelos')\n\ndiretorio_modelo_neuralmind_bert_base = diretorio_raiz_modelos.joinpath('bert-neuralmind').joinpath('base')\nsubdiretorio_modelo_neuralmind_bert_base = diretorio_modelo_neuralmind_bert_base.joinpath(\n 'bert-base-portuguese-cased_pytorch_checkpoint')\nvocab_bert_base = diretorio_modelo_neuralmind_bert_base.joinpath('vocab.txt')\n\ndiretorio_modelo_neuralmind_bert_large = diretorio_raiz_modelos.joinpath('bert-neuralmind').joinpath('large')\nsubdiretorio_modelo_neuralmind_bert_large = diretorio_modelo_neuralmind_bert_large.joinpath(\n 'bert-large-portuguese-cased_pytorch_checkpoint')\nvocab_bert_large = diretorio_modelo_neuralmind_bert_large.joinpath('vocab.txt')\n\ndiretorio_modelo_bert_finetuned = diretorio_raiz_modelos.joinpath('bert-neuralmind-finetuned')\n\n# URL para a API/microserviço que encapsula a consulta a dados de CNPJ. A ideia é que no futuro esta solução possa ser\n# substituída, por exemplo, a alguma API do Solr do TCU ou da solução MAPA da STI.\nurl_api_cnpj_aberta = 'http://localhost:8090/cnpj_util/razao_social?q='\n","repo_name":"SecexSaudeTCU/noticias_ner","sub_path":"noticias_ner/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"pt","doc_type":"code","stars":14,"dataset":"github-code","pt":"48"} +{"seq_id":"38647255311","text":"import pandas as pd\nimport tensorflow as tf\nimport logging\ntf.get_logger().setLevel(logging.ERROR)\nfrom tensorflow.keras.layers import Reshape, UpSampling2D, InputLayer, Lambda, ZeroPadding2D, AveragePooling2D\nimport dataset_prep\nimport depth_prediction_net\nimport loss\nimport matplotlib.pyplot as plt\nimport cv2\nimport numpy as np\n\nfrom tensorflow.compat.v1 import ConfigProto\nfrom tensorflow.compat.v1 import InteractiveSession\n\nconfig = ConfigProto()\nconfig.gpu_options.allow_growth = True\nsession = InteractiveSession(config=config)\n\n\n\n\ndataset_train = '/home/xiaoliu/zed_camera/path_2/RGB'\nground_truth = '/home/xiaoliu/zed_camera/path_2/Depth'\nwidth = 320\nheight = 180\nbatch_size = 16\n\nget_dataset = dataset_prep.get_dataset()\nget_depth_net = depth_prediction_net.get_depth_net()\nget_loss = loss.get_loss()\n\n\ndef generate_and_save_images(model, test_sample):\n pre_2, pre_3, pre_4, pre_5, pre_6 , predictions = model.predict(test_sample)\n fig = plt.figure(figsize=(4, 4))\n # fig = plt.figure()\n\n for i in range(predictions.shape[0]):\n plt.subplot(4, 4, i + 1)\n plt.imshow(predictions[i, :, :, 0])\n plt.axis('off')\n # plt.savefig(str(i)+'.png')\n # plt.show()\n # plt.savefig('image_at_epoch_{:04d}.png'.format(epoch))\n plt.show()\n return predictions\n\n\n\ntest_sample, depth_sample = get_dataset.select_batch(dataset_train, ground_truth, 16)\n\nprint(\"here: \", test_sample.shape)\n\n# Recreate the exact same model, including its weights and the optimizer\nmodel = tf.keras.models.load_model('model_1_DispNet_autoencoder.h5', custom_objects={\n 'autoencoder_loss': get_loss.autoencoder_loss})\n# model = tf.keras.models.load_model('U-net_depth.h5', custom_objects={'autoencoder_loss': autoencoder_loss})\n# Show the model architecture\n# model.summary()\n\npredictions = generate_and_save_images(model, test_sample)\n\n\n\n\nfig = plt.figure(figsize=(4, 4))\n\nfor i in range(test_sample.shape[0]):\n plt.subplot(4, 4, i + 1)\n plt.imshow(test_sample[i, :, :, :])\n plt.axis('off')\n # plt.show()\nplt.show() # display!\n\n\nfig = plt.figure(figsize=(4, 4))\n# fig = plt.figure()\nfor j in range(depth_sample[-1].shape[0]):\n plt.subplot(4, 4, j + 1)\n # plt.imshow(depth_sample[j, :, :, 0], cmap='gray')\n plt.imshow(depth_sample[-1][j, :, :, 0])\n plt.axis('off')\n # plt.savefig(str(j)+'-D.png')\n # plt.show()\nplt.show() # display!\n\n\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import mean_squared_log_error\nfrom sklearn.metrics import mean_absolute_error\nfrom math import sqrt\nimport numpy as np\nfrom statistics import mean \n\nrms = []\nrms_log = []\nmse = []\nd1 = []\nd2 = []\nd3 = []\n\nfor i in range(predictions.shape[0]):\n gt = depth_sample[-1][i, :, :, 0]*(255/20)\n pred = predictions[i, :, :, 0]*(255/20)\n rms_temp = sqrt(mean_squared_error(gt, pred))\n rms.append(rms_temp)\n rms_log_temp = sqrt(mean_squared_log_error(gt, pred))\n rms_log.append(rms_log_temp)\n mse_temp = mean_absolute_error(gt, pred)\n mse.append(mse_temp)\n\n thresh = np.maximum((gt / pred), (pred / gt))\n d1_temp = (thresh < 1.25).mean()\n d2_temp = (thresh < 1.25 ** 2).mean()\n d3_temp = (thresh < 1.25 ** 3).mean()\n d1.append(d1_temp)\n d2.append(d2_temp)\n d3.append(d3_temp)\n\nprint(mean(rms), mean(rms_log), mean(mse), mean(d1), mean(d2), mean(d3) )\n\n\n\n\n\n\n\n","repo_name":"liuxiao1468/Depth_prediction_network","sub_path":"depth_codebase/result_visualization.py","file_name":"result_visualization.py","file_ext":"py","file_size_in_byte":3388,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"6540639261","text":"import pandas as pd\nimport argparse\n\ndef count_genes_by_GO(interproscan_file, eggnog_file):\n interproscan_df = pd.read_excel(interproscan_file)\n eggnog_df = pd.read_excel(eggnog_file)\n\n interproscan_df['GO annotations'] = interproscan_df['GO annotations'].apply(lambda x: x if isinstance(x, str) else '')\n eggnog_df['GOs'] = eggnog_df['GOs'].apply(lambda x: x if isinstance(x, str) else '')\n\n interproscan_df['GO annotations'] = interproscan_df['GO annotations'].fillna('')\n eggnog_df['GOs'] = eggnog_df['GOs'].fillna('')\n\n non_empty_genes_by_GO_interproscan = interproscan_df[interproscan_df['GO annotations'].apply(lambda x: x.strip() != '')]['qseqid'].nunique()\n non_empty_genes_by_GO_eggnog = eggnog_df[eggnog_df['GOs'].apply(lambda x: x.strip() != '-')]['query'].nunique()\n\n combined_df = pd.concat([interproscan_df, eggnog_df], ignore_index=True, sort=False)\n combined_df['GO annotations'] = combined_df['GO annotations'].fillna('')\n combined_df['GOs'] = combined_df['GOs'].fillna('')\n\n non_empty_genes_combined = combined_df[combined_df['GO annotations'].apply(lambda x: x.strip() != '') | combined_df['GOs'].apply(lambda x: x.strip() != '-')]['qseqid'].nunique()\n\n return non_empty_genes_by_GO_interproscan, non_empty_genes_by_GO_eggnog, non_empty_genes_combined\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Interproscan과 eggnog의 GO annotations를 결합하고 유전자 수를 세는 프로그램\")\n parser.add_argument(\"--interpro\", type=str, help=\"interproscan 결과가 담긴 Excel 파일 경로\")\n parser.add_argument(\"--eggnog\", type=str, help=\"eggnog 결과가 담긴 Excel 파일 경로\")\n args = parser.parse_args()\n\n interproscan_result, eggnog_result, combined_result = count_genes_by_GO(args.interpro, args.eggnog)\n\n print(\"Interproscan에서 GO annotations로 기록된 유전자 수:\", interproscan_result)\n print(\"Eggnog에서 GOs로 기록된 유전자 수:\", eggnog_result)\n print(\"중복되지 않은 유전자 총 개수:\", combined_result)\n","repo_name":"woojunbang/combine_annotation_report","sub_path":"combine_eggnog_interpro.py","file_name":"combine_eggnog_interpro.py","file_ext":"py","file_size_in_byte":2066,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18451219656","text":"import json\nfrom django.http import JsonResponse\n\nclass RatedSerializer():\n \"\"\"The movie rated class\"\"\"\n\n def serializeData(model):\n \"\"\"returns a json object of type Rated\"\"\"\n return {\n 'rated': {\n 'comment' : model.comment,\n 'rating' : model.rating,\n 'timestamp' : model.timestamp,\n },\n }\n\n def toJsonArray(node_set):\n \"\"\"Returns a json array containing Rated json objects\"\"\"\n ratings_dict = {}\n rating_list = []\n for rating in node_set:\n rating_list.append(json.dumps(RatedSerializer.serializeData(rating)))\n ratings_dict['ratings'] = rating_list\n\n return JsonResponse(ratings_dict)\n","repo_name":"Carlita99/Recommender-System-Application","sub_path":"API/app/moviesapi/serializers/ratedSerializer.py","file_name":"ratedSerializer.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17731184587","text":"from typing import List, Tuple\nfrom .cwn_annot_types import (\n AnnotCommit, AnnotRecord, \n AnnotError, AnnotAction, \n AnnotCategory)\nfrom CwnGraph import CwnGraphUtils\n\nPatchError = Tuple[AnnotError, str]\nclass CwnPatcher: \n def __init__(self, commit: AnnotCommit):\n self.commit = commit\n self.errors = []\n \n def patch(self, V, E, meta): \n tape: List[AnnotRecord] = self.commit.tape\n for annot_x in tape:\n if annot_x.annot_category.is_edge():\n self.patch_edge(V, E, annot_x)\n elif annot_x.annot_category.is_node():\n self.patch_node(V, annot_x)\n else:\n self.errors.append((AnnotError.UnknownAnnotCategory, annot_x.annot_category))\n\n def patch_edge(self, V, E, rec: AnnotRecord):\n if rec.annot_action == AnnotAction.Delete:\n if rec.cwn_id in E:\n del E[rec.cwn_id]\n else:\n self.errors.append((AnnotError.DeletionError, rec.cwn_id))\n elif rec.annot_action in (AnnotAction.Edit, AnnotAction.Create):\n edge_id = rec.cwn_id\n if edge_id[0] in V and edge_id[1] in V:\n E[edge_id] = rec.data\n else:\n self.errors.append((AnnotError.NodeIdNotFound, rec.cwn_id))\n\n else:\n self.errors.append((AnnotError.UnsupportedAnnotError, rec.annot_action))\n\n return E\n\n def patch_node(self, V, rec: AnnotRecord):\n if rec.annot_action == AnnotAction.Delete:\n if rec.cwn_id in V:\n del V[rec.cwn_id]\n else:\n self.errors.append((AnnotError.DeletionError, rec.cwn_id))\n elif rec.annot_action in (AnnotAction.Edit, AnnotAction.Create):\n V[rec.cwn_id] = rec.data\n else:\n self.errors.append((AnnotError.UnsupportedAnnotError, rec.annot_action))\n\n return V\n","repo_name":"lopentu/CwnAnnot","sub_path":"src/CwnAnnot/cwn_patcher.py","file_name":"cwn_patcher.py","file_ext":"py","file_size_in_byte":1931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20290278357","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Nov 28 20:47:39 2022\n\n@author: frank\n\"\"\"\n\nfrom db_actions import actions\nimport time\n\nclass actions_db_monday_burger(actions):\n \n def check_connect(self):\n if self._cn is not None:\n return True\n return False\n \n\n def insert_customer(self,fname,lname,birth,email,address):\n \n # check if connection exists\n if self.check_connect() == False:\n return -1 # no connection\n \n # check if customer exists \n # combination of firstname, lastname, birthdate\n chk_customer_query = '''select cu_id from customer \n where cu_firstname=%s and cu_lastname=%s and cu_birthdate=%s'''\n cr = self._cn.cursor()\n cr.execute(chk_customer_query,(fname,lname,birth))\n customer_id = -1\n for row in cr: # loop results\n customer_id=row[0] # first column from first row\n break # there should be only one row\n if customer_id != -1: # customer already exists\n cr.close()\n return customer_id\n \n # customer does not exist, so insert into database\n insert_customer_query = '''insert into customer\n (cu_firstname,cu_lastname,cu_email,cu_address,cu_birthdate) \n values(%s,%s,%s,%s,%s)'''\n cr.execute(insert_customer_query,(fname,lname,email,address,birth))\n self._cn.commit()\n # get last customer id\n get_last_id = '''select max(cu_id) from customer'''\n cr.execute(get_last_id,())\n customer_id = -1\n for row in cr:\n customer_id=row[0]\n break\n cr.close() # close db cursor\n return customer_id\n \n\n def insert_sales_order(self,customer_id,status):\n\n # check if connection exists\n if self.check_connect() == False:\n return False\n \n # insert sales_order\n insert_order_query = '''insert into sales_order (sa_customerid,sa_statusid) \n values(%s,(select st_id from status where st_name = %s))'''\n cr = self._cn.cursor()\n cr.execute(insert_order_query,(customer_id,status))\n self._cn.commit()\n \n # get last sales_order id (only PAID)\n get_last_sales_order_id = '''select max(sa_id) from sales_order where\n sa_statusid = 1'''\n cr.execute(get_last_sales_order_id,())\n sales_order_id = -1\n for row in cr:\n sales_order_id=row[0]\n break\n cr.close()\n return sales_order_id\n \n \n def insert_product_order(self,products,sales_order_id):\n \n # check if connection exists\n if self.check_connect() == False:\n return False\n \n # check valid order (PAID status)\n if sales_order_id <= 0:\n return False\n \n # insert product_order\n insert_product_order_query = '''\n insert into product_order(pro_sales_orderid,pro_productid,pro_quantity,pro_price) \n values(%s,\n (select pr_id from product where ucase(pr_name) = ucase(%s)),\n %s,\n (select %s*po_unitprice*po_salesfactor*po_taxfactor from purchase_order \n where po_productid = (select pr_id from product where ucase(pr_name) = ucase(%s))))'''\n update_stock_query = '''\n update purchase_order set po_stock = po_stock - %s \n where po_productid = (select pr_id from product where ucase(pr_name) = ucase(%s))\n '''\n cr = self._cn.cursor() \n for p in products:\n cr.execute(insert_product_order_query,\n (sales_order_id,p,products[p],products[p],p))\n self._cn.commit()\n cr.execute(update_stock_query, (products[p],p))\n self._cn.commit() \n cr.close()\n\n \n def update_order_status(self,sales_order_id,status):\n\n # check if connection exists\n if self.check_connect() == False:\n return False\n\n # update status\n update_status_query = '''update sales_order set sa_statusid = 3 where sa_id = %s'''\n if status == 'DELIVERED':\n update_status_query = update_status_query.replace('3','4')\n cr = self._cn.cursor()\n cr.execute(update_status_query,(sales_order_id,))\n self._cn.commit()\n cr.close()\n \n \n def get_product_stock(self,category_id):\n \n # check if connection exists\n data = []\n if self.check_connect() == False:\n return [data]\n \n # get product stock\n get_stock_query = '''select pr_name,po_stock from purchase_order,product \n where pr_id = po_productid and pr_categoryid = %s'''\n \n # time stocktake\n t=time.localtime()\n now = str(t.tm_hour) + \":\" + str(t.tm_min)\n cr = self._cn.cursor()\n cr.execute(get_stock_query,(category_id,))\n for row in cr:\n data.append(list(row))\n data[-1].insert(0,now) # add time of stocktake\n cr.close()\n return data\n \n ","repo_name":"effevee/data_sql_python_frankv","sub_path":"dbs_en_python/db_actions_monday_burger.py","file_name":"db_actions_monday_burger.py","file_ext":"py","file_size_in_byte":5165,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15982727555","text":"import matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Conv2D , MaxPool2D , Flatten , Dropout \nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.optimizers import Adam\n\nfrom sklearn.metrics import classification_report,confusion_matrix\n\nimport tensorflow as tf\n\nimport cv2\nimport os\n\nimport numpy as np\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' \n\nimg_size = 224\nlabels = ['cfunc', 'circle', 'ellipse', 'lfunc', 'mfunc', 'sfunc', 'rfunc']\nlabels_ret = [\"cubic function\", \"circle\", \"ellipse\", \"linear function\", \"reciprocal function\", \"parabolic function\", \"square root function\"]\n\ndef get_data(data_dir):\n '''\n Compiles data from /data\n '''\n\n data = [] \n for label in labels: \n path = os.path.join(data_dir, label)\n class_num = labels.index(label)\n for img in os.listdir(path):\n try:\n img_arr = cv2.imread(os.path.join(path, img))[...,::-1] \n resized_arr = cv2.resize(img_arr, (img_size, img_size)) \n data.append([resized_arr, class_num])\n except Exception as e:\n print(e)\n return np.array(data, dtype=object)\n\ndef get_data_user(path):\n '''\n Formats graph retrieved from user\n '''\n\n data = [] \n for img in os.listdir(path):\n try:\n img_arr = cv2.imread(os.path.join(path, img))[...,::-1] \n resized_arr = cv2.resize(img_arr, (img_size, img_size)) \n data.append(resized_arr)\n except Exception as e:\n print(e)\n return np.array(data, dtype=object)\n\ndef train():\n '''\n Trains model and saves to /model.\n '''\n\n train = get_data('data/train')\n val = get_data('data/test')\n\n x_train = []\n y_train = []\n x_val = []\n y_val = []\n\n for feature, label in train:\n x_train.append(feature)\n y_train.append(label)\n\n for feature, label in val:\n x_val.append(feature)\n y_val.append(label)\n\n x_train = np.array(x_train) / 255\n x_val = np.array(x_val) / 255\n\n x_train.reshape(-1, img_size, img_size, 1)\n y_train = np.array(y_train)\n\n x_val.reshape(-1, img_size, img_size, 1)\n y_val = np.array(y_val)\n\n datagen = ImageDataGenerator(\n featurewise_center=False, \n samplewise_center=False,\n featurewise_std_normalization=False, \n samplewise_std_normalization=False,\n zca_whitening=False, \n rotation_range = 30, \n zoom_range = 0.2, \n width_shift_range=0.1, \n height_shift_range=0.1, \n horizontal_flip = True, \n vertical_flip=False) \n\n datagen.fit(x_train)\n\n model = Sequential()\n model.add(Conv2D(32,3,padding=\"same\", activation=\"relu\", input_shape=(224,224,3)))\n model.add(MaxPool2D())\n\n model.add(Conv2D(32, 3, padding=\"same\", activation=\"relu\"))\n model.add(MaxPool2D())\n\n model.add(Conv2D(64, 3, padding=\"same\", activation=\"relu\"))\n model.add(MaxPool2D())\n model.add(Dropout(0.4))\n\n model.add(Flatten())\n model.add(Dense(128,activation=\"relu\"))\n model.add(Dense(7, activation=\"softmax\"))\n\n model.summary()\n\n opt = Adam(lr=0.000001)\n model.compile(optimizer = opt , loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) , metrics = ['accuracy'])\n history = model.fit(x_train,y_train,epochs = 250 , validation_data = (x_val, y_val))\n\n model.save('model')\n\ndef use_model():\n '''\n Calls on saved model in /model and retrieves best answers.\n '''\n \n model_r = keras.models.load_model(\"model\")\n\n data = get_data_user('user')\n data = np.array(data) / 255\n data.reshape(-1, img_size, img_size, 1)\n data = np.asarray(data).astype(np.float32)\n data = tf.convert_to_tensor(data)\n predict = model_r.predict(data)\n \n likely = sorted(list(predict[0]))[-3:]\n likely.reverse()\n print()\n for i in likely:\n print(\"{} - {}\".format(labels_ret[list(predict[0]).index(i)], i))\n\ndef user_input():\n '''\n Get user input for equation\n '''\n\n other = input(\"If circle, ellipse, square root equations, enter [y]es: \")\n\n fig, axes = plt.subplots()\n \n axes.set_aspect( 1 )\n\n if other in ['y', 'yes']:\n params1 = input(\"Enter [y]es if circle or ellipse: \")\n if params1 in ['y', 'yes']:\n eq = input(\"Enter a equation for the ai to guess as (y = ) in terms of x without the sqrt: \").lower()\n x = np.linspace(-10, 10, 101)\n y = np.linspace(-10, 10, 101)\n with np.errstate(divide='ignore', invalid='ignore'):\n c, d, r = map(int, input(\"Give coef of first two terms and r separated by spaces: \").strip().split(\" \"))\n a, b = np.meshgrid( x , y )\n C = (a ** 2)/c + (b ** 2)/d - r\n axes.contour(a, b, C, [0])\n else:\n eq = input(\"Enter the the equation in (y = ) without the square root: \")\n x = np.linspace(-10, 10, 101)\n with np.errstate(divide='ignore', invalid='ignore'):\n y = np.sqrt(eval(eq))\n plt.plot(x, y)\n else:\n eq = input(\"Enter a equation for the ai to guess as (y = ) in terms of x: \").lower()\n x = np.linspace(-10, 10, 101)\n with np.errstate(divide='ignore', invalid='ignore'):\n y = eval(eq)\n plt.plot(x, y)\n\n fig.savefig('user/graph.png')\n print()\n\ndef run():\n '''\n Call all functions to run the script\n '''\n \n get_train = input(\"Train model? WARNING takes at least 6 hours depending on computer. If not, use given saved model. [y]es/[n]o: \").lower()\n print()\n if get_train == \"y\":\n train()\n \n user_input()\n use_model()\n\nrun()","repo_name":"calebyhan/CalebHan","sub_path":"Projects and Applications/functions_cnn/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5790,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"5086812616","text":"caballos = [\"Spirit\",\"Troya\",\"Pegazo\",\"Imperiozo\",\"Jumper\",\"Babieca\",\"Rocinante\", \"pegazo\"]\ncaballos_pedro = {}\ncaballos_pablo = {}\nresultado = \"\"\n\n\nfor caballo in caballos:\n\n victorias_ganadas = int(input(\"victorias de {}, a favor de pedro: \".format(caballo)))\n \n caballos_pedro[caballo[0]]=victorias_ganadas\n\nprint(\"\")\n\nfor caballo in caballos:\n\n victorias_ganadas = int(input(\"victorias de {}, a favor de pablo: \".format(caballo)))\n \n caballos_pablo[caballo[0]]=victorias_ganadas\n\nprint(caballos_pedro)\n\n\n\nfor clave in caballos_pablo:\n if caballos_pablo[clave] == caballos_pedro[clave]:\n resultado += \"z\"\n elif caballos_pablo[clave] > caballos_pedro[clave]:\n resultado += \"y\"\n else:\n resultado += \"x\"\n\n\nprint(resultado)\n","repo_name":"dperezc21/ejercicios","sub_path":"ejercicio/carrera de caballos.py","file_name":"carrera de caballos.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2920956491","text":"import autograd.numpy as np\nfrom autograd import jacobian\nimport matplotlib.pyplot as plt\n\n\ndef payoff_call(x, strike):\n return np.maximum(x - strike, 0.0)\n\n\ndef payoff_id(x, strike):\n return x\n\n\ndef sim_gbm(N, t, spot, strike, drift, vol, func, seed=None):\n M = len(t)\n dt = np.diff(t, axis=0)\n rng = np.random.default_rng(seed=seed)\n Z = rng.normal(loc=0.0, scale=1.0, size=(M-1, N))\n\n W = np.cumsum(np.concatenate([\n np.zeros(shape=(1, N)), np.sqrt(dt) * Z\n ]), axis=0)\n\n S = spot * np.exp((drift - 0.5 * vol ** 2) * t + vol * W)\n return func(S, strike)\n\n\nif __name__ == '__main__':\n seed = 1234\n N = 1000\n M = 52\n t0 = 0.0\n T = 1.0\n spot = 100.0\n strike = 100.0\n drift = 0.03\n vol = 0.2\n\n t = np.linspace(t0, T, M+1, True).reshape(-1, 1)\n\n from datetime import datetime\n\n start = datetime.now()\n S = sim_gbm(N, t, spot, strike, drift, vol, payoff_id, seed)\n stop = datetime.now()\n print(stop - start)\n\n start = datetime.now()\n dCdS = jacobian(sim_gbm, argnum=2)(N, t, spot, strike, drift, vol, payoff_call, seed)\n dCddrift = jacobian(sim_gbm, argnum=4)(N, t, spot, strike, drift, vol, payoff_call, seed)\n dCdvol = jacobian(sim_gbm, argnum=5)(N, t, spot, strike, drift, vol, payoff_call, seed)\n stop = datetime.now()\n print(stop - start)\n\n plt.scatter(S, dCdS, color='gray', alpha=.1)\n plt.show()\n\n\n","repo_name":"KennoCapital/CenterfoldCapital","sub_path":"application/experiments/test_of_AutoDiff_packages/black_scholes_pathwise_sens_autograd_numpy.py","file_name":"black_scholes_pathwise_sens_autograd_numpy.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"37894999640","text":"import json\nimport time\n\nfrom src.preprocessing.WikisourceQuerySender import WikisourceQuerySender\n\n# add_filter = [\"An Outpost of Progress\", \"The Machine Stops\", \"The Merry Men\", \"Rogues in the House\", \"Markheim\",\n# \"The Tower of the Elephant\", \"The Pool of the Black One\", \"The Story of Mimi-Nashi-H\\u014d\\u00efchi\",\n# \"Xuthal of the Dusk\", \"The Merry Men and Other Tales and Fables\", \"Black Colossus\",\n# \"Beyond the Black River\", \"The King of the Golden River\"]\n# # Files that could not have been read correctly for some reason, listed manually to exclude them from the dataset.\n\n\nclass DatasetCollector:\n\n @staticmethod\n def main(data_path, raw_query_path, filtered_path=None):\n sender = WikisourceQuerySender()\n with open(data_path, \"rb\") as f_data:\n data = json.load(f_data)\n titles = set([item[\"title\"] for item in data])\n\n filtered_titles = {}\n if filtered_path:\n with open(filtered_path, \"rb\") as filtered:\n filtered_titles = set(json.load(filtered))\n\n with open(raw_query_path, \"rb\") as fq:\n book_names = json.load(fq)\n for entry in book_names:\n next_command = input()\n if next_command == \"q\":\n break\n\n title = entry[\"itemLabel\"]\n if title in titles:\n print(f\"{title} already loaded\")\n continue\n elif title in filtered_titles:\n print(f\"Can't load {title}\")\n continue\n\n entry_parsed = sender.parse(entry=entry)\n print(entry_parsed)\n if entry_parsed:\n data.append(entry_parsed)\n else:\n filtered_titles.add(title)\n\n time.sleep(1) # so we don't DoS/get timed out by Wikisource\n\n with open(data_path, \"w\") as f_data:\n json.dump(data, f_data, indent=4)\n\n # Update the list of title our program was unable to read.\n with open(filtered_path, \"w\") as f_filtered:\n json.dump(list(filtered_titles), f_filtered, indent=1)\n","repo_name":"quantumFeline/fiction-chronological-dating","sub_path":"src/preprocessing/DatasetCollector.py","file_name":"DatasetCollector.py","file_ext":"py","file_size_in_byte":2200,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7538542","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\nimport sys\nimport os\nimport configparser\n\ndef 清空目录 (path):\n os.system(\"rd /s /Q \\\"\"+ path + \"\\\"\")\n if os.path.exists(path)==False:\n os.makedirs(path)\n \n \n return\ndef 复制目录 (path,pathGoTo):\n os.system(\"xcopy \\\"\"+ path+\"\\\" \\\"\" + pathGoTo + \"\\\" /Q /Y /H /R /E\")\n return\ndef 挂载配置单元 (FileName,KeyName):\n os.system (\"reg load \"+KeyName+\" \\\"\"+FileName+\"\\\"\")\n return\ndef 卸载配置单元 (KeyName):\n os.system (\"reg unload \"+KeyName)\n return\ndef 导入注册表项 (FileName):\n os.system (\"reg import \\\"\"+FileName+\"\\\"\")\n return\ndef 复制注册表项 (KeyName,toKeyName):\n os.system (\"reg copy \\\"\"+KeyName+\"\\\" \\\"\"+toKeyName+\"\\\" /S /F\")\n return \n\nos.system(\"title HotPE生成脚本\")\n\n\n运行目录 = os.path.split( os.path.realpath( sys.argv[0] ) )[0] + \"\\\\\"\n执行文件名 =sys.argv[0]\n\n# 初始化\nPE配置 = configparser.ConfigParser()\n\n# 读取配置文件\nPE配置.read(运行目录 +'PE_config.txt', encoding='ANSI')\n\nprint(\"正在清理文件\")\n清空目录 (运行目录 + \"TempFile\\\\apply\")\n清空目录 (运行目录 + \"TempFile\\\\config\")\n\n\n\n光驱盘符 = input (\"输入虚拟光驱盘符(不加冒号):\")\ninstallWim = 光驱盘符 + \":\\\\sources\\\\install.wim\"\nbootWim = 光驱盘符 + \":\\\\sources\\\\boot.wim\"\nboot分卷 = PE配置.get('wim', 'boot分卷')\ninstall分卷 = PE配置.get('wim', 'install分卷')\nwimlibImagex= 运行目录 + \"Bin\\\\Tools\\\\wimlib\\\\wimlib-imagex.exe\"\n\nprint(\"正在从boot.wim提取文件\")\n\nos.system(wimlibImagex+\" apply \"+bootWim+\" \"+str(boot分卷)+\" \"+运行目录+\"TempFile\\\\apply\")\n\nprint(\"正在从boot.wim提取Cat文件\")\n清空目录 (运行目录 + \"TempFile\\\\apply\\\\Windows\\\\System32\\\\CatRoot\\\\{127D0A1D-4EF2-11D1-8608-00C04FC295EE}\\\\\")\n清空目录 (运行目录 + \"TempFile\\\\apply\\\\Windows\\\\System32\\\\CatRoot\\\\{F750E6C3-38EE-11D1-85E5-00C04FC295EE}\\\\\")\nos.system(wimlibImagex+\" extract \"+bootWim+\" \"+str(boot分卷)+\" @\"+运行目录+\"Bin\\\\Files\\\\Cat.txt \"+\"--dest-dir=\"+运行目录+\"TempFile\\\\apply \"+\" --nullglob --no-acls\")\n\nprint(\"正在清理WinSxS文件\")\n清空目录 (运行目录 + \"TempFile\\\\apply\\\\Windows\\\\WinSxS\\\\\")\n\nprint(\"正在从install.wim提取文件\")\n#os.system(wimlibImagex+\" extract \"+installWim+\" \"+str(install分卷)+\" \\Windows\\System32\\Recovery\\winre.wim \"+\"--dest-dir=\"+运行目录+\"TempFile\\\\ \"+\" --nullglob --no-acls\")\nos.system(wimlibImagex+\" extract \"+installWim+\" \"+str(install分卷)+\" @\"+运行目录+\"Bin\\\\Files\\\\install.txt \"+\"--dest-dir=\"+运行目录+\"TempFile\\\\apply \"+\" --nullglob --no-acls\")\n\nprint(\"正在从删除无用文件\")\nfor line in open(运行目录+\"Bin\\\\Files\\\\delFiles.txt\", \"r\"): #打开文件\n rs = line.rstrip('\\n') # 移除行尾换行符\n if os.path.isfile(运行目录+\"TempFile\\\\apply\\\\\"+rs):\n os.system(\"del \"+运行目录+\"TempFile\\\\apply\\\\\"+rs+\" /F /Q\")\n if os.path.isdir(运行目录+\"TempFile\\\\apply\\\\\"+rs):\n os.system(\"rd \"+运行目录+\"TempFile\\\\apply\\\\\"+rs+\" /S /Q\")\n\nfor line in open(运行目录+\"Bin\\\\Files\\\\delFilesMore.txt\", \"r\"): #打开文件\n rs = line.rstrip('\\n') # 移除行尾换行符\n if os.path.isfile(运行目录+\"TempFile\\\\apply\\\\\"+rs):\n os.system(\"del \"+运行目录+\"TempFile\\\\apply\\\\\"+rs+\" /F /Q\")\n if os.path.isdir(运行目录+\"TempFile\\\\apply\\\\\"+rs):\n os.system(\"rd \"+运行目录+\"TempFile\\\\apply\\\\\"+rs+\" /S /Q\")\n\nfor line in open(运行目录+\"Bin\\\\Files\\\\delFilesMore(drivers).txt\", \"r\"): #打开文件\n rs = line.rstrip('\\n') # 移除行尾换行符\n if os.path.isfile(运行目录+\"TempFile\\\\apply\\\\\"+rs):\n os.system(\"del \"+运行目录+\"TempFile\\\\apply\\\\\"+rs+\" /F /Q\")\n if os.path.isdir(运行目录+\"TempFile\\\\apply\\\\\"+rs):\n os.system(\"rd \"+运行目录+\"TempFile\\\\apply\\\\\"+rs+\" /S /Q\")\n\nfor line in open(运行目录+\"Bin\\\\Files\\\\clearDir.txt\", \"r\"): #打开文件\n rs = line.rstrip('\\n') # 移除行尾换行符\n 清空目录(运行目录+\"TempFile\\\\apply\\\\\"+rs)\n \nprint(\"正在从install.wim提取注册表文件:system,drivers\")\nos.system(wimlibImagex+\" extract \"+installWim+\" \"+str(install分卷)+\" \\Windows\\System32\\config\\system \"+\"--dest-dir=\"+运行目录+\"TempFile\\\\config \"+\" --nullglob --no-acls\")\nos.system(wimlibImagex+\" extract \"+installWim+\" \"+str(install分卷)+\" \\Windows\\System32\\config\\drivers \"+\"--dest-dir=\"+运行目录+\"TempFile\\\\config \"+\" --nullglob --no-acls\")\n\nprint(\"正在添加文件:AddFiles\\*\")\n复制目录(运行目录+\"AddFiles\",运行目录+\"TempFile\\\\apply\")\n\nprint(\"正在挂载配置单元\")\n挂载配置单元 (运行目录+\"TempFile\\\\config\\\\drivers\",\"hklm\\os_drv\")\n挂载配置单元 (运行目录+\"TempFile\\\\config\\\\system\",\"hklm\\os_sys\")\n挂载配置单元 (运行目录+\"TempFile\\\\apply\\\\windows\\\\system32\\\\config\\\\default\",\"hklm\\pe_def\")\n挂载配置单元 (运行目录+\"TempFile\\\\apply\\\\windows\\\\system32\\\\config\\\\software\",\"hklm\\pe_soft\")\n挂载配置单元 (运行目录+\"TempFile\\\\apply\\\\windows\\\\system32\\\\config\\\\system\",\"hklm\\pe_sys\")\n挂载配置单元 (运行目录+\"TempFile\\\\apply\\\\windows\\\\system32\\\\config\\\\DRIVERS\",\"hklm\\pe_drv\")\n\nprint(\"正在导入注册表项\")\n\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\SOFT_精简注册表.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\CMD字体和透明.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\explorer.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\HDTunePro.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\pe_def.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\pe_soft.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\Pecmd.ini.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\StartIsBack_浅.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\Windows颜色模式浅.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\打开HotPE模块.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\任务管理器默认详细信息.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\任务栏合并按钮.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\任务栏图标.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\鼠标指针.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\开始菜单不显示搜索.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\开始菜单不显示最近打开项.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\控制面板界面.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\控制面板删除管理工具.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\控制面板删除任务栏和导航.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\控制面板删除设备和打印机.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\控制面板删除无效图标.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\控制面板删除字体.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\删除右键3D Edit.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\删除右键包含到库.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\删除右键个性化和显示设置.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\删除右键恢复到之前版本.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\删除右键设为壁纸.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\删除资源管理器内桌面等文件夹.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\视觉效果.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\修复此电脑右键管理.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\隐藏3D对象等文件夹.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\隐藏导航窗格.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\隐藏开始菜单启动和管理工具.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\隐藏映射网络驱动器.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\隐藏3D对象等文件夹.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\电源键默认重启.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\计算机属性.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\绕过TPM检测.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\右键用记事本打开文件.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\右键显示设置.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\HashTab.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\WinX开机动画.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\7-ZIP.reg\")\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\7-Zip-Zstandard.reg\")\n\n\nprint(\"正在修改C:\\\\为X:\\\\\")\nos.system(运行目录 + \"Bin\\\\Tools\\\\regfind.exe\"+\" -p HKEY_LOCAL_MACHINE\\\\pe_soft -y C:\\\\ -y -r X:\\\\\")\n\nprint(\"正在处理Interactive User\")\nos.system(运行目录 + \"Bin\\\\Tools\\\\regfind.exe\"+\" -p HKEY_LOCAL_MACHINE\\\\pe_soft\\Classes\\AppID -y Interactive User -r\")\n\nprint(\"复制必要的SYSTEM注册表到PE\")\nfor line in open(运行目录+\"\\\\Bin\\\\RegistryFiles\\\\pe_sys.txt\", \"r\"): #打开文件\n rs = line.rstrip('\\n') # 移除行尾换行符\n 复制注册表项(\"hklm\\\\os_sys\\\\\"+rs,\"hklm\\\\pe_sys\\\\\"+rs)\n\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\pe_sys.reg\")\n\nprint(\"复制必要的drivers注册表到PE\")\nfor line in open(运行目录+\"\\\\Bin\\\\RegistryFiles\\\\pe_drv.txt\", \"r\"): #打开文件\n rs = line.rstrip('\\n') # 移除行尾换行符\n 复制注册表项(\"hklm\\\\os_drv\\\\\"+rs,\"hklm\\\\pe_drv\\\\\"+rs)\n\nos.system(运行目录 + \"copyDriver.bat\")\n\n导入注册表项 (运行目录 + \"Bin\\\\RegistryFiles\\\\pe_drv.reg\") \n\nprint(\"正在修改图标\")\nif os.path.exists(运行目录+\"TempFile\\\\apply\\\\Windows\\\\System32\\\\imageres.dll\"):\n os.system(\"copy \\\"\"+运行目录+\"TempFile\\\\apply\\\\Windows\\System32\\\\imageres.dll\\\" \\\"\"+运行目录+\"Bin\\\\imageres_dll\\\\imageres.dll\\\"\")\n os.system(运行目录 + \"Bin\\\\imageres_dll\\\\cmd.bat\")\n os.system(\"del \"+运行目录+\"TempFile\\\\apply\\\\windows\\\\system32\\\\imageres.dll /F /S /Q\")\n os.system(\"del \"+运行目录+\"TempFile\\\\apply\\\\windows\\\\SysWOW64\\\\imageres.dll /F /S /Q\")\n os.system(\"copy \\\"\"+运行目录+\"Bin\\\\imageres_dll\\\\new_imageres.dll\\\" \\\"\"+运行目录+\"TempFile\\\\apply\\\\windows\\\\system32\\\\imageres.dll\\\"\")\n os.system(\"copy \\\"\"+运行目录+\"Bin\\\\imageres_dll\\\\new_imageres.dll\\\" \\\"\"+运行目录+\"TempFile\\\\apply\\\\windows\\\\SysWOW64\\\\imageres.dll\\\"\")\n #os.system(\"del \"+运行目录+\"TempFile\\\\imageres32.dll /F /S /Q\")\n #os.system(\"del \"+运行目录+\"TempFile\\\\temp_imageres32.dll /F /S /Q\")\n #os.system(\"del \"+运行目录+\"TempFile\\\\new_imageres32.dll /F /S /Q\")\n\nprint(\"正在卸载配置单元\")\n卸载配置单元 (\"hklm\\os_drv\")\n卸载配置单元 (\"hklm\\os_sys\")\n卸载配置单元 (\"hklm\\pe_def\")\n卸载配置单元 (\"hklm\\pe_soft\")\n卸载配置单元 (\"hklm\\pe_sys\")\n卸载配置单元 (\"hklm\\pe_drv\")\n\nos.system(\"del /f /q /ah \\\"\" + 运行目录 + \"TempFile\\\\apply\\\\Windows\\\\System32\\\\config\\\\*.*\\\"\")\n\nprint(\"正在破解USB弹出功能文件\")\nos.system(运行目录 +\"Bin\\\\Tools\\\\binmay.exe -u \\\"\" + 运行目录 + \"TempFile\\\\apply\\\\Windows\\\\System32\\\\DeviceSetupManager.dll\\\" -s u:SystemSetupInProgress -r u:DisableDeviceSetupMgr\")\n\nprint(\"正在删除dll备份文件\")\nos.system(\"del \\\"\" + 运行目录 + \"TempFile\\\\apply\\\\Windows\\\\System32\\\\DeviceSetupManager.dll.org\\\"\")\n\nprint(\"正在打包成Kernel.wim\")\nos.system(wimlibImagex+\" capture \\\"\" + 运行目录 + \"TempFile\\\\apply\\\" \\\"\"+运行目录+\"\\\\Kernel.wim\\\" \\\"HotPE\\\" --boot --compress=lzx --rebuild\")\n\nprint(\"正在打包成ISO\")\nos.system(\"del \"+运行目录+\"TempFile\\\\ISO\\\\HotPE\\\\Kernel.wim /F /S /Q\")\nos.system(\"copy \\\"\"+运行目录+\"Kernel.wim\\\" \\\"\"+运行目录+\"TempFile\\\\ISO\\\\HotPE\\\\Kernel.wim\\\"\")\nos.system(运行目录 +\"Bin\\\\Tools\\\\oscdimg.exe -m -o -u2 -udfver102 -h -bootdata:2#p0,e,b\"+运行目录+\"Bin\\\\Tools\\\\Etfsboot.com#pEF,e,b\"+���行目录+\"Bin\\\\Tools\\\\Efisys.bin -l\\\"HotPE工具箱\\\" \"+运行目录+\"TempFile\\\\ISO\\\\ \"+运行目录+\"HotPE工具箱.iso\")\n\ninput(\"构建结束,回车启动虚拟机测试\")\nos.system(运行目录 + \"启动虚拟机测试.bat\")\n","repo_name":"mrliu714/HotPEToolsBox","sub_path":"main.PY","file_name":"main.PY","file_ext":"py","file_size_in_byte":12411,"program_lang":"python","lang":"zh","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"22438259500","text":"class Solution:\n def search(self, nums, target):\n nums = self.removeDuplicates(nums)\n start, end = 0, len(nums) - 1\n\n while start <= end:\n mid = int((start + end) / 2)\n if nums[start] == target or nums[end] == target or nums[mid] == target:\n return True\n if nums[end] < target < nums[start]:\n return False\n if nums[end] > nums[start]:\n if nums[mid] > target:\n end = mid - 1\n else:\n start = mid + 1\n elif nums[start] < nums[mid]:\n if nums[mid] < target or nums[end] > target:\n start = mid + 1\n elif nums[start] < target:\n end = mid - 1\n continue\n else:\n if nums[mid] > target or nums[start] < target:\n end = mid - 1\n elif nums[end] > target:\n start = mid + 1\n continue\n\n return False\n\n def removeDuplicates(self, nums):\n res = []\n for v in nums:\n if not res or v != res[-1]:\n res.append(v)\n return res\n\n\nif __name__ == '__main__':\n solution = Solution()\n print(solution.search([1, 1, 2, 1], 2))\n","repo_name":"MadSkittles/leetcode","sub_path":"81.py","file_name":"81.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"28056781863","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Nov 9 12:24:14 2019\n\n@author: TrevorMorrisey\n\"\"\"\n\nimport peUtilities\n\ndef distinctPrimeFactors(factorCount):\n counter = 2\n while True:\n factors = peUtilities.getFactors(counter)\n primeFactors = countPrimes(factors)\n if primeFactors >= factorCount:\n allFactor = True\n for i in range(counter, counter + factorCount):\n factors = peUtilities.getFactors(i)\n primeFactors = countPrimes(factors)\n if primeFactors < factorCount:\n allFactor = False\n if allFactor:\n return counter\n counter += 1\n \ndef countPrimes(numList):\n count = 0\n for num in numList:\n if peUtilities.isPrime(num):\n count += 1\n return count","repo_name":"TrevorMorrisey/Project-Euler","sub_path":"Python/pe047.py","file_name":"pe047.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25173516203","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport argparse\nimport os\nfrom cudnn_record import cudnnTrace\nimport pickle\nfrom tqdm import tqdm\n\ndef main():\n\n parser = argparse.ArgumentParser(\n description=\"collect cudnn runtime information\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('input_dir', help=\"directory contains trace files\")\n parser.add_argument('--suffix', help=\"trace file suffix\",\n default=\".pkl\")\n\n args = parser.parse_args()\n\n for root, dirs, files in os.walk(args.input_dir):\n for input_file in files:\n if args.suffix in input_file:\n\n with open(os.path.join(root, input_file), 'rb') as f:\n cudnn_trace_list = pickle.load(f)\n\n trace_len = len(cudnn_trace_list)\n\n if trace_len == 0:\n continue\n\n for i in tqdm(range(trace_len), desc=input_file):\n if not cudnn_trace_list[i].runtime_info:\n cudnn_trace_list[i].collect_runtime_info()\n\n if i % 100 == 0:\n with open(os.path.join(root, input_file), 'wb') as f:\n pickle.dump(cudnn_trace_list, f)\n\n with open(os.path.join(root, input_file), 'wb') as f:\n pickle.dump(cudnn_trace_list, f)\n\nif __name__ == '__main__':\n main()\n","repo_name":"GD06/cudnn-tuning","sub_path":"collect_runtime_info.py","file_name":"collect_runtime_info.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"11659572067","text":"from app import app\nfrom lib.dropbox import DropboxApi\nfrom lib import auth\nfrom lib import errors\nimport models.user\nfrom flask import jsonify, request, g\nimport jwt\nimport re\n\n@app.route('/api/authorize/url', methods=['GET'])\ndef authorize():\n session = {}\n dropbox = DropboxApi()\n redirect_url = dropbox.dropbox_auth_start(app.config, session)\n return jsonify(url=redirect_url, csrf_token=session[\"dropbox-auth-csrf-token\"].decode(\"utf-8\"))\n\n@app.route('/api/authorize/finalize', methods=['POST'])\ndef finalize():\n session = {'dropbox-auth-csrf-token': request.json['csrf_token']}\n query = {'state': request.json['csrf_token'], 'code': request.json['code']}\n dropbox = DropboxApi()\n access_token, user_id, _ = dropbox.dropbox_auth_finish(app.config, session, query)\n user_info = dropbox.get_user_info(access_token)\n if user_info[\"verified\"] is False:\n raise errors.AppException(errors.DROPBOX_EMAIL_NOT_VERIFIED)\n user_id = models.user.create_or_find_user({\"dropbox_access_token\": access_token, \"dropbox_user_id\": user_id, **user_info})\n encoded = jwt.encode({\"user_id\": str(user_id)}, app.config[\"TOKEN_SECRET\"], algorithm='HS256')\n return jsonify(token=encoded.decode('utf-8'))\n\n@app.route('/api/authorize/key', methods=['POST'])\ndef authByKey():\n key = request.json['key']\n if re.match(\"^[A-Za-z-]+$\", key) is None or len(key) > 40:\n raise errors.AppException(errors.KEY_NOT_FOUND)\n user_info = models.user.find_user_by_api_key(key)\n if user_info is None:\n raise errors.AppException(errors.KEY_NOT_FOUND)\n encoded = jwt.encode({\"user_id\": str(user_info[\"_id\"])}, app.config[\"TOKEN_SECRET\"], algorithm='HS256')\n return jsonify(token=encoded.decode('utf-8'))\n\n@app.route('/api/authorize/info', methods=['GET'])\n@auth.auth_required\ndef get_user_info():\n return jsonify({\n \"name\": g.user[\"first_name\"] + \" \" + g.user[\"last_name\"],\n \"email\": g.user[\"email\"],\n \"settings\": g.user.get(\"settings\"),\n })\n\n@app.route('/api/user/settings', methods=['POST'])\n@auth.auth_required\ndef save_user_settings():\n settings = request.json\n models.user.save_settings(g.user[\"_id\"], settings)\n return jsonify({})\n","repo_name":"mb-dev/plan-my-time","sub_path":"api/controllers/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":2210,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"70712487506","text":"\nfrom Crypto.Hash import SHA256\nfrom Crypto.Signature import PKCS1_v1_5\nfrom Crypto.PublicKey import RSA\nfrom Crypto.Random import get_random_bytes\nfrom Crypto.Cipher import AES, PKCS1_OAEP\n\n# This function is implemented to sign the certificate by server\n# returns the signed certificate\n\n\ndef sign(user_name):\n with open(f\"{user_name}_public.txt\", \"r\") as public_txt:\n user_public_key = public_txt.read()\n \n sha_digest = SHA256.new()\n sha_digest.update(user_public_key.encode('utf-8'))\n\n with open(f\"server_private.pem\", \"r\") as private_pem:\n private_key = RSA.import_key(private_pem.read())\n\n sign_pkcs = PKCS1_v1_5.new(private_key)\n certificate = sign_pkcs.sign(sha_digest)\n\n print(f\"Signed certificate digest {certificate.hex()}\")\n return certificate\n\n# This function is implemented to verify the signed certificate\n\n\ndef verify(user_name, certificate):\n with open(f\"{user_name}_public.txt\", \"r\") as public_txt:\n user_public_key = public_txt.read()\n \n sha_digest = SHA256.new()\n sha_digest.update(user_public_key.encode('utf-8'))\n\n with open(f\"server_public.txt\", \"r\") as public_txt:\n public_key = RSA.import_key(public_txt.read())\n\n verify_pkcs = PKCS1_v1_5.new(public_key)\n\n is_verified = verify_pkcs.verify(sha_digest, certificate)\n\n return is_verified\n\n\ndef generate_keys(user_name):\n key = RSA.generate(2048)\n\n f = open(f'{user_name}_private.pem', 'wb')\n f.write(key.export_key('PEM'))\n f.close()\n\n public_key = key.publickey().export_key()\n\n f = open(f'{user_name}_public.txt', 'wb')\n f.write(public_key)\n f.close()\n\ndef save_certificate(user_name, certificate_hex):\n f = open(f'{user_name}_certificate.txt', 'w')\n print(certificate_hex)\n f.write(certificate_hex)\n f.close()\n\ndef import_certificate(user_name):\n with open(f\"{user_name}_certificate.txt\", \"r\") as hex_txt:\n hex = hex_txt.read()\n \n certificate = bytes.fromhex(hex)\n\n return certificate\n\ndef encrypt_text(file_name, public_key, data):\n # open the file to write into\n file_out = open(file_name, \"wb\")\n # generate random session key\n session_key = get_random_bytes(16)\n\n # Encrypt the session key with the public RSA key\n cipher_rsa = PKCS1_OAEP.new(public_key)\n enc_session_key = cipher_rsa.encrypt(session_key)\n\n # Encrypt the data with the AES session key\n cipher_aes = AES.new(session_key, AES.MODE_EAX)\n # encrypt\n ciphertext, tag = cipher_aes.encrypt_and_digest(data)\n # write into file\n [ file_out.write(x) for x in (enc_session_key, cipher_aes.nonce, tag, ciphertext) ]\n file_out.close()\n\ndef decrypt_text(file_name, private_key):\n # open the file that we will read up on\n file_in = open(file_name, \"rb\")\n\n # get the details from the file\n enc_session_key, nonce, tag, ciphertext = \\\n [ file_in.read(x) for x in (private_key.size_in_bytes(), 16, 16, -1) ]\n\n # Decrypt the session key with the private RSA key\n cipher_rsa = PKCS1_OAEP.new(private_key)\n # get session key as prior for the decrypt & verify\n session_key = cipher_rsa.decrypt(enc_session_key)\n\n # Decrypt the data with the AES session key\n cipher_aes = AES.new(session_key, AES.MODE_EAX, nonce)\n # decrypt\n data = cipher_aes.decrypt_and_verify(ciphertext, tag).decode(\"utf-8\")\n\n return data\n\n# to uncomment: Select all commanded line and press \"ctrl\" + \"/\"\n\n#-------------------------------------------------------------------------------\n# for 3rd Question\n\n# import random\n#\n# class Key:\n#\n# \tdef __init__(self, key=''):\n# \t\tif key == '':\n# \t\t\tself.key= self.generate()\n# \t\telse:\n# \t\t\tself.key = key.lower()\n#\n# \tdef verify(self):\n# \t\tscore = 0\n# \t\tcheck_digit = self.key[0]\n# \t\tcheck_digit_count = 0\n# \t\tchunks = self.key.split('-')\n# \t\tfor chunk in chunks:\n# \t\t\tif len(chunk) != 4:\n# \t\t\t\treturn False\n# \t\t\tfor char in chunk:\n# \t\t\t\tif char == check_digit:\n# \t\t\t\t\tcheck_digit_count += 1\n# \t\t\t\tscore += ord(char)\n# \t\tif score == 1772 and check_digit_count == 5:\n# \t\t\treturn True\n# \t\treturn False\n#\n# \tdef generate(self):\n# \t\tkey = ''\n# \t\tchunk = ''\n# \t\tcheck_digit_count = 0\n# \t\talphabet = 'abcdefghijklmnopqrstuvwxyz1234567890'\n# \t\twhile True:\n# \t\t\twhile len(key) < 25:\n# \t\t\t\tchar = random.choice(alphabet)\n# \t\t\t\tkey += char\n# \t\t\t\tchunk += char\n# \t\t\t\tif len(chunk) == 4:\n# \t\t\t\t\tkey += '-'\n# \t\t\t\t\tchunk = ''\n# \t\t\tkey = key[:-1]\n# \t\t\tif Key(key).verify():\n# \t\t\t\treturn key\n# \t\t\telse:\n# \t\t\t\tkey = ''\n#\n# \tdef __str__(self):\n# \t\tvalid = 'Invalid'\n# \t\tif self.verify():\n# \t\t\tvalid = 'Valid'\n# \t\treturn self.key.upper() + ':' + valid\n\n\n#--------------------------------------------------------------------------------------\n#for 4th question\n\n#!/usr/bin/env python3\n#\n# This is a simple script to encrypt a message using AES\n# with CBC mode in Python 3.\n# Before running it, you must install pycryptodome:\n#\n# $ python -m pip install PyCryptodome\n#\n# Author.: José Lopes\n# Date...: 2019-06-14\n# License: MIT\n##\n\n#\n# from hashlib import md5\n# from base64 import b64decode\n# from base64 import b64encode\n#\n# from Crypto.Cipher import AES\n# from Crypto.Random import get_random_bytes\n# from Crypto.Util.Padding import pad, unpad\n#\n#\n# class AESCipher:\n# def __init__(self, key):\n# self.key = md5(key.encode('utf8')).digest()\n#\n# def encrypt(self, data):\n# iv = get_random_bytes(AES.block_size)\n# self.cipher = AES.new(self.key, AES.MODE_CBC, iv)\n# return b64encode(iv + self.cipher.encrypt(pad(data.encode('utf-8'),\n# AES.block_size)))\n#\n# def decrypt(self, data):\n# raw = b64decode(data)\n# self.cipher = AES.new(self.key, AES.MODE_CBC, raw[:AES.block_size])\n# return unpad(self.cipher.decrypt(raw[AES.block_size:]), AES.block_size)\n#\n#\n# if __name__ == '__main__':\n# print('TESTING ENCRYPTION')\n# msg = input('Message...: ')\n# pwd = input('Password..: ')\n# print('Ciphertext:', AESCipher(pwd).encrypt(msg).decode('utf-8'))\n#\n# print('\\nTESTING DECRYPTION')\n# cte = input('Ciphertext: ')\n# pwd = input('Password..: ')\n# print('Message...:', AESCipher(pwd).decrypt(cte).decode('utf-8'))\n\n\n\n#------------------------------\n#same as above for 4th question\n\n# from hashlib import md5\n#\n# from Crypto.Cipher import AES\n# from Crypto.Random import get_random_bytes\n# from Crypto.Util.Padding import pad, unpad\n#\n#\n# class AESCipher:\n# def __init__(self, key):\n# password = key.encode('utf-8')\n# self.key = md5(password).digest()\n#\n# def encrypt(self, data):\n# vector = get_random_bytes(AES.block_size)\n# encryption_cipher = AES.new(self.key, AES.MODE_CBC, vector)\n# return vector + encryption_cipher.encrypt(pad(data, AES.block_size))\n#\n# def decrypt(self, data):\n# file_vector = data[:AES.block_size]\n# decryption_cipher = AES.new(self.key, AES.MODE_CBC, file_vector)\n# return unpad(decryption_cipher.decrypt(data[AES.block_size:]), AES.block_size)\n#\n#\n# if __name__ == '__main__':\n# print('TESTING ENCRYPTION')\n# msg = \"helloWorld\".encode('utf-8')\n# pwd = \"password\"\n#\n# encrypted = AESCipher(pwd).encrypt(msg)\n# print('Ciphertext:', encrypted)\n# print('\\nTESTING DECRYPTION')\n# decrypted = AESCipher(pwd).decrypt(encrypted).decode('utf-8')\n# print(\"Original data: \", msg.decode('utf-8'))\n# print(\"Decripted data:\", decrypted)\n# assert msg.decode('utf-8') == decrypted\n\n\n\n#----------------------------------------------------------------------------------\n\n#for 5th question\n#\n# #!/usr/bin/env python3\n# from hashlib import sha256\n# import os\n#\n# # Takes the path (as a string) to a SHA256SUMS file and a list of paths to\n# # local files. Returns true only if all files' checksums are present in the\n# # SHA256SUMS file and their checksums match\n# def integrity_is_ok( sha256sums_filepath, local_filepaths ):\n#\n# # first we parse the SHA256SUMS file and convert it into a dictionary\n# sha256sums = dict()\n# with open( sha256sums_filepath ) as fd:\n# for line in fd:\n# # sha256 hashes are exactly 64 characters long\n# checksum = line[0:64]\n#\n# # there is one space followed by one metadata character between the\n# # checksum and the filename in the `sha256sum` command output\n# filename = os.path.split( line[66:] )[1].strip()\n# sha256sums[filename] = checksum\n#\n# # now loop through each file that we were asked to check and confirm its\n# # checksum matches what was listed in the SHA256SUMS file\n# for local_file in local_filepaths:\n#\n# local_filename = os.path.split( local_file )[1]\n#\n# sha256sum = sha256()\n# with open( local_file, 'rb' ) as fd:\n# data_chunk = fd.read(1024)\n# while data_chunk:\n# sha256sum.update(data_chunk)\n# data_chunk = fd.read(1024)\n#\n# checksum = sha256sum.hexdigest()\n# if checksum != sha256sums[local_filename]:\n# return False\n#\n# return True\n#\n# if __name__ == '__main__':\n#\n# script_dir = os.path.split( os.path.realpath(__file__) )[0]\n# sha256sums_filepath = script_dir + '/SHA256SUMS'\n# local_filepaths = [ script_dir + '/MANIFEST' ]\n#\n# if integrity_is_ok( sha256sums_filepath, local_filepaths ):\n# print( \"INFO: Checksum OK\" )\n# else:\n# print( \"ERROR: Checksum Invalid\" )\n#","repo_name":"fatmabalci/CSE4057","sub_path":"cse4057-programming-assignments-master/Project2/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":9437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74190049425","text":"import pdb\nimport numpy as np\nimport tf_slim as slim\nimport tensorflow.compat.v1 as tf\ntf.disable_v2_behavior()\n\n\ndef conv_bn_tanh(net, output_channel, kernel, stride, use_bias, phase_train, scope):\n batch_norm_params = {\n 'is_training': phase_train,\n 'zero_debias_moving_mean': True,\n # Decay for the moving averages.\n 'decay': 0.995,\n # epsilon to prevent 0s in variance.\n 'epsilon': 0.001,\n # force in-place updates of mean and variance estimates\n 'updates_collections': None,\n # Moving averages ends up in the trainable variables collection\n 'variables_collections': [tf.GraphKeys.TRAINABLE_VARIABLES],\n }\n if use_bias == 0:\n conv = slim.conv2d(net, output_channel, kernel, stride=stride, normalizer_fn=slim.batch_norm,\n normalizer_params=batch_norm_params, activation_fn=tf.nn.tanh, biases_initializer=None, scope=scope)\n else:\n conv = slim.conv2d(net, output_channel, kernel, stride = stride, normalizer_fn=slim.batch_norm,\n normalizer_params=batch_norm_params, activation_fn=tf.nn.tanh, scope=scope)\n return conv\n\n\ndef bottleneck(input, t, c, n, s, phase_train, index, scopeName):\n net = input\n batch_norm_params = {\n 'is_training': phase_train,\n 'zero_debias_moving_mean': True,\n # Decay for the moving averages.\n 'decay': 0.995,\n # epsilon to prevent 0s in variance.\n 'epsilon': 0.001,\n # force in-place updates of mean and variance estimates\n 'updates_collections': None,\n # Moving averages ends up in the trainable variables collection\n 'variables_collections': [tf.GraphKeys.TRAINABLE_VARIABLES],\n }\n with slim.arg_scope([slim.conv2d, slim.separable_conv2d],\n weights_initializer=slim.initializers.xavier_initializer(),\n normalizer_fn=slim.batch_norm,\n normalizer_params=batch_norm_params,\n activation_fn=tf.nn.relu6,\n reuse=None):\n for i in range(n):\n with tf.variable_scope((scopeName+'bneck%d') % index) as scope:\n if s != 1 and i != 0:\n s = 1\n input_channel = net.shape[-1]\n if input_channel == c:\n input_net = net\n if t != 1:\n output_channel = t*input_channel\n index1 = 2\n net = slim.conv2d(net, output_channel, [\n 1, 1], scope=(scopeName+'bneck%d_conv%d_1') % (index, i+1))\n else:\n index1 = 1\n net = slim.separable_conv2d(net, None, [\n 3, 3], 1, s, padding='SAME', scope=(scopeName+'bneck%d_depthwise1_%d') % (index, i+1))\n net = slim.conv2d(net, c, [\n 1, 1], stride=1, activation_fn=None, scope=(scopeName+'bneck%d_conv%d_%d') % (index, i+1, index1))\n if input_channel == c and s == 1:\n net = input_net + net\n return net\n\n\ndef inference(inputData, model_def, phase_train, scopeName=None):\n inputData = tf.reshape(inputData, (-1, 551))\n net = inputData\n (index_conv, index_bneck, index_pool, index_fc) = (1, 1, 1, 1)\n for (t, c, n, n1, s) in model_def:\n if t == 0 or t == -1:\n layer = scopeName + 'conv' + str(index_conv)\n index_conv += 1\n net = conv_bn_tanh(net, c, [n, n1], s, t, phase_train, layer)\n elif t == 1 and c == 1:\n layer = scopeName + 'pool' + str(index_pool)\n index_pool += 1\n net = slim.avg_pool2d(\n net, [n,n1], stride=s,padding='SAME', scope=layer)\n elif t == -2:\n layer = scopeName + 'fc' + str(index_fc)\n index_fc += 1\n net = slim.fully_connected(net, n, scope=layer)\n if s == 1:\n net = tf.reshape(net, (-1, 32, 32, 1))\n else:\n net = bottleneck(net, t, c, n, s, phase_train, index_bneck, scopeName)\n index_bneck += 1\n net = tf.reshape(net, [-1, 1], name='logits')\n return net\n","repo_name":"Haiyue-Tian/Reinforcement-Learning-based-on-Strategy-Card-Games","sub_path":"rlcard/agents/mobileNet_agents/models/model2_1.py","file_name":"model2_1.py","file_ext":"py","file_size_in_byte":4258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74248698706","text":"import sys\nimport bluetooth\n#from subprocess import Popen, PIPE\nimport subprocess\nimport os\nimport binascii\n\nos.system('sudo hciconfig hci0 down')\nos.system('sudo hciconfig hci0 up')\nos.system('sudo hciconfig hci0 leadv 3')\n\n\nbd_addr = \"DC:A6:32:DE:78:1C\"\n\nport = 1\n\nfor line in sys.stdin:\n print('--- read csv---')\n line = line.split(',') \n dataurl = binascii.hexlify(line[0].encode())\n iterable = iter(dataurl.decode())\n dataurl = ' '.join(a+b for a, b in zip(iterable,iterable))\n os.system(f'sudo hcitool -i hci0 cmd 0x08 0x0008 19 02 01 06 03 03 aa fe 11 16 aa fe 10 00 03 {dataurl}')\n","repo_name":"JiaXiuSai/VSCapture","sub_path":"read_csv.py","file_name":"read_csv.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"9653004293","text":"# coding: utf-8\nimport sys\n# reload(sys)\n# sys.setdefaultencoding('utf8') #comment these two lines if use py3\n\nimport os\nimport re\nimport nltk\n# nltk.download()\nfrom nltk.corpus import stopwords #comment it after first run\nimport simplejson as json\n# import pickle\nimport numpy as np\n\ndef rm_html_tags(str):\n html_prog = re.compile(r'<[^>]+>',re.S)\n return html_prog.sub('', str)\n\ndef rm_html_escape_characters(str):\n pattern_str = r'"|&|<|>| |"|&|<|>| |似|眼|格|+|值|尼'\n escape_characters_prog = re.compile(pattern_str, re.S)\n return escape_characters_prog.sub('', str)\n\ndef rm_at_user(str):\n return re.sub(r'@[a-zA-Z_0-9]*', '', str)\n\ndef rm_url(str):\n return re.sub(r'http[s]?:[/+]?[a-zA-Z0-9_\\.\\/]*', '', str)\n\ndef rm_repeat_chars(str):\n return re.sub(r'(.)(\\1){2,}', r'\\1\\1', str)\n\ndef rm_hashtag_symbol(str):\n return re.sub(r'#', '', str)\n\ndef replace_emoticon(emoticon_dict, str):\n for k, v in emoticon_dict.items():\n str = str.replace(k, v)\n return str\n\ndef rm_time(str):\n return re.sub(r'[0-9][0-9]:[0-9][0-9]', '', str)\n\ndef rm_punctuation(current_tweet):\n return re.sub(r'[^\\w\\s]','',current_tweet)\n\n\ndef pre_process(str, porter):\n # do not change the preprocessing order only if you know what you're doing \n str = str.lower()\n str = rm_url(str) \n str = rm_at_user(str) \n str = rm_repeat_chars(str) \n str = rm_hashtag_symbol(str) \n str = rm_time(str) \n str = rm_punctuation(str)\n \n try:\n str = nltk.tokenize.word_tokenize(str)\n try:\n str = [porter.stem(t) for t in str]\n except:\n print(str)\n pass\n except:\n print(str)\n pass\n \n return str\n \n\n\nif __name__ == \"__main__\":\n data_dir = './data' ##Setting your own file path here.\n\n x_filename = 'samples.txt'\n y_filename = 'labels.txt'\n\n porter = nltk.PorterStemmer()\n stops = set(stopwords.words('english'))\n stops.add('rt')\n\n\n ##load and process samples\n print('start loading and process samples...')\n\nwords_stat = {} # record statistics of the df and tf for each word; Form: {word:[tf, df, tweet index]}\ntweets = []\ncnt = 0\nwith open(os.path.join(data_dir, x_filename), encoding='utf-8') as f:\n for i, line in enumerate(f):\n postprocess_tweet = []\n tweet_obj = json.loads(line.strip(), encoding='utf-8')\n content = tweet_obj['text'].replace(\"\\n\",\" \")\n description = tweet_obj['user']['description'].replace(\"\\n\",\" \")\n hashtag_dict = tweet_obj['entities']['hashtags']\n if len(hashtag_dict) > 0:\n hashtag_list = []\n for h in hashtag_dict:\n single_tag = h['text']\n hashtag_list.append(single_tag)\n hashtag = ' '.join(hashtag_list)\n else:\n hashtag = \"unknown\" \n content = content + description + hashtag\n words = pre_process(content, porter)\n for word in words:\n if word not in stops:\n postprocess_tweet.append(word)\n if word in words_stat.keys():\n words_stat[word][0] += 1\n if i != words_stat[word][2]:\n words_stat[word][1] += 1\n words_stat[word][2] = i\n else:\n words_stat[word] = [1,1,i]\n tweets.append(' '.join(postprocess_tweet))\n\n\n \n##saving the statistics of tf and df for each words into file\nprint(\"The number of unique words in data set is %i.\" %len(words_stat.keys()))\nlowTF_words = set()\nwith open(os.path.join(data_dir, 'early_words_statistics.txt'), 'w', encoding='utf-8') as f:\n f.write('TF\\tDF\\tWORD\\n')\n for word, stat in sorted(words_stat.items(), key=lambda i: i[1], reverse=True):\n f.write('\\t'.join([str(m) for m in stat[0:2]]) + '\\t' + word + '\\n')\n if stat[0]<2:\n lowTF_words.add(word)\nprint(\"The number of low frequency words is %d.\" %len(lowTF_words))\n# print(stops)\n\n\n###Re-process samples, filter low frequency words...\nfout = open(os.path.join(data_dir, 'early_samples_processed.txt'), 'w', encoding='utf-8')\ntweets_new = []\nfor tweet in tweets:\n words = tweet.split(' ')\n new = [] \n for w in words:\n if w not in lowTF_words:\n new.append(w)\n new_tweet = ' '.join(new)\n tweets_new.append(new_tweet)\n fout.write('%s\\n' %new_tweet)\nfout.close()\n\nprint(\"Preprocessing is completed\")\n\n\n\n\n\n","repo_name":"clairewangjia/Tweet-Text-Classifier","sub_path":"early_processor.py","file_name":"early_processor.py","file_ext":"py","file_size_in_byte":4568,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74924406225","text":"from flask import Flask, request\nfrom gmail_api import GmailAPI\nfrom whatsapp_bot import WhatsAppBot\nfrom twilio.twiml.messaging_response import MessagingResponse\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'top-secret!'\n\ngmail_api = GmailAPI()\nwhatsapp_bot = WhatsAppBot()\n\n@app.route('/notifications', methods=['POST'])\ndef notifications():\n # Gmail sends a POST request with a JSON body\n data = request.get_json()\n\n # Check if it's a new email notification\n if data['message']['data']:\n # Get the email ID from the notification\n email_id = data['message']['data']['emailId']\n\n # Fetch the email using the Gmail API\n email = gmail_api.get_email(email_id)\n\n # Check if it's a booking confirmation email\n if gmail_api.is_booking_email(email['subject']):\n # Extract the booking data from the email\n booking_data = gmail_api.extract_booking_data(email['body'])\n\n # Trigger the WhatsApp bot to send the first message\n whatsapp_bot.send_whatsapp_message(\n f\"Hello {booking_data['Guest Name']}, I'm Astraea, the AI avatar of the Lake Fairy lodge :) ill be assisting you during your stay, feel free to ask me any questions regarding the lodge and the surrounding area before or during your stay. Here's a little video about the lodge: [video_link]\",\n booking_data['Contact Phone']\n )\n\n return '', 204\n\n@app.route('/bot', methods=['POST'])\ndef bot():\n incoming_msg = request.values.get('Body', '')\n phone_number = request.values.get('WaId', '')\n\n if incoming_msg:\n # Get the chat log for this user, or start a new one\n chat_log = whatsapp_bot.chat_logs.get(phone_number, whatsapp_bot.start_chat_log)\n answer = whatsapp_bot.ask(incoming_msg, chat_log)\n whatsapp_bot.chat_logs[phone_number] = whatsapp_bot.append_interaction_to_chat_log(incoming_msg, answer, chat_log)\n whatsapp_bot.send_whatsapp_message(answer, phone_number)\n print(answer)\n else:\n whatsapp_bot.send_whatsapp_message(\"Message Cannot Be Empty!\")\n print(\"Message Is Empty\")\n r = MessagingResponse()\n r.message(\"\") \n return str(r)\n\nif __name__ == '__main__':\n # Authenticate with the Gmail API\n gmail_api.authenticate()\n\n # Set up Gmail push notifications\n gmail_api.watch('https://your-pythonanywhere-username.pythonanywhere.com/notifications')\n\n # Start the Flask app\n app.run()","repo_name":"SEMTEX99/WhatsappIntegration","sub_path":"WhatsappIntegration/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22816242306","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:\n dummy = ListNode()\n\n ptr = head\n new_ptr = dummy\n while ptr:\n slow = ptr\n fast = slow.next\n count = 0\n while fast and slow.val == fast.val:\n count += 1\n fast = fast.next\n if count == 0:\n new_ptr.next = slow\n new_ptr = new_ptr.next\n ptr = fast\n if new_ptr:\n new_ptr.next = None\n return dummy.next\n","repo_name":"mnhaqq/A2SV-problems","sub_path":"week_12/remove_duplicates_from_sorted_list_2.py","file_name":"remove_duplicates_from_sorted_list_2.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41776836339","text":"import cv2\nimport pyautogui as mouse\n\nmodel=cv2.CascadeClassifier('closed_palm.xml')\nvideo=cv2.VideoCapture(0)\n\nwhile True:\n ret,frames=video.read()\n objects=model.detectMultiScale(frames,1.2,10)\n if len(objects):\n mouse.press('space')\n cv2.imshow('Video',frames)\n \n if cv2.waitKey(1)&0xFF==ord('q'):\n break\n \nvideo.release()\ncv2.destroyAllWindows()","repo_name":"urguru/Machine-Learning-Projects","sub_path":"Dino_Fist/Gesture space control.py","file_name":"Gesture space control.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32466350992","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom .models import Issue\nfrom .filters import IssueFilter\nfrom django.contrib import messages\n# Create your views here.\nissues = [\n {\n 'author': 'Steve M',\n 'title': 'Slower rendering than expected',\n 'priority': 'Medium',\n 'content': 'An error occurs when attempting to...',\n 'date_posted': 'June 28, 2022'\n },\n {\n 'author': 'Mike C',\n 'title': 'HTTP request error',\n 'priority': 'Critical',\n 'content': 'An error occurs when attempting to...',\n 'date_posted': 'June 27, 2022'\n }\n]\n\n\n\ndef home(request):\n issues = Issue.objects.all()\n myFilter = IssueFilter(request.GET, queryset=issues)\n issues = myFilter.qs\n context = {\n 'issues': issues,\n 'myFilter':myFilter\n }\n if request.method == 'GET':\n if request.user.is_authenticated == False:\n messages.info(request, 'You need to register and log in to view your reports')\n\n return render(request, 'bugtracker/home.html', context)\n\n\n\ndef about(request):\n return render(request, 'bugtracker/about.html', {'title': 'About'})","repo_name":"Willshears/django-exchange","sub_path":"bugtracker/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"7808040897","text":"import sys\nsys.stdin = open(\"input.txt\")\n\ndef in_order(v):\n if v:\n in_order(left[v])\n print(P[v], end=\"\")\n in_order(right[v])\n\nfor tc in range(1, 11):\n N = int(input())\n P = [0] * (N+1)\n left = [0] * (N+1)\n right = [0] * (N+1)\n for _ in range(N):\n p, alpha, *C = input().split()\n p = int(p)\n P[p] = alpha\n if C:\n for c in map(int, C):\n if not left[p]:\n left[p] = c\n else:\n right[p] = c\n print('#{}'.format(tc), end=\" \")\n in_order(1)\n print()\n\n","repo_name":"asooso1/ssafy_algorithm","sub_path":"0827/박기웅/1231_중위 순회/s1.py","file_name":"s1.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"3212539121","text":"from django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render, redirect\nfrom django.contrib import messages\n\n\nfrom .models import Article, ArticleComment\nfrom . import utils\nfrom . import forms\n\ndef article_list(request):\n articles = Article.objects.all().order_by('date')\n articles = articles.reverse()\n return render(request, 'articles/article_list.html', {'articles':articles})\n\n@login_required(login_url = \"/accounts/login\")\ndef postcomment(request):\n if request.method == \"POST\":\n\n comment = forms.CommentForm(request.POST)\n if comment.is_valid():\n instance = comment.save(commit=False)\n instance.user = request.user\n post_slug = request.POST.get('post_slug')\n par_id = request.POST.get('par_id')\n if par_id != None:\n par_comment = ArticleComment.objects.get(id=par_id)\n instance.parent = par_comment\n instance.height = par_comment.height+20\n post = Article.objects.get(slug=post_slug)\n instance.post = post\n instance.save()\n instance = ArticleComment.objects.get(id=instance.id)\n if par_id != None:\n par_comment.child.add(instance)\n next = post.get_absolute_url()\n return redirect(next)\n return redirect(\"articles:articles_list\")\n\ndef article_details(request, slug):\n article = Article.objects.get(slug=slug)\n comments = utils.get_commnets(post=article)\n comment = forms.CommentForm()\n context = {\n 'article':article,\n 'comment':comment,\n 'comments':comments\n }\n template = 'articles/article_details.html'\n return render(request, template, context)\n\n@login_required(login_url = \"/accounts/login\")\ndef article_create(request):\n if request.method == \"POST\":\n form = forms.CreateArticle(request.POST)\n if form.is_valid():\n instance = form.save(commit=False)\n instance.author = request.user\n instance.slug = utils.link_generator()\n instance.save()\n messages.success(request, \"Your article created sucessfully!\")\n return redirect(\"articles:articles_list\")\n else:\n form = forms.CreateArticle()\n return render(request, \"articles/article_create.html\", \n {'form':form, 'type': \"Create\"})\n\n\n@login_required(login_url = \"/accounts/login\")\ndef article_update(request, slug):\n instance = Article.objects.get(slug=slug)\n \n if request.user != instance.author:\n return redirect(\"articles:articles_list\")\n\n if request.method == \"POST\":\n form = forms.CreateArticle(request.POST, instance=instance)\n if form.is_valid():\n form.save()\n messages.success(request, \"Your article updated sucessfully!\")\n return redirect(\"articles:articles_list\")\n else:\n form = forms.CreateArticle(instance=instance)\n return render(request, \"articles/article_create.html\", \n {'form':form, 'type': \"Update\"})\n\n\n@login_required(login_url = \"/accounts/login\")\ndef article_delete(request, slug):\n instance = Article.objects.get(slug=slug)\n if request.user == instance.author:\n instance.delete()\n messages.success(request, \"Your article deleted sucessfully!\")\n return redirect(\"articles:articles_list\")","repo_name":"gaddopur/DjangoBlog","sub_path":"articles/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34740355800","text":"fnameDPR='../DPRData/Atlantic/2A.GPM.DPR.V8-20180723.20180830-S183511-E200744.025593.V06A.HDF5'\r\nfnameDPR='../monthly/SEAsia/2A.GPM.DPR.V8-20180723.20180602-S021248-E034522.024198.V06A.HDF5'\r\nfrom netCDF4 import Dataset\r\nimport numpy as np\r\nimport pickle\r\n\r\n\r\nimport glob\r\n\r\ndef readSfcRainS(fname):\r\n fh=Dataset(fname,'r')\r\n sfcRain=fh['NS/SLV/precipRateNearSurface'][:,:]\r\n return sfcRain\r\n#rainL=[]\r\n#for f in fs:\r\n# rain=readSfcRainS(f)\r\n# rainL.append(rain.sum())\r\n#rainL=np.array(rainL)\r\n#inds=np.argsort(rainL)\r\nimport pickle\r\n#pickle.dump(inds,open('sortedInd.pklz','wb'))\r\n\r\nindx=range(327)\r\n#stop\r\ndef readSfcRainCmb(fname,latmin,latmax,a):\r\n fh=Dataset(fname,'r')\r\n lat=fh['NS/Latitude'][:,24]\r\n a0=np.nonzero((lat-latmin)*(lat-latmax)<0)\r\n pType=(fh['NS/Input/precipitationType'][a[0],:]/1e7).astype(int)\r\n sfcRain=fh['NS/surfPrecipTotRate'][a[0],:]\r\n #pRate=fh['NS/precipTotRate'][a[0],:,:]\r\n binNodes=fh['NS/phaseBinNodes'][a[0],:]\r\n lat=fh['NS/Latitude'][a[0],:]\r\n #print(fh['DiagGroup'])\r\n tb=fh['DiagGroup/dset1'][a[0],:,:]\r\n fh.close()\r\n return sfcRain,binNodes,a, lat, pType, tb\r\n\r\ndef readSfcRainCmbX(fname,latmin,latmax):\r\n fh=Dataset(fname,'r')\r\n lat=fh['FS/Latitude'][:,24]\r\n a=np.nonzero((lat-latmin)*(lat-latmax)<0)\r\n sfcRain=fh['FS/surfPrecipTotRate'][a[0],:]\r\n pType=(fh['FS/Input/precipitationType'][a[0],:]/1e7).astype(int)\r\n #pRate=fh['NS/precipTotRate'][a[0],:,:]\r\n binNodes=fh['FS/phaseBinNodes'][a[0],:]\r\n lat=fh['FS/Latitude'][a[0],:]\r\n\r\n fh.close()\r\n return sfcRain,binNodes,a, lat, pType\r\n\r\ndef readSfcRain(fname,a,latmin,latmax):\r\n fh=Dataset(fname,'r')\r\n lat=fh['FS/Latitude'][:,24]\r\n a=np.nonzero((lat-latmin)*(lat-latmax)<0)\r\n sfcRain=fh['NS/SLV/precipRateNearSurface'][a[0],:]\r\n lat=fh['NS/Latitude'][a[0],:]\r\n lon=fh['NS/Longitude'][a[0],:]\r\n sfcType=fh['NS/PRE/landSurfaceType'][a[0],:]\r\n h0=fh['NS/VER/heightZeroDeg'][a[0],:]\r\n bz=fh['NS/VER/binZeroDeg'][a[0],:]\r\n bcf=fh['NS/PRE/binClutterFreeBottom'][a[0],:]\r\n btop=fh['NS/PRE/binStormTop'][a[0],:]\r\n pType=(fh['NS/CSF/typePrecip'][a[0],:]/1e7).astype(int)\r\n binBB=fh['NS/CSF/binBBPeak'][a[0],:]\r\n bsfc=fh['NS/PRE/binRealSurface'][a[0],:]\r\n return lat,lon,sfcRain,sfcType,h0,pType,binBB,bsfc\r\n\r\ndef readSfcRainFS(fname,a,latmin,latmax):\r\n fh=Dataset(fname,'r')\r\n lat=fh['FS/Latitude'][:,24]\r\n a=np.nonzero((lat-latmin)*(lat-latmax)<0)\r\n sfcRain=fh['FS/SLV/precipRateNearSurface'][a[0],:]\r\n lat=fh['FS/Latitude'][a[0],:]\r\n lon=fh['FS/Longitude'][a[0],:]\r\n sfcType=fh['FS/PRE/landSurfaceType'][a[0],:]\r\n h0=fh['FS/VER/heightZeroDeg'][a[0],:]\r\n bz=fh['FS/VER/binZeroDeg'][a[0],:]\r\n bcf=fh['FS/PRE/binClutterFreeBottom'][a[0],:]\r\n btop=fh['FS/PRE/binStormTop'][a[0],:]\r\n pType=(fh['FS/CSF/typePrecip'][a[0],:]/1e7).astype(int)\r\n binBB=fh['FS/CSF/binBBPeak'][a[0],:]\r\n bsfc=fh['FS/PRE/binRealSurface'][a[0],:]\r\n zm=fh['FS/PRE/zFactorMeasured'][a[0],:,:,:]\r\n snowIce=fh['FS/PRE/snowIceCover'][a[0],:]\r\n return lat,lon,sfcRain,sfcType,h0,pType,binBB,bsfc,zm,bz,bcf,snowIce\r\nimport glob\r\n#fs=[]\r\n#for i in range(1,31):\r\n# fs1=glob.glob(\"/gpmdata/2018/08/%2.2i/Xradar/2A.GPM.DPR*\"%i)\r\n# fs.extend(sorted(fs1))\r\n#print(len(fs))\r\n\r\nrainL=[]\r\n\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib\r\n\r\nsfcCMB_st_L=np.zeros((49),float)\r\nsfcCMB6_st_L=np.zeros((49),float)\r\nsfcCMBX_st_L=np.zeros((49),float)\r\nsfcDPR_st_L=np.zeros((49),float)\r\ncountR_st_L=np.zeros((49),float)\r\n\r\nsfcCMB_cv_L=np.zeros((49),float)\r\nsfcCMB6_cv_L=np.zeros((49),float)\r\nsfcCMBX_cv_L=np.zeros((49),float)\r\nsfcDPR_cv_L=np.zeros((49),float)\r\ncountR_cv_L=np.zeros((49),float)\r\n\r\nsfcCMB_st_O=np.zeros((49),float)\r\nsfcCMB6_st_O=np.zeros((49),float)\r\nsfcCMBX_st_O=np.zeros((49),float)\r\nsfcDPR_st_O=np.zeros((49),float)\r\ncountR_st_O=np.zeros((49),float)\r\n\r\nsfcCMB_cv_O=np.zeros((49),float)\r\nsfcCMB6_cv_O=np.zeros((49),float)\r\nsfcCMBX_cv_O=np.zeros((49),float)\r\nsfcDPR_cv_O=np.zeros((49),float)\r\ncountR_cv_O=np.zeros((49),float)\r\n\r\nfs=sorted(glob.glob(\"V6X/2B*\"))\r\nlatmin=-60\r\nlatmax=-40\r\ncountMiss=np.zeros((4),float)\r\n\r\ntbL=[]\r\nzmL=[]\r\nbzdL=[]\r\nbcfL=[]\r\ncoordL=[]\r\nbsfcL=[]\r\nsfcRainL=[]\r\njL=[]\r\n\r\ntbL2=[]\r\nbzdL2=[]\r\nbcfL2=[]\r\ncoordL2=[]\r\nbsfcL2=[]\r\nsfcRainL2=[]\r\njL2=[]\r\n\r\nfor f in fs[:300]:\r\n sfcRainCMB,nodes,ac,latCMBX,pTypeCMB=readSfcRainCmbX(f,latmin,latmax)\r\n print(f)\r\n sdate=f.split('.')[-3]\r\n year=sdate[0:4]\r\n mm=sdate[4:6]\r\n day=sdate[6:8]\r\n orb=f.split('.')[-2]\r\n print(f,orb)\r\n fdpr=glob.glob('/itedata/ITE749/%s/%s/%s/radar/2A.GPM.DPR.V9*%s*'%(year,mm,day,orb))\r\n fcmb=glob.glob('/gpmdata/%s/%s/%s/radar/2B.GPM.DPR*COR*%s*'%(year,mm,day,orb))\r\n fcmb1=glob.glob('/itedata/ITE745/%s/%s/%s/radar/2B.GPM.DPR*COR*%s*'%(year,mm,day,orb))\r\n print(fdpr[0])\r\n #latmin=latCMBX[:,24].min()-0.0\r\n #latmax=latCMBX[:,24].max()+0.0\r\n lat,lon,sfcRain,sfcType,h0,pType,binBB,bsfc,zm,bzd,\\\r\n bcf,snowIce=readSfcRainFS(fdpr[0],ac,latmin,latmax)\r\n\r\n print(lat[0]-latCMBX[0])\r\n #stop\r\n sfcRainCMBv6,nodes,a,\\\r\n latCMB,pTypeCMB,tb=readSfcRainCmb(fcmb[0],latmin,latmax,ac)\r\n print(latCMBX[0]-latCMB[0])\r\n sfcRainCMBX,nodesX,aX,latCMBX2,pTypeCMBX=readSfcRainCmbX(fcmb1[0],latmin,latmax)\r\n #\r\n #stop\r\n a=np.nonzero(pType>0)\r\n b=np.nonzero(sfcType[a]!=0)\r\n if len(b[0])>0:\r\n if sfcRainCMBv6[a][b].max()>50:\r\n ind=np.argmax(sfcRainCMBv6[a][b])\r\n print('nodes=',nodes[a[0][b[0][ind]],a[1][b[0][ind]],:])\r\n print(sfcRainCMBv6[a][b].max(),sfcRainCMB[a][b].max(),sfcRainCMBX[a][b].max())\r\n\r\n for i,j in zip(a[0],a[1]):\r\n if i==sfcRain.shape[0]-1:\r\n continue\r\n if sfcRain[i,j]==sfcRain[i,j]:\r\n if pType[i,j]==1:\r\n if sfcType[i,j]!=0:\r\n sfcCMB_st_L[j]+=sfcRainCMB[i,j]\r\n sfcCMB6_st_L[j]+=sfcRainCMBv6[i,j]\r\n sfcCMBX_st_L[j]+=sfcRainCMBX[i,j]\r\n sfcDPR_st_L[j]+=sfcRain[i,j]\r\n countR_st_L[j]+=1\r\n if pTypeCMB[i,j]<1:\r\n countMiss[0]+=1\r\n else:\r\n sfcCMB_st_O[j]+=sfcRainCMB[i,j]\r\n sfcCMB6_st_O[j]+=sfcRainCMBv6[i,j]\r\n sfcCMBX_st_O[j]+=sfcRainCMBX[i,j]\r\n sfcDPR_st_O[j]+=sfcRain[i,j]\r\n countR_st_O[j]+=1\r\n if snowIce[i,j]==0:\r\n bsfcL.append(bsfc[i,j,0])\r\n bzdL.append(bzd[i,j])\r\n zmL.append(zm[i,j,100:,:])\r\n tbL.append(tb[i,j,:])\r\n coordL.append([lon[i,j],lat[i,j]])\r\n sfcRainL.append(sfcRainCMB[i,j])\r\n bcfL.append(bcf[i,j])\r\n jL.append([j,1])\r\n\r\n if pTypeCMB[i,j]<1:\r\n countMiss[1]+=1\r\n if pType[i,j]==2:\r\n if sfcType[i,j]!=0:\r\n sfcCMB_cv_L[j]+=sfcRainCMB[i,j]\r\n sfcCMB6_cv_L[j]+=sfcRainCMBv6[i,j]\r\n sfcCMBX_cv_L[j]+=sfcRainCMBX[i,j]\r\n sfcDPR_cv_L[j]+=sfcRain[i,j]\r\n countR_cv_L[j]+=1\r\n if pTypeCMB[i,j]<1:\r\n countMiss[2]+=1\r\n else:\r\n sfcCMB_cv_O[j]+=sfcRainCMB[i,j]\r\n sfcCMB6_cv_O[j]+=sfcRainCMBv6[i,j]\r\n sfcCMBX_cv_O[j]+=sfcRainCMBX[i,j]\r\n sfcDPR_cv_O[j]+=sfcRain[i,j]\r\n countR_cv_O[j]+=1\r\n if snowIce[i,j]==0:\r\n bsfcL.append(bsfc[i,j,0])\r\n bzdL.append(bzd[i,j])\r\n zmL.append(zm[i,j,100:,:])\r\n tbL.append(tb[i,j,:])\r\n sfcRainL.append(sfcRainCMB[i,j])\r\n coordL.append([lon[i,j],lat[i,j]])\r\n bcfL.append(bcf[i,j])\r\n jL.append([j,2])\r\n if pTypeCMB[i,j]<1:\r\n countMiss[3]+=1\r\n \r\n a=np.nonzero(pType==0)\r\n b=np.nonzero(sfcType[a]!=0)\r\n for i,j in zip(a[0],a[1]):\r\n if i==sfcRain.shape[0]-1:\r\n continue\r\n if snowIce[i,j]==0:\r\n bsfcL2.append(bsfc[i,j,0])\r\n bzdL2.append(bzd[i,j])\r\n #zmL.append(zm[i,j,100:,:])\r\n tbL2.append(tb[i,j,:])\r\n coordL2.append([lon[i,j],lat[i,j]])\r\n sfcRainL2.append(sfcRainCMB[i,j])\r\n bcfL2.append(bcf[i,j])\r\n jL2.append([j,0])\r\n print('Missed Ocean =',countMiss[1]/countR_st_O.sum(),countMiss[3]/countR_cv_O.sum(),\\\r\n (countMiss[1]+countMiss[3])/(countR_st_O.sum()+countR_cv_O.sum()))\r\n print('Missed Land =',countMiss[0]/countR_st_L.sum(),countMiss[2]/countR_cv_L.sum(),\\\r\n (countMiss[0]+countMiss[2])/(countR_st_L.sum()+countR_cv_L.sum()))\r\n bL=(sum(sfcCMB_cv_L)+ sum(sfcCMB_st_L))/\\\r\n (sum(sfcCMB6_cv_L)+ sum(sfcCMB6_st_L))\r\n bLx=(sum(sfcCMBX_cv_L)+ sum(sfcCMBX_st_L))/\\\r\n (sum(sfcCMB6_cv_L)+ sum(sfcCMB6_st_L))\r\n bO=(sum(sfcCMB_cv_O)+ sum(sfcCMB_st_O))/\\\r\n (sum(sfcCMB6_cv_O)+ sum(sfcCMB6_st_O))\r\n bOx=(sum(sfcCMBX_cv_O)+ sum(sfcCMBX_st_O))/\\\r\n (sum(sfcCMB6_cv_O)+ sum(sfcCMB6_st_O))\r\n print('syst_diff=> Land=',bL,bLx,' Ocean=',bO,bOx)\r\nplt.figure(figsize=(12,8))\r\nplt.suptitle('SO Winter') \r\nplt.subplot(221)\r\nplt.plot(sfcCMB_st_L/countR_st_L)\r\nplt.plot(sfcCMB6_st_L/countR_st_L)\r\nplt.plot(sfcCMBX_st_L/countR_st_L)\r\nplt.plot(sfcDPR_st_L/countR_st_L)\r\nplt.legend(['CV7','CV6','ITE745','DITE749'],ncols=2)\r\nplt.title('Stratiform Land')\r\nplt.subplot(223)\r\nplt.plot(sfcCMB_st_O/countR_st_O)\r\nplt.plot(sfcCMB6_st_O/countR_st_O)\r\nplt.plot(sfcCMBX_st_O/countR_st_O)\r\nplt.plot(sfcDPR_st_O/countR_st_O)\r\nplt.title('Stratiform Ocean')\r\nplt.subplot(222)\r\nplt.plot(sfcCMB_cv_L/countR_cv_L)\r\nplt.plot(sfcCMB6_cv_L/countR_cv_L)\r\nplt.plot(sfcCMBX_cv_L/countR_cv_L)\r\nplt.plot(sfcDPR_cv_L/countR_cv_L)\r\nplt.title('Convective Land')\r\nplt.subplot(224)\r\nplt.plot(sfcCMB_cv_O/countR_cv_O)\r\nplt.plot(sfcCMB6_cv_O/countR_cv_O)\r\nplt.plot(sfcCMBX_cv_O/countR_cv_O)\r\nplt.plot(sfcDPR_cv_O/countR_cv_O)\r\nplt.title('Convective Ocean')\r\nplt.tight_layout()\r\nplt.savefig('condRainSO_cmp2.png')\r\n\r\n#plt.plot(0.5*(np.array(countBB)+np.array(countnoBB)))\r\n#plt.xlabel('Ray')\r\n#plt.ylabel('Counts')\r\n#plt.legend(['BB','noBB','Average'])\r\n\r\n# 1.1383305980412695 1.2234138453398562 Ocean= 0.9886373783085047 1.0046354827886301\r\nimport xarray as xr\r\ntbx=xr.DataArray(tbL,dims=['ns','nt'])\r\nzmx=xr.DataArray(zmL,dims=['ns','nz','n2'])\r\nbsfcx=xr.DataArray(bsfcL,dims=['ns'])\r\nbcfx=xr.DataArray(bcfL,dims=['ns'])\r\nbzdx=xr.DataArray(bzdL,dims=['ns'])\r\njx=xr.DataArray(jL,dims=['ns','n2'])\r\ncoordx=xr.DataArray(coordL,dims=['ns','n2'])\r\nsfcRainX=xr.DataArray(sfcRainL,dims=['ns'])\r\nd=xr.Dataset({\"Tb\":tbx,\"Zm\":zmx,\"bsfc\":bsfcx,\"bzd\":bzdx,\"j\":jx,\"sfcRain\":sfcRainX,\\\r\n \"bcf\":bcfx,\"coord\":coordx})\r\nd.to_netcdf(\"SO_traininDataSet_2.nc\")\r\n\r\ntbx2=xr.DataArray(tbL2,dims=['ns','nt'])\r\nbsfcx2=xr.DataArray(bsfcL2,dims=['ns'])\r\nbcfx2=xr.DataArray(bcfL2,dims=['ns'])\r\nbzdx2=xr.DataArray(bzdL2,dims=['ns'])\r\njx2=xr.DataArray(jL2,dims=['ns','n2'])\r\ncoordx2=xr.DataArray(coordL2,dims=['ns','n2'])\r\nsfcRainX2=xr.DataArray(sfcRainL2,dims=['ns'])\r\nd2=xr.Dataset({\"Tb\":tbx2,\"bsfc\":bsfcx2,\"bzd\":bzdx2,\"j\":jx2,\"sfcRain\":sfcRainX2,\\\r\n \"bcf\":bcfx2,\"coord\":coordx2})\r\nd2.to_netcdf(\"SO_traininDataSet_noPrecip.nc\")\r\n\r\npickle.dump([sfcCMB_cv_O,sfcCMB_st_O,countR_cv_O,countR_st_O],\\\r\n open('SO_ratesAndCounts.pklz','wb'))\r\n","repo_name":"mgrecu35/radarOnly","sub_path":"plotInputFS_SO.py","file_name":"plotInputFS_SO.py","file_ext":"py","file_size_in_byte":11783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9575198812","text":"def high(x):\n '''\n Given a string of words, you need to find the highest scoring word.\n Each letter of a word scores points according to its position in the alphabet: a = 1, b = 2, c = 3 etc.\n You need to return the highest scoring word as a string.\n If two words score the same, return the word that appears earliest in the original string.\n All letters will be lowercase and all inputs will be valid.\n '''\n\n return max(x.split(), key=lambda k: sum(ord(c) - 96 for c in k))\n\ntest1 = high('man i need a taxi up to ubud')\ntest2 = high('what time are we climbing up the volcano')\ntest3 = high('aa b')\n\nprint(test3)\n","repo_name":"Django0033/codewars","sub_path":"python/highest-scoring-word/highest-score-world-other-solution1.py","file_name":"highest-score-world-other-solution1.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5551795258","text":"import discord\nfrom discord.ext import commands\nfrom core.classes import Cog_Extension\nimport json\nimport os\nwith open('setting.json','r',encoding='utf8') as jset:\n jdata = json.load(jset)\nbanmsguserid = []\nonMessageUser = int()\ndef chonMessageUser(a):\n global onMessageUser\n onMessageUser = a\nclass Msg(Cog_Extension):\n\n @commands.Cog.listener()\n async def on_message(self,msg):\n try:\n if msg.author.id in banmsguserid:\n await msg.delete()\n except discord.errors.NotFound:\n pass\n if msg.content[:1] == jdata['command_prefix']:\n return\n if str(msg.channel.type) == 'private' and msg.author != self.bot.user and str(msg.author.id) != jdata['owner']:\n user2 = self.bot.get_user(int(jdata['owner']))\n print(msg.content)\n if msg.author.id == onMessageUser:\n await user2.send(str(msg.content))\n else:\n await user2.send(str(msg.author)+'('+str(msg.author.id)+'):\\n'+str(msg.content))\n chonMessageUser(msg.author.id)\n if str(msg.channel.type) == 'private' and msg.author != self.bot.user and str(msg.author.id) == jdata['owner']:\n user = self.bot.get_user(int(onMessageUser))\n await user.send(msg.content)\n pass\n \n @commands.command()\n async def setuserid(self,ctx,userid:int=0):\n if ctx.author.id == int(jdata['owner']):\n if userid != 0 and len(str(userid)) == 18:\n user = self.bot.get_user(userid)\n if user != None:\n chonMessageUser(int(userid))\n\n @commands.command()\n async def sayd(self,ctx,*,msg:str='/0'):\n await ctx.message.delete()\n if msg == '/0':\n pass\n else:\n await ctx.send(msg)\n \n @commands.command()\n async def edit(self,ctx,msgid,*,remsg):\n if ctx.author.id == int(jdata['owner']):\n await ctx.message.delete()\n guild = self.bot.get_guild(ctx.message.guild.id)\n channel = guild.get_channel(ctx.message.channel.id)\n msg = await channel.fetch_message(msgid)\n await msg.edit(content=remsg)\n \n @commands.command()\n async def tts(self,ctx,*,msg):\n await ctx.message.delete()\n await ctx.send(msg, tts=True)\n print('{}說:{}'.format(ctx.message.author,msg))\n #print(str(ctx.message.author) +'說:'+ msg)\n \n @commands.command()\n async def banmsg(self,ctx):\n if ctx.message.author.id == ctx.guild.owner_id or str(ctx.message.author.id) == jdata['owner']:\n await ctx.message.delete()\n a=0\n for i in ctx.message.mentions:\n if i.id in banmsguserid and a == 0:\n await ctx.send('此人已被BanMsg')\n a+=1\n else:\n banmsguserid.append(i.id)\n else:\n await ctx.send('權限不足 本指令只提供給伺服器傭有者 \\n本伺服器傭有者為 <@{}>'.format(ctx.guild.owner_id))\n\n \n @commands.command()\n async def banmsglist(self,ctx):\n guild = ctx.guild\n a=0\n message ='```css'\n for i in banmsguserid:\n member = guild.get_member(i)\n message+='\\n{}'.format(member)\n a+=1\n message += '\\n```'\n if a == 0:\n await ctx.send('```css\\n尚未有人被BanMsg\\n```')\n else:\n await ctx.send(message)\n\n @commands.command()\n async def unbanmsg(self,ctx):\n if ctx.message.author.id == ctx.guild.owner_id or str(ctx.message.author.id) == jdata['owner']:\n await ctx.message.delete()\n a=0\n for i in ctx.message.mentions:\n if i.id not in banmsguserid and a == 0:\n await ctx.send('此人尚未被BanMsg')\n a+=1\n else:\n banmsguserid.remove(i.id)\n else:\n await ctx.send('權限不足 本指令只提供給伺服器傭有者 \\n本伺服器傭有者為 <@{}>'.format(ctx.guild.owner_id))\n\n @commands.command(aliases=['su'])\n async def senduser(self,ctx,userid: int=0,*,msg:str='\\0'):\n if ctx.author.id == int(jdata['owner']):\n if userid == 0:\n pass\n else:\n user = self.bot.get_user(int(userid))\n if user == None:\n pass\n else:\n if msg == '\\0':\n pass\n else:\n await user.send(msg)\n pass\n\n @commands.command()\n async def help(self,ctx):\n await ctx.send('```css\\n'\n +str(jdata['command_prefix'])+'ping 顯示機器人延遲\\n'\n +str(jdata['command_prefix'])+'ran 骰子遊戲1~10\\n'\n +str(jdata['command_prefix'])+'clear [num] 刪除指定數量的聊天內容\\n'\n +str(jdata['command_prefix'])+'sayd [msg] 使機器人說話\\n'\n #+str(jdata['command_prefix'])+'member 顯示伺服器中所有人的狀態\\n'\n #+str(jdata['command_prefix'])+'offline 顯示離線名單\\n'\n #+str(jdata['command_prefix'])+'online 顯示上線名單\\n'\n +str(jdata['command_prefix'])+'user 顯示個人訊息(管理員Debug用)\\n'\n +str(jdata['command_prefix'])+'ms 開始踩地雷遊戲 請找管理員開啟\\n'\n +str(jdata['command_prefix'])+'color help 顏色修改提示\\n'\n +str(jdata['command_prefix'])+'math [整數20~50] 開始math遊戲\\n'\n +str(jdata['command_prefix'])+'ooxx 開始OOXX遊戲\\n'\n +str(jdata['command_prefix'])+'snake 貪吃蛇(分數上限:88)\\n'\n +'=============AABB=============\\n'\n +str(jdata['command_prefix'])+'aabb help 顯示AABB遊戲提示\\n'\n +str(jdata['command_prefix'])+'aabb s 開始終極密碼\\n'\n +str(jdata['command_prefix'])+'autoreset 終極密碼自動重啟\\n'\n #+str(jdata['command_prefix'])+'invite [tag玩家] 邀請他人進入目前語音頻道'\n +'```')\n\n \n @commands.command()\n async def emmsg(self,ctx,msgid,em):\n msg = await ctx.message.channel.fetch_message(int(msgid))\n print(msg.content)\n await ctx.message.delete()\n if len(em)<18:\n await msg.add_reaction(em)\n else:\n emoji = self.bot.get_emoji(int(((em.split('>'))[0])[-18:]))\n await msg.add_reaction(emoji)\n\n @commands.command()\n async def clear(self,ctx,num:int):\n if ctx.message.author.id == ctx.guild.owner_id or str(ctx.message.author.id) == jdata['owner']:\n purge = await ctx.channel.purge(limit=num+1)\n if len(purge) >= 50 :\n await ctx.send('https://tenor.com/view/explode-blast-blow-nuclear-boom-gif-15025770')\n print('{} ---ID {}在 << {} >> 頻道使用了clear指令刪除了{}個對話'.format(ctx.message.author,ctx.message.author.id,ctx.channel.name,len(purge)-1))\n else:\n await ctx.send('權限不足 本指令只提供給伺服器傭有者 \\n本伺服器傭有者為 <@{}>'.format(ctx.guild.owner_id))\n\ndef setup(bot):\n bot.add_cog(Msg(bot))","repo_name":"Wuchieh/dcbotpy","sub_path":"cmds/msg.py","file_name":"msg.py","file_ext":"py","file_size_in_byte":7204,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28738890544","text":"import os\nimport bpy\nimport bmesh\nfrom bgl import *\nfrom bpy.props import *\nfrom math import radians, degrees\nfrom .. utils import update_bevel_modifier_if_necessary\nfrom ... utils.context import ExecutionContext\nfrom . soft_sharpen import soft_sharpen_object\nfrom ... preferences import tool_overlays_enabled, get_hops_preferences_colors_with_transparency, Hops_display_time, Hops_fadeout_time\nfrom ... utils.blender_ui import get_location_in_current_3d_view\nfrom ... utils.objects import get_modifier_with_type, apply_modifiers\nfrom ... overlay_drawer import show_custom_overlay, disable_active_overlays, show_text_overlay\nfrom ... graphics.drawing2d import set_drawing_dpi, draw_horizontal_line, draw_boolean, draw_text, draw_box, draw_logo_csharp\n\nmod_types = [\n (\"BOOLEAN\", \"Boolean\", \"\"),\n (\"MIRROR\", \"Mirror\", \"\"),\n (\"BEVEL\", \"Bevel\", \"\"),\n (\"SOLIDIFY\", \"Solidify\", \"\"),\n (\"ARRAY\", \"Array\", \"\"),]\n\nclass ComplexSharpenOperator(bpy.types.Operator):\n bl_idname = \"hops.complex_sharpen\"\n bl_label = \"C-Sharp\"\n bl_options = {\"REGISTER\", \"UNDO\"}\n bl_description = \"Sharpen the mesh while bevelling on sharp edges\"\n \n items = [(x.identifier, x.name, x.description, x.icon)\n for x in bpy.types.Modifier.bl_rna.properties['type'].enum_items]\n\n\n modifier_types = EnumProperty(name = \"Modifier Types\", default = {'BOOLEAN', 'SOLIDIFY'},\n options = {\"ENUM_FLAG\"}, items = mod_types)\n\n segment_amount = IntProperty(name=\"Segments\", description = \"Segments For Bevel\", default = 3, min = 1, max = 12)\n\n bevelwidth = FloatProperty(name=\"Bevel Width Amount\",\n description=\"Set Bevel Width\",\n default=0.0200,\n min = 0.002,\n max =1.50)\n\n sharpness = FloatProperty(name = \"Sharpness\", default = radians(30),\n min = radians(1), max = radians(180), subtype = \"ANGLE\")\n\n auto_smooth_angle = FloatProperty(name = \"Auto Smooth Angle\", default = radians(60),\n min = 0.0, max = radians(180), subtype = \"ANGLE\")\n\n additive_mode = BoolProperty(name = \"Additive Mode\",\n description = \"Don't clear existing edge properties\",\n default = True)\n\n sub_d_sharpening = BoolProperty(name = \"Sub-D Sharpening\")\n\n profile_value = 0.70\n reveal_mesh = True\n\n @classmethod\n def poll(cls, context):\n object = context.active_object\n if object is None: return False\n return object.type == \"MESH\" and object.mode == \"OBJECT\"\n\n def draw(self, context):\n layout = self.layout\n box = layout.box()\n col = box.column()\n object = bpy.context.active_object\n if object.hops.status != \"CSTEP\":\n col.label(\"Modifiers Applied By Csharp\")\n col.prop(self, \"modifier_types\", expand=True)\n \n col.label(\"\")\n col.label(\"General Parameters\")\n col.prop(self, \"sharpness\")\n col.prop(self, \"auto_smooth_angle\")\n col.prop(self, \"segment_amount\")\n col.prop(self, \"bevelwidth\")\n \n col.label(\"\")\n col.label(\"Sharpening Parameters\")\n box.prop(self, \"additive_mode\")\n box.prop(self, \"sub_d_sharpening\")\n\n def invoke(self, context, event):\n self.execute(context)\n \n object = bpy.context.active_object\n if object.hops.status != \"CSTEP\":\n if tool_overlays_enabled():\n disable_active_overlays()\n self.wake_up_overlay = show_custom_overlay(draw,\n parameter_getter = self.parameter_getter,\n location = get_location_in_current_3d_view(\"CENTER\", \"BOTTOM\", offset = (0, 130)),\n location_type = \"CUSTOM\",\n stay_time = Hops_display_time(),\n fadeout_time = Hops_fadeout_time())\n\n return {\"FINISHED\"}\n\n def parameter_getter(self):\n return self.sharpness, self.auto_smooth_angle, self.additive_mode, self.sub_d_sharpening, self.segment_amount, self.bevelwidth\n\n def execute(self, context):\n active = bpy.context.active_object\n \n object = bpy.context.active_object\n if object.hops.status == \"CSTEP\":\n self.sharpness = radians(40)\n self.additive_mode = True\n if tool_overlays_enabled():\n text = \"Don't Csharpen Cstepped Meshes!\"\n show_text_overlay(text = text, font_size = 16, stay_time = Hops_display_time(), fadeout_time = Hops_fadeout_time())\n \n if object.hops.status != \"CSTEP\":\n if object.hops.status == \"CSHARP\":\n soft_sharpen_object(\n context.active_object, \n self.sharpness, \n self.auto_smooth_angle, \n self.additive_mode, \n self.sub_d_sharpening, \n self.reveal_mesh)\n \n complex_sharpen_active_object(\n context.active_object,\n self.sharpness,\n self.auto_smooth_angle,\n self.additive_mode,\n self.sub_d_sharpening,\n self.modifier_types,\n self.segment_amount,\n self.bevelwidth,\n self.reveal_mesh)\n\n update_bevel_modifier_if_necessary(\n context.active_object,\n self.segment_amount, \n self.bevelwidth,\n self.profile_value)\n\n bpy.ops.object.select_all(action='DESELECT')\n active.select = True\n\n try: self.wake_up_overlay()\n except: pass\n \n return {\"FINISHED\"}\n\ndef complex_sharpen_active_object(object, sharpness, auto_smooth_angle, additive_mode, sub_d_sharpening, modifier_types, segment_amount, bevelwidth, reveal_mesh):\n with ExecutionContext(mode = \"OBJECT\", active_object = object):\n apply_modifiers(object, modifier_types)\n if sub_d_sharpening == False:\n soft_sharpen_object(object, sharpness, auto_smooth_angle, additive_mode, sub_d_sharpening, reveal_mesh) \n if object.hops.status == \"SUBSHARP\":\n sub_d_sharpening == True\n soft_sharpen_object(object, sharpness, auto_smooth_angle, additive_mode, sub_d_sharpening, reveal_mesh) \n \n object = bpy.context.active_object\n if sub_d_sharpening == True:\n object.hops.status = \"SUBSHARP\"\n \n else:\n if object.hops.status != \"CSTEP\":\n object.hops.status = \"CSHARP\"\n\n# Overlay\n###################################################################\n\ndef draw(display, parameter_getter):\n sharpness, auto_smooth_angle, additive_mode, sub_d_sharpening, segment_amount, bevelwidth = parameter_getter()\n scale_factor = 0.9\n\n glEnable(GL_BLEND)\n glEnable(GL_LINE_SMOOTH)\n\n set_drawing_dpi(display.get_dpi() * scale_factor)\n dpi_factor = display.get_dpi_factor() * scale_factor\n line_height = 18 * dpi_factor\n line_length = 270\n\n transparency = display.transparency\n\n color_text1, color_text2, color_border, color_border2 = get_hops_preferences_colors_with_transparency(transparency)\n region_width = bpy.context.region.width\n\n\n\n # Box\n ########################################################\n\n location = display.location\n x, y = location.x - 60* dpi_factor, location.y - 118* dpi_factor\n\n draw_box(0, 43 *dpi_factor, region_width, -4 * dpi_factor, color = color_border2)\n draw_box(0, 0, region_width, -82 * dpi_factor, color = color_border)\n\n draw_logo_csharp(color_border2)\n\n\n # Name\n ########################################################\n\n\n draw_text(\"CSHARPEN\", x - 380 *dpi_factor , y -12*dpi_factor,\n align = \"LEFT\", size = 20 , color = color_text2)\n\n # Fitst Coloumn\n ########################################################\n x = x - 160 * dpi_factor\n r = 34 * dpi_factor\n\n #do we use it ?\n '''draw_text(\"BEVELS WERE ADDED\", x + line_length * dpi_factor, y - 42 * dpi_factor,\n align = \"RIGHT\", size = 9, color = color_text2)'''\n\n\n draw_text(\"ADDITIVE MODE\", x + r, y,\n align = \"LEFT\", color = color_text2)\n\n draw_boolean(additive_mode, x, y , size = 11, alpha = transparency)\n\n draw_text(\"SUB D SHARPENING\", x + r, y - line_height,\n align = \"LEFT\", color = color_text2)\n \n draw_boolean(sub_d_sharpening, x, y - line_height, size = 11, alpha = transparency)\n\n\n # Second Column\n ########################################################\n\n x = x + 300 * dpi_factor\n\n draw_text(\"SHARPNESS:\", x, y,\n align = \"RIGHT\", size = 12, color = color_text2)\n\n draw_text(\"{}°\".format(round(degrees(sharpness))), x + 30 * dpi_factor, y,\n align = \"RIGHT\", size = 12, color = color_text2)\n\n draw_text(\"SMOOTHING ANGLE:\", x, y - line_height,\n align = \"RIGHT\", size = 12, color = color_text2)\n\n draw_text(\"{}°\".format(round(degrees(auto_smooth_angle))), x + 30 * dpi_factor, y - line_height,\n align = \"RIGHT\", size = 12, color = color_text2)\n\n # Third Coloumn\n ########################################################\n x = x + 160 * dpi_factor\n\n draw_text(\"BEVEL SEGMENTS:\", x , y,\n align = \"RIGHT\", size = 12, color = color_text2)\n\n draw_text(\"{}\".format(segment_amount), x + r, y,\n align = \"RIGHT\", size = 12, color = color_text2)\n\n draw_text(\"BEVEL WIDTH:\", x , y - line_height,\n align = \"RIGHT\", size = 12, color = color_text2)\n\n draw_text(\"{}\".format('%.2f'%(bevelwidth)), x + r, y - line_height,\n align = \"RIGHT\", size = 12, color = color_text2)\n \n\n glDisable(GL_BLEND)\n glDisable(GL_LINE_SMOOTH) \n \n","repo_name":"mx1001/hops_p","sub_path":"operators/sharpeners/complex_sharpen.py","file_name":"complex_sharpen.py","file_ext":"py","file_size_in_byte":9966,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"1102411667","text":"from time import sleep\nfrom dataclasses import dataclass\nfrom vue.shared.infrastructure.facades.dom import Dom\n\n\n@dataclass\nclass Element:\n __dom: Dom\n\n def __int__(self, dom: Dom):\n self.__dom = dom\n\n def set_value(self, element_id: str, value: str) -> None:\n if not self.__dom:\n return None\n\n input_element = self.__dom.find_by_id(element_id)\n input_element.send_keys(value)\n sleep(0.2)\n\n def set_value_by_name(self, element_name: str, value: str) -> None:\n if not self.__dom:\n return None\n\n input_element = self.__dom.find_by_name(element_name)\n input_element.send_keys(value)\n sleep(0.2)\n\n @staticmethod\n def set_value_in_input(input_element: object, value: str) -> None:\n input_element.send_keys(value)\n sleep(0.2)\n\n def set_value_by_xpath(self, xpath: str, value: str) -> None:\n input_element = self.__dom.find_by_xpath(xpath)\n input_element.send_keys(value)\n sleep(0.2)\n","repo_name":"eacevedof/prj_python37","sub_path":"selenium/vue/shared/infrastructure/facades/element.py","file_name":"element.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"73108451024","text":"# This is a game where you have to get to the cherry without being touched by the monsters\r\n\r\nimport pygame\r\nimport random\r\n\r\n# Initialise game\r\npygame.init()\r\n\r\n# Constants for screen width and height\r\nSCREEN_WIDTH = 1040\r\nSCREEN_HEIGHT = 680\r\n\r\n# Create screen object\r\nscreen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))\r\n\r\n# Load images for player, enemy and prize\r\nplayer = pygame.image.load(\"C:/Users/Jaco-PC/Dropbox/Gerhardus jacobus Steyn-50451/Introduction to Programming/Task 15/player.jpg\")\r\nenemy = pygame.image.load(\"C:/Users/Jaco-PC/Dropbox/Gerhardus jacobus Steyn-50451/Introduction to Programming/Task 15/monster.jpg\")\r\nprize = pygame.image.load(\"C:/Users/Jaco-PC/Dropbox/Gerhardus jacobus Steyn-50451/Introduction to Programming/Task 15/prize.jpg\")\r\n\r\n# Get dimentions of images\r\nplayer_height = player.get_height()\r\nplayer_width = player.get_width()\r\nenemy_height = enemy.get_height()\r\nenemy_width = enemy.get_width()\r\nprize_height = prize.get_height()\r\nprize_width = prize.get_width()\r\n\r\n# Storing the positions of the player, enemies and prize\r\nplayer_x_position = 0\r\nplayer_y_position = random.randint(0, SCREEN_HEIGHT - player_height)\r\n\r\nenemy1_x_position = SCREEN_WIDTH - enemy_width\r\nenemy1_y_position = random.randint(0, SCREEN_HEIGHT - enemy_height)\r\nenemy2_x_position = SCREEN_WIDTH - enemy_width\r\nenemy2_y_position = random.randint(0, SCREEN_HEIGHT - enemy_height)\r\nenemy3_x_position = SCREEN_WIDTH - enemy_width\r\nenemy3_y_position = random.randint(0, SCREEN_HEIGHT - enemy_height)\r\n\r\nprize_x_position = SCREEN_WIDTH / 2\r\nprize_y_position = SCREEN_HEIGHT / 2\r\n\r\n# Boolean variables to check which key is pressed\r\nkeyUp = False\r\nkeyDown = False\r\nkeyLeft = False\r\nkeyRight = False\r\n\r\n# Speed and direction of enemies\r\nenemy1_change_x = 0.3\r\nenemy1_change_y = 0.2\r\nenemy2_change_x = 0.15\r\nenemy2_change_y = 0.3\r\nenemy3_change_x = 0.2\r\nenemy3_change_y = 0.15\r\n\r\n# Run until the user asks to quit\r\nrunning = True\r\n\r\nwhile running:\r\n \r\n # Fill background\r\n screen.fill(0)\r\n screen.blit(player, (player_x_position, player_y_position))\r\n screen.blit(enemy, (enemy1_x_position, enemy1_y_position))\r\n screen.blit(enemy, (enemy2_x_position, enemy2_y_position))\r\n screen.blit(enemy, (enemy3_x_position, enemy3_y_position))\r\n screen.blit(prize, (prize_x_position, prize_y_position))\r\n\r\n # Update the screen\r\n pygame.display.flip()\r\n\r\n # Check if user clicks close button on window\r\n for event in pygame.event.get():\r\n\r\n # If windows close button is clicked, quit the game\r\n if event.type == pygame.QUIT:\r\n running = False \r\n\r\n # Is a button pressed?\r\n if event.type == pygame.KEYDOWN:\r\n\r\n # Check which key is pressed\r\n if event.key == pygame.K_UP: \r\n keyUp = True\r\n if event.key == pygame.K_DOWN:\r\n keyDown = True\r\n if event.key == pygame.K_LEFT:\r\n keyLeft = True\r\n if event.key == pygame.K_RIGHT:\r\n keyRight = True\r\n\r\n # Is the button released?\r\n if event.type == pygame.KEYUP:\r\n\r\n # Check which key is pressed\r\n if event.key == pygame.K_UP: \r\n keyUp = False\r\n if event.key == pygame.K_DOWN:\r\n keyDown = False\r\n if event.key == pygame.K_LEFT:\r\n keyLeft = False\r\n if event.key == pygame.K_RIGHT:\r\n keyRight = False\r\n\r\n # What to do when a certain button is pressed?\r\n if keyUp == True:\r\n if player_y_position > 0: # Check that player doesn't move off screen\r\n player_y_position -= 1\r\n if keyDown == True:\r\n if player_y_position < SCREEN_HEIGHT - player_height: # Check that player doesn't move off screen\r\n player_y_position += 1\r\n if keyLeft == True:\r\n if player_x_position > 0: # Check that player doesn't move off screen\r\n player_x_position -= 1\r\n if keyRight == True:\r\n if player_x_position < SCREEN_WIDTH - player_width: # Check that player doesn't move off screen\r\n player_x_position += 1\r\n\r\n # Assign variable to player size\r\n player_box = pygame.Rect(player.get_rect())\r\n\r\n # Update player_box to stay around player\r\n player_box.top = player_y_position\r\n player_box.left = player_x_position\r\n\r\n # Assign variable to enemy size\r\n enemy1_box = pygame.Rect(enemy.get_rect())\r\n enemy2_box = pygame.Rect(enemy.get_rect())\r\n enemy3_box = pygame.Rect(enemy.get_rect())\r\n\r\n # Update enemy#_box to stay around enemy\r\n enemy1_box.top = enemy1_y_position\r\n enemy1_box.left = enemy1_x_position\r\n enemy2_box.top = enemy2_y_position\r\n enemy2_box.left = enemy2_x_position\r\n enemy3_box.top = enemy3_y_position\r\n enemy3_box.left = enemy3_x_position\r\n\r\n # Assign variable to prize size\r\n prize_box = pygame.Rect(prize.get_rect())\r\n\r\n # Update prize_box to stay around prize\r\n prize_box.top = prize_y_position\r\n prize_box.left = prize_x_position\r\n\r\n # Test collision of enemy and player\r\n if player_box.colliderect(enemy1_box) or player_box.colliderect(enemy2_box) or player_box.colliderect(enemy3_box):\r\n print(\"YOU LOSE!\")\r\n pygame.quit()\r\n exit(0)\r\n\r\n # Test collision of player and prize\r\n if player_box.colliderect(prize_box):\r\n print(\"YOU WIN!\")\r\n pygame.quit()\r\n exit(0)\r\n\r\n # Move the enemies around\r\n enemy1_x_position += enemy1_change_x\r\n enemy1_y_position += enemy1_change_y\r\n enemy2_x_position += enemy2_change_x\r\n enemy2_y_position += enemy2_change_y\r\n enemy3_x_position += enemy3_change_x\r\n enemy3_y_position += enemy3_change_y\r\n\r\n # Change enemies' direction when wall is hit\r\n if enemy1_x_position > (SCREEN_WIDTH - enemy_width) or enemy1_x_position < 0:\r\n enemy1_change_x = enemy1_change_x * -1\r\n if enemy1_y_position > (SCREEN_HEIGHT - enemy_height) or enemy1_y_position < 0:\r\n enemy1_change_y = enemy1_change_y * -1\r\n\r\n if enemy2_x_position > (SCREEN_WIDTH - enemy_width) or enemy2_x_position < 0:\r\n enemy2_change_x = enemy2_change_x * -1\r\n if enemy2_y_position > (SCREEN_HEIGHT - enemy_height) or enemy2_y_position < 0:\r\n enemy2_change_y = enemy2_change_y * -1\r\n\r\n if enemy3_x_position > (SCREEN_WIDTH - enemy_width) or enemy3_x_position < 0:\r\n enemy3_change_x = enemy3_change_x * -1\r\n if enemy3_y_position > (SCREEN_HEIGHT - enemy_height) or enemy3_y_position < 0:\r\n enemy3_change_y = enemy3_change_y * -1\r\n\r\npygame.quit()","repo_name":"Gainzislife/Simple-Game","sub_path":"cap2_game.py","file_name":"cap2_game.py","file_ext":"py","file_size_in_byte":6572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12470109483","text":"#coding=utf-8;\n\nimport tornado.web\nimport tornado.httpserver\nimport tornado.ioloop\nimport os\nimport tornado.gen\n\n\n\nimport time\n\n\"\"\"\n 先访问sleep,sleep 会阻塞now\n 使用异步装饰器 和 异步生成器 解决此问题\n 1> @tornado.web.asynchronous 是异步装饰器,可以在向改变其行为的方法上面加上装饰器\n 使用异步装饰器的时候,tornado 不会自己关闭连接 需要显式的调用self.finish\n\n 2> tornado.gen 模块,提供一个更为整洁的方式进行异步请求\n\n 如下的方式,就不会进行阻塞\n\n\"\"\"\n\n\nclass SleepHandler(tornado.web.RequestHandler):\n @tornado.web.asynchronous\n @tornado.gen.coroutine\n def get(self, *args, **kwargs):\n yield tornado.gen.Task(tornado.ioloop.IOLoop.instance().add_timeout,time.time()+5);\n self.write(\"when i sleep 5s\");\n\n\nclass NowHandler(tornado.web.RequestHandler):\n def get(self, *args, **kwargs):\n self.write(\"i hope you see me now\");\n\n\napp = tornado.web.Application([(\"/sleep\",SleepHandler),(r\"/now\",NowHandler)]);\n\n\nif __name__ == '__main__':\n http_server = tornado.httpserver.HTTPServer(app);\n http_server.listen(8080);\n tornado.ioloop.IOLoop.instance().start();\n\n\n","repo_name":"AlexanderYeah/SKTornadoWorkSpace","sub_path":"Lession13/asyncHTTPClient_learn.py","file_name":"asyncHTTPClient_learn.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18418926202","text":"from __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\n\r\nimport tensorflow as tf\r\nimport numpy as np\r\nimport argparse\r\nimport os\r\nimport json\r\nimport glob\r\nimport random\r\nimport collections\r\nimport math\r\nimport time\r\n\r\nparser = argparse.ArgumentParser() #创建类实例\r\nparser.add_argument(\"--input_dir\",help = \"path to folder containing images\")\r\nparser.add_argument(\"--mode\",required=True,choices=[\"train\",\"test\",\"export\"])\r\nparser.add_argument(\"--output_dir\",required=True,help=\"where to put output files\")\r\nparser.add_argument(\"--seed\",type=int)\r\nparser.add_argument(\"--checkpoint\",default=None,help=\"directory with checkpoint to resume training from or use for testing\")\r\n\r\nparser.add_argument(\"--max_steps\",type=int,help=\"number of training steps(0 to disable)\")\r\nparser.add_argument(\"--max_epochs\", type=int, help=\"number of training epochs\")\r\nparser.add_argument(\"--summary_freq\", type=int, default=100, help=\"update summaries every summary_freq steps\")\r\nparser.add_argument(\"--progress_freq\", type=int, default=50, help=\"display progress every progress_freq steps\")\r\nparser.add_argument(\"--trace_freq\", type=int, default=0, help=\"trace execution every trace_freq steps\")\r\nparser.add_argument(\"--display_freq\", type=int, default=0, help=\"write current training images every display_freq steps\")\r\nparser.add_argument(\"--save_freq\", type=int, default=5000, help=\"save model every save_freq steps, 0 to disable\")\r\n\r\nparser.add_argument(\"--aspect_ratio\", type=float, default=1.0, help=\"aspect ratio of output images (width/height)\")\r\nparser.add_argument(\"--lab_colorization\", action=\"store_true\", help=\"split input image into brightness (A) and color (B)\")\r\nparser.add_argument(\"--batch_size\", type=int, default=1, help=\"number of images in batch\")\r\nparser.add_argument(\"--which_direction\", type=str, default=\"AtoB\", choices=[\"AtoB\", \"BtoA\"])\r\nparser.add_argument(\"--ngf\", type=int, default=64, help=\"number of generator filters in first conv layer\")\r\nparser.add_argument(\"--ndf\", type=int, default=64, help=\"number of discriminator filters in first conv layer\")\r\nparser.add_argument(\"--scale_size\", type=int, default=286, help=\"scale images to this size before cropping to 256x256\")\r\nparser.add_argument(\"--flip\", dest=\"flip\", action=\"store_true\", help=\"flip images horizontally\")\r\nparser.add_argument(\"--no_flip\", dest=\"flip\", action=\"store_false\", help=\"don't flip images horizontally\")\r\nparser.set_defaults(flip=True)\r\nparser.add_argument(\"--lr\", type=float, default=0.0002, help=\"initial learning rate for adam\")\r\nparser.add_argument(\"--beta1\", type=float, default=0.5, help=\"momentum term of adam\")\r\nparser.add_argument(\"--l1_weight\", type=float, default=100.0, help=\"weight on L1 term for generator gradient\")\r\nparser.add_argument(\"--gan_weight\", type=float, default=1.0, help=\"weight on GAN term for generator gradient\")\r\n\r\nparser.add_argument(\"--output_filetype\",default=\"png\",choices=[\"png\",\"jpeg\"]) #添加命令行参数\r\na = parser.parse_args() #返回namespace\r\n\r\nEPS = 1e-12 #???\r\nCROP_SIZE = 256\r\n\r\nExamples = collections.namedtuple(\"Examples\",\"paths,inputs,targets,count,steps_per_epoch\") #返回一个名为Examples,包含属性:paths,inputs,targets,count,steps_per_epoch,的类\r\nModel = collections.namedtuple(\"Model\",\"outputs,predict_real,predict_fake,discrim_loss,discrim_grads_and_vars,gen_loss_GAN,gen_loss_L1,gen_grads_and_vars,train\")\r\n\r\ndef preprocess(image): #???\r\n with tf.name_scope(\"preprocess\"):\r\n #[0,1] => [-1,1]\r\n return image * 2 - 1\r\n\r\ndef deprocess(image): #???\r\n with tf.name_scope(\"deprocess\"):\r\n #[-1,1] => [0,1]\r\n return (image + 1)/2 #image像素 范围\r\n\r\ndef preprocess_lab(lab): #???\r\n with tf.name_scope(\"preprocess_lab\"):\r\n L_chan,a_chan,b_chan = tf.unstack(lab,axis=2)\r\n #L_chan: black and white with input range [0,100]\r\n #a_chan / b_chan : color channels with input range ~[-110,110],not exact\r\n #[0,100] => [-1,1], ~[-110,110] => [-1,1]\r\n return [L_chan / 50 - 1,a_chan / 110,b_chan /110]\r\n\r\ndef deprocess_lab(L_chan,a_chan,b_chan):#???\r\n with tf.name_scope(\"deprocess_lab\"):\r\n # this is axis=3 instead of axis=2 because we process inidvidual images but deprocess batches\r\n return tf.stack([(L_chan + 1) /2 * 100,a_chan * 110,b_chan * 110],axis=3)\r\n\r\ndef augment(image,brightness): #将图像转换成彩色的???\r\n #(a,b)color channels,combinewith L channel and convert to rgb\r\n a_chan , b_chan = tf.unstack(image,axis=3)\r\n L_chan = tf.squeeze(brightness,axis=3)\r\n lab = deprocess_lab(L_chan,a_chan,b_chan)\r\n rgb = lab_to_rgb(lab)\r\n return rgb\r\n \r\ndef conv(batch_input,out_channels,stride):\r\n with tf.variable_scope(\"conv\"):\r\n in_channels = batch_input.get_shape()[3]\r\n filter = tf.get_variable(\"filter\",[4,4,in_channels,out_channels],dtype=tf.float32,initializer = tf.random_normal_initializer(0,0.02))\r\n # [batch,in_height,in_width,in_channels],[filter_widht,filter_height,in_channels,out_channels]\r\n # => [batch,out_height,out_width,out_channels]\r\n padded_input = tf.pad(batch_input,[[0,0],[1,1],[1,1],[0,0]],mode=\"CONSTANT\")\r\n conv = tf.nn.conv2d(padded_input,filter,[1,stride,stride,1],padding=\"VALID\")\r\n return conv\r\n\r\ndef lrelu(x,a):\r\n with tf.name_scope(\"lrelu\"):\r\n # adding these together creates the leak part and linear part\r\n # then cancels them out by subtracting/adding an absolute value term\r\n # leak: a*x/2 - a*abs(x)/2\r\n # linear: x/2 + abs(x)/2\r\n\r\n # this block looks like it has 2 inputs on the graph unless we do this\r\n x = tf.identity(x)\r\n return (0.5 * (1+a)) * x + (0.5 * (1 - a)) * tf.abs(x)\r\n\r\ndef batchnorm(input): #batch normalization\r\n with tf.variable_scope(\"batchnorm\"):\r\n # this block looks like it has 3 inputs on the graph unless we do this\r\n input = tf.identity(input)\r\n\r\n channels = input.get_shape()[3]\r\n offset = tf.get_variable(\"offset\", [channels], dtype=tf.float32, initializer=tf.zeros_initializer())\r\n scale = tf.get_variable(\"scale\", [channels], dtype=tf.float32, initializer=tf.random_normal_initializer(1.0, 0.02))\r\n mean, variance = tf.nn.moments(input, axes=[0, 1, 2], keep_dims=False)\r\n variance_epsilon = 1e-5\r\n normalized = tf.nn.batch_normalization(input, mean, variance, offset, scale, variance_epsilon=variance_epsilon)\r\n return normalized\r\n\r\ndef deconv(batch_input, out_channels):\r\n with tf.variable_scope(\"deconv\"):\r\n batch, in_height, in_width, in_channels = [int(d) for d in batch_input.get_shape()]\r\n filter = tf.get_variable(\"filter\", [4, 4, out_channels, in_channels], dtype=tf.float32, initializer=tf.random_normal_initializer(0, 0.02))\r\n # [batch, in_height, in_width, in_channels], [filter_width, filter_height, out_channels, in_channels]\r\n # => [batch, out_height, out_width, out_channels]\r\n conv = tf.nn.conv2d_transpose(batch_input, filter, [batch, in_height * 2, in_width * 2, out_channels], [1, 2, 2, 1], padding=\"SAME\")\r\n return conv\r\n\r\ndef check_image(image): #确定image形式 3维\r\n assertion = tf.assert_equal(tf.shape(image)[-1], 3, message=\"image must have 3 color channels\")\r\n with tf.control_dependencies([assertion]):\r\n image = tf.identity(image)\r\n\r\n if image.get_shape().ndims not in (3, 4):\r\n raise ValueError(\"image must be either 3 or 4 dimensions\")\r\n\r\n # make the last dimension 3 so that you can unstack the colors\r\n shape = list(image.get_shape())\r\n shape[-1] = 3\r\n image.set_shape(shape)\r\n return image\r\n\r\n# based on https://github.com/torch/image/blob/9f65c30167b2048ecbe8b7befdc6b2d6d12baee9/generic/image.c\r\ndef rgb_to_lab(srgb): #???\r\n with tf.name_scope(\"rgb_to_lab\"):\r\n srgb = check_image(srgb)\r\n srgb_pixels = tf.reshape(srgb, [-1, 3])\r\n\r\n with tf.name_scope(\"srgb_to_xyz\"):\r\n linear_mask = tf.cast(srgb_pixels <= 0.04045, dtype=tf.float32)\r\n exponential_mask = tf.cast(srgb_pixels > 0.04045, dtype=tf.float32)\r\n rgb_pixels = (srgb_pixels / 12.92 * linear_mask) + (((srgb_pixels + 0.055) / 1.055) ** 2.4) * exponential_mask\r\n rgb_to_xyz = tf.constant([\r\n # X Y Z\r\n [0.412453, 0.212671, 0.019334], # R\r\n [0.357580, 0.715160, 0.119193], # G\r\n [0.180423, 0.072169, 0.950227], # B\r\n ])\r\n xyz_pixels = tf.matmul(rgb_pixels, rgb_to_xyz)\r\n\r\n # https://en.wikipedia.org/wiki/Lab_color_space#CIELAB-CIEXYZ_conversions\r\n with tf.name_scope(\"xyz_to_cielab\"):\r\n # convert to fx = f(X/Xn), fy = f(Y/Yn), fz = f(Z/Zn)\r\n\r\n # normalize for D65 white point\r\n xyz_normalized_pixels = tf.multiply(xyz_pixels, [1/0.950456, 1.0, 1/1.088754])\r\n\r\n epsilon = 6/29\r\n linear_mask = tf.cast(xyz_normalized_pixels <= (epsilon**3), dtype=tf.float32)\r\n exponential_mask = tf.cast(xyz_normalized_pixels > (epsilon**3), dtype=tf.float32)\r\n fxfyfz_pixels = (xyz_normalized_pixels / (3 * epsilon**2) + 4/29) * linear_mask + (xyz_normalized_pixels ** (1/3)) * exponential_mask\r\n\r\n # convert to lab\r\n fxfyfz_to_lab = tf.constant([\r\n # l a b\r\n [ 0.0, 500.0, 0.0], # fx\r\n [116.0, -500.0, 200.0], # fy\r\n [ 0.0, 0.0, -200.0], # fz\r\n ])\r\n lab_pixels = tf.matmul(fxfyfz_pixels, fxfyfz_to_lab) + tf.constant([-16.0, 0.0, 0.0])\r\n\r\n return tf.reshape(lab_pixels, tf.shape(srgb))\r\n\r\ndef lab_to_rgb(lab):\r\n with tf.name_scope(\"lab_to_rgb\"):\r\n lab = check_image(lab)\r\n lab_pixels = tf.reshape(lab, [-1, 3])\r\n\r\n # https://en.wikipedia.org/wiki/Lab_color_space#CIELAB-CIEXYZ_conversions\r\n with tf.name_scope(\"cielab_to_xyz\"):\r\n # convert to fxfyfz\r\n lab_to_fxfyfz = tf.constant([\r\n # fx fy fz\r\n [1/116.0, 1/116.0, 1/116.0], # l\r\n [1/500.0, 0.0, 0.0], # a\r\n [ 0.0, 0.0, -1/200.0], # b\r\n ])\r\n fxfyfz_pixels = tf.matmul(lab_pixels + tf.constant([16.0, 0.0, 0.0]), lab_to_fxfyfz)\r\n\r\n # convert to xyz\r\n epsilon = 6/29\r\n linear_mask = tf.cast(fxfyfz_pixels <= epsilon, dtype=tf.float32)\r\n exponential_mask = tf.cast(fxfyfz_pixels > epsilon, dtype=tf.float32)\r\n xyz_pixels = (3 * epsilon**2 * (fxfyfz_pixels - 4/29)) * linear_mask + (fxfyfz_pixels ** 3) * exponential_mask\r\n\r\n # denormalize for D65 white point\r\n xyz_pixels = tf.multiply(xyz_pixels, [0.950456, 1.0, 1.088754])\r\n\r\n with tf.name_scope(\"xyz_to_srgb\"):\r\n xyz_to_rgb = tf.constant([\r\n # r g b\r\n [ 3.2404542, -0.9692660, 0.0556434], # x\r\n [-1.5371385, 1.8760108, -0.2040259], # y\r\n [-0.4985314, 0.0415560, 1.0572252], # z\r\n ])\r\n rgb_pixels = tf.matmul(xyz_pixels, xyz_to_rgb)\r\n # avoid a slightly negative number messing up the conversion\r\n rgb_pixels = tf.clip_by_value(rgb_pixels, 0.0, 1.0)\r\n linear_mask = tf.cast(rgb_pixels <= 0.0031308, dtype=tf.float32)\r\n exponential_mask = tf.cast(rgb_pixels > 0.0031308, dtype=tf.float32)\r\n srgb_pixels = (rgb_pixels * 12.92 * linear_mask) + ((rgb_pixels ** (1/2.4) * 1.055) - 0.055) * exponential_mask\r\n\r\n return tf.reshape(srgb_pixels, tf.shape(lab))\r\n\r\ndef load_examples():\r\n if a.input_dir is None or not os.path.exists(a.input_dir):\r\n raise Exception(\"input_dir does not exist\")\r\n #获取input 文件\r\n input_paths = glob.glob(os.path.join(a.input_dir,\"*.jpg\")) #找出所有相关文件名\r\n decode = tf.image.decode_ipeg\r\n if len(input_paths) == 0:\r\n input_paths = glob.glob(os.path.join(a.input_dir,\"*.png\"))\r\n decode = tf.image.decode_png\r\n\r\n if len(input_paths) == 0: \r\n raise Exception(\"input_dir contains no image files\")\r\n\r\n def get_name(path):\r\n name,_ = os.path.splitext(os.path.basename(path))\r\n return name\r\n #将input 文件按不同类别分类\r\n if all(get_name(path).isdigit() for path in input_paths): #如果图片名为digit,则按digit分类\r\n input_paths = sorted(input_paths,key = lambda path: int(get_name(path)))\r\n else:\r\n input_paths = sorted(input_paths)#否则,按文件名分类\r\n #获取input_images\r\n with tf.name_scope(\"load_images\"):\r\n path_queue = tf.train.string_input_producer(input_paths,shuffle=a.mode == \"train\") #根据Input_paths创建一个输入队列\r\n reader = tf.WholeFileReader()\r\n paths,contents = reader.read(path_queue)#读取文件\r\n raw_input = decode(contents)#解密文件\r\n raw_input = tf.image.convert_image_dtype(raw_input,dtype=tf.float32) #图片归一化,返回[0,1]浮点类型数据\r\n\r\n assertion = tf.assert_equal(tf.shape(raw_input)[2],3,message=\"image does not have 3 channels\")\r\n with tf.control_dependencies([assertion]):#在有些机器学习程序中我们想要指定某些操作执行的依赖关系,这时我们可以使用tf.control_dependencies()来实现。 control_dependencies(control_inputs)返回一个控制依赖的上下文管理器,使用with关键字可以让在这个上下文环境中的操作都在control_inputs 执行\r\n raw_input = tf.identity(raw_input)#如果image有3channel,则执行该语句;返回一个一模一样的新的tensor\r\n\r\n raw_input.set_shape([None,None,3]) #???\r\n #将images分为A,B两类,并将A,B分到inputs,和,targets里边\r\n if a.lab_colorization:\r\n lab = rgb_to_lab(raw_input) #转为灰白图像???\r\n L_chan,a_chan,b_chan = preprocess_lab(lab) #???\r\n a_images = tf.expand_dims(L_chan,axis=2)\r\n b_images = tf.stack([a_chan,b_chan],axis=2)\r\n else:\r\n width = tf.shape(raw_input)[1]\r\n a_images = preprocess(raw_input[:,:width//2,:])#???\r\n b_images = preprocess(raw_input[:,width//2:,:])\r\n if a.which_direction == \"AtoB\":\r\n inputs,targets = [a_images,b_images]\r\n elif a.which_direction == \"BtoA\":\r\n inputs,targets = [b_images,a_images]\r\n else:\r\n raise Exception(\"invaild direction\")\r\n\r\n seed = random.randint(0,2**31 - 1) #???\r\n def transform(image): #将image转到相同尺寸大小\r\n r = image\r\n if a.flip:\r\n r = tf.image.random_flip_left_right(r,seed=seed)\r\n r = tf.image.resize_images(r,[a.scale_size,a.scale_size],method=tf.image.ResizeMethod.AREA)\r\n\r\n offset = tf.cast(tf.floor(tf.random_uniform([2],0,a.scale_size - CROP_SIZE + 1,seed = seed)),dtype = tf.int32)\r\n if a.scale_size > CROP_SIZE:\r\n r = tf.image.crop_to_bounding_box(r,offset[0],offset[1],CROP_SIZE,CROP_SIZE)\r\n elif a.scale_size < CROP_SIZE:\r\n raise Exception(\"scale size cannot be less than crop size\")\r\n return r\r\n #将inputs和targets中image size根据要求作统一\r\n with tf.name_scope(\"input_images\"):\r\n imput_images = transform(inputs)\r\n\r\n with tf.name_scope(\"target_images\"):\r\n target_images = transform(targets)\r\n #对inputs 和 targets 分批次\r\n paths_batch,inputs_batch,targets_path = tf.train.batch([paths,input_images,target_images],batch_size = a.batch_size)\r\n step_per_epoch = int(math.ceil(len(input_paths)/a.batch_size))\r\n #返回Examples类实例\r\n return Examples(paths=paths_batch, \r\n inputs=inputs_batch,\r\n targets=targets_batch,\r\n count=len(input_paths),\r\n steps_per_epoch=steps_per_epoch,\r\n )\r\n\r\ndef create_generator(generator_inputs,generator_outputs_channels):\r\n layers = []\r\n\r\n with tf.variable_scope(\"encoder_1\"):\r\n output = conv(generator_inputs,a.ngf,stride=2)\r\n layers.append(output)\r\n\r\n layer_specs = [\r\n a.ngf * 2,\r\n a.ngf * 4,\r\n a.ngf * 8,\r\n a.ngf * 8,\r\n a.ngf * 8,\r\n a.ngf * 8,\r\n a.ngf * 8,\r\n ]\r\n\r\n for out_channels in layer_specs:\r\n with tf.variable_scope(\"encoder_%d\" % (len(layers) + 1)):\r\n rectified = lrelu(layers[-1],0.2)\r\n convolved = conv(rectified,out_channels,stride=2)\r\n output = batchnorm(convolved)\r\n layers.append(output)\r\n\r\n layer_specs = [\r\n (a.ngf * 8,0.5),\r\n (a.ngf * 8,0.5),\r\n (a.ngf * 8,0.5),\r\n (a.ngf * 8,0.0),\r\n (a.ngf * 4,0.0),\r\n (a.ngf * 2,0.0),\r\n (a.ngf,0.0),\r\n ]\r\n\r\n num_encoder_layers = len(layers)\r\n for decoder_layer,(out_channels,dropout) in enumerate(layer_specs):\r\n skip_layer = num_encoder_layers - decoder_layer - 1 #???层间跳跃,引用RNN的一种处理方法,他是为了解决overfitting而设立的??? 为了防止梯度过饱和,如果网络优化到一定程度,没有再继续的必要,可以通过“跳跃”维持原状,具体细节,需要重新复习\r\n with tf.variable_scope(\"decoder_%d\" % (skip_layer + 1)):\r\n if decoder_layer == 0:\r\n input = layers[-1]\r\n else:\r\n input = tf.concat([layers[-1],layers[skip_layer]],axis=3)\r\n\r\n rectified = tf.nn.relu(input)\r\n output = deconv(rectified,out_channels)\r\n output = batchnorm(output)\r\n\r\n if dropout > 0.0: #防止过拟合的一种手段,即只对部分结点进行优化\r\n output = tf.nn.dropout(output,keep_prob = 1- dropout)\r\n \r\n layers.append(output) #先卷积,然后在反卷积\r\n\r\n with tf.variable_scope(\"decoder_1\"):\r\n input = tf.concat([layers[-1],layers[0]],axis=3)\r\n rectified = tf.nn.relu(input)\r\n output = deconv(rectified,generator_outputs_channels)\r\n output = tf.tanh(output)\r\n layers.append(output)\r\n\r\n return layers[-1]\r\n\r\ndef create_model(inputs, targets):\r\n def create_discriminator(discrim_inputs, discrim_targets):#创建判别网络\r\n n_layers = 3\r\n layers = []\r\n\r\n # 2x [batch, height, width, in_channels] => [batch, height, width, in_channels * 2]\r\n input = tf.concat([discrim_inputs, discrim_targets], axis=3)#将目标图片,以及生成网络图片组合,作为判别网络的输入\r\n\r\n # layer_1: [batch, 256, 256, in_channels * 2] => [batch, 128, 128, ndf]\r\n with tf.variable_scope(\"layer_1\"):\r\n convolved = conv(input, a.ndf, stride=2)\r\n rectified = lrelu(convolved, 0.2)\r\n layers.append(rectified) #将卷积层 添加到 layers 中\r\n\r\n # layer_2: [batch, 128, 128, ndf] => [batch, 64, 64, ndf * 2]\r\n # layer_3: [batch, 64, 64, ndf * 2] => [batch, 32, 32, ndf * 4]\r\n # layer_4: [batch, 32, 32, ndf * 4] => [batch, 31, 31, ndf * 8]\r\n for i in range(n_layers):\r\n with tf.variable_scope(\"layer_%d\" % (len(layers) + 1)): #进行3次卷积\r\n out_channels = a.ndf * min(2**(i+1), 8) #规定output 的channel\r\n stride = 1 if i == n_layers - 1 else 2 # last layer here has stride 1\r\n convolved = conv(layers[-1], out_channels, stride=stride)\r\n normalized = batchnorm(convolved)\r\n rectified = lrelu(normalized, 0.2)\r\n layers.append(rectified)\r\n\r\n # layer_5: [batch, 31, 31, ndf * 8] => [batch, 30, 30, 1]\r\n with tf.variable_scope(\"layer_%d\" % (len(layers) + 1)): #在进行一次卷积,然后输出概率\r\n convolved = conv(rectified, out_channels=1, stride=1)\r\n output = tf.sigmoid(convolved)\r\n layers.append(output)\r\n\r\n return layers[-1] #返回概率值\r\n\r\n with tf.variable_scope(\"generator\") as scope:\r\n out_channels = int(targets.get_shape()[-1])\r\n outputs = create_generator(inputs, out_channels) #创建“由生成网络生成的图片”,其图片大小与target一致,G(y) , x\r\n\r\n # create two copies of discriminator, one for real pairs and one for fake pairs\r\n # they share the same underlying variables\r\n with tf.name_scope(\"real_discriminator\"):\r\n with tf.variable_scope(\"discriminator\"):\r\n # 2x [batch, height, width, channels] => [batch, 30, 30, 1]\r\n predict_real = create_discriminator(inputs, targets) #判断y与x的相似度\r\n\r\n with tf.name_scope(\"fake_discriminator\"):\r\n with tf.variable_scope(\"discriminator\", reuse=True):\r\n # 2x [batch, height, width, channels] => [batch, 30, 30, 1]\r\n predict_fake = create_discriminator(inputs, outputs) #判断y与G(y)的相似度\r\n\r\n with tf.name_scope(\"discriminator_loss\"):\r\n # minimizing -tf.log will try to get inputs to 1\r\n # predict_real => 1\r\n # predict_fake => 0\r\n discrim_loss = tf.reduce_mean(-(tf.log(predict_real + EPS) + tf.log(1 - predict_fake + EPS))) #计算 判别网络损失\r\n\r\n with tf.name_scope(\"generator_loss\"):\r\n # predict_fake => 1\r\n # abs(targets - outputs) => 0\r\n gen_loss_GAN = tf.reduce_mean(-tf.log(predict_fake + EPS))\r\n gen_loss_L1 = tf.reduce_mean(tf.abs(targets - outputs))\r\n gen_loss = gen_loss_GAN * a.gan_weight + gen_loss_L1 * a.l1_weight #计算 生成网络损失\r\n\r\n with tf.name_scope(\"discriminator_train\"):\r\n discrim_tvars = [var for var in tf.trainable_variables() if var.name.startswith(\"discriminator\")]\r\n discrim_optim = tf.train.AdamOptimizer(a.lr, a.beta1)\r\n discrim_grads_and_vars = discrim_optim.compute_gradients(discrim_loss, var_list=discrim_tvars)\r\n discrim_train = discrim_optim.apply_gradients(discrim_grads_and_vars) #对判别损失进行梯度优化\r\n\r\n with tf.name_scope(\"generator_train\"): #对生成损失进行梯度优化\r\n with tf.control_dependencies([discrim_train]):\r\n gen_tvars = [var for var in tf.trainable_variables() if var.name.startswith(\"generator\")]\r\n gen_optim = tf.train.AdamOptimizer(a.lr, a.beta1)\r\n gen_grads_and_vars = gen_optim.compute_gradients(gen_loss, var_list=gen_tvars) #计算梯度\r\n gen_train = gen_optim.apply_gradients(gen_grads_and_vars)#使用计算到的梯度来更新variable\r\n\r\n ema = tf.train.ExponentialMovingAverage(decay=0.99) #滑动平均\r\n update_losses = ema.apply([discrim_loss, gen_loss_GAN, gen_loss_L1])\r\n\r\n global_step = tf.contrib.framework.get_or_create_global_step()\r\n incr_global_step = tf.assign(global_step, global_step+1)\r\n\r\n return Model(\r\n predict_real=predict_real,\r\n predict_fake=predict_fake,\r\n discrim_loss=ema.average(discrim_loss),\r\n discrim_grads_and_vars=discrim_grads_and_vars, #计算梯度,需要sess.run()\r\n gen_loss_GAN=ema.average(gen_loss_GAN),\r\n gen_loss_L1=ema.average(gen_loss_L1),\r\n gen_grads_and_vars=gen_grads_and_vars, #计算梯度,需要sess.run()\r\n outputs=outputs,\r\n train=tf.group(update_losses, incr_global_step, gen_train), #返回一个Model类; tf.group(input) input是一组operation,当tf.group()完成时,里边的operation也就完成了\r\n )\r\n\r\ndef save_images(fetches, step=None):\r\n image_dir = os.path.join(a.output_dir, \"images\") #image的保存路径,没有就创建\r\n if not os.path.exists(image_dir):\r\n os.makedirs(image_dir)\r\n\r\n filesets = []\r\n for i, in_path in enumerate(fetches[\"paths\"]):#fetches中存有所有sample,每个sample又分为input,output,target3个image\r\n name, _ = os.path.splitext(os.path.basename(in_path.decode(\"utf8\"))) #文件名\r\n fileset = {\"name\": name, \"step\": step}\r\n for kind in [\"inputs\", \"outputs\", \"targets\"]:\r\n filename = name + \"-\" + kind + \".png\" #文件名格式\r\n if step is not None:\r\n filename = \"%08d-%s\" % (step, filename)\r\n fileset[kind] = filename #将input,output,target文件名分别存入key下\r\n out_path = os.path.join(image_dir, filename) #定义输出路径\r\n contents = fetches[kind][i] #取出kind下第I个image内容,并写入out_path\r\n with open(out_path, \"wb\") as f:\r\n f.write(contents)\r\n filesets.append(fileset) #将各个sample文件存入filesets\r\n return filesets #返回filesets; fileset共有5个key;filesets中存有所有sample信息;\r\n\r\ndef append_index(filesets, step=False):\r\n index_path = os.path.join(a.output_dir, \"index.html\")#将所有结果都整合到一个html文件中\r\n if os.path.exists(index_path):#如果已经建立了output_dir,则追加 info,否则,写入\r\n index = open(index_path, \"a\")\r\n else:\r\n index = open(index_path, \"w\")\r\n index.write(\"\")\r\n if step:#如果有step的信息,则写入Html文件\r\n index.write(\"\")\r\n index.write(\"\")\r\n\r\n for fileset in filesets:\r\n index.write(\"\")\r\n\r\n if step:\r\n index.write(\"\" % fileset[\"step\"])\r\n index.write(\"\" % fileset[\"name\"])#写入sample名字\r\n\r\n for kind in [\"inputs\", \"outputs\", \"targets\"]:\r\n index.write(\"\" % fileset[kind])#写入具体的sample地址,应该是可以直接将image读入html中吧???\r\n\r\n index.write(\"\")\r\n return index_path #返回这个html文件\r\n\r\ndef main():\r\n if tf.__version__.split('.')[0] != \"1\":\r\n raise Exception(\"Tensorflow version 1 required\")\r\n\r\n if a.seed is None:#确定op的执行种子,使得各个op在同一状态执行,避免随机性\r\n a.seed = random.randint(0, 2**31 - 1)\r\n\r\n tf.set_random_seed(a.seed)\r\n np.random.seed(a.seed)\r\n random.seed(a.seed)\r\n\r\n if not os.path.exists(a.output_dir):#如果output_dir不存在,则创建\r\n os.makedirs(a.output_dir)\r\n\r\n if a.mode == \"test\" or a.mode == \"export\":\r\n if a.checkpoint is None:#如果此时要执行的是test操作,或者时export操作,而checkpoint没有,则报错\r\n raise Exception(\"checkpoint required for test mode\")\r\n\r\n # load some options from the checkpoint\r\n options = {\"which_direction\", \"ngf\", \"ndf\", \"lab_colorization\"}\r\n with open(os.path.join(a.checkpoint, \"options.json\")) as f:\r\n for key, val in json.loads(f.read()).items():\r\n if key in options:\r\n print(\"loaded\", key, \"=\", val)#将checkpoint中的value值赋给各个option\r\n setattr(a, key, val) #给a的属性key赋值\r\n # disable these features in test mode\r\n a.scale_size = CROP_SIZE\r\n a.flip = False\r\n\r\n for k, v in a._get_kwargs():#给a的属性赋值\r\n print(k, \"=\", v)\r\n\r\n with open(os.path.join(a.output_dir, \"options.json\"), \"w\") as f:\r\n f.write(json.dumps(vars(a), sort_keys=True, indent=4))#将python数据结构var(a)转为json结构\r\n\r\n if a.mode == \"export\": #如果想要export generator graph\r\n # export the generator to a meta graph that can be imported later for standalone generation\r\n if a.lab_colorization:\r\n raise Exception(\"export not supported for lab_colorization\")\r\n\r\n input = tf.placeholder(tf.string, shape=[1]) #input\r\n input_data = tf.decode_base64(input[0])\r\n input_image = tf.image.decode_png(input_data)\r\n\r\n # remove alpha channel if present\r\n input_image = tf.cond(tf.equal(tf.shape(input_image)[2], 4), lambda: input_image[:,:,:3], lambda: input_image)\r\n # convert grayscale to RGB\r\n input_image = tf.cond(tf.equal(tf.shape(input_image)[2], 1), lambda: tf.image.grayscale_to_rgb(input_image), lambda: input_image)\r\n\r\n input_image = tf.image.convert_image_dtype(input_image, dtype=tf.float32)\r\n input_image.set_shape([CROP_SIZE, CROP_SIZE, 3]) #修正input的size\r\n batch_input = tf.expand_dims(input_image, axis=0)\r\n\r\n with tf.variable_scope(\"generator\"): #返回的是:generator生成的output,需要sess.run()吧???\r\n batch_output = deprocess(create_generator(preprocess(batch_input), 3)) \r\n\r\n output_image = tf.image.convert_image_dtype(batch_output, dtype=tf.uint8)[0]\r\n if a.output_filetype == \"png\":\r\n output_data = tf.image.encode_png(output_image)\r\n elif a.output_filetype == \"jpeg\":\r\n output_data = tf.image.encode_jpeg(output_image, quality=80)\r\n else:\r\n raise Exception(\"invalid filetype\")\r\n output = tf.convert_to_tensor([tf.encode_base64(output_data)]) #将output转为tensor???\r\n\r\n key = tf.placeholder(tf.string, shape=[1]) #key代表的是什么??? 占位符;input\r\n inputs = {\r\n \"key\": key.name, \r\n \"input\": input.name\r\n }\r\n tf.add_to_collection(\"inputs\", json.dumps(inputs))#将tf.add_to_collection(a,b)将元素b添加到列表a中;\r\n outputs = {\r\n \"key\": tf.identity(key).name,\r\n \"output\": output.name,\r\n }\r\n tf.add_to_collection(\"outputs\", json.dumps(outputs))\r\n\r\n init_op = tf.global_variables_initializer()\r\n restore_saver = tf.train.Saver() #加载saver\r\n export_saver = tf.train.Saver() #导入saver???\r\n\r\n with tf.Session() as sess:\r\n sess.run(init_op) #初始化全局变量\r\n print(\"loading model from checkpoint\")\r\n checkpoint = tf.train.latest_checkpoint(a.checkpoint) #checkpoint路径\r\n restore_saver.restore(sess, checkpoint)#将checkpoint数据加载进来\r\n print(\"exporting model\")\r\n export_saver.export_meta_graph(filename=os.path.join(a.output_dir, \"export.meta\"))#支持以json导出metagraphdef\r\n export_saver.save(sess, os.path.join(a.output_dir, \"export\"), write_meta_graph=False) #将数据保存到export中\r\n\r\n return #疑问??? key,input都是占位符,在利用他们进行运算时,为什么没有sess.run(),\r\n\r\n examples = load_examples() #下载sample\r\n print(\"examples count = %d\" % examples.count)\r\n\r\n # inputs and targets are [batch_size, height, width, channels]\r\n model = create_model(examples.inputs, examples.targets) #建立model\r\n\r\n # undo colorization splitting on images that we use for display/output\r\n if a.lab_colorization:\r\n if a.which_direction == \"AtoB\":\r\n # inputs is brightness, this will be handled fine as a grayscale image\r\n # need to augment targets and outputs with brightness\r\n targets = augment(examples.targets, examples.inputs) #返回的是rgb???\r\n outputs = augment(model.outputs, examples.inputs) #返回的是rgb???\r\n # inputs can be deprocessed normally and handled as if they are single channel\r\n # grayscale images\r\n inputs = deprocess(examples.inputs) #input变为grayscale\r\n elif a.which_direction == \"BtoA\":\r\n # inputs will be color channels only, get brightness from targets\r\n inputs = augment(examples.inputs, examples.targets) #input变为rgb\r\n targets = deprocess(examples.targets)#grayscale\r\n outputs = deprocess(model.outputs)#grayscale\r\n else:\r\n raise Exception(\"invalid direction\")\r\n else:\r\n inputs = deprocess(examples.inputs) #grayscale\r\n targets = deprocess(examples.targets)#grayscale\r\n outputs = deprocess(model.outputs)#grayscale\r\n\r\n def convert(image):\r\n if a.aspect_ratio != 1.0:\r\n # upscale to correct aspect ratio\r\n size = [CROP_SIZE, int(round(CROP_SIZE * a.aspect_ratio))]\r\n image = tf.image.resize_images(image, size=size, method=tf.image.ResizeMethod.BICUBIC)\r\n\r\n return tf.image.convert_image_dtype(image, dtype=tf.uint8, saturate=True)\r\n\r\n # reverse any processing on images so they can be written to disk or displayed to user\r\n with tf.name_scope(\"convert_inputs\"):\r\n converted_inputs = convert(inputs) \r\n\r\n with tf.name_scope(\"convert_targets\"):\r\n converted_targets = convert(targets)\r\n\r\n with tf.name_scope(\"convert_outputs\"):\r\n converted_outputs = convert(outputs)\r\n\r\n with tf.name_scope(\"encode_images\"):\r\n display_fetches = {\r\n \"paths\": examples.paths,\r\n \"inputs\": tf.map_fn(tf.image.encode_png, converted_inputs, dtype=tf.string, name=\"input_pngs\"), #inputs中含有Input,input是一个placeholder\r\n \"targets\": tf.map_fn(tf.image.encode_png, converted_targets, dtype=tf.string, name=\"target_pngs\"),\r\n \"outputs\": tf.map_fn(tf.image.encode_png, converted_outputs, dtype=tf.string, name=\"output_pngs\"), #outputs中包含key(placeholder),和,output(tensor)\r\n }#tf.map_fn() 映射函数:将png映射到image\r\n\r\n # summaries\r\n with tf.name_scope(\"inputs_summary\"):\r\n tf.summary.image(\"inputs\", converted_inputs)\r\n\r\n with tf.name_scope(\"targets_summary\"):\r\n tf.summary.image(\"targets\", converted_targets)\r\n\r\n with tf.name_scope(\"outputs_summary\"):\r\n tf.summary.image(\"outputs\", converted_outputs)\r\n\r\n with tf.name_scope(\"predict_real_summary\"):\r\n tf.summary.image(\"predict_real\", tf.image.convert_image_dtype(model.predict_real, dtype=tf.uint8))\r\n\r\n with tf.name_scope(\"predict_fake_summary\"):\r\n tf.summary.image(\"predict_fake\", tf.image.convert_image_dtype(model.predict_fake, dtype=tf.uint8))\r\n\r\n tf.summary.scalar(\"discriminator_loss\", model.discrim_loss)\r\n tf.summary.scalar(\"generator_loss_GAN\", model.gen_loss_GAN)\r\n tf.summary.scalar(\"generator_loss_L1\", model.gen_loss_L1)\r\n\r\n for var in tf.trainable_variables():\r\n tf.summary.histogram(var.op.name + \"/values\", var)\r\n\r\n for grad, var in model.discrim_grads_and_vars + model.gen_grads_and_vars:\r\n tf.summary.histogram(var.op.name + \"/gradients\", grad)\r\n\r\n with tf.name_scope(\"parameter_count\"):\r\n parameter_count = tf.reduce_sum([tf.reduce_prod(tf.shape(v)) for v in tf.trainable_variables()])\r\n\r\n saver = tf.train.Saver(max_to_keep=1)\r\n\r\n logdir = a.output_dir if (a.trace_freq > 0 or a.summary_freq > 0) else None\r\n sv = tf.train.Supervisor(logdir=logdir, save_summaries_secs=0, saver=None) #管理模型训练过程\r\n with sv.managed_session() as sess:\r\n print(\"parameter_count =\", sess.run(parameter_count))\r\n\r\n if a.checkpoint is not None:\r\n print(\"loading model from checkpoint\")\r\n checkpoint = tf.train.latest_checkpoint(a.checkpoint)\r\n saver.restore(sess, checkpoint)\r\n\r\n max_steps = 2**32\r\n if a.max_epochs is not None:\r\n max_steps = examples.steps_per_epoch * a.max_epochs\r\n if a.max_steps is not None:\r\n max_steps = a.max_steps\r\n\r\n if a.mode == \"test\":\r\n # testing\r\n # at most, process the test data once\r\n max_steps = min(examples.steps_per_epoch, max_steps)\r\n for step in range(max_steps):\r\n results = sess.run(display_fetches) #path,output,input,target,output ,所有需要的输入都在这里 ???creat_model()时已经输入\r\n filesets = save_images(results)\r\n for i, f in enumerate(filesets):\r\n print(\"evaluated image\", f[\"name\"])\r\n index_path = append_index(filesets)\r\n\r\n print(\"wrote index at\", index_path)\r\n else:\r\n # training\r\n start = time.time()\r\n\r\n for step in range(max_steps):\r\n def should(freq):\r\n return freq > 0 and ((step + 1) % freq == 0 or step == max_steps - 1)\r\n\r\n options = None\r\n run_metadata = None\r\n if should(a.trace_freq):\r\n options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE) #定义tensorflow运行选项\r\n run_metadata = tf.RunMetadata() #定义tensorflow运行元信息\r\n\r\n fetches = {\r\n \"train\": model.train,\r\n \"global_step\": sv.global_step,\r\n }\r\n\r\n if should(a.progress_freq):\r\n fetches[\"discrim_loss\"] = model.discrim_loss\r\n fetches[\"gen_loss_GAN\"] = model.gen_loss_GAN\r\n fetches[\"gen_loss_L1\"] = model.gen_loss_L1\r\n\r\n if should(a.summary_freq):\r\n fetches[\"summary\"] = sv.summary_op\r\n\r\n if should(a.display_freq):\r\n fetches[\"display\"] = display_fetches\r\n\r\n results = sess.run(fetches, options=options, run_metadata=run_metadata) #sess.run()input...隐含???是的,creat_model()中已经输入\r\n\r\n if should(a.summary_freq):\r\n print(\"recording summary\")\r\n sv.summary_writer.add_summary(results[\"summary\"], results[\"global_step\"])\r\n\r\n if should(a.display_freq):\r\n print(\"saving display images\")\r\n filesets = save_images(results[\"display\"], step=results[\"global_step\"])\r\n append_index(filesets, step=True)\r\n\r\n if should(a.trace_freq):\r\n print(\"recording trace\")\r\n sv.summary_writer.add_run_metadata(run_metadata, \"step_%d\" % results[\"global_step\"])\r\n\r\n if should(a.progress_freq):\r\n # global_step will have the correct step count if we resume from a checkpoint\r\n train_epoch = math.ceil(results[\"global_step\"] / examples.steps_per_epoch)\r\n train_step = (results[\"global_step\"] - 1) % examples.steps_per_epoch + 1\r\n rate = (step + 1) * a.batch_size / (time.time() - start)\r\n remaining = (max_steps - step) * a.batch_size / rate\r\n print(\"progress epoch %d step %d image/sec %0.1f remaining %dm\" % (train_epoch, train_step, rate, remaining / 60))\r\n print(\"discrim_loss\", results[\"discrim_loss\"])\r\n print(\"gen_loss_GAN\", results[\"gen_loss_GAN\"])\r\n print(\"gen_loss_L1\", results[\"gen_loss_L1\"])\r\n\r\n if should(a.save_freq):\r\n print(\"saving model\")\r\n saver.save(sess, os.path.join(a.output_dir, \"model\"), global_step=sv.global_step)\r\n\r\n if sv.should_stop():\r\n break\r\n\r\n\r\nmain()\r\n\r\n#总结一下:\r\n#在main()中进行export , test, train 3种操作\r\n#其中,export,用到saver.restore() ,saver.save(),不用sess.run(),不用return\r\n#test,用到creat_model(),直接用sess.run(model.outputs)就可以,其中creat_model()需要的input,targets,已经在main中表明creat_model(examples.input,examples.target),因此,不需feed_dict\r\n#train,依然是用到creat_model() 中的model.train(),因此,直接sess.run(),由于input已经在creat_model()中定义,不需feed_dict\r\n\r\n#所得example均从shell中输入他的路径\r\n\r\n#还有2点需要说明:\r\n#一个是:\r\n#creat_generator() 最后输出的是output image,在通篇code中,只书写过程,但是,没有sess.run();同样的,在creat_model()中也没有sess.run(),所有的sess.run()均是在test和train()中进行的;\r\n\r\n#creat_generator()只是定义了生成网络结构,以及,利用该结构,生成的output_image(return)\r\n#creat_dicriminator() 同generator()\r\n#creat_model() 将 generator()和discriminator()结合起来,计算pix2pix损失,返回一个 pix2pix Model,这个model带有各种需要sess.run()的属性\r\n\r\n","repo_name":"wbqjyjy/Deep-Learning-Program","sub_path":"21个项目玩转深度学习/chapter 9 pix2pix模型与自动上色技术/pix2pix.py","file_name":"pix2pix.py","file_ext":"py","file_size_in_byte":40068,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"} +{"seq_id":"5766599825","text":"import operator\nimport os\n\n########################################################################\n# DESCOMPRIME IMAGEM #\n########################################################################\n\ndef getBitStringDescomprimida(filename):\n bitStringDescomprimida = \"\"\n grupoString = \"\"\n\n bitString = getBitString(filename)\n sizeBitString = len(bitString)\n \n grupo = int(bitString[0:8],2)\n lixo = int(bitString[8:16],2)\n header = getHeader(bitString[16:], grupo)\n arvore = gerarArvore(header, grupo)\n codigos = constroiCodAPartirDaArvore(arvore)\n\n dataPosition = len(header)+16\n for choke in range(dataPosition, sizeBitString, grupo):\n if sizeBitString - dataPosition != lixo:\n bitStringDescomprimida += bitList_to_bitString(codigos[int(choke, 2)])\n\n return bitStringDescomprimida\n\n# New\n# Funciona\n# Devolve a arvore em post-order\ndef getPostOrder(bitString, grupo):\n numSimbolos = 2**grupo\n \n position = 0\n header = \"\"\n \n countNumSimbolo = 0\n bitsRemainder = 0\n isSimbolo = False\n \n while(countNumSimbolo != numSimbolos):\n c = bitString[position]\n if isSimbolo:\n bitsRemainder -= 1\n if bitsRemainder == 0:\n countNumSimbolo += 1\n isSimbolo = False\n else:\n if c == '1':\n bitsRemainder = grupo\n isSimbolo = True\n header += c\n position += 1\n\n return header\n\ndef bitString_to_bitList(bitString):\n\treturn [int(l) for l in bitString]\n\ndef bitList_to_bitString(bitList):\n bitString = \"\"\n \n for bit in bitList:\n bitString += str(bit)\n \n return bitString\n\n# New\n# Funciona\ndef constroiCodAPartirDaArvore(arvore):\n if arvore == None:\n return {}\n else:\n if isNo(arvore[0]):\n no = {arvore[0]:[]}\n return no\n else:\n esquerda = insereZeros(constroiCodAPartirDaArvore(arvore[0]))\n direita = insereUns(constroiCodAPartirDaArvore(arvore[1]))\n esquerda.update(direita)\n return esquerda\n# New\n# Funciona\ndef insereZeros(dict):\n { k:(v.append(0)) for k,v in dict.items()}\n return dict\n# New\n# Funciona\ndef insereUns(dict):\n { k:(v.append(1)) for k,v in dict.items()}\n return dict\n\n# New\n# gera a arvore a partir da bitstring que representa a arvore em pos ordem\n# Funciona\ndef gerarArvore(bitString, group, posicao=[]):\n resultado = [None, None]\n if posicao[0] > (len(bitString) - 1):\n return None\n\n if(posicao[0] < len(bitString) and bitString[posicao[0]] == '0' and resultado[0] == None):\n posicao[0] += 1\n resultado[0] = gerarArvore(bitString, group, posicao)\n \n if(posicao[0] < len(bitString) and bitString[posicao[0]] == '0' and resultado[1] == None):\n posicao[0] += 1\n resultado[1] = gerarArvore(bitString, group, posicao)\n\n if(posicao[0] < len(bitString) and bitString[posicao[0]] == '1' and resultado[0] == None):\n \n resultado[0] = int(bitString[posicao[0]+1:posicao[0] + group + 1],2)\n posicao[0] += 1 + group\n\n if(posicao[0] < len(bitString) and bitString[posicao[0]] == '1' and resultado[1] == None):\n \n resultado[1] = int(bitString[posicao[0]+1:posicao[0] + group + 1],2)\n posicao[0] += 1 + group\n\n return resultado\n \n#print(gerarArvore('011100010101100100', 2, [0]))\n\n\"\"\"faz o get do simbolo de um no\"\"\" \ndef getSimbolo(no):\n\treturn no\n\t\n\"\"\"funcao que codifica um simbolo de acordo com uma arvore de huffman que recebe como \nargumento. Devolve a lista com o codigo corresponte ao simbolo.\"\"\" \ndef codificaSimbolo(simbolo, numSimbolos):\n\tcodigo = []\n\tnum = numSimbolos\n\tramoActual = arvore\n\twhile not isNo(ramoActual) :\n\t\tif isNo(ramoActual) == list:\n\t\t\tcodigo.append(0)\n\t\t\tramoActual = ramoActual[0]\n\t\telif type(ramoActual) == int:\n\t\t\tcodigo.append(1)\n\t\t\tramoActual = ramoActual[1]\n\treturn codigo\n\ndef geraCodigos(arvore):\n\tsimbolos = getSimbolos(arvore)\n\treturn {s:codificaSimbolo(s, arvore) for s in simbolos}\n\n\"\"\"funcao para criar no com o simbolo e numero de simbolos\"\"\"\ndef criaNo(simbolo):\n\treturn simbolo\n\n\"\"\"verifica se o objecto que recebe como argumento cumpre com as condicoes para ser um no\n devolve true se for um no e false caso nao seja\"\"\"\ndef isNo(x):\n return isinstance(x, int)\n\n\"\"\"faz o get do simbolo de um no\"\"\" \ndef getSimbolo(no):\n\treturn no\n\n\"\"\"faz o get do ramo direito da arvore de huffman\"\"\"\ndef getRamoDir(no):\n\treturn no[1]\n\n\"\"\"faz o get do ramo esquerdo da arvore de huffman\"\"\"\ndef getRamoEsq(no):\n\treturn no[0]\n\ndef getSimbolos(t):\n\tif isNo(t):\n\t\treturn [t]\n\telif t != None:\n\t\treturn getSimbolos(t)\n\t\n\t\t\n\"\"\"retorna uma string com os bits da imagem\"\"\"\ndef getBitString(ficheiro):\n file = open(ficheiro, \"rb\").read()\n string = \"\"\n mascara = 1\n for byte in file:\n for i in range(7, -1, -1):\n string += str((byte>>i) & mascara)\n return string\n\n\"\"\"Funcao para descodificar uma lista com uma sequencia de 0's e 1's devolvendo uma lista\n com os simbolos pela ordem que estao na sequencia recebida como argumento \"\"\"\ndef descodificaBits(cod, arvore):\n\tif cod == []:\n\t\treturn []\n\tramoActual = arvore\n\tramoSeguinte = None\n\tdescodificacao = []\n\twhile cod != []:\n\t\tramoSeguinte = seleccionaRamo(cod[0], ramoActual)\n\t\tif isNo(ramoSeguinte):\n\t\t\tdescodificacao.append(getSimbolo(ramoSeguinte))\n\t\t\tramoActual = arvore\n\t\telse:\n\t\t\tramoActual = ramoSeguinte\n\t\tdel cod[0]\n\treturn descodificacao\n\t\n\"\"\"Selecciona o ramo a seguir de acordo com o bit lido, para o ramo \n filho esquerdo se for 0 ou para o direito se for 1\"\"\"\ndef seleccionaRamo(bit, tree):\n if bit == 0:\n return getRamoEsq(tree)\n elif bit == 1:\n return getRamoDir(tree)\t\n\ndef descomprime():\n\tficheiro = ''\n\tficheiro = input(\"Insira o ficheiro que deseja descomprimir(Do tipo ficheiro.cpbm) : \")\n\twhile not os.path.exists(ficheiro):\n\t\tprint(\"ERRO: Ficheiro nao existente.\\n\")\n\t\tficheiro = input(\"Insira o ficheiro que deseja descomprimir(Do tipo ficheiro.cpbm) : \")\n\tgrupo = ''\n\tnumSimbolos = ''\n\t\n\tbitString = getBitString(ficheiro)\n\tfor i in range(len(bitString)):\n\t\tif 0 <= i < 8:\n\t\t\tgrupo += bitString[i]\n\t\telif 8<=i<24:\n\t\t\tnumSimbolos += bitString[i]\n\tbitString = bitString[24:]\n\tgrupo = int(grupo, 2)\n\tnumSimbolos = int(numSimbolos, 2)\n\tarvore = descodificaArvoreCods(bitString, numSimbolos, grupo)\n\treturn arvore\n\t\n","repo_name":"rjcf18/Trabs_Exerc_Univ","sub_path":"BSc/Teoria Informacao/Comp_Desc_Blahut/src/descomprime.py","file_name":"descomprime.py","file_ext":"py","file_size_in_byte":6463,"program_lang":"python","lang":"pt","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"7073751589","text":"import re\n\nfrom setuptools import setup\n\nwith open('waifu/__init__.py', 'r') as f:\n version = re.search(r'^__version__\\s*=\\s*[\\'\"]([^\\'\"]*)[\\'\"]', f.read(), re.MULTILINE).group(1)\n\nwith open('README.md', 'r') as f:\n readme = f.read()\n\nsetup(\n name='waifu-py',\n version=version,\n packages=['waifu'],\n url='https://github.com/IchBinLeoon/waifu-py',\n project_urls={\n 'Issue tracker': 'https://github.com/IchBinLeoon/waifu-py/issues'\n },\n license='MIT',\n author='IchBinLeoon',\n description='A simple Python wrapper for the waifu.pics API',\n long_description=readme,\n long_description_content_type='text/markdown',\n python_requires='>=3.6',\n install_requires=[\n 'requests',\n 'aiohttp'\n ],\n classifiers=[\n 'Development Status :: 5 - Production/Stable',\n 'License :: OSI Approved :: MIT License',\n 'Intended Audience :: Developers',\n 'Natural Language :: English',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3.8',\n 'Programming Language :: Python :: 3.9',\n 'Topic :: Internet',\n 'Topic :: Software Development :: Libraries',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n 'Topic :: Utilities'\n ]\n)\n","repo_name":"IchBinLeoon/waifu-py","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"48"} +{"seq_id":"22102910790","text":"from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.db.models import Q, Case, When, DateTimeField, F, TimeField\nimport datetime\n\n\nclass Pack(models.Model):\n name = models.CharField(max_length=200)\n size = models.IntegerField(default=100)\n subscribers = models.ManyToManyField(User, related_name='subscribed_to', blank=True, null=True)\n created_at = models.DateTimeField(auto_now_add=True)\n modified_at = models.DateTimeField(auto_now=True)\n deleted_at = models.DateTimeField(blank=True, null=True)\n deleted = models.BooleanField(default=False)\n\n def __str__(self):\n return self.name\n\n\nclass Image(models.Model):\n title = models.CharField(max_length=200)\n image = models.ImageField(max_length=300)\n pack = models.ForeignKey(Pack, related_name='images', on_delete=models.SET_NULL, blank=True, null=True)\n viewed_by = models.ManyToManyField(User, related_name='images_viewed', through='ImageView')\n created_at = models.DateTimeField(auto_now_add=True)\n modified_at = models.DateTimeField(auto_now=True)\n deleted_at = models.DateTimeField(blank=True, null=True)\n deleted = models.BooleanField(default=False)\n\n def __str__(self):\n return self.title\n\n def view(self, user):\n view, created = self.views.get_or_create(user=user)\n view.save()\n view.view()\n\n\nclass ImageView(models.Model):\n image = models.ForeignKey(Image, on_delete=models.CASCADE, related_name='views')\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n viewed_at = models.DateTimeField(auto_now=True)\n count = models.IntegerField(default=0)\n\n def __str__(self):\n return f'{self.user.username}: {self.image.title}'\n\n def view(self):\n self.count += 1\n self.save()\n\n\nclass Game(models.Model):\n start_time = models.DateTimeField(auto_now_add=True)\n end_time = models.DateTimeField(default=None, blank=True, null=True)\n game_duration = models.TimeField(default=datetime.time(minute=2))\n time_limit = models.IntegerField(default=120)\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n\n\ndef get_next_image(user):\n import random\n all_images = Image.objects.filter(pack__subscribers=user)\n # Order by the last time this user saw this image, with unseen images at the top\n all_images = all_images.annotate(\n last_seen_at=Case(\n When(views__user=user, then=F('views__viewed_at')),\n default=None,\n output_field=DateTimeField()\n )).order_by('last_seen_at')\n num_unseen_images = all_images.filter(last_seen_at__isnull=True).count()\n upper_limit = max(num_unseen_images, 20)\n upper_limit = min(upper_limit, all_images.count() - 1) # In case there are < 20 images\n image = all_images[random.randint(0, upper_limit)]\n image.view(user)\n return image\n\n\n# Takes a negative or 0 index to get previously viewed images\ndef get_image_at_index(user, index):\n images = Image.objects.filter(pack__subscribers=user)\n # Since QuerySets don't support negative indexing\n # we reverse the order and index by the absolute value\n images = images.order_by('-views__viewed_at').all()\n max_index = images.count() - 1\n image = images[min(abs(index), max_index)]\n return image\n","repo_name":"ariannedee/Stochastica","sub_path":"stochastica_site/presentation/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3289,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"70417140946","text":"from matplotlib.font_manager import FontProperties\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.dates import date2num\r\nimport numpy as np\r\nimport datetime\r\nfrom matplotlib.ticker import FormatStrFormatter, StrMethodFormatter\r\n\r\n\r\ndef barras_dobles(bought, manufactured, mod):\r\n # Obtenemos la posicion de cada etiqueta en el eje de X\r\n\r\n # tamaño de cada barra\r\n width = 0.7\r\n axes = 0.2\r\n\r\n fig, ax = plt.subplots()\r\n fig.set_size_inches(7.38, 6.13)\r\n if bought.get('B') == None:\r\n datos = [[int(bought['a']), int(bought['b']), int(bought['c']), int(bought['d']), int(bought['e'])],\r\n [int(manufactured['a']), int(manufactured['b']), int(manufactured['c']), int(manufactured['d']), int(manufactured['e'])]]\r\n\r\n else:\r\n datos = [[int(bought.get('B')['a']), int(bought.get('B')['b']), int(bought.get('B')['c']), int(bought.get('B')['d']), int(bought.get('B')['e'])],\r\n [int(manufactured.get('M')['a']), int(manufactured.get('M')['b']), int(manufactured.get('M')['c']), int(manufactured.get('M')['d']), int(manufactured.get('M')['e'])]]\r\n\r\n print(datos)\r\n X = np.arange(0, 10, step=2)\r\n # Generamos las barras para el conjunto de hombres\r\n p1 = plt.bar(X + 0.00, datos[0], color=\"#AFCB1D\", width=width)\r\n p2 = plt.bar(X + width, datos[1], color=\"#00000066\", width=width)\r\n # plt.bar(X + 2 * width, datos[2], color=\"#545454\", width=width)\r\n # plt.bar(X + 3 * width, datos[3], color=\"#86C05E\", width=width)\r\n # plt.bar(X + 4 * width, datos[4], color=\"black\", width=width)\r\n plt.xticks(X + 0.4, [\"Prototype\", \"100uds\", \"1,000uds\", \"10,000uds\", \"50,000uds\"])\r\n\r\n # Añadimos las etiquetas de identificacion de valores en el grafico\r\n ax.set_ylabel('Unitary cost [€]')\r\n\r\n # ax.set_xticks(x)\r\n # ax.set_xticklabels(asistencia)\r\n # Añadimos un legen() esto permite mmostrar con colores a que pertence cada valor.\r\n if bought.get('B') == None:\r\n plt.legend(['Before MOD', 'After MOD'])\r\n else:\r\n plt.legend(['Bought components', 'Manufactured components'])\r\n fig.tight_layout()\r\n plt.xlabel('Number of Produced Units')\r\n\r\n def autolabel(rects):\r\n \"\"\"Funcion para agregar una etiqueta con el valor en cada barra\"\"\"\r\n for rect in rects:\r\n height = rect.get_height()\r\n plt.annotate('{}'.format(height),\r\n xy=(rect.get_x() + rect.get_width() / 2, height),\r\n xytext=(0, 0), # 3 points vertical offset\r\n textcoords=\"offset points\",\r\n ha='center', va='bottom', color='black', fontweight='bold', rotation=0)\r\n\r\n # Añadimos las etiquetas para cada barra\r\n\r\n autolabel(p1)\r\n autolabel(p2)\r\n\r\n # plt.ylim(0, 2200)\r\n\r\n ax.yaxis.set_major_formatter(FormatStrFormatter('%d'))\r\n\r\n ax.yaxis.set_major_formatter(StrMethodFormatter('{x:,}'))\r\n\r\n # Mostramos la grafica con el metodo show()\r\n plt.grid(lw=0.1)\r\n if mod == str(False):\r\n fig.savefig('Manufactured_and_bought_MOD_False.png', bbox_inches=\"tight\")\r\n elif mod == str(True):\r\n fig.savefig('Manufactured_and_bought_MOD_True.png', bbox_inches=\"tight\")\r\n else:\r\n fig.savefig('Manufacturado_vs_bought.png', bbox_inches=\"tight\")\r\n\r\n\r\n plt.show()\r\n\r\ndef barras_simple(bought):\r\n width = 0.7\r\n\r\n fig, ax = plt.subplots()\r\n datos = [[round(bought.get('B')['a']), round(bought.get('B')['b']), round(bought.get('B')['c']),\r\n round(bought.get('B')['d']), round(bought.get('B')['e'])]]\r\n\r\n X = np.arange(0, 10, step=2)\r\n p1 = plt.bar(X, datos[0], color=\"#AFCB1D\", width=width)\r\n\r\n def autolabel(rects):\r\n \"\"\"Funcion para agregar una etiqueta con el valor en cada barra\"\"\"\r\n for rect in rects:\r\n height = rect.get_height()\r\n plt.annotate('{}'.format(height),\r\n xy=(rect.get_x() + rect.get_width() / 2, height),\r\n xytext=(0, 0), # 3 points vertical offset\r\n textcoords=\"offset points\",\r\n ha='center', va='bottom', color='black', fontweight='bold')\r\n\r\n # Añadimos las etiquetas para cada barra\r\n\r\n ax.yaxis.set_major_formatter(FormatStrFormatter('%d'))\r\n ax.yaxis.set_major_formatter(StrMethodFormatter('{x:,}'))\r\n ax.set_ylabel('Unitary cost [€]')\r\n autolabel(p1)\r\n plt.xlabel('Number of Produced Units')\r\n plt.xticks(X, [\"Prototype\", \"100uds\", \"1,000uds\", \"10,000uds\", \"50,000uds\"])\r\n\r\n plt.grid(lw=0.1)\r\n plt.legend(['Bought components'])\r\n plt.show()","repo_name":"josgarcam/InnBalance_evaluation_cost","sub_path":"graph/manufactured_and_bought.py","file_name":"manufactured_and_bought.py","file_ext":"py","file_size_in_byte":4621,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15552739130","text":"import heapq\r\nimport sys\r\nv,e = map(int,sys.stdin.readline().split())\r\nstart = int(sys.stdin.readline())\r\n\r\n\r\ngraph = {}\r\nfor i in range(1,v+1):\r\n graph[i] = {}\r\n\r\nfor i in range(e):\r\n u,w,v = map(int,sys.stdin.readline().split())\r\n if w in graph[u]:\r\n graph[u][w] = min(graph[u][w],v)\r\n else:\r\n graph[u][w] = v\r\n\r\ndef dijkstra(graph,start):\r\n\r\n distances = {node : float('inf') for node in graph}\r\n distances[start] = 0\r\n queue = []\r\n heapq.heappush(queue, [distances[start], start])\r\n\r\n while queue:\r\n current_distance, current_node = heapq.heappop(queue)\r\n\r\n if distances[current_node] < current_distance:\r\n continue\r\n \r\n for adjacent, weight in graph[current_node].items():\r\n distance = current_distance + weight\r\n\r\n if distance < distances[adjacent]:\r\n distances[adjacent] = distance\r\n heapq.heappush(queue, [distance,adjacent])\r\n\r\n return distances\r\n\r\ndist = dijkstra(graph,start)\r\nfor i,v in dist.items():\r\n if v == float('inf'):\r\n print(\"INF\")\r\n else:\r\n print(v)\r\n\r\n\r\n","repo_name":"kyungminkim-dev/Algorithm_Problem","sub_path":"baekjoon/1753최단경로.py","file_name":"1753최단경로.py","file_ext":"py","file_size_in_byte":1135,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73612495505","text":"#Split to training, validation and test dataset\n#params: inputpath,outputpath, seed to reproduce\n#param: ratio default for training and validation (.8, .2) for ML and \n# training, validation and test for NN\ninputpath=input(\"Enter the data folder: \")\n\ndef split_folders_ML(inputpath=\"./Imagery\",outputpath=\"output\",seed=1337,ratio=(.8, .2)):\n try:\n split_folders.ratio(inputpath, outputpath, seed, ratio) # default values\n if len(ratio)==3:\n test,train,validation=[folder for folder in os.listdir(outputpath)]\n train,validation=os.path.abspath(outputpath)+\"/\"+train+\"/\", os.path.abspath(outputpath)+\"/\"+validation+\"/\"\n test=os.path.abspath(outputpath)+\"/\"+test+\"/\"\n print(\"Location for the training, validation and test sets: \", train,validation,test)\n else:\n train,test=[folder for folder in os.listdir(outputpath)]\n train,validation=os.path.abspath(outputpath)+\"/\"+train+\"/\", os.path.abspath(outputpath)+\"/\"+validation+\"/\"\n print(\"Location for the training and validation sets: \", train,validation)\n except:\n print('Check the entered value:\\n Input path: {0}\\n, Output path:{1}\\n,seed: {2}\\n, ratio (tuple ranges 0 to 1): {3}\\n',\n inputpath,outputpath,seed,ratio)\n return train,validation,test\n\n#\ntrain,validation,test=split_folders_ML(inputpath,\"output\",1337,(.8,.1,.1))","repo_name":"devbudhathoki/NeuralNetwork","sub_path":"SplitDatasets.py","file_name":"SplitDatasets.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"24932718166","text":"\nimport argparse\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\nimport cv2\nimport numpy as np\nfrom torch.utils.tensorboard import SummaryWriter\n\n# In[4]:\n\n\nclass LeNet5(nn.Module):\n def __init__(self):\n super(LeNet5, self).__init__()\n self.conv1 = nn.Conv2d(1, 6, 5, padding=2)\n self.conv2 = nn.Conv2d(6, 16, 5)\n self.fc1 = nn.Linear(16*5*5, 120)\n self.fc2 = nn.Linear(120, 84)\n self.fc3 = nn.Linear(84, 10)\n \n def forward(self, x):\n x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))\n x = F.max_pool2d(F.relu(self.conv2(x)), (2, 2))\n x = x.view(x.size()[0], -1)\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n \n return x\n\n\n# In[5]:\n\n# In[8]:\n\n\n# 训练过程\ndef train(model, device, train_loader, criterion, optimizer, epoch):\n model.train()\n running_loss = 0.\n for batch_idx, (data, target) in enumerate(train_loader):\n data, target = data.to(device), target.to(device)\n optimizer.zero_grad()\n output = model(data)\n loss = criterion(output, target)\n loss.backward()\n running_loss += loss.item()\n optimizer.step()\n if (batch_idx+1)%30 == 0:\n print(\"Train Epoch: {} [{}/{} ({:.2f}%)]\\tLoss: {:.6f}\\n\".format(\n epoch, batch_idx*len(data), len(train_loader.dataset), 100.*batch_idx/len(train_loader), loss.item()))\n with open('./lenet5_train_log.txt', 'a+') as f:\n f.write(\"Train Epoch: {} [{}/{} ({:.2f}%)]\\tLoss: {:.6f}\\n\".format(\n epoch, batch_idx*len(data), len(train_loader.dataset), 100.*batch_idx/len(train_loader), loss.item()))\n\n with SummaryWriter('./scalar') as writer:#自动调用close()\n writer.add_scalar('scalar/train_loss', running_loss/len(train_loader.dataset), epoch)\n writer.add_scalar('scalar/train_accuracy', eval(model, device, train_loader, criterion), epoch)\n writer.add_scalar('scalar/test_accuracy', eval(model, device, test_loader, criterion, is_train=False), epoch)\n# In[9]:\n\n\n# 评估函数\ndef eval(model, device, test_loader, criterion, is_train=True):\n model.eval()\n test_loss = 0\n correct = 0\n with torch.no_grad():\n for data, target in test_loader:\n data, target = data.to(device), target.to(device)\n output = model(data)\n test_loss += criterion(output, target).item()\n # 获得最大概率下标\n pred = output.max(1, keepdim=True)[1]\n correct += pred.eq(target.view_as(pred)).sum().item()\n \n test_loss /= len(test_loader.dataset)\n if is_train:\n print('\\nTrain Average Loss: {:.4f}, Accuracy: {}/{} ({:.2f})%\\n'.format(\n test_loss, correct, len(test_loader.dataset), 100.*correct/len(test_loader.dataset)))\n with open('./lenet_train_log.txt', 'a+') as f:\n f.write('\\nTrain Average Loss: {:.4f}, Accuracy: {}/{} ({:.2f})%\\n'.format(\n test_loss, correct, len(test_loader.dataset), 100.*correct/len(test_loader.dataset)))\n else:\n print('\\nValid Average Loss: {:.4f}, Accuracy: {}/{} ({:.2f})%\\n'.format(\n test_loss, correct, len(test_loader.dataset), 100.*correct/len(test_loader.dataset)))\n with open('./lenet_train_log.txt', 'a+') as f:\n f.write('\\nValid Average Loss: {:.4f}, Accuracy: {}/{} ({:.2f})%\\n'.format(\n test_loss, correct, len(test_loader.dataset), 100.*correct/len(test_loader.dataset)))\n return 100.*correct/len(test_loader.dataset)\n\n\n# In[33]:\n\n\ndef predict(model_path, img_path):\n model = torch.load(model_path)\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n model = model.to(device)\n model.eval()\n img = cv2.imread(img_path)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n trans = transforms.Compose([\n transforms.Resize((28,28)),\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ])\n img = trans(img).to(device)\n img = img.unsqueeze(0)\n output = model(img)\n prob = F.softmax(output, dim=1)\n pred = prob.max(dim=1)[1].item()\n return pred\n\n\n# add parser\nparser = argparse.ArgumentParser(description='LeNet5_Predictor')\nparser.add_argument('-img_path', type=str, help='待检测的文件路径')\nparser.add_argument('-model_path', type=str, help='加载的模型文件路径')\nif __name__ == '__main__':\n\t# model_path = 'LetNet5_model_cifar.pth'\n args = parser.parse_args()\n img_path = args.img_path\n model_path = args.model_path\n pred = predict(model_path, img_path)\n print(pred)","repo_name":"CCHD/computer-vision-homework","sub_path":"hw3/lenet_predict.py","file_name":"lenet_predict.py","file_ext":"py","file_size_in_byte":4721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71725249106","text":"\"\"\"\n给定一组字符,使用原地算法将其压缩。\n压缩后的长度必须始终小于或等于原数组长度。\n数组的每个元素应该是长度为1 的字符(不是 int 整数类型)。\n在完成原地修改输入数组后,返回数组的新长度。\n进阶:\n你能否仅使用O(1) 空间解决问题?\n\n示例 1:\n输入:\n[\"a\",\"a\",\"b\",\"b\",\"c\",\"c\",\"c\"]\n输出:\n返回 6 ,输入数组的前 6 个字符应该是:[\"a\",\"2\",\"b\",\"2\",\"c\",\"3\"]\n说明:\n\"aa\" 被 \"a2\" 替代。\"bb\" 被 \"b2\" 替代。\"ccc\" 被 \"c3\" 替代。\n示例 2:\n输入:\n[\"a\"]\n\n输出:\n返回 1 ,输入数组的前 1 个字符应该是:[\"a\"]\n解释:\n没有任何字符串被替代。\n\"\"\"\n\n\nclass Solution(object):\n def compress(self, chars):\n \"\"\"\n :type chars: List[str]\n :rtype: int\n \"\"\"\n # 重新整理字符串的指针\n k = 0\n i = 0\n while i < len(chars):\n # 相同字符串的右下标\n j = i + 1\n while j < len(chars) and chars[i] == chars[j]:\n j += 1\n\n # 得到相同字符串的长度\n length = j - i\n\n # 给头字母赋值\n chars[k] = chars[i]\n k += 1\n\n # 假如是length > 1的话,说明要往后面填数字\n if length > 1:\n for c in str(length):\n chars[k] = c\n k += 1\n\n # 更新左下标\n i = j - 1\n i += 1\n\n # 返回我们填完数字的最后一位\n return k\n\n# https://www.acwing.com/video/1844/\n\n","repo_name":"Andrewlearning/Leetcoding","sub_path":"leetcode/String/443m. 压缩字符串.py","file_name":"443m. 压缩字符串.py","file_ext":"py","file_size_in_byte":1610,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17440949807","text":"# init structlog\nimport structlog\n\nstructlog.configure(\n processors=[\n structlog.stdlib.filter_by_level,\n structlog.processors.TimeStamper(fmt='iso'),\n structlog.stdlib.add_logger_name,\n structlog.stdlib.add_log_level,\n structlog.stdlib.PositionalArgumentsFormatter(),\n structlog.processors.StackInfoRenderer(),\n structlog.processors.format_exc_info,\n structlog.processors.UnicodeDecoder(),\n structlog.processors.ExceptionPrettyPrinter(),\n structlog.stdlib.ProcessorFormatter.wrap_for_formatter,\n ],\n context_class=structlog.threadlocal.wrap_dict(dict),\n logger_factory=structlog.stdlib.LoggerFactory(),\n wrapper_class=structlog.stdlib.BoundLogger,\n cache_logger_on_first_use=True,\n)\n\nlogger = structlog.get_logger(__name__)\n\n\ndef hard_work(a: int) -> None:\n logger.info('very_important_event', a=a)\n","repo_name":"b0g3r/pytest-structlog-issue-example","sub_path":"example/logic.py","file_name":"logic.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"43637541626","text":"from setuptools import setup, find_packages\n\nwith open ('README.rst', encoding='UTF-8') as f:\n readme = f.read()\n\nsetup(\n name='hr',\n version='1.0.0',\n description='Command line export utility, Linuxacademy tasks',\n long_description=readme,\n author='Eszter Bolla',\n author_email='bolla.eszter@gmail.com',\n packages=find_packages('src'),\n package_dir={'':'src'},\n install_requires=[],\n entry_points={\n 'console_scripts' : 'hr=hr.cli:main',\n },\n )\n\n","repo_name":"bollae/linuxaca_clitool","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34259009892","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom django.http import Http404, HttpResponse, HttpResponseRedirect\nfrom django.core.urlresolvers import reverse\nfrom django.conf import settings\nfrom django.contrib.auth import login as manual_login\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.template import loader\nfrom oauth2client import client\nfrom oauth2client.client import OAuth2Credentials as Credentials\nfrom oauth2client.client import verify_id_token\nfrom apiclient.discovery import build\nimport httplib2, functools, hashlib, uuid, gzip, json, requests\nfrom apps.accounts.models import Account, BigQueryProject, User, UserConnection\nfrom premailer import transform\n\n\ndef index(request):\n return render(request, 'accounts/index.html')\n\ndef invite(request):\n return render(request, 'accounts/invite.html')\n\ndef invite_post(request):\n if not request.user.can_invite:\n return render(request, 'errors/403.html', status=403)\n email = request.POST.get('email')\n try:\n user = User.objects.get(email=email)\n if user.account:\n return HttpResponseRedirect(reverse('accounts_invite') + '?success=0')\n user.account = request.user.account\n except User.DoesNotExist:\n user = User(email=email, account=request.user.account)\n if request.POST.get('send') == 'yes':\n subject = 'Welcome to a colorful world!'\n body = transform(loader.render_to_string('emails/invite.html', dict(user=user, me=request.user, message=request.POST.get('message'))))\n email_message = EmailMultiAlternatives(subject, body, 'Master Yoda ', [user.email])\n html_email = transform(loader.render_to_string('emails/invite.html', dict(user=user, me=request.user, message=request.POST.get('message'))))\n email_message.attach_alternative(html_email, 'text/html')\n email_message.send()\n user.save()\n return HttpResponseRedirect(reverse('accounts_invite') + '?success=1')\n\ndef get_flow(request):\n return client.flow_from_clientsecrets(\n settings.GA_JSON_PATH,\n scope='https://www.googleapis.com/auth/bigquery',\n redirect_uri=request.build_absolute_uri(reverse('accounts_bigquery_connect_callback')))\n\ndef bq_connect(request):\n account = request.user.account\n if not account.credentials:\n flow = get_flow(request)\n return redirect(flow.step1_get_authorize_url())\n bq_project = account.bq_project\n if not bq_project:\n return redirect(bq_choose_project)\n return redirect(index)\n\ndef oauth_callback(request):\n account = request.user.account\n auth_code = request.GET.get('code')\n flow = get_flow(request)\n credentials = flow.step2_exchange(auth_code)\n account.credentials = credentials.to_json()\n account.save()\n return redirect(bq_connect)\n\ndef bq_choose_project(request):\n account = request.user.account\n credentials = Credentials.from_json(account.credentials)\n http_auth = credentials.authorize(httplib2.Http())\n bigquery_service = build('bigquery', 'v2', http=http_auth)\n results = bigquery_service.projects().list().execute()\n return render(request, 'accounts/choose-project.html', dict(projects=results.get('projects', [])))\n\ndef bq_choose_project_post(request):\n account = request.user.account\n project_id = request.POST.get('project_id')\n bq_project = BigQueryProject(project_id=project_id)\n bq_project.save()\n account.bq_project = bq_project\n account.save()\n return redirect(bq_connect)\n\ndef bq_remove_project(request):\n account = request.user.account\n account.bq_project = None\n account.save()\n return redirect(bq_connect)\n\ndef login_google(request):\n print(request.META.get('HTTP_REFERER'))\n #print(request.build_absolute_uri(reverse('login_google_callback')))\n connection = UserConnection(referrer_path=request.GET.get('next', '/'))\n connection.save()\n url = 'https://accounts.google.com/o/oauth2/auth?client_id='\n url += settings.GA_CLIENT_ID\n url += '&response_type=code&max_auth_age=0&scope=openid email&redirect_uri='\n url += request.build_absolute_uri(reverse('login_google_callback'))\n url += '&state=' + str(connection.token)\n return redirect(url)\n\ndef login_google_callback(request):\n url = 'https://www.googleapis.com/oauth2/v3/token?code='\n url += request.GET.get('code')\n url += '&client_id='\n url += settings.GA_CLIENT_ID\n url += '&client_secret='\n url += settings.GA_CLIENT_SECRET\n url += '&redirect_uri='\n url += request.build_absolute_uri(reverse('login_google_callback'))\n url += '&grant_type=authorization_code'\n r = requests.post(url)\n jwt = verify_id_token(r.json().get('id_token'), settings.GA_CLIENT_ID)\n email = jwt.get('email').lower()\n try:\n user = User.objects.get(email=email)\n except User.DoesNotExist:\n user = User(email=email)\n user.save()\n user.backend = 'django.contrib.auth.backends.ModelBackend'\n try:\n connection = UserConnection.objects.get(token=request.GET.get('state'), user__isnull=True)\n except UserConnection.DoesNotExist:\n return redirect('home')\n manual_login(request, user)\n connection.user = user\n connection.save()\n if connection.referrer_path:\n return redirect(connection.referrer_path)\n return redirect('home')\n\ndef aws_connect(request):\n return render(request, 'accounts/aws-credentials.html')\n\ndef aws_connect_post(request):\n account = request.user.account\n account.aws_access_key_id = request.POST.get('key')\n account.aws_secret_access_key = request.POST.get('secret')\n account.save()\n return redirect(index)\n\ndef aws_remove(request):\n account = request.user.account\n account.aws_access_key_id = None\n account.aws_secret_access_key = None\n account.save()\n return redirect(aws_connect)\n\ndef error_404(request):\n return render(request, 'errors/404.html', status=404)\ndef error_400(request):\n return render(request, 'errors/400.html', status=400)\ndef error_403(request):\n return render(request, 'errors/403.html', status=403)\ndef error_500(request):\n return render(request, 'errors/500.html', status=500)","repo_name":"aeud/sing","sub_path":"apps/accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"44214274864","text":"import torch\nimport torch.nn as nn\n\nfrom torchvision.utils import make_grid\nfrom tensorboardX import SummaryWriter\n\nimport os\nfrom tqdm import tqdm\nimport numpy as np\nfrom collections import defaultdict\nfrom utils.log import log\n\n\nclass BaseGAN:\n def __init__(self, cfg, writer):\n \"\"\"\n __init__ BaseGAN consturctor\n\n Args:\n cfg (Munch): Munch Config Object\n \"\"\"\n super().__init__()\n self.cfg = cfg\n self.n_critic = 1 if self.cfg.n_critic is None else self.cfg.n_critic\n\n self.writer = writer\n self.train_step = 0\n\n self.__post_epoch_hooks = []\n\n def _update_model_optimizers(self):\n pass\n\n def generator_step(self, data):\n raise NotImplementedError(\"method not implemented!\")\n\n def critic_step(self, data):\n raise NotImplementedError(\"method not implemented!\")\n\n def train_epoch(self, dataloader):\n self.metrics = defaultdict(list)\n\n loop = tqdm(dataloader, desc=\"Trg Itr: \", ncols=75, leave=False)\n\n for ix, data in enumerate(loop):\n self.critic_step(data)\n if ix % self.n_critic == 0:\n self.generator_step(data)\n\n self.log_step_losses(self.metrics, self.train_step)\n\n if ix % self.cfg.viz_freq == 0:\n self.vizualize_gen(dataloader, self.train_step)\n\n self.train_step += 1\n\n # * call the registered hooks\n for hook in self.__post_epoch_hooks:\n hook()\n\n def _generator_loss(self, **kwargs):\n pass\n\n def _critic_loss(self, **kwargs):\n pass\n\n def sample_noise(self):\n return torch.randn(self.cfg.batch_size, self.cfg.z_dim, 1, 1).to(\n self.cfg.device\n )\n\n def log_step_losses(self, metrics, step, train=True):\n ses = \"train\" if train else \"val\"\n for key in metrics:\n self.writer.add_scalar(\n f\"{ses}-step/{key}\", metrics[key][-1], step\n )\n\n def log_epoch_losses(self, metrics, step, train=True):\n ses = \"train\" if train else \"val\"\n for key in metrics:\n self.writer.add_scalar(\n f\"{ses}-ep/{key}\", np.mean(metrics[key]), step\n )\n\n def vizualize_gen(self, dataloader, step, n_samples=16):\n n_samples = min(n_samples, self.cfg.batch_size)\n fake_images = self.generate_images(n_samples=n_samples)\n real_images = iter(dataloader).next()[0][:n_samples]\n\n grid = make_grid(fake_images, nrow=4, normalize=True)\n self.writer.add_image(\"fake-images\", grid, step)\n\n grid = make_grid(real_images, nrow=4, normalize=True)\n self.writer.add_image(\"real-images\", grid, step)\n\n return\n\n def generate_images(self, n_samples):\n self.netG.eval()\n with torch.no_grad():\n noise = self.sample_noise()[:n_samples]\n fake_images = self.netG(noise)\n return fake_images\n\n def save_model(self, ckpt_dir: str, current_ep: int):\n out_path = os.path.join(ckpt_dir, f\"netG-{(current_ep+1):03d}.tar\")\n self._ckpt(self.netG, out_path)\n\n out_path = os.path.join(ckpt_dir, f\"netD-{(current_ep+1):03d}.tar\")\n self._ckpt(self.netD, out_path)\n\n def _ckpt(self, model, path):\n \"\"\"\n _ckpt makes checkpoint\n\n Args:\n model (nn.Module): module to save\n path (str): save path\n \"\"\"\n if isinstance(model, torch.nn.DataParallel):\n torch.save(model.module.state_dict(), path)\n","repo_name":"aadhithya/gan-zoo-pytorch","sub_path":"base/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3535,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"48"} +{"seq_id":"5320439121","text":"# 给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。\nclass Solution:\n def trap(self, height: List[int]) -> int:\n # 思路:因此,对于每一根柱子,能接住雨水的量,就是左右两侧最高柱子的最小值与当前柱子的高度的差值,最后,将所有的柱子能接住的雨水量相加即可\n n = len(height)\n\n right = [0] * n\n right_max = 0\n for i in range(n - 1, -1, -1):\n right_max = max(right_max, height[i])\n right[i] = right_max\n\n left = [0] * n\n left_max = 0\n for i in range(n):\n left_max = max(left_max, height[i])\n left[i] = left_max\n \n total = 0\n for i in range(n):\n total += min(left[i], right[i]) - height[i]\n return total\n \n\nclass Solve:\n '''\n 思路:每根柱子能接住的雨水,即是左右两侧最高柱子的的最小值,与当前柱子的差值\n 然后把每根柱子的水量加起来就可以了\n '''\n def trap(height):\n n = len(height)\n right = [0]*n\n right_max = 0\n for i in range(n-1, -1, -1):\n right_max = max(right_max, height[i])\n right[i] = right_max\n left = [0]*n\n left_max = 0\n for j in range(n):\n left_max = max(left_max, height[j])\n left[j] = left_max\n total = 0\n for i in range(n):\n total += min(right[i], left[i]) - height[i]\n return total \n","repo_name":"02Bigboy/leetcode_top100","sub_path":"42_接雨水.py","file_name":"42_接雨水.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"24798581230","text":"# file = open('D:/桌面备份文件/207操作手册.txt', encoding='gbk')\n\n# readline() 只读取一行\n# print(file.readline())\n\n# 如果想读取多行,可以用下面的方法\n# while True:\n# countent =file.readline()\n# print(countent)\n# if countent == ''\n# break\n\n# readlines() 将读取所有行的数据,保存到一个列表里\n# x = file.readlines()\n# print(x)\n\n\n# 指定长度的读取\n# file.read(104) 不以rb形式读取,就是读取字数\n\n# 找荐使用这一种方式循环读取,二进制,每次读取1024字节,以节省内存\nfile = open('D:/华宇互联网庭审使用介绍(发布版).wmv', mode='rb')\nwhile True:\n content = file.read(1024)\n if not content:\n break\n print(content)\n\nfile.close()\n","repo_name":"weizt/python_studying","sub_path":"文件、异常/04-文件的读取方式.py","file_name":"04-文件的读取方式.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"2312190746","text":"\"\"\"\n Tool Name: AccidentHistoryFlag\n Source Name: accident_history_eq.py\n Author: Ethan Rucker\n Required Arguments:\n The path to the Geodatabase Workspace\n Description: \n Sets accident history flag based on following criteria:\n Ten-Year Crashes > 6 --> \"Hi 10 yr crash\"\n Five-Year Crashes > 2 --> \"Hi 5 yr crash\"\n Three-Year Crashes > 1 --> \"Recent crashes\"\n\"\"\"\n\nimport arcpy, sys\n\narcpy.env.workspace = arcpy.GetParameterAsText(0)\nedit = arcpy.da.Editor(arcpy.env.workspace)\nfc = r\"SpeedHump\\SpeedHumpAnalysis\"\nfields = [\"TEYA\", \"FYA\", \"THYA\", \"AH\"]\n\ndef acc_hist_flag(ten_year, five_year, three_year):\n if ten_year and ten_year > 6:\n return \"Hi 10 yr crash\"\n elif five_year and five_year > 2:\n return \"Hi 5 yr crash\"\n elif three_year and three_year > 1:\n return \"Recent crashes\"\n return \"\"\n\ntry:\n\n edit.startEditing(False, True)\n edit.startOperation()\n\n with arcpy.da.UpdateCursor(fc, fields) as cursor:\n for row in cursor:\n row[3] = acc_hist_flag(row[0], row[1], row[2])\n arcpy.AddMessage(row[3])\n cursor.updateRow(row)\n\n edit.stopOperation()\n edit.stopEditing(True)\n\nexcept Exception as err:\n \"\"\" Error Handling \"\"\"\n\n arcpy.AddError(err)\n sys.exit(1)\n\n","repo_name":"erucker-gis/speed-hump-app","sub_path":"Scripts/accident_history_eq.py","file_name":"accident_history_eq.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9617294547","text":"import numpy as np\nimport xlearn as xl\nimport pandas as pd\nfrom sklearn.datasets import load_iris\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.model_selection import train_test_split\n\n\npath_test=\"/Users/jianjun.yue/PycharmGItHub/data/titanic/test_pre.csv\"\npath=\"/Users/jianjun.yue/PycharmGItHub/data/titanic/train_pre.csv\"\ndata=pd.read_csv(path)\ndata_test=pd.read_csv(path_test)\nprint(\"--------------RandomForestClassifier---------------\")\npredictors=[\"Pclass\",\"Sex\",\"Age\",\"SibSp\",\"Parch\",\"Fare_scaler\",\"Embarked\",\"NameLength\"]\ntrain=data[predictors]\nX=train\ny=data[\"Survived\"]\nX_submission=data_test[predictors]\nprint(X_submission.head())\nprint(\"---------------------------\")\nprint(train.head())\n\nX_train,X_test,y_train,y_test=train_test_split(train,y,test_size=0.2,random_state=1)\n#\n# # Load dataset\n# iris_data = load_iris()\n# X = iris_data['data']\n# y = (iris_data['target'] == 2)\n#\n# X_train,X_val,y_train,y_val = train_test_split(X, y, test_size=0.3, random_state=0)\n\n# param:\n# 0. binary classification\n# 1. model scale: 0.1\n# 2. epoch number: 10 (auto early-stop)\n# 3. learning rate: 0.1\n# 4. regular lambda: 1.0\n# 5. use sgd optimization method\n# linear_model = xl.LRModel(task='binary', init=0.1,\n# epoch=10, lr=0.1,\n# reg_lambda=1.0, opt='sgd')\nparam = {'task':'binary', 'lr':0.2, 'lambda':0.002, 'metric':'acc'}\nmodel=xl.FMModel()\n\n\n\nmodel.fit(X_train, y_train)\npreds =model.predict(X_test)\nprint(\"FMModel ROC AUC:%.3f\" % roc_auc_score(y_true=y_test,y_score=preds))\nprint(\"FMModel accuracy_scorer:%.3f\" % accuracy_score(y_true=y_test,y_pred=preds))\n\n\n\n# Start to train\nmodel.fit(X_train, y_train,\n eval_set=[X_test, y_test],\n is_lock_free=False)\n\ny_submission=model.predict(X_submission)\n\ny_pred=pd.DataFrame()\ny_pred[\"PassengerId\"]=data_test[\"PassengerId\"]\ny_pred[\"Survived\"]=y_submission\ny_pred[\"Survived\"]=y_pred[\"Survived\"].apply(lambda x: int(x))\ny_pred.to_csv('/Users/jianjun.yue/KmmtML/data/kaggle/titanic/tensorflow/xlearn_submission.csv',index=None)","repo_name":"jianjunyue/KmmtML","sub_path":"Test/FM/FM.py","file_name":"FM.py","file_ext":"py","file_size_in_byte":2113,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"19873600114","text":"import pyaudio\nimport numpy as np\nimport math\nimport multiprocessing\nimport functools\nimport time\n\ncos_columns = {}\n\ndef calculate_cos(k, n, t):\n global cos_columns\n cos_column = np.array(list(map(lambda x: np.cos((n + k)*x), t)))\n cos_columns[(n, k)] = cos_column\n\ndef calculate_cos_column(n, length):\n t = np.linspace(0, np.pi, length)\n with multiprocessing.Pool(10) as p:\n p.map(functools.partial(calculate_cos, n=n, t=t), range(20, 2000))\n\ndef compute_integral(signals, n, k):\n if (n, k) not in cos_columns:\n t = np.linspace(0, np.pi, len(signals))\n cos_column = np.array(list(map(lambda x: np.cos((n + k)*x), t)))\n cos_columns[(n, k)] = cos_column\n else:\n cos_column = cos_columns[(n, k)]\n\n integral = np.trapz(signals*cos_column,dx=np.pi/(len(signals)-1))*(4/np.pi)\n return integral\n\ndef find_coefficients(signals, n):\n coefficients = []\n for i in range(20, 2000):\n ans = round(compute_integral(signals, n, i*2*np.pi))\n if ans != 0:\n coefficients.append((ans, i))\n if len(coefficients) >= 3:\n coefficients = tuple(coefficients)\n return coefficients\n\ndef play_sine_waves(coes, duration):\n p = pyaudio.PyAudio()\n fs = 44100\n volume = 0.5\n \n stream = p.open(format=pyaudio.paFloat32, channels=1, rate=fs, output=True)\n for c in coes:\n samples = (c[0][0]*np.sin(2*np.pi*np.arange(fs*duration)*c[0][1]/fs) + c[1][0]*np.sin(2*np.pi*np.arange(fs*duration)*c[1][1]/fs) + c[2][0]+np.sin(2*np.pi*np.arange(fs*duration)*c[2][1]/fs)).astype(np.float32)\n stream.write(volume*samples)\n stream.stop_stream()\n stream.close()\n p.terminate()\n\ndef big_calc(n):\n data = np.transpose(np.genfromtxt('am_radio_extension.csv', delimiter=','))\n\n start_time = time.time()\n calculate_cos_column(n, len(data[0]))\n print('Calculating cosines took: ' + str(time.time() - start_time) + ' seconds')\n\n all_coefficients = []\n\n start_time = time.time()\n with multiprocessing.Pool(10) as p:\n all_coefficients = np.array(list(p.map(functools.partial(find_coefficients, n=n), data)))\n print('Calculating coefficients took: ' + str(time.time() - start_time) + ' seconds')\n return all_coefficients\n\ndef main():\n freq = float(input('frequency: '))\n n = freq*(2*np.pi)\n interval = float(input('interval: '))\n\n all_coefficients = []\n try:\n all_coefficients = np.load('big_coefficients_' + str(freq) + '.npy')\n except:\n all_coefficients = big_calc(n)\n np.save('big_coefficients_' + str(freq) + '.npy', all_coefficients)\n \n print('Sound time!!')\n play_sine_waves(all_coefficients, interval)\n\nif __name__ == '__main__':\n main()\n","repo_name":"waddlepon/bigradio","sub_path":"bigradio2.py","file_name":"bigradio2.py","file_ext":"py","file_size_in_byte":2748,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5297856572","text":"\"\"\"\nKarthik Udupa : IMT2018510\nKhaveesh : IMT2018036\nKeshav Singhal : IMT2018511\n\"\"\"\n\nfrom typing import Dict\n\nfrom getType import getType\nfrom hexAdd import hexAdd\nfrom iType import iType2Args, iType3Args\nfrom jType import jType\nfrom rType import rType\n\nwith open(\"matrix_mul_asm_input.txt\") as file:\n open(\"out.o\", \"w\").close()\n counter = 0\n icount = 0\n jcount = 0\n rcount = 0\n labelstraddr: Dict[str, str] = {}\n set2 = [\"BEQ\", \"BNE\", \"BLT\", \"BGT\", \"BLTZ\", \"BLEZ\", \"BGTZ\"]\n while True:\n string = file.readline()\n if string == \"\":\n break\n label = string.find(\":\")\n if label != -1:\n labelstraddr[string[0:label]] = hexAdd(counter)\n string = string[label + 1 :]\n counter += 1\n counter = 0\n file.seek(0)\n while True:\n bad_char = [\",\", \"$\", \"\\\\n\"]\n string = file.readline()\n if string == \"\":\n break\n label = string.find(\":\")\n if label != -1:\n string = string[label + 1 :]\n if len(string) == 0:\n break\n for i in range(len(string) - 1):\n if string[i] == \",\" and string[i + 1] != \" \":\n string = string[:i] + \" \" + string[i + 1 :]\n string = \"\".join([i for i in string if i not in bad_char])\n data = string.split()\n\n print(hexAdd(counter) + \": \", end=\"\")\n counter += 1\n instType = getType(data[0])\n if instType == \"R\":\n if len(data) == 2:\n rType(data[0], data[1], \"\", \"\")\n elif len(data) == 3:\n rType(data[0], data[1], data[2], \"\")\n else:\n rType(data[0], data[1], data[2], data[3])\n rcount += 1\n elif instType == \"J\":\n jType(labelstraddr.get(data[1]))\n jcount += 1\n else:\n if data[0].upper() in set2:\n if len(data) == 3:\n data[2] = str(labelstraddr.get(data[2]))\n iType2Args(data[0], data[1], data[2])\n elif len(data) == 4:\n data[3] = str(labelstraddr.get(data[3]))\n iType3Args(data[0], data[1], data[2], data[3])\n else:\n if len(data) == 3:\n iType2Args(data[0], data[1], data[2])\n elif len(data) == 4:\n iType3Args(data[0], data[1], data[2], data[3])\n icount += 1\n\n print(\"\\nNumber of R-Type Instructions : \" + str(rcount))\n print(\"Number of I-Type Instructions : \" + str(icount))\n print(\"Number of J-Type Instructions : \" + str(jcount))\n","repo_name":"khaveesh/MIPS-Assembler","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":2629,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"73085898704","text":"import pandas as pd\r\nimport numpy as np\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\nimport random\r\n\r\ndf = pd.read_csv('multiseries.csv')\r\n\r\nt = df['LOAD_DTE'] = pd.to_datetime(df['LOAD_DTE'])\r\nc = df['REF_CNT']\r\ns = df['STDV']\r\nm = df['MEAN']\r\nl = df['LCL']\r\nu = df['UCL']\r\n\r\n\r\npossibilities = [ u'_classic_test',\r\n u'bmh',\r\n u'classic',\r\n u'dark_background',\r\n u'fivethirtyeight',\r\n u'ggplot',\r\n u'grayscale',\r\n u'seaborn',\r\n u'seaborn-bright',\r\n u'seaborn-colorblind',\r\n u'seaborn-dark',\r\n u'seaborn-darkgrid',\r\n u'seaborn-dark-palette',\r\n u'seaborn-deep',\r\n u'seaborn-muted',\r\n u'seaborn-notebook',\r\n u'seaborn-paper',\r\n u'seaborn-pastel',\r\n u'seaborn-poster',\r\n u'seaborn-talk',\r\n u'seaborn-ticks',\r\n u'seaborn-white',\r\n u'seaborn-whitegrid']\r\n\r\n\r\nx = random.choice([x for x in possibilities])\r\n\r\nx = 'grayscale'\r\nplt.style.use(x)\r\n\r\ntick_spacing = 1\r\n\r\nfig, ax = plt.subplots(figsize=(8,5.5))\r\n\r\nax.plot(t, c, marker='o', markerfacecolor='blue', markersize=3, color='skyblue', linewidth=2, label='Referal Count')\r\nax.plot(t, m, color='b', label='Mean', linestyle='dashed')\r\nax.plot(t, l, marker='', color='red', linewidth=2, label='Lower Control Limit')\r\nax.plot(t, u, marker='', color='red', linewidth=2, label='Upper Control Limit')\r\nax.set_title(x)\r\n\r\n\r\nplt.xticks(rotation=90)\r\nplt.legend()\r\nplt.tight_layout()\r\nplt.show()\r\n\r\n","repo_name":"j2white/control-charts-expanded","sub_path":"csv_control_example.py","file_name":"csv_control_example.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8125711141","text":"from collections import Counter\n\n\nclass Solution(object):\n def findLeastNumOfUniqueInts(self, arr, k):\n \"\"\"\n :type arr: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n counter = Counter(arr)\n counter = sorted(counter.items(), key=lambda x: x[1])\n res = len(counter)\n for i in range(len(counter)):\n v = counter[i][1]\n if k - v < 0:\n break\n else:\n k -= v\n res -= 1\n return res\n\n\nif __name__ == \"__main__\":\n s = Solution()\n print(s.findLeastNumOfUniqueInts([5, 5, 4], 1))\n","repo_name":"YingbingZhu/python_leetcode","sub_path":"array/1481. Least Number of Unique Integers after K Removals.py","file_name":"1481. Least Number of Unique Integers after K Removals.py","file_ext":"py","file_size_in_byte":621,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21023801153","text":"\"\"\"\nПоместите этот код в hotels/rooms/router.py, если хотите\nувидеть работу SQLAlchemy ORM и получить вложенные структуры данных\n\"\"\"\n\nfrom sqlalchemy import select\nfrom sqlalchemy.orm import selectinload, joinedload\nfrom app.hotels.models import Hotels\nfrom app.hotels.rooms.models import Rooms\nfrom app.bookings.models import Bookings\nfrom app.database import async_session_maker\nfrom fastapi.encoders import jsonable_encoder\n\n\n@router.get(\"/example/no_orm\")\nasync def get_noorm():\n async with async_session_maker() as session:\n query = (\n select(\n Rooms.__table__.columns,\n Hotels.__table__.columns,\n Bookings.__table__.columns\n )\n .join(Hotels, Rooms.hotel_id==Hotels.id)\n .join(Bookings, Bookings.room_id==Rooms.id)\n )\n res = await session.execute(query)\n res = res.mappings().all()\n return res\n\n\n@router.get(\"/example/orm\")\nasync def get_noorm():\n async with async_session_maker() as session:\n query = (\n select(Rooms)\n .options(joinedload(Rooms.hotel))\n .options(selectinload(Rooms.bookings))\n )\n res = await session.execute(query)\n res = res.scalars().all()\n res = jsonable_encoder(res)\n return res\n\n\n# SELECT запрос без использования ORM стиля\n[\n {\n # Данные о номере\n \"room_id\": 1,\n \"room_name\": \"Номер люкс\",\n\n # Данные об отеле\n \"hotel_name\": \"Отель Алтай 5 звезд\",\n \"hotel_description\": \"...\",\n\n # Данные о брони\n \"booking_id\": 1,\n \"price\": 123\n },\n {\n \"room_id\": 1,\n \"room_name\": \"Номер люкс\",\n\n \"hotel_name\": \"Отель Алтай 5 звезд\",\n \"hotel_description\": \"...\",\n\n \"booking_id\": 2,\n \"price\": 321\n }\n]\n\n\n# SELECT запрос с использованием ORM стиля\n[\n {\n # Данные о номере\n \"id\": 1,\n \"name\": \"Номер люкс\",\n \"hotel\": {\n # Данные об отеле\n \"id\": 2,\n \"name\": \"Отель Алтай 5 звезд\",\n \"description\": \"...\"\n },\n \"bookings\": [\n # Данные о всех бронях\n {\n \"id\": 1,\n \"price\": 123\n },\n {\n \"id\": 2,\n \"price\": 321\n }\n ]\n },\n]","repo_name":"ejina21/pet_project","sub_path":"course_helpers/orm_vs_noorm.py","file_name":"orm_vs_noorm.py","file_ext":"py","file_size_in_byte":2637,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"69904645266","text":"# simple nearest mean classifier for data with 13 features and 3 classes\r\n# import train.csv and test.csv\r\n# result include min error rate, standard deviation and plot\r\nimport csv\r\nimport numpy as np\r\nfrom plotDecBoundaries import plotDecBoundaries\r\n\r\n# array to store all train feature data\r\ndata_train = np.zeros((89, 13))\r\n# array to store all train label\r\nlabel_train = np.zeros(89, dtype=np.int)\r\n# array to store all train mean\r\nmean_train = np.zeros((78, 6))\r\n\r\ndata_test = np.zeros((89, 13))\r\nlabel_test = np.zeros(89, dtype=np.int)\r\n\r\n# index to store trip_cnt and corresponding 2 features\r\nindex_train = np.zeros((78, 2))\r\nindex_test = np.zeros((78, 2))\r\n\r\ntrip_cnt_train = 0\r\ntrip_cnt_test = 0\r\ntrip_cnt_result = 0\r\n\r\n# arrays to store error number and error rate\r\nerror_cnt_train = 0\r\nerror_all_train = []\r\nerror_rate_train = []\r\n\r\nerror_cnt_test = 0\r\nerror_all_test = []\r\nerror_rate_test = []\r\n\r\ni_train = 0\r\ni_test = 0\r\nj_train = 0\r\nj_test = 0\r\n\r\n# load train data into data_train and label_train\r\nwith open('dataset/wine_train.csv') as csvfile:\r\n reader = csv.reader(csvfile)\r\n\r\n for row in reader:\r\n for j_train in range(0, 13):\r\n data_train[i_train, j_train] = float(row[j_train])\r\n\r\n label_train[i_train] = int(row[13])\r\n i_train += 1\r\n\r\n# main 2-dimension loop to calculate error rate\r\nfor dim_x_train in range(0, 12):\r\n for dim_y_train in range(dim_x_train + 1, 13):\r\n\r\n # store index\r\n index_train[trip_cnt_train, 0] = dim_x_train\r\n index_train[trip_cnt_train, 1] = dim_y_train\r\n\r\n sum1_x = 0\r\n sum1_y = 0\r\n sum2_x = 0\r\n sum2_y = 0\r\n sum3_x = 0\r\n sum3_y = 0\r\n\r\n class1_cnt = 0\r\n class2_cnt = 0\r\n class3_cnt = 0\r\n\r\n # select two features from data_train\r\n # reshape the 2 arrays and combine them into a 89 * 2 array\r\n train_select = np.hstack((data_train[:, dim_x_train].reshape(89, 1), data_train[:, dim_y_train].reshape(89, 1)))\r\n\r\n # calculate sum based on class\r\n for row_cnt_train in range(0, 89):\r\n if label_train[row_cnt_train] == 1:\r\n sum1_x += train_select[row_cnt_train, 0]\r\n sum1_y += train_select[row_cnt_train, 1]\r\n class1_cnt += 1\r\n elif label_train[row_cnt_train] == 2:\r\n sum2_x += train_select[row_cnt_train, 0]\r\n sum2_y += train_select[row_cnt_train, 1]\r\n class2_cnt += 1\r\n else:\r\n sum3_x += train_select[row_cnt_train, 0]\r\n sum3_y += train_select[row_cnt_train, 1]\r\n class3_cnt += 1\r\n\r\n # calculate and store the sample mean\r\n mean_train[trip_cnt_train, 0] = sum1_x / class1_cnt\r\n mean_train[trip_cnt_train, 1] = sum1_y / class1_cnt\r\n mean_train[trip_cnt_train, 2] = sum2_x / class2_cnt\r\n mean_train[trip_cnt_train, 3] = sum2_y / class2_cnt\r\n mean_train[trip_cnt_train, 4] = sum3_x / class3_cnt\r\n mean_train[trip_cnt_train, 5] = sum3_y / class3_cnt\r\n\r\n # reshape the current mean into a 3 * 2 array\r\n mean_train_reshaped = mean_train[trip_cnt_train, :].reshape(3, 2)\r\n\r\n trip_cnt_train += 1\r\n\r\n # calculate distance and compare\r\n for m in range(0, 89):\r\n d1_train = np.sqrt(np.sum(np.square(train_select[m] - mean_train_reshaped[0])))\r\n d2_train = np.sqrt(np.sum(np.square(train_select[m] - mean_train_reshaped[1])))\r\n d3_train = np.sqrt(np.sum(np.square(train_select[m] - mean_train_reshaped[2])))\r\n\r\n # count error data points\r\n # not taking points on boundary into consideration\r\n if d1_train < d2_train and d1_train < d3_train and label_train[m] != 1:\r\n error_cnt_train += 1\r\n elif d2_train < d1_train and d2_train < d3_train and label_train[m] != 2:\r\n error_cnt_train += 1\r\n elif d3_train < d2_train and d3_train < d1_train and label_train[m] != 3:\r\n error_cnt_train += 1\r\n\r\n # write current number of error points into the array\r\n error_all_train.append(error_cnt_train)\r\n # write current error rate into the array\r\n error_rate_train.append(error_cnt_train / i_train)\r\n\r\n error_cnt_train = 0\r\n\r\nwith open('dataset/wine_test.csv') as csvfile:\r\n reader = csv.reader(csvfile)\r\n\r\n for row in reader:\r\n for j_test in range(0, 13):\r\n data_test[i_test, j_test] = float(row[j_test])\r\n\r\n label_test[i_test] = int(row[13])\r\n i_test += 1\r\n\r\nfor dim_x_test in range(0, 12):\r\n for dim_y_test in range(dim_x_test + 1, 13):\r\n index_test[trip_cnt_test, 0] = dim_x_test\r\n index_test[trip_cnt_test, 1] = dim_y_test\r\n\r\n test_select = np.hstack((data_test[:, dim_x_test].reshape(89, 1), data_test[:, dim_y_test].reshape(89, 1)))\r\n mean_test_reshaped = mean_train[trip_cnt_test, :].reshape(3, 2)\r\n\r\n trip_cnt_test += 1\r\n\r\n for m in range(0, 89):\r\n d1_test = np.sqrt(np.sum(np.square(test_select[m] - mean_test_reshaped[0])))\r\n d2_test = np.sqrt(np.sum(np.square(test_select[m] - mean_test_reshaped[1])))\r\n d3_test = np.sqrt(np.sum(np.square(test_select[m] - mean_test_reshaped[2])))\r\n\r\n if d1_test < d2_test and d1_test < d3_test and label_test[m] != 1:\r\n error_cnt_test += 1\r\n elif d2_test < d1_test and d2_test < d3_test and label_test[m] != 2:\r\n error_cnt_test += 1\r\n elif d3_test < d2_test and d3_test < d1_test and label_test[m] != 3:\r\n error_cnt_test += 1\r\n\r\n error_all_test.append(error_cnt_test)\r\n error_rate_test.append(error_cnt_test / 89)\r\n\r\n error_cnt_test = 0\r\n\r\n# looking for the data with min error rate\r\nfor n in range(0, 78):\r\n # if find the min error rate data\r\n if error_all_train[n] == min(error_all_train):\r\n trip_cnt_result = n\r\n\r\n# looking for result features in index\r\nfirst_row = int(index_train[trip_cnt_result, 0])\r\nsecond_row = int(index_train[trip_cnt_result, 1])\r\n# select result features and combine them into a 89 * 2 array\r\nresult_reshaped = np.hstack((data_train[:, first_row].reshape(89, 1), data_train[:, second_row].reshape(89, 1)))\r\n# select sample mean in mean_recorder\r\nmean_reshaped = mean_train[trip_cnt_result, :].reshape(3, 2)\r\n\r\nprint(\"train first feature:\", int(index_train[trip_cnt_result, 0] + 1))\r\nprint(\"train second feature:\", int(index_train[trip_cnt_result, 1] + 1))\r\nprint(\"train min error rate:\", min(error_rate_train))\r\nprint(\"train error rate standard deviation:\", (np.var(error_rate_train)) ** 0.5)\r\nprint(\"test min error rate\", error_rate_test[trip_cnt_result])\r\nprint(\"test error rate standard deviation:\", (np.var(error_rate_test)) ** 0.5)\r\nplotDecBoundaries(result_reshaped, label_train, mean_reshaped)","repo_name":"L1nRider/nearest-mean-classifier","sub_path":"NearestMeanClassifierFor13F3C.py","file_name":"NearestMeanClassifierFor13F3C.py","file_ext":"py","file_size_in_byte":6895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31586815140","text":"import math\n#link to problem: https://leetcode.com/problems/majority-element/\n\n#very naive solution:\n#store a key for every number we come across, and increment counter for it\n#return key with max counter\ndef majorityElement1(nums):\n mapp = {}\n for x in nums:\n if x in mapp:\n mapp[x]+=1\n else:\n mapp[x]=1\n return max(mapp, key=mapp.get)\n\n\nprint(majorityElement1([1,1,1,1,1,1,8])) #1\n\n\n#second way, a bit less obvious:\n# since the majority element must show up more than the floor(n/2), when sorted\n# the middle index should hold the majority element\n\n##QUICKSORT------\ndef partition(arr, start, end):\n #will hold index of an element that is greater than our pivot (arr[end])\n #aka it has to track the number of elements that are smaller than our pivot\n #since the number_of_elements = our index of where the pivot should be, we can\n #just use it as our index at the end\n j = start\n for x in range(start,end):\n if arr[x] < arr[end]:\n arr[x],arr[j]=arr[j],arr[x]\n j+=1\n #here we swap the pivot with our element at j which should be just bigger than pivot\n arr[j],arr[end]=arr[end],arr[j]\n return j\n\ndef quickSort(arr, start, end):\n #if we are on the same index, it's all sorted\n if start >= end:\n return\n else:\n #split it and sort prior to pivot and post pivot\n part = partition(arr, start, end)\n quickSort(arr, start, part-1)\n quickSort(arr, part+1, end)\n\ndef majorityElement2(nums):\n quickSort(nums, 0, len(nums)-1)\n return nums[int(math.ceil(len(nums)/2.0))]\n\nprint(majorityElement2([8,8,8,8,1,1,1])) #8\n\n#third way and the least obvious: Boyer-Moore algorithmn\n#assume the first element is the majority, if the next element does not match\n#the current majority element, detract 1 from the counter\n#if counter is 0, then we set the current element as the new majority\n\n##this works because:\n#1. if we come across a pair of the majority element side by side, then we skip\n# at the very least another number which makes the counter hit 0 for the last element if the rest of the\n# majority element is dispersed evenly, in which case the last element is the majority element\n# i.e. [1,1,3,3,1]\n\n#2. the counter hits 0 by the last element which is the majority element if its dispersed evenly\n# i.e. [1,3,1,3,1]\n\n#3. the counter doesnt hit 0 by the time you hit the last element, in which case you return the majority\n# i.e. [1,1,1,3,3]\n\ndef BoyerMooreMajorityElement(nums):\n maj = nums[0]\n counter = 1\n for x in nums:\n if x != maj:\n counter-=1\n if counter==0:\n maj = x\n counter = 1\n else:\n counter+=1\n return maj\n\nprint(BoyerMooreMajorityElement([8,8,8,8,1,1,1])) #8\n","repo_name":"GoGitThat/leetcodeProblems","sub_path":"easy/majorityElement.py","file_name":"majorityElement.py","file_ext":"py","file_size_in_byte":2804,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"1101717647","text":"# project/app/services/sendmail_service.py\nfrom flask_mail import Mail, Message\nfrom datetime import datetime\n\n# https://pythonhosted.org/Flask-Mail/\n# https://myaccount.google.com/lesssecureapps)\n# https://accounts.google.com/DisplayUnlockCaptcha\n# https://mail.google.com/mail/#settings/fwdandpop\n\nclass SendmailService():\n\n _recipients = []\n _subject = \"no subject - \"+datetime.today().strftime('%Y-%m-%d %H:%M:%S')\n _body = \"\"\n _html = \"\"\n _sender = \"\"\n\n def __init__(self, flaskapp):\n self.flaskapp = flaskapp\n\n def set_sender(self, strsender):\n self._sender = strsender\n\n def set_subject(self, strsubject):\n self._subject = strsubject\n\n def set_body(self, strbody):\n self._body = strbody\n\n def set_html(self, strhtml):\n self._html = strhtml\n\n def add_recipient(self, strmail):\n self._recipients.append(strmail)\n\n def send(self):\n #https://temp-mail.org/\n objmail = Mail(self.flaskapp)\n \n objmsg = Message(\n subject = self._subject,\n sender = self._sender,\n recipients = self._recipients\n )\n \n if self._body != \"\":\n objmsg.body = self._body\n\n if self._html != \"\":\n objmsg.html = self._html\n\n #bug(objmsg, \"objmsg\")\n\n retcode = True\n try:\n objmail.send(objmsg)\n except SMTPAuthenticationError:\n retcode = 2\n except SMTPServerDisconnected:\n retcode = 3\n except SMTPException:\n retcode = 1\n \n return retcode\n \n \n\n\n\n","repo_name":"eacevedof/prj_python37","sub_path":"platziflask/project/app/services/sendmail_service.py","file_name":"sendmail_service.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"36249580300","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def reverseList(self, head, prev=None):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n \n #1 75p\n if not head:\n return head\n \n if not head.next:\n return head\n \n if not head.next.next:\n current = head\n head.next.next = head\n head = head.next\n current.next = None\n return head\n \n prev = head\n current = head.next\n next_node = head.next.next\n prev.next = None\n \n while current:\n current.next = prev\n prev = current\n current = next_node\n if next_node:\n next_node = next_node.next\n \n return prev\n \n #2 75p\n current = head\n \n while current:\n head = head.next\n current.next = prev\n current, prev = head, current\n \n return prev\n \n \"\"\"\n #3 Recursive 15p\n if not head:\n return prev\n \n current = head\n head = head.next\n current.next = prev\n \n return self.reverseList(head, current)\n \n \"\"\"\n","repo_name":"doyleju/LC","sub_path":"linked_list/206_reverse_linked_list.py","file_name":"206_reverse_linked_list.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12445444873","text":"#coding=utf-8;\n\n# Demo 2 翻译文本\n\n# 1 导入依赖库\nimport urllib.request\nimport urllib.parse\n# 有道翻译 通过审查元素查到的链接 下面的链接不是在网站上找到的,这个链接是自己在网上找的\n\ncontent = input(\"pls input the word you need to translate---\");\n\nurl = \"http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc\";\n# 传递的数据 按照审查元素中网络中的参数\t\ndata = {};\ndata['doctype'] = 'json';\ndata['i'] = content;\ndata['version'] = '2.1';\ndata['keyfrom'] = 'fanyi.web';\ndata['typoResult'] = 'true';\ndata['type'] = 'AUTO';\ndata['ue'] = 'UTF-8';\n\n# 先将提交到服务器的数据进行转码\ndata = urllib.parse.urlencode(data).encode('utf-8');\nresponse = urllib.request.urlopen(url,data);\n\nhtml = response.read().decode('utf-8');\n\n\n# 2 将爬到的json进行优化展示\nimport json\n# target 是个 字典 ,直接取到翻译的内容\ntarget = json.loads(html);\n\n# 输出翻译的结果\nprint (\"Result:---\" + target['translateResult'][0][0][\"tgt\"]);\n\n\n\n\n\n\n\n\n","repo_name":"AlexanderYeah/SKPythonWorkSpace","sub_path":"SKPythonWorkSpace/urllib2.py","file_name":"urllib2.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"36615312762","text":"import numpy as np\nfrom sklearn.preprocessing import normalize\n\nclass Data_Reader(object):\n def __init__(self):\n self.answerTypes = [] # Answers for each tcp packet (i.e. normal, malicious, etc.)\n self.tcpFieldTypes = [] # Each field type for a tcp packet (i.e. protocol, service, etc.)\n self.symbolicOptions = {} # All symbolic option types\n self.data = {}\n self.dataArray = []\n self.newDataArray = []\n self.newFullDataArray = []\n self.answersArray = []\n self.answerKeyArray = []\n self.dataTypeFileName = \"\"\n self.dataFileName = \"\"\n self.normalize = False\n\n\n def readDataFiles(self, dataTypeFileName, dataFileName):\n self.read_dataTypes_file(dataTypeFileName)\n self.read_data_file(dataFileName)\n\n\n def read_dataTypes_file(self, filename):\n for num, line in enumerate(open(filename), 1):\n # First line is the tcp answer types\n if num == 1:\n for item in line.split('.')[0].split(','):\n self.answerTypes.append(item)\n # All other lines are tcp field types\n else:\n self.tcpFieldTypes.append(line.split('.')[0].split(':'))\n \n # build up the dictionary for symbolic options\n for num, item in enumerate(self.tcpFieldTypes, 0):\n if 'symbolic' in item[1]:\n self.symbolicOptions[num] = []\n\n\n def read_data_file(self, dataFileName):\n for line in open(dataFileName):\n key = line.split(',')[-1].split('.')[0]\n\n if key not in self.data:\n self.data[key] = [line.split(',')[:-1]]\n else:\n self.data[key].append(line.split(',')[:-1])\n \n \n def get_data(self):\n return self.data\n\n\n def normalizeData(self, origData):\n if self.normalize:\n return normalize(origData, axis=1, norm='l1')\n else:\n return origData\n\n def convertSymbolic(self, data):\n tmpDataArray = []\n tmpDataArray.append([])\n\n # for each line of data get each field and the field number\n for fieldNum, field in enumerate(data, 0):\n\n if fieldNum == 0:\n symFieldNum = 1\n elif fieldNum == 1:\n symFieldNum = 3\n else:\n symFieldNum = -99\n\n # check if the field is a symbolic field\n if symFieldNum in self.symbolicOptions:\n\n # check if that symbol has been added to the symbolic\n # options, if not add it\n # and get the value of that symbolic field\n if field not in self.symbolicOptions[symFieldNum]:\n self.symbolicOptions[symFieldNum].append(field)\n fieldVal = float(self.symbolicOptions[symFieldNum].index(field))\n else:\n fieldVal = float(self.symbolicOptions[symFieldNum].index(field))\n\n # Not symbolic, then just convert to float\n else:\n fieldVal = float(data[fieldNum])\n\n tmpDataArray[0].append(fieldVal)\n \n return self.normalizeData(np.array(tmpDataArray).astype(float))\n\n def get_data_array(self, DOS=False):\n self.dataArray = []\n self.answersArray = []\n self.answerKeyArray = []\n\n # DOS Types: land, back, neptune, teardrop, pod, smurf\n if DOS: # For DOS only messages\n # 22 bad types, 1 good\n for key in list(self.data.keys()):\n if key == 'normal':\n for item in self.data[key][:60]: # 50 - 60 is useful\n self.dataArray.append(item)\n self.answersArray.append([0]) # 0 for good data\n self.answerKeyArray.append(key)\n elif key == 'land':\n for item in self.data[key][:30]: # 10 - 30 is useful\n self.dataArray.append(item)\n self.answersArray.append([1]) # 1 for malicious data\n self.answerKeyArray.append(key)\n else:\n # 22 bad types, 1 good\n for key in list(self.data.keys()):\n if key == 'normal':\n for item in self.data[key][:66]:\n self.dataArray.append(item)\n self.answersArray.append([0]) # 0 for good data\n self.answerKeyArray.append(key)\n else:\n for item in self.data[key][:3]:\n self.dataArray.append(item)\n self.answersArray.append([1]) # 1 for malicious data\n self.answerKeyArray.append(key)\n \n self.newDataArray = []\n\n # loop over the each line of data\n for lineNum, line in enumerate(self.dataArray, 0):\n\n self.newDataArray.append([])\n\n # for each line of data get each field and the field number\n for fieldNum, field in enumerate(line, 0):\n\n if fieldNum == 1 or fieldNum == 3 or fieldNum == 6: # or fieldnNum == 2\n\n # check if the field is a symbolic field\n if fieldNum in self.symbolicOptions:\n\n # check if that symbol has been added to the symbolic options, if not add it\n # and get the value of that symbolic field\n if field not in self.symbolicOptions[fieldNum]:\n self.symbolicOptions[fieldNum].append(field)\n fieldVal = float(self.symbolicOptions[fieldNum].index(field))\n else:\n fieldVal = float(self.symbolicOptions[fieldNum].index(field))\n\n # Not symbolic, then just convert to float\n else:\n fieldVal = float(self.dataArray[lineNum][fieldNum])\n\n self.newDataArray[lineNum].append(fieldVal)\n \n return self.normalizeData(np.array(self.newDataArray).astype(float)), np.array(self.answersArray).astype(float), self.answerKeyArray\n\n\n\n def get_full_data_array(self, DOS=False):\n self.fullDataArray = []\n self.fullAnswersArray = []\n self.fullAnswerKeyArray = []\n\n if DOS: # For DOS only messages\n # 22 bad types, 1 good\n for key in list(self.data.keys()):\n if key == 'normal':\n for item in self.data[key]:\n self.fullDataArray.append(item)\n self.fullAnswersArray.append([0]) # 0 for good data\n self.fullAnswerKeyArray.append(key)\n elif key == 'land': #key == 'back' or or key == 'neptune' or key == 'teardrop' or key == 'pod' or key =='smurf'\n for item in self.data[key]:\n self.fullDataArray.append(item)\n self.fullAnswersArray.append([1]) # 1 for malicious data\n self.fullAnswerKeyArray.append(key)\n else:\n # 22 bad types, 1 good\n for key in list(self.data.keys()):\n if key == 'normal':\n for item in self.data[key]:\n self.fullDataArray.append(item)\n self.fullAnswersArray.append([0]) # 0 for good data\n self.fullAnswerKeyArray.append(key)\n else:\n for item in self.data[key]:\n self.fullDataArray.append(item)\n self.fullAnswersArray.append([1]) # 1 for malicious data\n self.fullAnswerKeyArray.append(key)\n\n self.newFullDataArray = []\n \n # loop over the each line of data\n for lineNum, line in enumerate(self.fullDataArray, 0):\n\n self.newFullDataArray.append([])\n\n # for each line of data get each field and the field number\n for fieldNum, field in enumerate(line, 0):\n\n if fieldNum == 1 or fieldNum == 3 or fieldNum == 6: # or fieldnNum == 2\n\n # check if the field is a symbolic field\n if fieldNum in self.symbolicOptions:\n\n # check if that symbol has been added to the symbolic options, if not add it\n # and get the value of that symbolic field\n if field not in self.symbolicOptions[fieldNum]:\n self.symbolicOptions[fieldNum].append(field)\n fieldVal = float(self.symbolicOptions[fieldNum].index(field))\n else:\n fieldVal = float(self.symbolicOptions[fieldNum].index(field))\n\n # Not symbolic, then just convert to float\n else:\n fieldVal = float(self.fullDataArray[lineNum][fieldNum])\n\n self.newFullDataArray[lineNum].append(fieldVal)\n \n return self.normalizeData(np.array(self.newFullDataArray).astype(float)), np.array(self.fullAnswersArray).astype(float), self.fullAnswerKeyArray","repo_name":"bneedy/PyIDS","sub_path":"PyIDS/Data_Reader.py","file_name":"Data_Reader.py","file_ext":"py","file_size_in_byte":9198,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32822073827","text":"# _*_ coding:utf-8 _*_\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n# Import TensorFlow >= 1.10 and enable eager execution\nimport re\nimport os\nimport sys\nimport time\nimport logging\nimport numpy as np\nimport tensorflow as tf\nlayers = tf.keras.layers\ntf.enable_eager_execution()\nabspath = os.path.dirname(os.path.realpath(__file__))\nabspath = os.path.abspath(abspath)\nsys.path.append(abspath)\nsys.path.append(os.path.join(abspath, '../utils'))\n\nfrom Logger import logger\nfrom TransferUtils import *\n\n\nclass EncoderLayer(tf.keras.Model):\n def __init__(self, d_model, num_heads, dff, rate=0.1):\n super(EncoderLayer, self).__init__()\n\n self.mha = MultiHeadAttention(d_model, num_heads)\n self.ffn = point_wise_feed_forward_network(d_model, dff)\n\n self.layernorm1 = tf.keras.layers.BatchNormalization()\n self.layernorm2 = tf.keras.layers.BatchNormalization()\n\n #self.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-6)\n #self.layernorm2 = tf.keras.layers.LayerNormalization(epsilon=1e-6)\n\n self.dropout1 = tf.keras.layers.Dropout(rate)\n self.dropout2 = tf.keras.layers.Dropout(rate)\n\n def call(self, x, training, mask):\n attn_output, _ = self.mha(x, x, x, mask) # (batch_size, input_seq_len, d_model)\n attn_output = self.dropout1(attn_output, training=training)\n out1 = self.layernorm1(x + attn_output) # (batch_size, input_seq_len, d_model)\n\n ffn_output = self.ffn(out1) # (batch_size, input_seq_len, d_model)\n ffn_output = self.dropout2(ffn_output, training=training)\n out2 = self.layernorm2(out1 + ffn_output) # (batch_size, input_seq_len, d_model)\n\n return out2\n\n\nclass Encoder(tf.keras.Model):\n def __init__(self,\n num_layers=2,\n d_model=512,\n num_heads=4,\n dff=1024,\n rate=0.1,\n used_rnn=False,\n max_width=1600):\n super(Encoder, self).__init__()\n\n self.used_rnn = used_rnn\n self.conv1 = layers.Conv2D(48, kernel_size=(3, 3), activation='relu', padding='same', name='conv1')\n self.pool1 = layers.MaxPooling2D(pool_size=(2, 2), strides=(2, 2), name='pool1')\n self.conv2 = layers.Conv2D(96, kernel_size=(3, 3), activation='relu', padding='same', name='conv2')\n self.pool2 = layers.MaxPooling2D(pool_size=(2, 2), strides=(2, 2), name='pool2')\n self.conv3 = layers.Conv2D(128, kernel_size=(3, 3), activation='relu', padding='same', name='conv3')\n self.conv4 = layers.Conv2D(128, kernel_size=(3, 3), activation='relu', padding='same', name='conv4')\n\n self.padd4 = layers.ZeroPadding2D(padding=(0, 1))\n self.pool4 = layers.MaxPooling2D(pool_size=(2, 2), strides=(2, 1), padding='valid', name='pool3')\n self.conv5 = layers.Conv2D(256, kernel_size=(3, 3), activation='relu', padding='same', name='conv5')\n self.bncv5 = layers.BatchNormalization(axis=-1, name='bnconv5')\n self.conv6 = layers.Conv2D(256, kernel_size=(3, 3), activation='relu', padding='same', name='conv6')\n self.bncv6 = layers.BatchNormalization(axis=-1, name='bnconv6')\n self.pddd6 = layers.ZeroPadding2D(padding=(0, 1))\n self.pool6 = layers.MaxPooling2D(pool_size=(2, 2), strides=(2, 1), padding='valid', name='pool4')\n self.conv7 = layers.Conv2D(512, kernel_size=(2, 2), activation='relu', padding='valid', name='conv7')\n\n self.dff = dff\n self.rate = rate\n self.d_model = d_model\n self.num_heads = num_heads\n self.max_width = max_width\n self.num_layers = num_layers\n self.transfer_enc_layers = []\n self.dropout = tf.keras.layers.Dropout(rate)\n self.pos_encoding = positional_encoding(self.max_width, self.d_model)\n\n if self.num_layers > 0:\n assert(self.d_model % self.num_heads == 0)\n\n units = self.d_model\n rnn_type = 'gru'\n assert (rnn_type in ('rnn', 'lstm', 'gru'))\n if rnn_type == 'rnn':\n rnn_class = tf.nn.rnn_cell.RNNCell\n elif rnn_type == 'lstm':\n rnn_class = tf.nn.rnn_cell.LSTMCell\n elif rnn_type == 'gru':\n rnn_class = tf.nn.rnn_cell.GRUCell\n\n if used_rnn:\n rnn_fw_name = 'encode_rnn_fw0'\n rnn_bw_name = 'encode_rnn_bw0'\n self.rnn_fw0 = rnn_class(num_units=units, dtype=tf.float32, name=rnn_fw_name)\n self.rnn_bw0 = rnn_class(num_units=units, dtype=tf.float32, name=rnn_bw_name)\n\n rnn_fw_name = 'encode_rnn_fw1'\n rnn_bw_name = 'encode_rnn_bw1'\n self.rnn_fw1 = rnn_class(num_units=units, dtype=tf.float32, name=rnn_fw_name)\n self.rnn_bw1 = rnn_class(num_units=units, dtype=tf.float32, name=rnn_bw_name)\n self.rnn_multi_fw = tf.nn.rnn_cell.MultiRNNCell([self.rnn_fw0, self.rnn_fw1])\n self.rnn_multi_bw = tf.nn.rnn_cell.MultiRNNCell([self.rnn_bw0, self.rnn_bw1])\n #self.rnn_multi_fw = tf.nn.rnn_cell.DropoutWrapper(self.rnn_multi_fw, 0.9, 0.95, 0.95)\n #self.rnn_multi_bw = tf.nn.rnn_cell.DropoutWrapper(self.rnn_multi_bw, 0.9, 0.95, 0.95)\n\n self.dense_layer = tf.keras.layers.Dense(self.d_model)\n for layer_id in range(num_layers):\n self.transfer_enc_layers.append(EncoderLayer(self.d_model, self.num_heads, self.dff, self.rate))\n\n def bidirectional_rnn_foreward(self, inputs, rnn_fw_inst, rnn_bw_inst):\n outputs_fb, output_states = tf.nn.bidirectional_dynamic_rnn(cell_fw=rnn_fw_inst,\n cell_bw=rnn_bw_inst,\n inputs=inputs,\n dtype=tf.float32,\n time_major=False)\n\n logger.debug(\"outputs_fb size: {}\".format(len(outputs_fb)))\n logger.debug(\"outputs_fb[0] shape:{}\".format(outputs_fb[0].shape))\n logger.debug(\"outputs_fb[1] shape:{}\".format(outputs_fb[1].shape))\n logger.debug(\"output_states size: {}\".format(len(output_states)))\n logger.debug(\"output_states 0 0 shape: {}\".format(output_states[0][0].shape))\n logger.debug(\"output_states 0 1 shape: {}\".format(output_states[0][1].shape))\n result = tf.concat(outputs_fb, axis=2)\n fw_status, bw_status = output_states\n return result, fw_status\n\n def dynamic_rnn_foreward(self, inputs, rnn_cell_inst):\n outputs, state = tf.nn.dynamic_rnn(cell=rnn_cell_inst,\n inputs=inputs,\n time_major=False)\n return outputs, state\n\n def get_sequence_lengths(self, widths):\n return tf.cast(tf.div(widths, 4) + 1, dtype=tf.int32)\n\n def get_reverse_points(self, points):\n ret_points = []\n for point in points:\n pointx, pointy = point\n anchor_xcent = 4 * pointx + 2\n anchor_xsoff = max(anchor_xcent - 4, 0)\n anchor_xeoff = max(anchor_xcent + 4, 0)\n\n anchor_ycent = 16 * pointy + 8\n anchor_ysoff = max(anchor_ycent - 16, 0)\n anchor_yeoff = max(anchor_ycent + 16, 0)\n\n positions = []\n for anchory_off in range(anchor_ysoff, anchor_yeoff):\n if int(anchory_off / 16.0) != pointy:\n continue\n for anchorx_off in range(anchor_xsoff, anchor_xeoff):\n if int(anchorx_off / 4.0) == pointx:\n positions.append([int(anchorx_off), int(anchory_off)])\n ret_points.append(positions)\n return ret_points\n\n\n def call(self, inputs, widths, training):\n\n features = self.conv1(inputs)\n features = self.pool1(features)\n features = self.conv2(features)\n features = self.pool2(features)\n features = self.conv3(features)\n features = self.conv4(features)\n features = self.padd4(features)\n features = self.pool4(features)\n features = self.conv5(features)\n features = self.bncv5(features, training=training)\n features = self.conv6(features)\n features = self.bncv6(features, training=training)\n features = self.pddd6(features)\n features = self.pool6(features)\n features = self.conv7(features)\n\n logger.debug(\"B*H*W*C features shape: {}\".format(features.shape))\n\n features_s = tf.shape(features)\n features_b = features_s[0]\n features_h = features_s[1]\n features_w = features_s[2]\n features_c = features_s[3]\n # B*H*W*C-->BH*W*C\n features = tf.reshape(features, [features_b * features_h, features_w, features_c])\n logger.debug(\"B*H*W*C-->BH*W*C shape: {}\".format(features.shape))\n if self.used_rnn:\n features, fw_status = self.bidirectional_rnn_foreward(features, self.rnn_multi_fw, self.rnn_multi_bw)\n\n features = self.dense_layer(features)\n logger.debug(\"BH*W*C-->BH*W*D shape: {}\".format(features.shape))\n\n weight_mask = None\n if widths is not None:\n widths = self.get_sequence_lengths(widths)\n logger.debug('widths shape {}, {}'.format(widths.shape, widths))\n widths = tf.reshape(widths, [-1, 1], name='seq_len')\n widths = tf.concat([widths for h in range(features_h)], axis=-1)\n widths = tf.reshape(widths, [-1])\n weight_mask = tf.sequence_mask(widths, features_w, dtype=tf.float32)\n weight_mask = tf.reshape(weight_mask, [features_b, features_h * features_w])\n logger.debug(\"weight mask shape: {}\".format(weight_mask.shape))\n\n #this code cause loss degrade failed\n #if self.num_layers > 0:\n # features *= tf.math.sqrt(tf.cast(self.d_model, tf.float32))\n # features += self.pos_encoding[:, :features_w, :]\n\n features += self.pos_encoding[:, :features_w, :]\n \n # BH*W*D --> B*HW*D\n features = tf.reshape(features, [features_b, features_h * features_w, -1])\n\n logger.debug(\"features shape: {}\".format(features.shape))\n if self.num_layers > 0:\n mask = None\n if weight_mask is not None:\n mask = tf.matmul(tf.expand_dims(weight_mask, -1),\n tf.expand_dims(weight_mask, -1), transpose_b=True)\n mask = tf.expand_dims(1.0 - mask, axis=1)\n features = self.dropout(features, training=training)\n for i in range(self.num_layers):\n features = self.transfer_enc_layers[i](features, training, mask)\n\n return features, weight_mask\n\n\nif __name__ == '__main__':\n import numpy as np\n data = np.random.random((4, 48, 64, 3))\n widths = [2, 4, 6, 8]\n data = tf.convert_to_tensor(data, dtype=tf.float32)\n ecnoder = Encoder(1)\n features, weight_mask = ecnoder(data, widths, True)\n print(\"features shape: {}\".format(features.shape))\n print(\"weight shape: {}\".format(weight_mask.shape))\n print(weight_mask)\n\n\n","repo_name":"attendfov/att_ctc_tf2","sub_path":"transformer/Encoder.py","file_name":"Encoder.py","file_ext":"py","file_size_in_byte":11211,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"25311182336","text":"me = 9999\nma = 0\nfor n in range(1, 4):\n num = int(input('Digite um número: '))\n \n if num == me and num == má: \n me = num\n ma = num\n\n else:\n if num < me:\n me = num\n if num > ma:\n ma = num\n\nprint('===' * 7)\nprint('O menor número foi {}'.format(me))\nprint('O maior número foi {}'.format(ma))\nprint('===' * 7)\n\n","repo_name":"WinikeCuamba/pythonEx","sub_path":"ex114.py","file_name":"ex114.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"41796570118","text":"# -*- coding:utf-8 -*-\n\"\"\"\n作者:lby\n日期:2020年10月16日\n\"\"\"\n\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n\nclass Solution(object):\n def addTwoNumbers(self, l1: ListNode, l2: ListNode):\n if l1 is None:\n return l2\n if l2 is None:\n return l1\n\n tmp = ListNode(0)\n res = tmp\n flag = 0\n while l1 or l2:\n tmpsum = 0\n if l1:\n tmpsum = l1.val\n l1 = l1.next\n if l2:\n tmpsum += l2.val\n l2 = l2.next\n tmpres = ((tmpsum + flag) % 10)\n flag = ((tmpsum + flag) // 10)\n res.next = ListNode(tmpres)\n res = res.next\n if flag:\n res.next = ListNode(1)\n res = tmp.next\n del tmp\n return res\n","repo_name":"Shizcliff/Leetcode","sub_path":"code/两数相加.py","file_name":"两数相加.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"43730134110","text":"# -*- coding:utf-8 -*-\n# __author__='ligang'\n\n\n#检验是否含有中文字符\ndef is_contains_chinese(strs):\n for _char in strs:\n if '\\u4e00' <= _char <= '\\u9fa5':\n return True\n return False\n\n\ndef is_chinese(uchar):\n \"\"\"判断一个unicode是否是汉字\"\"\"\n if uchar >= u'\\u4e00' and uchar <= u'\\u9fa5':\n #print(uchar, True)\n return True\n else:\n #print(uchar, False)\n return False\n\n\ndef is_alphabet(uchar):\n \"\"\"判断一个unicode是否是英文字母\"\"\"\n if (uchar >= u'\\u0041' and uchar <= u'\\u005a') or (uchar >= u'\\u0061' and uchar <= u'\\u007a'):\n return True\n else:\n return False\n\n\ndef count_str(content):\n space_count = 0\n digit_count = 0\n alphabet_count = 0\n chinese_count = 0\n other_count = 0\n\n for i in content:\n # 判断是否为空格\n if i.isspace():\n #print(i, \"isspace\")\n space_count += 1\n # 判断是否为数字\n elif i.isdigit():\n #print(i, \"isdigit\")\n digit_count += 1\n # 判断是否为英文字符\n elif is_alphabet(i):\n #print(i, \"is_alphabet\")\n alphabet_count += 1\n # 判断是否为中文字符\n elif is_chinese(i):\n #print(i, \"is_chinese\")\n chinese_count += 1\n # 判断是否为其他字符\n else:\n #print(i, \"is either\")\n other_count += 1\n\n return {\n \"space_count\": space_count,\n \"digit_count\": digit_count,\n \"alphabet_count\": alphabet_count,\n \"chinese_count\": chinese_count,\n \"other_count\": other_count,\n }\n\n","repo_name":"ligang-super/PythonProjects","sub_path":"common/common_string.py","file_name":"common_string.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7900318731","text":"import sys\ninput = sys.stdin.readline\nfrom collections import deque\n\nn, m = map(int, input().split())\nmaps = [list(map(int, input().split())) for _ in range(n)]\ncheck = False\nday = 0\n\ndef bfs(x,y):\n q = deque()\n q.append((x,y))\n while q:\n x,y = q.popleft()\n dx = [-1,1,0,0]\n dy = [0,0,-1,1]\n for k in range(4):\n nx = x+dx[k]\n ny = y+dy[k]\n if 0<=nx= 2: # 섬이 2개 이상 생성되면 종료해야지\n check = True\n break\n\n day += 1\n\nif check:\n print(day)\nelse:\n print(0) # 없으니까 여기로","repo_name":"GayeonKimm/CT","sub_path":"BOJ/BFS/2573 빙산.py","file_name":"2573 빙산.py","file_ext":"py","file_size_in_byte":1564,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17368572515","text":"from pymongo import MongoClient\n\ntry:\n\tconn = MongoClient()\n\tprint(\"Connected successfully!!!\")\nexcept:\n\tprint(\"Could not connect to MongoDB\")\n\ndb = conn.ecom_db\ncollection = db.products\n\nprod1 = {\"name\":\"Monte Carlo\",\"color\":\"green\",\"price\":1100}\nprod2 = {\"name\":\"Arrow\",\"color\":\"yellow\",\"price\":800}\nprod3 = {\"name\":\"GAP\",\"color\":\"white\",\"price\":1200}\nprod4 = {\"name\":\"Tantra\",\"color\":\"yellow\",\"price\":1400}\nprod5 = {\"name\":\"Tommy Hilfiger\",\"color\":\"green\",\"price\":2000}\n\ncollection.insert_one(prod1)\ncollection.insert_one(prod2)\ncollection.insert_one(prod3)\ncollection.insert_one(prod4)\ncollection.insert_one(prod5)\n\nprint(\"Data inserted Successfully\")\n\n# Printing the data inserted\ncursor = collection.find()\nfor record in cursor:\n\tprint(record)\n","repo_name":"sunnychaudhari/flask-mongo","sub_path":"inser_records.py","file_name":"inser_records.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30544181904","text":"import os, re\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport json\nfrom collections import Counter\n\n\"\"\"\n--- 說明 ---\nx:閘門垂直\ny:閘門水平\nz:輸送帶方向\n\"\"\"\n\n\nclass obj:\n def __init__(self, x=0, y=0, z=0, serialID=None):\n self.x = abs(x)\n self.y = abs(y)\n self.z = abs(z)\n self.serialID = serialID\n self.pic_path = f'pictures/{self.serialID}.jpg'\n self.volumn = round((self.x * self.y * self.z)/1000, 1)\n\n def size(self):\n # assert self.volumn >= 0\n\n if self.volumn > 500:\n return 'large'\n elif self.volumn < 250:\n return 'small'\n else:\n return 'medium'\n\n\n# --- constants ---\n\nTHRESHOLD = 8 # mm 6\nSPEED = 16 # mm/s\nCONVEYOR_DIST = 413 # mm\nGATE_WIDTH = 170 # mm\n\n\n# --- functions ---\n\ndef is_object(x, y):\n if x!=0 and y!=0:\n if CONVEYOR_DIST - x >= THRESHOLD or GATE_WIDTH - y >=THRESHOLD:\n return True\n return False\n\n # xs = [dists[0] for dists in window]\n # ys = [dists[1] for dists in window]\n\n # if all([CONVEYOR_DIST - x > THRESHOLD for x in xs]) or all([CONVEYOR_DIST - y > THRESHOLD for y in ys]):\n # return True\n \n # return False\n\n\ndef get_est_x(xs:list):\n real_xs = [CONVEYOR_DIST - x for x in xs]\n try:\n avg_x = round(sum(real_xs)/len(real_xs), 1)\n except ZeroDivisionError:\n avg_x = 0\n #return round(avg_x, 2) # use mean as the estimated distance\n return avg_x\n # return max(dists, key=dists.count) # use mode as the estimated distance\n\n\ndef get_est_y(ys:list):\n real_ys = [GATE_WIDTH - y for y in ys]\n try:\n avg_y = round(sum(real_ys)/len(real_ys), 1)\n except ZeroDivisionError:\n avg_y = 0\n #return round(avg_y, 2) # use mean as the estimated distance\n return avg_y\n # return max(dists, key=dists.count) # use mode as the estimated distance\n\n\ndef get_est_z(start, end):\n elapsedTime = end - start\n elapsedTime = elapsedTime.total_seconds() # from timedelta to float\n len_z = elapsedTime * SPEED\n return round(len_z, 1)\n\n\ndef log_json(object):\n with open('logfile.json', 'r+') as f:\n log = json.load(f)\n\n log[object.serialID] = {}\n log[object.serialID]['x'] = object.x\n log[object.serialID]['y'] = object.y\n log[object.serialID]['z'] = object.z\n log[object.serialID]['volumn'] = object.volumn\n log[object.serialID]['size'] = object.size()\n log[object.serialID]['picture'] = object.pic_path\n\n f.seek(0)\n json.dump(log, f, indent=4)\n\n\ndef get_prev_n(n):\n with open('logfile.json', 'r+') as f:\n log = json.load(f)\n serialIDs = sorted(log, reverse=True)[1:n+1]\n\n prev3 = {i:log[i] for i in serialIDs}\n return prev3\n\n\ndef log_line(entries):\n for i in entries:\n objInfo = '# ------------\\n'\n objInfo += f'object ID: {i}\\n'\n objInfo += f'length of x: {entries[i][\"x\"]}\\n'\n objInfo += f'length of y: {entries[i][\"y\"]}\\n'\n objInfo += f'length of z: {entries[i][\"z\"]}\\n'\n objInfo += f'object volumn: {entries[i][\"volumn\"]}\\n'\n objInfo += f'object size range: {entries[i][\"size\"]}'\n \n os.system(f'echo \"{objInfo}\" > IDfolder/{i}.txt')\n objInfo = ''\n\n\ndef draw_distribution(att:str):\n with open('logfile.json', 'r') as f:\n log = json.load(f)\n \n data = np.array([log[serialID][att] for serialID in log])\n data = dict(Counter(data))\n vals = np.array(list(data.values()))\n labels = list(data.keys())\n\n plt.pie(vals, labels=labels, autopct='%1.1f%%')\n plt.title(f'Distribution of {att}')\n plt.savefig(f'piecharts/{att}.png')\n\n\nif __name__ == \"__main__\":\n # write_log(x)\n # write_log(x)\n # log_json(x)\n draw_distribution('size')\n # log_line(get_latest_3())\n\n","repo_name":"patorikkulee/tof-obj-detection","sub_path":"tof_utils.py","file_name":"tof_utils.py","file_ext":"py","file_size_in_byte":3861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22448833885","text":"# building a translator\nfrom translate import Translator\n\ntranslator = Translator(to_lang=\"ja\")\ntext = ''\n\n\ntry:\n with open('translation_file.txt', 'r') as f:\n text = f.read()\n translation = translator.translate(text)\n print(translation)\nexcept FileNotFoundError as err:\n print(\"file Not found\")\n\ntry:\n with open('translated_file.txt', 'w') as f:\n f.write(translation)\nexcept FileExistsError as err:\n raise err","repo_name":"SirriCelles/ZTM-python-Exercise","sub_path":"files/file_exercise.py","file_name":"file_exercise.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"23054178036","text":"# -*- coding: utf-8 -*-\nfrom django.db import models\nfrom django.contrib.contenttypes import generic\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.auth.models import User\nfrom django.utils.safestring import mark_safe\nfrom django.utils.html import strip_tags\nfrom django.contrib.comments.models import Comment\nimport datetime\n\nclass Activity(models.Model):\n # 액션 고유 ID. 지울 때 쓴다. 예: judge-problem-opened-417\n key = models.CharField(max_length=255, db_index=True, unique=True)\n # 액션 카테고리. 카테고리별 뉴스피드를 볼 때 쓴다. 예: wiki, judge,\n # membership\n category = models.CharField(max_length=64, db_index=True)\n # 액션 타입. css 클래스를 정하는 데 쓴다.. -_-; 예: wiki-edit,\n # problem-solved, posted, commented\n type = models.CharField(max_length=64)\n # 액터\n actor = models.ForeignKey(User, null=True, related_name='actor')\n # {actor} {target} {action_object} 를 갖는 문자열\n verb = models.CharField(max_length=255)\n\n admin_only = models.BooleanField(default=False) # 더 이상 사용되지 않고 권한 기반으로 변경됨\n\n target_content_type = models.ForeignKey(ContentType,\n related_name='target_content_type',\n blank=True,\n null=True)\n target_object_id = models.PositiveIntegerField(blank=True,\n null=True)\n target = generic.GenericForeignKey('target_content_type','target_object_id')\n\n action_object_content_type = models.ForeignKey(ContentType,\n related_name='action_object_content_type',\n blank=True,\n null=True)\n action_object_object_id = models.PositiveIntegerField(blank=True,null=True)\n action_object = generic.GenericForeignKey('action_object_content_type',\n 'action_object_object_id')\n timestamp = models.DateTimeField(db_index=True)\n\n class Meta:\n permissions = (\n ('read_activity', 'Can read this activity'),\n )\n\n @staticmethod\n def translate(kwargs):\n args = {}\n for k, v in kwargs.iteritems():\n if k in [\"target\", \"action_object\"]:\n ct = ContentType.objects.get_for_model(v.__class__)\n pk = v.id\n args[k + \"_content_type\"] = ct\n args[k + \"_object_id\"] = pk\n else:\n args[k] = v\n return args\n\n @staticmethod\n def new(**kwargs):\n if \"timestamp\" not in kwargs:\n kwargs[\"timestamp\"] = datetime.datetime.now()\n return Activity(**Activity.translate(kwargs))\n\n @staticmethod\n def delete_all(**kwargs):\n return Activity.objects.filter(**Activity.translate(kwargs)).delete()\n\n def render(self, spoiler_replacement=None):\n from judge.models import Problem\n def wrap_in_link(object, spoiler_replacement):\n if not object: return \"\"\n if spoiler_replacement:\n unicode_rep = spoiler_replacement\n elif isinstance(object, Comment):\n unicode_rep = strip_tags(object.comment)\n if len(unicode_rep) > 50:\n unicode_rep = unicode_rep[:47] + \"..\"\n else:\n unicode_rep = unicode(object)\n if object.get_absolute_url:\n return \"\".join(['' % object.get_absolute_url(),\n unicode_rep,\n ''])\n return unicode_rep\n return mark_safe(self.verb.format(actor=wrap_in_link(self.actor, None),\n action_object=wrap_in_link(self.action_object, spoiler_replacement),\n target=wrap_in_link(self.target, None)))\n","repo_name":"jongman/algospot","sub_path":"www/newsfeed/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4042,"program_lang":"python","lang":"en","doc_type":"code","stars":141,"dataset":"github-code","pt":"48"} +{"seq_id":"37516898474","text":"import logging\nimport colorama\nfrom colorama import Fore, Style\nfrom terminaltables import SingleTable\nfrom pprint import pformat\nimport datetime\n\nfrom me4storage.api.session import Session\nfrom me4storage.common.exceptions import ApiError\nfrom me4storage.common.nsca import CheckResult\nimport me4storage.common.util as util\nimport me4storage.common.tables as tables\nimport me4storage.common.formatters\n\nfrom me4storage.api import show, modify, delete\nfrom me4storage import commands\n\nlogger = logging.getLogger(__name__)\n\ndef pool(args, session):\n\n pools = show.pools(session)\n pool_names = [pool.name for pool in pools]\n if len(pools) == 0:\n logger.warn(f\"No pools present. Nothing to do...\")\n rc = CheckResult.OK\n return rc.value\n\n if args.delete_pool_all is True:\n logger.info(f\"Deleting all pools present...\")\n delete.pools(session, pool_names)\n else:\n for requested_pool in args.delete_pool_names:\n if requested_pool not in pool_names:\n logger.warn(f\"Pool {requested_pool} is not present. Nothing to do...\")\n continue\n else:\n logger.info(f\"Deleting pool {requested_pool}...\")\n delete.pools(session, [requested_pool])\n\n rc = CheckResult.OK\n return rc.value\n\ndef host_group(args, session):\n\n host_groups = show.host_groups(session)\n host_group_names = [host_group.name for host_group in host_groups]\n if len(host_groups) == 0:\n logger.warn(f\"No host_groups present. Nothing to do...\")\n rc = CheckResult.OK\n return rc.value\n\n if args.delete_host_group_all is True:\n logger.info(f\"Deleting all host groups present...\")\n delete.host_groups(session,\n names=['all'],\n delete_hosts=args.delete_host_group_hosts)\n else:\n for requested_host_group in args.delete_host_group_names:\n if requested_host_group not in host_group_names:\n logger.warn(f\"Host Group {requested_host_group} is not present. Nothing to do...\")\n continue\n else:\n logger.info(f\"Deleting host_group {requested_host_group}...\")\n delete.host_groups(session,\n names=[requested_host_group],\n delete_hosts=args.delete_host_group_hosts)\n\n rc = CheckResult.OK\n return rc.value\n\ndef host_configuration(args, session):\n\n logger.info(f\"Deleting all host groups present...\")\n delete.host_groups(session,\n names=['all'],\n delete_hosts=True)\n\n logger.info(f\"Deleting all initiator nicknames...\")\n delete.initiator_nickname(session,\n name='all')\n\n rc = CheckResult.OK\n return rc.value\n\ndef configuration(args, session):\n\n pools = show.pools(session)\n pool_names = [pool.name for pool in pools]\n if len(pools) > 0:\n logger.info(f\"Deleting all pools present...\")\n delete.pools(session, pool_names)\n else:\n logger.info(f\"No pools present. Nothing to do...\")\n\n logger.info(f\"Deleting all host groups present...\")\n delete.host_groups(session,\n names=['all'],\n delete_hosts=True)\n\n logger.info(f\"Deleting all initiator nicknames...\")\n delete.initiator_nickname(session,\n name='all')\n\n rc = CheckResult.OK\n return rc.value\n\ndef mapping(args, session):\n # Check if host or host_group was requested to unmap from\n if args.delete_mapping_host_group:\n host_group = args.delete_mapping_host_group\n # Check if requested host group is configured\n host_groups = show.host_groups(session)\n if host_group not in [hg.name for hg in host_groups]:\n logger.error(\"Host group {host_group} not configured...\")\n rc = CheckResult.CRITICAL\n return rc.value\n\n # Define initiators string, according to required syntax for mapping\n # See: https://www.dell.com/support/manuals/uk/en/ukbsdt1/powervault-me4012/me4_series_cli_pub/command-syntax?guid=guid-08ed6612-4713-4221-bc66-e3a6808b422a&lang=en-us\n initiators=f\"{host_group}.*.*\"\n else:\n host = args.delete_mapping_host\n # Define initiators string, according to required syntax for mapping\n # See: https://www.dell.com/support/manuals/uk/en/ukbsdt1/powervault-me4012/me4_series_cli_pub/command-syntax?guid=guid-08ed6612-4713-4221-bc66-e3a6808b422a&lang=en-us\n initiators=f\"{host_group}.*\"\n\n # Check if specific volume requested to unmap\n if args.delete_mapping_volume:\n volume_name = args.delete_mapping_volume.strip()\n volumes = show.volumes(session)\n if volume_name not in [vol.name for vol in volumes]:\n logger.error(\"Volume {volume_name} not present...\")\n rc = CheckResult.CRITICAL\n return rc.value\n\n logger.info(f\"Unmapping volume: {volume.volume_name} \"\n f\"from initiators: {initiators}\")\n delete.mapping(session,\n initiators=[initiators],\n volumes=[volume.volume_name])\n\n else:\n # Unmap all volumes from initiators\n volumes = show.volumes(session)\n for volume in volumes:\n logger.info(f\"Unmapping volume: {volume.volume_name} \"\n f\"from initiators: {initiators}\")\n delete.mapping(session,\n initiators=[initiators],\n volumes=[volume.volume_name])\n\n rc = CheckResult.OK\n return rc.value\n","repo_name":"mjrasobarnett/python-me4storage","sub_path":"me4storage/commands/delete.py","file_name":"delete.py","file_ext":"py","file_size_in_byte":5671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35350038922","text":"import datetime\nimport math\nimport os\n\nimport torchaudio\nfrom matplotlib.font_manager import FontProperties\nfrom transformers import Wav2Vec2Processor\nimport torch.nn as nn\nfrom config import Args\nfrom preprocess.process_utils import MODMA_code\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nfrom torch.utils.data import dataset\nfrom torchvision import transforms\nimport random\n\nplt.rcParams['font.sans-serif'] = ['Simhei'] # 显示中文\nplt.rcParams['axes.unicode_minus'] = False # 显示负号\nplt.rcParams['font.size'] = \"14.0\"\nfont_small = FontProperties(family=\"Simhei\", size=10)\n# font_song = FontProperties(fname=r'c:\\windows\\Fonts\\simsun.ttc', size=16) # 宋体\n# font_TimesNewsman = FontProperties(family='Times New Roman', size=8)\n\nCLASS_LABELS = [\"angry\", \"boredom\", \"disgust\", \"fear\", \"happy\", \"neutral\", \"sad\"]\nIEMOCAP_LABELS = ['angry', 'excited', 'frustrated', 'happy', 'neutral', 'sad']\nMODMA_LABELS = ['HC', 'MDD']\nRAVDESS_LABELS = [\"angry\", \"calm\", \"disgust\", \"fear\", \"happy\", \"normal\", \"sad\", \"surprised\"]\ndpi = 300\nplt.rcParams['font.family'] = ['SimHei']\n\n\nclass EarlyStopping:\n \"\"\"Early stops the training if validation accuracy doesn't change after a given patience.\"\"\"\n\n def __init__(self, patience=5, use_acc: float = 80.0):\n \"\"\"\n Args:\n patience (int): How long to wait after last time validation loss improved. Default: 5\n use_acc (float): 只有当验证集准确率大于use_acc,才会触发早停止\n \"\"\"\n self.patience = patience\n self.patience_ = patience\n self.use_acc = use_acc\n self.last_val_acc = 0\n\n def __call__(self, val_acc) -> bool:\n if (abs(self.last_val_acc - val_acc) < 1e-9) and (val_acc > self.use_acc):\n self.patience -= 1\n else:\n self.patience = 5\n self.last_val_acc = val_acc\n if self.patience == 1:\n print(f\"The validation accuracy has not changed in {self.patience_} iterations, stop train\")\n print(f\"The final validation accuracy is {val_acc}\")\n return True\n else:\n return False\n\n\ndef load_dataset(dataset_name, spilt_rate, random_seed, version='V2', order=3):\n \"\"\"\n 加载数据集\n \"\"\"\n data = np.load(f'preprocess/data/{dataset_name}_{version}_order3.npy', allow_pickle=True).item()\n x = data['x'][:, :order * 13, :]\n y = data['y']\n Num = x.shape[0] # 样本数\n dataset = myDataset(x, y) # input shape of x: [样本数,特征维度,时间步] input shape of y: [样本数,类别数]\n spilt_num = len(spilt_rate)\n lengths = []\n for i in range(spilt_num):\n lengths.append(int(Num * spilt_rate[i]))\n if spilt_num > 1:\n lengths[-1] = Num - sum(lengths[:-1])\n\n datasets = torch.utils.data.random_split(dataset, lengths, generator=torch.Generator().manual_seed(random_seed))\n return datasets\n\n\ndef load_loader(dataset_name, spilt_rate, batch_size, random_seed, version='V2', order=3):\n \"\"\"\n 加载数据加载器(用在域适应)\n \"\"\"\n datasets = load_dataset(dataset_name, spilt_rate, random_seed, version, order)\n loaders = []\n for dt in datasets:\n loaders.append(\n torch.utils.data.dataloader.DataLoader(\n dataset=dt,\n batch_size=batch_size,\n ))\n return loaders\n\n\ndef sample_dataset(data_loader, sample_num, batch_size):\n \"\"\"\n 随机采样数据\n \"\"\"\n sample_index = random.sample(range(len(data_loader.dataset)), sample_num)\n samples = data_loader.dataset[sample_index]\n sample_loader = torch.utils.data.dataloader.DataLoader(\n dataset=myDataset(samples[0], samples[1]),\n batch_size=batch_size\n )\n return sample_loader\n\n\ndef dataset_num_class(dataset_name):\n \"\"\"\n 用在域适应中,返回数据集对应的类别数\n \"\"\"\n num_class = []\n for name in dataset_name:\n if name == \"IEMOCAP\":\n num_class.append(6)\n elif name == \"MODMA\":\n num_class.append(2)\n elif name == \"CASIA\":\n num_class.append(6)\n elif name == \"RAVDESS\":\n num_class.append(8)\n elif name == \"ABC\":\n num_class.append(6)\n elif name == \"TESS\":\n num_class.append(7)\n elif name == \"eNTERFACE\":\n num_class.append(6)\n else:\n raise NotImplementedError\n return num_class\n\n\ndef seed_everything(random_seed):\n \"\"\"确定随机数,以便于复现 但是会很慢\n \n Args:\n random_seed (int): \n \"\"\"\n random.seed(random_seed)\n np.random.seed(random_seed)\n torch.manual_seed(random_seed)\n os.environ['PYTHONHASHSEED'] = str(random_seed)\n\n if torch.cuda.is_available():\n torch.cuda.manual_seed(random_seed)\n torch.cuda.manual_seed_all(random_seed)\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = True\n\n\ndef load_multi_dataset(name, spilt_rate, random_seed, batch_size, out_type=True, length=-1, version=\"v2\", order=3):\n \"\"\"为多个数据集生成对应的Dataloader\n\n Args:\n name (str): 数据集名称\n spilt_rate (list): 训练集,验证集,测试集分割比例\n random_seed (int): 随机数种子\n batch_size (int): 批次大小\n length(int): 当length=-1时,选择所有的数据,否则选择length个数据\n out_type(bool): 控制返回哪些loader,True返回训练和验证,false返回测试\n version(str): 决定数据版本\n order(int): 39维,26维,13维MFCC\n\n Returns:\n Dataloader: 数据加载器\n \"\"\"\n\n data = np.load(f\"preprocess/data/{name}_{version}_order{order}.npy\", allow_pickle=True).item()\n x = data['x']\n y = data['y']\n actual_length = y.shape[0]\n if actual_length > length != -1:\n delete_index = random.sample(range(actual_length), actual_length - length)\n x = np.delete(x, delete_index, axis=0)\n y = np.delete(y, delete_index, axis=0)\n dataset = myDataset(x=x, y=y)\n train_num = int(x.shape[0] * spilt_rate[0])\n val_num = int(x.shape[0] * spilt_rate[1])\n test_num = x.shape[0] - train_num - val_num\n train_dataset, val_dataset, test_dataset = torch.utils.data.random_split(dataset, [train_num, val_num, test_num],\n generator=torch.Generator().manual_seed(\n random_seed))\n if out_type:\n train_loader = torch.utils.data.dataloader.DataLoader(\n dataset=train_dataset,\n batch_size=batch_size,\n )\n val_loader = torch.utils.data.dataloader.DataLoader(\n dataset=val_dataset,\n batch_size=batch_size,\n )\n return train_loader, val_loader\n else:\n test_loader = torch.utils.data.dataloader.DataLoader(\n dataset=test_dataset,\n batch_size=batch_size,\n )\n return test_loader\n\n\ndef load_meta_dataset(name, length=256, version=\"V2\", order=3, return_residual=False, appendix=None):\n \"\"\"\n 加载元学习数据集\n\n Args:\n name: 数据集的名字\n length: 截取长度\n version: 数据集版本\n order: 数据集阶数\n return_residual: 是否返回剩余的数据集(用作测试数据集)\n appendix: 是否输出数据集标号\n \"\"\"\n data = np.load(f\"../preprocess/data/{name}_{version}_order{order}.npy\", allow_pickle=True).item()\n x = data['x']\n y = data['y']\n if y.shape[0] < length:\n length = y.shape[0]\n random_index = np.random.permutation(y.shape[0])\n cut_index = random_index[:length]\n x_cut = x[cut_index]\n y_cut = y[cut_index]\n meta_dataset = myDataset(x=x_cut, y=y_cut, appendix=appendix)\n if return_residual:\n residual_index = random_index[length:]\n x_res = x[residual_index]\n y_res = y[residual_index]\n residual_dataset = myDataset(x=x_res, y=y_res)\n return meta_dataset, residual_dataset\n else:\n return meta_dataset\n\n\ndef accuracy_cal_numpy(y_pred, y_true):\n \"\"\"\n 计算准确率(numpy)\n \"\"\"\n predict = np.argmax(y_pred.numpy(), 1)\n label = np.argmax(y_true.numpy(), 1)\n true_num = (predict == label).sum()\n return true_num\n\n\ndef accuracy_cal(y_pred, y_true):\n \"\"\"\n 计算准确率(torch)\n \"\"\"\n predict = torch.max(y_pred.data, 1)[1] # torch.max()返回[values, indices],torch.max()[1]返回indices\n if len(y_true.data.shape) == 1:\n label = y_true.data\n else:\n label = torch.max(y_true.data, 1)[1]\n true_num = (predict == label).sum()\n return true_num\n\n\ndef compare_key(src_key: str, tgt_key: str):\n \"\"\"\n 比较两个权重的键,并返回不同的部分(用于加载预训练模型)\n \"\"\"\n src_key = src_key.split('.')\n tgt_key = tgt_key.split('.')\n mini_len = min(len(src_key), len(tgt_key))\n tmp_src_key = None\n tmp_tgt_key = None\n for i in range(1, mini_len + 1):\n if src_key[-i] != tgt_key[-i]:\n tmp_src_key, tmp_tgt_key = src_key[:len(src_key) - i + 1], tgt_key[:len(tgt_key) - i + 1]\n break\n if isinstance(tmp_src_key, list):\n tmp_src_key = '.'.join(tmp_src_key)\n if isinstance(tmp_tgt_key, list):\n tmp_tgt_key = '.'.join(tmp_tgt_key)\n return tmp_src_key, tmp_tgt_key\n\n\ndef confusion_matrix(pred, labels, conf_matrix):\n \"\"\"\n 更新混淆矩阵\n \"\"\"\n pred = torch.max(pred, 1)[1]\n labels = torch.max(labels, 1)[1]\n for p, t in zip(pred, labels):\n conf_matrix[p, t] += 1\n return conf_matrix\n\n\ndef plot_matrix(cm, labels_name, model_name: str, title='混淆矩阵', normalize=False,\n result_path: str = \"results/\"):\n \"\"\"绘制混淆矩阵,保存并返回\n\n Args:\n cm: 计算出的混淆矩阵的值\n labels_name: 标签名\n model_name: 保存的图片名\n title: 生成的混淆矩阵的标题\n normalize: True:显示百分比, False:显示个数\n result_path: 保存路径\n\n Returns: 图窗\n\n \"\"\"\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n print(\"Normalized confusion matrix\")\n else:\n print('Confusion matrix, without normalization')\n print(cm)\n fig = plt.figure(figsize=(4, 4), dpi=120)\n # 画图,如果希望改变颜色风格,可以改变此部分的cmap=plt.get_cmap('Blues')处\n plt.imshow(cm, interpolation='nearest', cmap=plt.get_cmap('Blues'))\n plt.colorbar() # 绘制图例\n # 图像标题\n plt.title(title)\n # 绘制坐标\n num_local = np.array(range(len(labels_name)))\n axis_labels = labels_name\n plt.xticks(num_local, axis_labels, rotation=45) # 将标签印在x轴坐标上, 并倾斜45度\n plt.yticks(num_local, axis_labels) # 将标签印在y轴坐标上\n # x,y轴长度一致(问题1解决办法)\n plt.axis(\"equal\")\n # x轴处理一下,如果x轴或者y轴两边有��白的话(问题2解决办法)\n ax = plt.gca() # 获得当前axis\n left, right = plt.xlim() # 获得x轴最大最小值\n ax.spines['left'].set_position(('data', left))\n ax.spines['right'].set_position(('data', right))\n for edge_i in ['top', 'bottom', 'right', 'left']:\n ax.spines[edge_i].set_edgecolor(\"white\")\n thresh = cm.max() / 2.\n # 将百分比打印在相应的格子内,大于thresh的用白字,小于的用黑字\n for i in range(np.shape(cm)[0]):\n for j in range(np.shape(cm)[1]):\n if normalize:\n plt.text(j, i, format(int(cm[i][j] * 100 + 0.5), 'd') + '%',\n ha=\"center\", va=\"center\",\n color=\"white\" if cm[i][j] > thresh else \"black\") # 如果要更改颜色风格,需要同时更改此行\n else:\n plt.text(j, i, int(cm[i][j]),\n ha=\"center\", va=\"center\",\n color=\"white\" if cm[i][j] > thresh else \"black\")\n plt.tight_layout()\n # plt.subplots_adjust(left=0.01,bottom=0.1)\n plt.ylabel('真实标签', fontproperties=font_small)\n plt.xlabel('预测标签', fontproperties=font_small)\n plt.savefig(result_path + \"images/\" + model_name + \"_confusion_matrix.jpg\", dpi=dpi)\n # 显示\n # plt.show()\n return fig\n\n\nclass myDataset(dataset.Dataset):\n \"\"\"\n 自定义数据集\n \"\"\"\n\n def __init__(self, x, y, train=True, appendix=None):\n super(myDataset, self).__init__()\n self.train = train # 训练和测试时对数据的处理可能不同\n self.appendix = appendix\n self.transforms = transforms.Compose([\n transforms.ToTensor(),\n # transforms.Normalize(mean=[0.5], std=[0.5])\n ])\n self.x = x\n self.y = y\n\n def __getitem__(self, index):\n data = self.x[index]\n label = self.y[index]\n if self.appendix is not None:\n return data, label, self.appendix\n else:\n return data, label\n\n def __len__(self):\n return len(self.y)\n\n\nclass myWavLoader(dataset.Dataset):\n \"\"\"\n 直接加载音频原始数据作为输入(wav2vec2, hubert)\n \"\"\"\n\n def __init__(self, files, duration=10) -> None:\n super(myWavLoader, self).__init__()\n self.files = files\n self.duration = duration\n self.processor = Wav2Vec2Processor.from_pretrained(\"facebook/wav2vec2-base\")\n\n def __getitem__(self, index):\n data, sr = torchaudio.load(self.files[index])\n label = MODMA_code(self.files[index].split('/')[-2])\n expect_length = sr * self.duration\n if data.shape[1] >= expect_length:\n data = data[:, :expect_length]\n else:\n padding = torch.zeros([1, expect_length - data.shape[1]])\n data = torch.cat([data, padding], dim=1)\n data = data.squeeze(0)\n data = self.processor(data, return_tensors=\"pt\", padding=\"longest\", sampling_rate=sr).input_values\n return data.squeeze(0).float(), label.astype(np.float32)\n\n def get_seq_len(self):\n data = self.__getitem__(0)\n return data[0].shape[-1]\n\n def __len__(self):\n return len(self.files)\n\n\nclass Metric:\n \"\"\"\n 存储模型训练和测试时的指标\n \"\"\"\n\n def __init__(self, mode=\"train\"):\n if mode == \"train\":\n self.mode = \"train\"\n self.train_acc = []\n self.train_loss = []\n self.val_acc = []\n self.val_loss = []\n self.best_val_acc = [0, 0] # [val_acc, train_acc]\n elif mode == \"test\":\n self.mode = \"test\"\n self.test_acc = 0\n self.test_loss = 0\n self.confusion_matrix = None\n self.report = None\n else:\n print(\"wrong mode !!! use default mode train\")\n self.mode = \"train\"\n self.train_acc = []\n self.train_loss = []\n self.val_acc = []\n self.val_loss = []\n self.best_val_acc = [0, 0]\n\n def item(self) -> dict:\n \"\"\"\n 返回各种指标的字典格式数据\n Returns: dict\n\n \"\"\"\n if self.mode == \"train\":\n data = {\"train_acc\": self.train_acc, \"train_loss\": self.train_loss,\n \"val_acc\": self.val_acc, \"val_loss\": self.val_loss, 'best_val_acc': self.best_val_acc}\n else:\n data = {\"test_acc\": self.test_acc, \"test_loss\": self.test_loss}\n return data\n\n\ndef get_newest_file(path, suffix='pt'):\n \"\"\"\n 获取路径下最新的文件\n \"\"\"\n all_files = os.listdir(path)\n files = []\n for file in all_files:\n if os.path.splitext(file)[1] == f'.{suffix}': # 目录下包含.json的文件\n files.append(file)\n files.sort(key=lambda x: int(os.path.getmtime((path + \"\\\\\" + x))))\n file_new = os.path.join(path, files[-1])\n return file_new\n\n\ndef plot(metric: dict, model_name: str, result_path: str = \"results/\"):\n \"\"\"\n 绘制训练集,验证集准确率和损失变化曲线图\n \"\"\"\n train_acc = metric['train_acc']\n train_loss = metric['train_loss']\n val_loss = metric[\"val_loss\"]\n val_acc = metric['val_acc']\n epoch = np.arange(len(train_acc)) + 1\n\n plt.figure()\n plt.plot(epoch, train_acc)\n plt.plot(epoch, val_acc)\n plt.legend([\"train accuracy\", \"validation accuracy\"])\n plt.xlabel(\"epoch\")\n plt.ylabel(\"accuracy(%)\")\n plt.title(\"train accuracy and validation accuracy\")\n plt.savefig(result_path + \"images/\" + model_name + \"_accuracy.png\", dpi=dpi)\n # plt.show()\n\n plt.figure()\n plt.plot(epoch, train_loss)\n plt.plot(epoch, val_loss)\n plt.legend([\"train loss\", \"validation loss\"])\n plt.xlabel(\"epoch\")\n plt.ylabel(\"loss\")\n plt.title(\"train loss and validation loss\")\n plt.savefig(result_path + \"images/\" + model_name + \"_loss.png\", dpi=dpi)\n # plt.show()\n\n\ndef plot_meta(metric: dict, epoch: int, dataset_name: list, model_name: str,\n result_path: str = \"results/\"):\n \"\"\"\n 绘制训练集,验证集准确率和损失变化曲线图(元学习)\n Args:\n metric:\n epoch: 迭代次数\n model_name: 模型名\n dataset_name: 数据集名\n result_path: 保存路径\n \"\"\"\n train_acc = metric['train_acc']\n train_loss = metric['train_loss']\n val_loss = metric[\"val_loss\"]\n val_acc = metric['val_acc']\n num_dataset = len(dataset_name)\n acc = np.zeros([epoch, num_dataset])\n epoch_range = np.arange(epoch) + 1\n for i in range(num_dataset):\n acc[:, i] = train_acc[i::num_dataset]\n plt.figure()\n plt.plot(epoch_range, acc)\n plt.legend(dataset_name)\n plt.xlabel(\"epoch\")\n plt.ylabel(\"accuracy(%)\")\n plt.title(\"train accuracy\")\n plt.savefig(result_path + \"images/\" + model_name + \"dataset_accuracy.png\", dpi=dpi)\n\n plt.figure()\n plt.plot(epoch_range, acc[:, -1])\n plt.plot(epoch_range, val_acc)\n plt.legend([\"train accuracy\", \"validation accuracy\"])\n plt.xlabel(\"epoch\")\n plt.ylabel(\"accuracy(%)\")\n plt.title(\"train accuracy and validation accuracy\")\n plt.savefig(result_path + \"images/\" + model_name + f\"{dataset_name[-1]}_accuracy.png\", dpi=dpi)\n # plt.show()\n\n # plt.figure()\n # plt.plot(epoch, train_loss)\n # plt.plot(epoch, val_loss)\n # plt.legend([\"train loss\", \"validation loss\"])\n # plt.xlabel(\"epoch\")\n # plt.ylabel(\"loss\")\n # plt.title(\"train loss and validation loss\")\n # plt.savefig(result_path + \"images/\" + model_name + \"_loss.png\", dpi=dpi)\n\n\ndef plot_2(path, name: str, result_path: str = \"results/\", ):\n \"\"\"同时画出准确率和损失变化曲线图\n\n Args:\n path: metric的路径\n name: 保存图片的名称\n result_path: 保存图片的路径\n\n Returns:\n \"\"\"\n metric = np.load(path, allow_pickle=True).item()\n train_acc = metric['train_acc']\n train_loss = metric['train_loss']\n val_loss = metric[\"val_loss\"]\n val_acc = metric['val_acc']\n epoch = np.arange(len(train_acc)) + 1\n plt.figure(figsize=(14, 6))\n plt.subplot(1, 2, 1)\n plt.plot(epoch, train_acc)\n plt.plot(epoch, val_acc)\n plt.legend([\"训练集准确率\", \"验证集准确率\"])\n plt.xlabel(\"迭代轮次\")\n plt.ylabel(\"准确率(%)\")\n plt.title(\"训练集与验证集准确率变化曲线图\")\n plt.subplot(1, 2, 2)\n plt.plot(epoch, train_loss)\n plt.plot(epoch, val_loss)\n plt.legend([\"训练集损失\", \"验证集损失\"])\n plt.xlabel(\"迭代轮次\")\n plt.ylabel(\"损失\")\n plt.title(\"训练集与验证集损失变化曲线图\")\n plt.savefig(result_path + \"images/\" + name + \"acc_and_loss.svg\", dpi=dpi)\n\n\nclass LayerNorm1d(nn.Module):\n \"\"\"层归一化\n 相当于 \n nn.Sequential(\n Rearrange(\"N C L -> N L C\"),\n nn.LayerNorm(39, eps=1e-6),\n Rearrange(\"N L C -> N C L\")\n )\n 输入格式 [N C L]\n \"\"\"\n\n def __init__(self, num_channels: int, eps: float = 1e-6) -> None:\n super().__init__()\n self.weight = nn.Parameter(torch.ones(num_channels))\n self.bias = nn.Parameter(torch.zeros(num_channels))\n self.eps = eps\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n u = x.mean(1, keepdim=True)\n s = (x - u).pow(2).mean(1, keepdim=True)\n x = (x - u) / torch.sqrt(s + self.eps)\n x = self.weight[:, None] * x + self.bias[:, None]\n return x\n\n\nclass logger:\n \"\"\"\n 日志记录(仅作为参考,更多的时候看Tensorboard中的记录)\n \"\"\"\n\n def __init__(self, model_name: str, addition: str, filename: str = \"log.txt\"):\n self.model_name = model_name\n self.addition = addition\n self.time = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n self.filename = filename\n self.is_start = False\n\n def start(self):\n if not self.is_start:\n with open(self.filename, 'a') as f:\n f.write(\"\\n========================\\t\" + self.time + \"\\t========================\\n\")\n f.write(f\"model name: \\t{self.model_name}\\n\")\n f.write(f\"addition: \\t{self.addition}\\n\")\n self.is_start = True\n\n def train(self, train_metric: Metric):\n with open(self.filename, 'a') as f:\n f.write(\"\\n========================\\t\" + \"train begin\" + \"\\t========================\\n\")\n f.write(\"train(final): \\t\\t\" + \"train loss: {:.4f}\\t train accuracy: {:.3f}\\t validation loss: {:.4f}\\t \"\n \"validation accuracy: {:.3f} \\n\".format(train_metric.train_loss[-1],\n train_metric.train_acc[-1],\n train_metric.val_loss[-1],\n train_metric.val_acc[-1]))\n f.write(\"train(max_min): \\t\" + \"train loss: {:.4f}\\t train accuracy: {:.3f}\\t validation loss: {:.4f}\\t \"\n \"validation accuracy: {:.3f} \\n\".format(min(train_metric.train_loss),\n max(train_metric.train_acc),\n min(train_metric.val_loss),\n max(train_metric.val_acc)))\n f.write(\"best val accuracy: {:3f} \\t corresponding train accuracy: {:3f}\\n\"\n .format(train_metric.best_val_acc[0], train_metric.best_val_acc[1]))\n f.write(\"========================\\t\" + \"train end\" + \"\\t========================\\n\")\n\n def test(self, test_metric: Metric):\n with open(self.filename, 'a') as f:\n f.write(\"\\n========================\\t\" + \"test begin\" + \"\\t========================\\n\")\n f.write(\"test: \\t\\t\\t\" + \"test loss: \\t{:.4f} \\t test accuracy:\\t {:.3f} \\n\".format(test_metric.test_loss,\n test_metric.test_acc))\n f.write(\"confusion matrix: \\n\")\n for i in range(len(test_metric.confusion_matrix)):\n f.write(str(test_metric.confusion_matrix[i]) + '\\n')\n f.write(\"\\n\")\n f.write(\"classification report: \\n\")\n f.write(test_metric.report)\n f.write(\"\\n\")\n f.write(\"========================\\t\" + \"test end\" + \"\\t========================\\n\")\n\n\ndef l2_regularization(model, alpha: float):\n \"\"\"\n L2正则化(加损失)\n\n Args:\n model: 模型\n alpha: L2正则化参数\n\n Returns: L2损失\n\n \"\"\"\n l2_loss = []\n for module in model.modules():\n if type(module) is torch.nn.Conv2d or type(module) is torch.nn.Linear:\n l2_loss.append((module.weight ** 2).sum() / 2.0)\n return alpha * sum(l2_loss)\n\n\ndef onehot2int(onehot):\n \"\"\"\n onehot -> int(应该没用)\n \"\"\"\n label = torch.max(onehot.data, 1)[1]\n return label\n\n\ndef smooth_labels(labels, factor=0.1):\n \"\"\"\n 标签平滑(在loss函数设置label_smoothing=0.1能起到一样的效果)\n\n Args:\n labels: 原始标签\n factor: 平滑超参数\n\n Returns: 平滑后的标签\n\n \"\"\"\n labels *= (1 - factor)\n labels += (factor / labels.shape[1])\n return labels\n\n\ndef noam(d_model, step, warmup):\n \"\"\"\n noam scheduler\n \"\"\"\n fact = min(step ** (-0.5), step * warmup ** (-1.5))\n return fact * (d_model ** (-0.5))\n\n\nclass NoamScheduler:\n def __init__(self, optimizer, d_model, initial_lr, warmup):\n self.optimizer = optimizer\n self.d_model = d_model\n self.initial_lr = initial_lr\n self.warmup = warmup\n self.lr = 0\n\n def step(self, steps):\n self.lr = self.initial_lr * noam(d_model=self.d_model, step=steps + 1, warmup=self.warmup)\n for param_groups in self.optimizer.param_groups:\n param_groups['lr'] = self.lr\n\n def get_lr(self):\n return self.lr\n\n\ndef plot_noam(args: Args):\n \"\"\"\n 绘制noam scheduler的学习率变化曲线\n \"\"\"\n lr = []\n for i in range(1000):\n lr.append(args.initial_lr * noam(d_model=args.d_model, step=i + 1, warmup=args.warmup))\n plt.plot(lr)\n plt.show()\n\n\ndef cleanup():\n \"\"\"\n 获取清除文件的命令行方法\n \"\"\"\n print(\"如果想要删除一个目录下所有的png格��图片,可以切换到该目录下在控制台输入: del /a /f /s /q \\\"*.png\\\"\")\n\n\nclass WarmupScheduler:\n \"\"\"\n 用在Transformer的训练中,主要用在CNN_ML_Transformer中\n \"\"\"\n\n def __init__(self, optimizer, n_step, warmup, d_model, initial_lr):\n self.optimizer = optimizer\n self.n_step = n_step\n self.warmup = warmup\n self.d_model = d_model\n self.initial_lr = initial_lr\n\n def step(self):\n fact = min(self.n_step ** (-0.5), self.n_step * self.warmup ** (-1.5)) * (self.d_model ** (-0.5))\n self.optimizer.param_groups[0]['lr'] = self.initial_lr * fact\n\n\ndef cal_seq_len(seq_len: int, scale: int):\n \"\"\"\n 计算经过池化后的序列长度(向下取整)\n\n Args:\n seq_len: 原始序列长\n scale: 池化大小\n\n Returns: 经过池化操作的序列长度\n\n \"\"\"\n return math.floor(seq_len / scale)\n\n\ndef check_dir():\n \"\"\"\n 创建models, results/images/, results/data 文件夹\n \"\"\"\n if not os.path.exists(\"models\"):\n os.makedirs(\"models\")\n if not os.path.exists(\"results\"):\n os.makedirs(\"results\")\n if not os.path.exists(\"results/images\"):\n os.makedirs(\"results/images\")\n if not os.path.exists(\"results/data\"):\n os.makedirs(\"results/data\")\n\n\ndef print_model(model):\n \"\"\"\n 打印模型参数,梯度\n \"\"\"\n for name, params in model.named_parameters():\n print('-->name:', name)\n print('-->para:', params)\n print('-->grad_requires:', params.requires_grad)\n print('-->grad_value:', params.grad)\n print(\"===\")\n\n\ndef log_model(model, val_acc):\n \"\"\"\n 记录模型参数,梯度\n \"\"\"\n with open(\"model.txt\", 'a') as f:\n f.write(str(val_acc) + \"\\n\")\n for name, params in model.named_parameters():\n f.write(f'-->name: {name} \\n')\n # print('-->para:', params)\n # f.write(f'-->grad_requires:{params.requires_grad}')\n f.write(f'-->grad_value:{params.grad} \\n')\n f.write(\"===\\n\")\n\n\ndef mask_input(x, p):\n \"\"\"\n 对输入进行遮盖\n\n Args:\n x: 输入特征\n p: 遮盖概率\n \"\"\"\n batch_size, _, seq_len = x.shape\n mask = torch.rand(batch_size, 1, seq_len).to(x.device)\n mask = mask.ge(p)\n mask_x = x * mask\n return mask_x\n\n\nif __name__ == \"__main__\":\n # plot_2(r\"D:\\graduate_code\\SER_depression\\stores\\results\\data\\MultiTIM_train_ADD_DIFF_MODMA_order3_drop1_mfcc_epoch100_l2re2_lr0004_pretrainFalse_clusterFalse_train_metric.npy\", \"MultiTIM_MODMA\")\n # args = Args()\n # plot_noam(args=args)\n # data = np.load(\n # r\"D:\\graduate_code\\SER_depression\\stores\\results\\data\\MultiTIM_train_ADD_DIFF_MODMA_order3_drop1_mfcc_epoch100_l2re2_lr0004_pretrainFalse_clusterFalse_train_metric.npy\",\n # allow_pickle=True).item()\n plot_2(path=\"stores/results/data/ddg/train_ddg4_3.npy\", name=\"ddg4_3_acc_and_loss\", result_path=\"stores/results/\")\n pass\n","repo_name":"Xiang-M-J/SER_depression","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":28636,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"44462180035","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 20 13:15:55 2018\n\n@author: ahall\n\"\"\"\n\nfrom quakefeeds import QuakeFeed\nimport time\nimport math\nimport Adafruit_CharLCD as LCD\nimport aurorawatchuk\nimport RPi.GPIO as GPIO\n\n#setup pins\nGPIO.setmode(GPIO.BCM)\nGPIO.setwarnings(False)\nGPIO.setup(12,GPIO.OUT)\n\n\n\n#setup lcd\n\n# Raspberry Pi pin configuration:\nlcd_rs = 27 # Note this might need to be changed to 21 for older revision Pi's.\nlcd_en = 22\nlcd_d4 = 25\nlcd_d5 = 24\nlcd_d6 = 23\nlcd_d7 = 18\nlcd_backlight = 4\n\n\n# Define LCD column and row size for 16x2 LCD.\nlcd_columns = 16\nlcd_rows = 2\n\n#initialise the lcd\nlcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7, \n lcd_columns, lcd_rows, lcd_backlight)\n\nwhile(True):\n\n lcd.clear()\n GPIO.output(12,GPIO.LOW)\n \n #query api and retrieve data for last 24 hours\n feed = QuakeFeed(\"4.5\", \"day\")\n last_quake = feed[0]\n \n title = last_quake.get('properties').get('title')\n magnitude = last_quake.get('properties').get('mag')\n q_time = last_quake.get('properties').get('time')\n q_time=time.strftime(\"%D %H:%M\", time.gmtime(int(str(q_time)[0:10])))\n \n #look for mag 7+ earthquakes in last day\n i=0\n #marker to indicate whether 7+ quake occured today\n hi_mag_quake=False\n hi_quake=str()\n for quake in feed:\n mag = quake.get('properties').get('mag')\n \n if(mag >= 7):\n hi_mag_quake=True\n hi_quake = feed[i].get('properties').get('title')\n hq_time = feed[i].get('properties').get('time')\n hq_time = time.strftime(\"%D %H:%M\", time.gmtime(int(str(hq_time)[0:9])))\n else:\n hi_quake = None\n \n i=i+1\n \n #print results to lcd\n\n #print details of hi mag quake\n if(hi_mag_quake):\n GPIO.output(12,GPIO.HIGH)\n for i in range(len(hi_quake)+len(hq_time)):\n lcd.clear()\n lcd.message('MAG 7+ QUAKE' + '\\n')\n lcd.message((' ' + hi_quake + ' ' + hq_time)[i:i+lcd_columns])\n time.sleep(0.3)\n \n \n \n\n for i in range(len(title) + len(q_time)):\n lcd.clear()\n lcd.message('last quake' + '\\n')\n lcd.message((' ' + title+ ' ' +q_time)[i:i+lcd_columns])\n time.sleep(0.3) \n \n\n #print last quake \n lcd.message('last quake: '+q_time+title)\n for i in range(lcd_columns+len(title)+len(q_time)):\n time.sleep(0.3)\n lcd.move_left()\n \n \n #AURORA DATA\n aurorawatchuk.user_agent = 'test'\n awuk = aurorawatchuk.AuroraWatchUK(raise_=False)\n stat = awuk.status\n \n lcd.message(\"Aurora Status:\\n\"+ awuk.status.level)\n time.sleep(5)\n \n lcd.message(\"Disturbance:\\n\"+ awuk.activity.latest.value + \"nT\")\n time.sleep(5)\n \n alert_msg = 'AT THIS TIME OF THE YEAR...IN THIS PART OF THE COUNTRY'\n if(awuk.status == \"red\"):\n for i in range(lcd_columns+len(alert_msg)):\n lcd.clear()\n lcd.message(\"AURORA BOREALIS\" + \"\\n\")\n lcd.message(alert_msg)\n time.sleep(0.3)\n lcd.move_left()\n if(i%2==0):\n GPIO.output(12,GPIO.HIGH)\n else:\n GPIO.output(12,GPIO.LOW)\n\n \n \n\n \n \n \n \n","repo_name":"lambdaBoost/USGS-earthquake-monitor","sub_path":"live-quake.py","file_name":"live-quake.py","file_ext":"py","file_size_in_byte":3357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13261571978","text":"from enum import Enum\n\nimport zmq\n\nfrom models.InternalMessage import InternalMessage\nfrom models.Room import Room\nfrom models.User import User\nfrom utils import Serializer\nfrom AWorker import AWorker\nimport Constants\nimport Proxy\n\n\nclass Text():\n WELCOME = \"<= Welcome to the XYZ chat server\\r\\n\" \\\n \"<= Login Name ?\\r\\n\"\n LOGIN_ALREADY_USED = \"<= Sorry, name taken.\\r\\n\"\n WELCOME_LOGGED = \"<= Welcome {0}!\\r\\n\"\n ENTERING_ROOM = \"<= entering room: {0}\\r\\n\"\n JOINED = \"<= * new user joined {0}: {1}!\\r\\n\"\n LEAVING_ROOM = \"<= * user has left {0}: {1}\\r\\n\"\n Y_LEAVING_ROOM = \"<= * user has left {0}: {1} (** this is you)\\r\\n\"\n END_LIST = \"<= end of list.\\r\\n\"\n USER = \"<= * {0}\\r\\n\"\n Y_USER = \"<= * {0} (** this is you)\\r\\n\"\n QUIT = \"<= BYE\\r\\n\"\n ROOM_NOT_FOUND = \"<= The room: {0} doesn't exist\\r\\n\"\n ROOM_NOT_JOINED = \"<= You haven't joined any room.\\r\\n\"\n\n\nclass Commands(Enum):\n create = 1\n configure = 2\n join = 3\n leave = 4\n quit = 5\n hard_quit = 6\n\n\n##\n## The Users is a Worker handling every requests related to the users\n## it store the official list of users, modify it, broadcast it.\n##\n## The command: /leave is considered in Users' scope\n##\nclass Controller(AWorker):\n PUSHER = \"users_pusher\"\n ROOMS = \"rooms\"\n\n def __init__(self, context):\n super(Controller, self).__init__(context)\n\n self.commands = {\n Commands.create.name: Controller.create,\n Commands.configure.name: Controller.configure,\n Commands.join.name: Controller.join,\n Commands.leave.name: Controller.leave,\n Commands.quit.name: Controller.quit,\n Commands.hard_quit.name: Controller.hard_quit\n }\n\n self.users = {}\n self.rooms = []\n self.sub.setsockopt_string(zmq.SUBSCRIBE, Constants.InternalTopics.rooms.name)\n\n #########################\n # Private\n #########################\n\n def share_users(self):\n string = Serializer.dict_to_string(self.users)\n self.pub.send_multipart([Constants.InternalTopics.users.name.encode(), string.encode()])\n\n @staticmethod\n def build_entering_message(room, others, user):\n user_messages = [Text.USER.format(value.get_login()) for (key, value) in others]\n user_messages.append(Text.Y_USER.format(user.get_login()))\n\n messages = [\n Text.ENTERING_ROOM.format(room),\n ''.join(sorted(user_messages)),\n Text.END_LIST\n ]\n return ''.join(messages)\n\n @staticmethod\n def internal_create(internal_message):\n return InternalMessage(internal_message.get_identity(), Proxy.Commands.send.name, Text.WELCOME)\n\n @staticmethod\n def internal_configure(internal_message, users):\n name = internal_message.get_arguments()\n # Compare if the name is taken\n others = [key for (key, value) in users.items() if value.get_login() == name]\n succeed = len(others) == 0\n message = Text.WELCOME_LOGGED.format(name) if succeed else Text.LOGIN_ALREADY_USED\n return succeed, InternalMessage(internal_message.get_identity(), Proxy.Commands.send.name, message)\n\n @staticmethod\n def internal_join(internal_message, users, rooms):\n # Check if the room exist\n user = users[internal_message.get_identity()]\n room = internal_message.get_arguments()\n if len([item for item in rooms if item.get_name() == room]) == 0:\n err = InternalMessage(internal_message.get_identity(), Proxy.Commands.send.name, Text.ROOM_NOT_FOUND.format(room))\n return False, [err]\n # Notify the users in the room\n message = Text.JOINED.format(room, user.get_login())\n others = [(key, value) for (key, value) in users.items() if value.get_room() == room]\n messages = [InternalMessage(key, Proxy.Commands.send.name, message) for (key, value) in others]\n # Notify the user\n message = Controller.build_entering_message(room, others, user)\n messages.append(InternalMessage(internal_message.get_identity(), Proxy.Commands.send.name, message))\n return True, sorted(messages, key=lambda message: message.get_identity())\n\n @staticmethod\n def internal_leave(internal_message, users):\n user = users[internal_message.get_identity()]\n if user.get_room() == \"\":\n err = InternalMessage(internal_message.get_identity(), Proxy.Commands.send.name, Text.ROOM_NOT_JOINED)\n return False, [err]\n # Notify the users in the room\n message = Text.LEAVING_ROOM.format(user.get_room(), user.get_login())\n messages = [InternalMessage(key, Proxy.Commands.send.name, message) for (key, value) in users.items()\n if value.get_room() == user.get_room() and key != internal_message.get_identity()]\n message = Text.Y_LEAVING_ROOM.format(user.get_room(), user.get_login())\n messages.append(InternalMessage(internal_message.get_identity(), Proxy.Commands.send.name, message))\n return True, messages\n\n @staticmethod\n def internal_quit(internal_message, users):\n quit_messages = [\n InternalMessage(internal_message.get_identity(), Proxy.Commands.send.name, Text.QUIT),\n InternalMessage(internal_message.get_identity(), Proxy.Commands.close.name)\n ]\n\n succeed, messages = Controller.internal_leave(internal_message, users)\n if not succeed:\n messages = []\n messages.extend(quit_messages)\n return messages\n\n #########################\n # Commands\n #########################\n\n def create(self, internal_message):\n internal = self.internal_create(internal_message)\n self.users[internal_message.get_identity()] = User()\n self.pusher.send_json(internal.to_json())\n\n def configure(self, internal_message):\n succeed, internal = self.internal_configure(internal_message, self.users)\n if succeed:\n user = self.users[internal_message.get_identity()]\n user.set_login(internal_message.get_arguments())\n self.pusher.send_json(internal.to_json())\n\n def join(self, internal_message):\n succeed, messages = self.internal_join(internal_message, self.users, self.rooms)\n if not succeed:\n self.pusher.send_json(messages[0].to_json())\n return\n for message in messages:\n self.pusher.send_json(message.to_json())\n # Update the user\n user = self.users[internal_message.get_identity()]\n user.set_room(internal_message.get_arguments())\n\n def leave(self, internal_message):\n succeed, messages = self.internal_leave(internal_message, self.users)\n if not succeed:\n self.pusher.send_json(messages[0].to_json())\n return\n for message in messages:\n self.pusher.send_json(message.to_json())\n # Update the user\n user = self.users[internal_message.get_identity()]\n user.set_room(\"\")\n\n def quit(self, internal_message):\n # Leave the room if the user belongs to one\n messages = self.internal_quit(internal_message, self.users)\n for message in messages:\n self.pusher.send_json(message.to_json())\n # Update the user\n self.users.pop(internal_message.get_identity())\n\n def hard_quit(self, internal_message):\n # Leave the room if the user joined one\n succeed, messages = self.internal_leave(internal_message, self.users)\n if not succeed:\n messages = []\n # Notify the user from the room if the user joined one\n for message in messages:\n self.pusher.send_json(message.to_json())\n self.users.pop(internal_message.get_identity())\n\n #########################\n # AWorker\n #########################\n\n def get_pusher(self):\n return self.PUSHER\n\n def get_topics(self):\n return [self.ROOMS]\n\n def from_client(self, internal_message):\n if not internal_message.is_valid():\n return\n # Execute the command\n if internal_message.get_command() in self.commands:\n self.commands[internal_message.get_command()](self, internal_message)\n # Share the modified list of users\n self.share_users()\n\n def from_broadcast(self, topic, message):\n if topic == Constants.InternalTopics.rooms.name:\n self.rooms = Serializer.string_to_array(Room, message)\n\n#########################\n# Standalone option\n#########################\n\n\ndef main():\n context = zmq.Context()\n controller = Controller(context)\n controller.run()\n\nif __name__ == \"__main__\":\n main()","repo_name":"gsiffert/RGames","sub_path":"sources/Users.py","file_name":"Users.py","file_ext":"py","file_size_in_byte":8690,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36074092909","text":"import random, json\n\nwith open('words.json', 'r') as file:\n words = json.loads(file.read())\n\n\nclass Wordle:\n\n def __init__(self):\n self.word = words[random.randint(0,len(words))]\n\n\ndef validate(guess, word):\n validation = ''\n for i, char in enumerate(guess):\n if char == word[i]:\n validation += f'[*{char}*]'\n elif guess.count(char, i) <= word.count(char) and validation.count(f'*{char}*') < word.count(char):\n validation += f'[{char}*]'\n else:\n validation += f'[{char}]'\n return validation\n\n\ndef main():\n wordle = Wordle()\n remaining_guesses = 6\n while remaining_guesses > 0:\n guess = str(input()).lower()\n if guess.isalpha() and len(guess) == 5:\n remaining_guesses -= 1\n print(validate(guess, wordle.word))\n if guess == wordle.word:\n print(f'Success! Solved in {str(6 - remaining_guesses)} attempt(s)')\n break\n else:\n print('Word must be 5 characters')\n print(f'The word was: {wordle.word}')\n\nif __name__ == '__main__':\n main()","repo_name":"evandanderson/wordle","sub_path":"wordle.py","file_name":"wordle.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38823076464","text":"from sklearn.model_selection import train_test_split\n\n\nclass TTS:\n def __init__(self, df, test_size):\n self.df = df\n self.ts = test_size\n\n def Split(self):\n last_column = self.df.columns[-1]\n X = self.df.loc[:, self.df.columns != last_column]\n y = self.df.iloc[:, -1]\n\n # keep the probability of examples constant in the training and testing: enable the stratify:\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=self.ts, random_state=42,\n shuffle=True, stratify=y)\n\n # X_train, X_test, y_train, y_test.tolist() -> To compare the indexes.\n trainData = X_train.assign(Class=y_train.tolist())\n trainData = trainData.reset_index(drop=True)\n\n return trainData, X_test, y_test\n","repo_name":"MSc-MGomaa/MCTS-for-Rule-based-Classification-Tasks","sub_path":"Split.py","file_name":"Split.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23254462134","text":"'''\r\nCreated on 27 Nov 2017\r\n\r\n@author: RCLEGG2@BLOOMBERG.NET\r\n'''\r\n\r\nimport logging\r\n\r\nclass Action:\r\n \r\n def __init__(self, name, executor=None):\r\n \r\n logging.info(\"Initializing Action: \" + name)\r\n \r\n self.name = name\r\n self.actionExecutor = executor\r\n\r\n logging.info(\"Initialized Action: \" + name)\r\n \r\n def execute(self, dataSet):\r\n\r\n logging.info(\"Executing Action: \" + self.name + \" with dataSet: \" + dataSet.name)\r\n\r\n if not self.actionExecutor == None:\r\n logging.info(\"Calling Action executor\")\r\n self.actionExecutor.execute(dataSet)\r\n logging.info(\"Called Action executor\")\r\n \r\n\r\n \r\n ","repo_name":"rikclegg/old_py_RuleMSX","sub_path":"action.py","file_name":"action.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20547875448","text":"import pygame\nimport numpy as np\n#Colors\nWHITE = (255, 255, 255)\nBLUE = (0, 0, 255)\nRED = (255, 0, 0)\nGREEN = (0, 255, 0)\nBLACK = (0, 0, 0)\nORANGE = pygame.Color('sienna3')\n\nclass Flush():\n\tdef __init__(self, screen, player_x, player_y, player_size):\n\t\tself.size = 6\n\t\tself.color = None\n\t\tself.x = player_x\n\t\tself.y = player_y\n\t\tself.screen = screen\n\t\tself.size = player_size\n\t\tself.initial_size = player_size\n\t\tself.blob_touched = []\n\n\tdef power_hit(self, unit_id, units):\n\t\tunit = units[unit_id]\n\t\t#if distance between the 2 center is == to radius sum\n\t\tif np.sqrt((self.x-unit.x)**2+(self.y-unit.y)**2) <= (self.size+unit.size):\n\t\t\tif unit_id in self.blob_touched:\n\t\t\t\treturn\n\t\t\telse:\n\t\t\t\tself.blob_touched.append(unit_id)\n\t\t\t\tself.power_flush_contacts(unit_id, units)\n\n\tdef power_flush_contacts(self, unit_id, units):\n\t\tunit = units[unit_id]\n\t\tif self.color in [BLUE, GREEN, RED]:\n\t\t\tidx_p = self.color.index(255)\n\t\t\tnew_color = list(unit.color)\n\t\t\tif new_color[idx_p]==255:\n\t\t\t\tunit.move_x = -unit.move_x\n\t\t\t\tunit.move_y = -unit.move_y\n\t\t\telse: new_color[idx_p]=255\n\t\t\tunit.color = tuple(new_color)\n\t\telif self.color == WHITE:\n\t\t\tprint('r')\n\n\n\tdef update(self, pnjblob_units):\n\t\tself.size += 1\n\t\t#self.units = pnjblob_units\n\t\tfor pnj_id in pnjblob_units:\n\t\t\tself.power_hit(pnj_id, pnjblob_units)\n\t\tself.to_display(self.screen)\n\t\n\tdef to_display(self, screen):\n\t\tpygame.draw.circle(screen, self.color, (self.x, self.y), self.size, 2)\n\t\n\t\t'''def power_flush_contacts(player, blob_units):\n\tpower_units = player.power\n\tfor power_id, power in list(power_units.items()):#usefull when multi types power launched\n\t\tfor blob_id, blob in list(blob_units.items()):\n\t\t\tif power_hit(power, blob):\n\t\t\t\tplayer.size += blob.size/2\n\t\t\t\tblob.size /= 2\n\t\t\tif blob.size <=1:\n\t\t\t\tdel blob_units[blob_id]\n\t'''\nclass WhiteFlush(Flush):\n\tdef __init__(self, screen, player_x, player_y, player_size):\n\t\tsuper().__init__(screen, player_x, player_y, player_size)\n\t\t\"\"\"\n\t\tplayer_x = absis of player when he casted the spell\n\t\tplayer_y = ordonate of player when he caster the spell\n\t\t\"\"\"\n\t\tself.color = WHITE\n\nclass RedFlush(Flush):\n\tdef __init__(self, screen, player_x, player_y, player_size):\n\t\tsuper().__init__(screen, player_x, player_y, player_size)\n\t\t\"\"\"\n\t\tplayer_x = absis of player when he casted the spell\n\t\tplayer_y = ordonate of player when he caster the spell\n\t\t\"\"\"\n\t\tself.color = RED\n\nclass BlueFlush(Flush):\n\tdef __init__(self, screen, player_x, player_y, player_size):\n\t\tsuper().__init__(screen, player_x, player_y, player_size)\n\t\t\"\"\"\n\t\tplayer_x = absis of player when he casted the spell\n\t\tplayer_y = ordonate of player when he caster the spell\n\t\t\"\"\"\n\t\tself.color = BLUE\n\nclass GreenFlush(Flush):\n\tdef __init__(self, screen, player_x, player_y, player_size):\n\t\tsuper().__init__(screen, player_x, player_y, player_size)\n\t\t\"\"\"\n\t\tplayer_x = absis of player when he casted the spell\n\t\tplayer_y = ordonate of player when he caster the spell\n\t\t\"\"\"\n\t\tself.color = GREEN","repo_name":"polopolopopo13/blob_game","sub_path":"power_class.py","file_name":"power_class.py","file_ext":"py","file_size_in_byte":2953,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39899592940","text":"import os\nimport fileinput\nimport shutil\nimport csv\n####################################Functions####################################################################\ndef makefile (name, path, text):\n os.chdir(path)\n newfile = open(name, \"w\")\n newfile.write(text)\n newfile.close()\n\ndef is_number(s):\n try:\n float(s)\n return True\n except ValueError:\n return False\n\ndef extraction (keyword, datapath , output):\n\tos.chdir (datapath)\n\tff = open (output, \"w\")\t\n\tout = csv.writer(ff)\n\tout.writerow ([\"name\" , \"energy\"])\t\t\n\tfor filename in os.listdir (datapath):\n\t\tif filename.endswith(\".pdbqt\"):\n\t\t\tf = open (filename, \"r\")\n\t\t\tfilename2=filename[:-6]\n\t\t\tfor line in f:\n\t\t\t\tif keyword in line:\n\t\t\t\t\twords = line.split()\n\t\t\t\t\tfor word in words:\n\t\t\t\t\t\tanswer = is_number(word)\n\t\t\t\t\t\tif answer == True:\n\t\t\t\t\t\t\tif abs(float(word)) > 1:\t\t\n\t\t\t\t\t\t\t\tout.writerow ([filename2 , word])\n\n\n#######################################################################################################################\npath = \"F:/Dockrun_MR1-4nqc-A/\"\n#Results \nextraction (\"0.000 0.000\", path + \"output1/\", \"results.csv\")\n","repo_name":"shamsaraj/Virtual-Screening","sub_path":"utilities/extraction docking results from vina output.py","file_name":"extraction docking results from vina output.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19888085760","text":"from django.urls import path\nfrom django.contrib.admin.views.decorators import staff_member_required\nfrom .views import (OfferCreateView, OfferDeleteView, OfferDetailView,\n OfferListView, OfferUpdateView, SubcategoryAPIView, ItemListView, SaveCategoriesAPIView)\n\napp_name = \"offers\"\n\nurlpatterns = [\n path('', OfferListView.as_view(), name=\"offer-list\") ,\n path('/', OfferDetailView.as_view(), name=\"offer-detail\"),\n path('/update/', staff_member_required(OfferUpdateView.as_view()), name=\"offer-update\"),\n path('/delete/', staff_member_required(OfferDeleteView.as_view()), name=\"offer-delete\"),\n path('create/', staff_member_required(OfferCreateView.as_view()), name=\"offer-create\"),\n path('get_subcategories/', SubcategoryAPIView.as_view(), name='get_subcategories'),\n path('categories/', staff_member_required(ItemListView.as_view()), name='categories'),\n path('save_categories/', staff_member_required(SaveCategoriesAPIView.as_view()), name='save-categories'),\n]\n","repo_name":"41v4/supermarkets-offers","sub_path":"offers/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8126458961","text":"class Solution(object):\n def characterReplacement(self, s, k):\n \"\"\"\n :type s: str\n :type k: int\n :rtype: int\n \"\"\"\n res = 0\n max_freq = 0\n start = 0\n n = len(s)\n freq = {}\n for end in range(n):\n freq[s[end]] = freq.get(s[end], 0) + 1\n # max_freq would not decrease\n max_freq = max(max_freq, freq[s[end]])\n # not a valid substring\n if (end - start + 1) - max_freq > k:\n freq[s[start]] -= 1\n start += 1\n # the substring length would not decrease\n res = end - start + 1\n print(freq)\n return res\n\nif __name__ == \"__main__\":\n s = \"ABAA\"\n k = 0\n Solution().characterReplacement(s, k)\n","repo_name":"YingbingZhu/python_leetcode","sub_path":"sliding_windows/424. Longest Repeating Character Replacement.py","file_name":"424. Longest Repeating Character Replacement.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42534856759","text":"#! /usr/local/bin/python3\n\nfrom collections import Counter\nimport sys\n\nyear = \"2021\"\nday = \"14\"\nproblem = \"Extended Polymerization\"\nprint(f\"--- Day {day}: {problem} ---\")\nprint(f\"--- Part Two ---\")\nprint(f\"Detailed instructions can be found here: https://adventofcode.com/{year}/day/{day}#part2\")\n\nprint(f\"> **Given**: a polymer template and a list of pair insertion rules\")\nprint(f\"> **Return**: What do you get if you take the quantity of the most common element and subtract the quantity of the least common element?\")\nprint(f\"> **NOTE**: these pairs overlap: the second element of one pair is the first element of the next pair. Also, because all pairs are considered simultaneously, inserted elements are not considered to be part of a pair until the next step.\")\n\ndata = sys.stdin.readlines()\nprint(f\"{data}\")\n\n\nsteps = 40\ntemplate = \"\"\nrules = {}\n\nfor i, l in enumerate(data):\n if i == 0:\n template = l.strip()\n elif i == 1:\n continue\n else:\n (pair, ins) = l.strip().split(' -> ')\n rules[pair] = ins\n\nprint(template)\nprint(rules)\nprint(\"\")\n\npolymer = template\npoly_map = {}\n\nfor p, pep in enumerate(list(template)):\n if p + 1 < len(template):\n pep2 = polymer[p+1]\n pair = f\"{pep}{pep2}\"\n\n if pair in poly_map:\n poly_map[pair] += 1\n else:\n poly_map[pair] = 1 \n\n### DUMB\n#for s in range(0, steps + 1):\n# if s == 0:\n# print(f\"Template: {polymer}\")\n# else:\n# poly_pep = []\n# for p, pep in enumerate(list(polymer)):\n# ins = \"\"\n# if p + 1 < len(polymer):\n# ins = rules[f\"{pep}{polymer[p+1]}\"]\n# poly_pep.append(f\"{pep}{ins}\")\n# polymer = \"\".join(poly_pep)\n# print(f\"After step {s} : {len(polymer)}: {polymer}\")\n#\n#poly_count = Counter(list(polymer))\n#poly_features = poly_count.most_common()\n#most = poly_features[0][1]\n#least = poly_features[-1][1]\n#print(poly_features)\n#print(most - least)\n\n### SMART\nfor s in range(0, steps + 1):\n if s == 0:\n print(f\"--> Template: {poly_map}\")\n else:\n next_map = {}\n for pair in poly_map:\n pair_count = poly_map[pair]\n [pep, pep2] = list(pair)\n ins = rules[pair]\n \n npair = f\"{pep}{ins}\"\n npair2 = f\"{ins}{pep2}\"\n\n if npair in next_map:\n next_map[npair] += pair_count\n else:\n next_map[npair] = pair_count\n\n if npair2 in next_map:\n next_map[npair2] += pair_count\n else:\n next_map[npair2] = pair_count\n poly_map = next_map\n\n print(f\"--> After step {s} {sum(poly_map.values())}: {poly_map}\")\n\nsmart_count = {\n template[-1]: 1\n }\nfor pair in poly_map:\n pair_count = poly_map[pair]\n [pep, _] = list(pair)\n\n if pep in smart_count:\n smart_count[pep] += pair_count\n else:\n smart_count[pep] = pair_count\n\nprint(smart_count)\ns_count = sorted(smart_count.values(), reverse=True)\nmost = s_count[0]\nleast = s_count[-1]\nprint(most - least)\n\n","repo_name":"queuebit/adventofcode","sub_path":"2021/days/14/aoc_polymerization2.py","file_name":"aoc_polymerization2.py","file_ext":"py","file_size_in_byte":3096,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30614955801","text":"from django import template\nfrom djangobb_forum import settings as forum_settings\nimport hashlib\nfrom django.utils.six.moves.urllib.parse import urlencode\nimport math\nfrom datetime import datetime, timedelta\nfrom django.utils.timesince import timesince\n\n\nregister = template.Library()\n\n\n@register.simple_tag(takes_context=True)\ndef gravatar(context, email):\n if forum_settings.GRAVATAR_SUPPORT:\n if 'request' in context:\n is_secure = context['request'].is_secure()\n else:\n is_secure = False\n size = max(forum_settings.AVATAR_WIDTH, forum_settings.AVATAR_HEIGHT)\n url = 'https://secure.gravatar.com/avatar/%s?' if is_secure \\\n else 'http://www.gravatar.com/avatar/%s?'\n url = url % hashlib.md5(email.lower().encode('ascii')).hexdigest()\n url += urlencode({\n 'size': size,\n 'default': forum_settings.GRAVATAR_DEFAULT,\n })\n return url.replace('&', '&')\n else:\n return ''\n\n\n@register.simple_tag(takes_context=True)\ndef minutes_to_duration(context, minutes):\n if minutes != '':\n #seconds = math.floor((new Date() - date)/1000),\n interval = math.floor(int(minutes) / 525600)\n # console.log(\"seconds: \" + seconds + \" interval: \" + interval)\n if interval >= 1:\n return str(interval) + \" years\"\n interval = math.floor(minutes / 42800)\n if interval >= 1:\n return str(interval) + \" months\"\n interval = math.floor(minutes / 1440)\n if interval >= 1:\n return str(interval) + \" days\"\n interval = math.floor(minutes / 60)\n if interval >= 1:\n return str(interval) + \" hours\"\n return str(math.floor(minutes)) + \" minutes\"\n return ''\n\n\n@register.simple_tag(takes_context=True)\ndef age_from_char_epoch(context, value):\n if value != '':\n now = datetime.now()\n value = datetime.fromtimestamp(int(value))\n try:\n difference = now - value\n except Exception:\n return value\n\n if difference <= timedelta(minutes=1):\n return 'just now'\n return '%(time)s ago' % {'time': timesince(value)} # .split(', ')[0]}\n return ''\n","repo_name":"aldenjenkins/ThiccGaming","sub_path":"site/thicc/apps/stats/templatetags/stat_tags.py","file_name":"stat_tags.py","file_ext":"py","file_size_in_byte":2228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18100607597","text":"from django.conf.urls import url\nfrom . import views\n\napp_name = 'catalog'\n\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^books/$', views.BookListView.as_view(), name='book_list'),\n url(r'^book/(?P[0-9]+)$', views.BookDetailView.as_view(), name='book_detail'),\n\n url(r'^book/(?P[-\\w]+)/renew/$', views.renew_book, name='renew_book'),\n\n url(r'^authors/$', views.AuthorListView.as_view(), name='author_list'),\n url(r'^author/(?P\\d+)$', views.AuthorDetailView.as_view(), name='author_detail'),\n url(r'^authors/add/$', views.AuthorCreate.as_view(), name='add_author'),\n url(r'^authors/update/(?P\\d+)/$', views.AuthorUpdate.as_view(), name='update_author'),\n url(r'^author/delete/(?P\\d+)$', views.AuthorDelete.as_view(), name='delete_author'),\n url(r'^mybooks/$', views.BorrowedBookList.as_view(), name='my_borrowed_book_list'),\n url(r'^borrowed/$', views.AllBorrowedBookList.as_view(), name='all_borrowed_book_list'),\n url(r'^about/$', views.AboutView.as_view(), name='about'),\n url(r'^register/$', views.RegisterationView.as_view(), name='registeration'),\n # url(r'^contact/$', views.ContactView.as_view(), name='contact'),\n # url(r'^authors/$', views.author_listing, name='author_list'),\n # url(r'^author/(?P\\d+)$', views.AuthorDetailView.as_view(), name='author_detail'),\n]","repo_name":"eyobofficial/library","sub_path":"catalog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20471509184","text":"\"\"\"\n网页分页功能,封装了一个类,如果要使用需要传三个参数,current_page, total_count, url_prefix\n\"\"\"\n\n\n# 封装分页类\nclass MyPage(object):\n\n def __init__(self, current_page, total_count, url_prefix, per_page=10, max_show=7):\n \"\"\"\n 初始化一个我自己定义的分页实例\n :param current_page: 当前页码\n :param total_count: 总的数据量\n :param url_prefix: 分页中a标签的url前缀\n :param per_page: 每一个显示多少条数据\n :param max_show: 页面上最多显示多少个页码\n \"\"\"\n self.total_count = total_count\n self.per_page = per_page\n self.max_show = max_show\n self.url_prefix = url_prefix\n\n # 最多显示页码数的一半\n half_show = max_show // 2\n # 因为URL取到的参数是字符串格式,需要转换成int类型\n try:\n current_page = int(current_page)\n except Exception as e:\n # 如果输入的页码不是正经页码,默认展示第一页\n current_page = 1\n # 求总共需要多少页显示\n total_page, more = divmod(total_count, per_page)\n if more:\n total_page += 1\n # 如果输入的当前页码数大于总数据的页码数,默认显示最后一页\n if current_page > total_page:\n current_page = total_page\n self.current_page = current_page\n\n # 计算一下显示页码的起点和终点\n show_page_start = current_page - half_show\n show_page_end = current_page + half_show\n # 特殊情况特殊处理\n # 1. 当前页码 - half_show <= 0\n if current_page - half_show <= 0:\n show_page_start = 1\n show_page_end = max_show\n # 2. 当前页码数 + hale_show >= total_page\n if current_page + half_show >= total_page:\n show_page_end = total_page\n show_page_start = total_page - max_show + 1\n # 3. 总共需要的页码数 < max_show\n if total_page < max_show:\n show_page_start = 1\n show_page_end = total_page\n\n self.show_page_start = show_page_start\n self.show_page_end = show_page_end\n self.total_page = total_page\n\n # 数据切片的起点\n @property\n def start(self):\n return (self.current_page - 1) * self.per_page\n\n # 数据切片的终点\n @property\n def end(self):\n return self.current_page * self.per_page\n # 序号也跟着变\n def num(self):\n return (self.current_page-1)*self.per_page\n\n # 分页的html代码\n def page_html(self):\n tmp = []\n page_html_start = ''\n tmp.append(page_html_start)\n # 添加一个首页\n tmp.append('
  • 首页
  • '.format(self.url_prefix))\n # 添加一个上一页\n # 当当前页是第一页的时候不能再点击上一页\n if self.current_page - 1 <= 0:\n tmp.append(\n '
  • «
  • ')\n else:\n tmp.append(\n '
  • «
  • '.format(\n self.url_prefix, self.current_page - 1))\n # for循环添加要展示的页码\n for i in range(self.show_page_start, self.show_page_end + 1):\n # 如果for循环的页码等于当前页码,给li标签加一个active的样式\n if self.current_page == i:\n tmp.append('
  • {0}
  • '.format(i, self.url_prefix))\n else:\n tmp.append('
  • {0}
  • '.format(i, self.url_prefix))\n # 添加一个下一页\n # 当前 当前页已经是最后一页,应该不让下一页按钮能点击\n if self.current_page + 1 > self.total_page:\n tmp.append(\n '
  • »
  • ')\n else:\n tmp.append(\n '
  • »
  • '.format(\n self.url_prefix, self.current_page + 1))\n # 添加一个尾页\n tmp.append('
  • 尾页
  • '.format(self.url_prefix, self.total_page))\n tmp.append(page_html_end)\n\n page_html = \"\".join(tmp)\n return page_html","repo_name":"huningfei/asset","sub_path":"asset/mypage.py","file_name":"mypage.py","file_ext":"py","file_size_in_byte":4715,"program_lang":"python","lang":"zh","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"10354612860","text":"import os\nimport nltk\n\nsno = nltk.wordnet.WordNetLemmatizer()\n\n#allFileNum = 0\ndef printPath(path):\n\t#global allFileNum\n\tfilesList = os.listdir(path)\n\t\n\toutputPath = path + '\\\\keywords_2017.csv'\n\toutputFile = open(outputPath,'w',encoding = \"utf-8\")\n\t\n\t#dataBase = open(path2,'r',encoding = \"utf-8\")\n\t\n\tfor fileName in filesList:\n\t\tkeywordList = []\n\t\tfilePath = path + '\\\\' + fileName\n\t\t#print(filePath)\n\t\tid = fileName[:6]\n\t\t\n\t\t#get keywords list\n\t\tf1 = open(filePath,'r',encoding = \"utf-8\")\n\t\ttext = f1.readlines()\n\t\tfor line in text:\n\t\t\tline = line[:-1]\n\t\t\tline2 = line.strip('_')\n\t\t\tkeywordList.append(line2)\n\t\tf1.close()\n\t\t\n\t\t#add location and disease to keywords list\n\t\tpass\n\t\t\n\t\t#filter keywords\n\t\tkeywordListStemmered = []\n\t\tcount = 0;\n\t\tkeywordListNew = []\n\t\tkeywordListStemmeredNew = []\n\t\tfor word in keywordList:\n\t\t\tkeywordListStemmered.append(sno.lemmatize(word))\n\t\t\tcount = count + 1\n\t\tfor i in range(0,count):\n\t\t\tif keywordListStemmered[i] not in keywordListStemmeredNew:\n\t\t\t\tkeywordListStemmeredNew.append(keywordListStemmered[i])\n\t\t\t\tkeywordListNew.append(keywordList[i])\n\t\tprint(id,keywordListNew, file = outputFile)\n\t#print(files)\n\toutputFile.close()\npath = 'report\\\\reports\\\\temp\\\\2017_keywords'\npath2 = 'report\\\\reports\\\\ProdMED_2017'\nprintPath(path)","repo_name":"ykevingrox/ProMedProject","sub_path":"keywordsToFormat.py","file_name":"keywordsToFormat.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"18576958240","text":"cipher = [20, 8, 5, 14, 21, 13, 2, 5, 18, 19, 13, 1, 19, 15, 14]\n\n\nfor i in range(len(cipher)):\n cipher[i] += 64\n\nprint(cipher[0])\n\na = list(map(lambda x: chr(x), cipher))\nprint(a)","repo_name":"SauDoge/picoCTF_picoGym_writeups","sub_path":"Cryptography/TheNumber/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":183,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35530885069","text":"import FWCore.ParameterSet.Config as cms\n\nprocess = cms.Process(\"qgMiniTupleProducer\")\n\n# Settings for local tests\nprocess.load(\"FWCore.MessageService.MessageLogger_cfi\")\nprocess.MessageLogger.cerr.FwkReport.reportEvery = 100\nprocess.maxEvents = cms.untracked.PSet(input = cms.untracked.int32(100))\nprocess.source = cms.Source(\"PoolSource\", \n fileNames = cms.untracked.vstring('file:AOD.root')\n)\n\n# Standard configurations\nprocess.load('Configuration.StandardSequences.Services_cff')\nprocess.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff')\nprocess.load(\"Configuration.StandardSequences.MagneticField_cff\")\n#process.load(\"Geometry.TrackerGeometryBuilder.trackerGeometryDB_cfi\") \nprocess.load(\"Configuration.Geometry.GeometryRecoDB_cff\") \nprocess.GlobalTag.globaltag = 'MCRUN2_74_V9A::All'\n\n# Use TFileService to put trees from different analyzers in one file\nprocess.TFileService = cms.Service(\"TFileService\", \n fileName = cms.string(\"qgMiniTuple.root\"),\n closeFileFast = cms.untracked.bool(True)\n)\n\n\n# Sequence for making all jet collections\n# To do: add puppi jets when CMSSW recipe is available\nprocess.load('RecoJets.Configuration.RecoPFJets_cff')\nprocess.load('RecoJets.Configuration.RecoGenJets_cff')\nprocess.load('RecoJets.Configuration.GenJetParticles_cff')\nprocess.myRecoPFJets = cms.Sequence(process.fixedGridRhoFastjetAll + process.pfNoPileUpJMESequence + process.genParticlesForJets + \n process.ak4GenJets + process.ak4PFJets + process.ak4PFJetsCHS\n)\n\n# Jet energy corrections and b-tagging\nprocess.load('JetMETCorrections.Configuration.DefaultJEC_cff')\nprocess.load('QGDev.qgMiniTuple.RecoBTagAK4_cff')\nprocess.load('QGDev.qgMiniTuple.RecoBTagAK4CHS_cff')\n\n# Use clones of the QGTagger process for the different jet collections available [CMSSW_7_4_X and higher]\n# process.load('RecoJets.JetProducers.QGTagger_cfi')\n# process.QGTaggerAK4 \t\t= process.QGTagger.clone(srcJets = 'ak4PFJets',\t\tjetsLabel = 'QGL_AK4PF')\n# process.QGTaggerAK4chs \t= process.QGTagger.clone(srcJets = 'ak4PFJetsCHS',\tjetsLabel = 'QGL_AK4PFchs')\n\n# Init qgMiniTuple analyzer for AK4, make clones for the other ones\nprocess.qgMiniTupleAK4 = cms.EDAnalyzer(\"qgMiniTuple\",\n rhoInputTag\t\t\t= cms.InputTag('fixedGridRhoFastjetAll'),\n vertexInputTag\t\t= cms.InputTag('offlinePrimaryVerticesWithBS'),\n jetsInputTag\t\t= cms.InputTag('ak4PFJets'),\n pfCandidatesInputTag\t= cms.InputTag('particleFlow'),\n genJetsInputTag\t\t= cms.InputTag('ak4GenJets'),\n jec\t\t\t\t= cms.string('ak4PFL1FastL2L3'),\n genParticlesInputTag\t= cms.InputTag('genParticles'),\n csvInputTag\t\t\t= cms.InputTag('ak4CombinedInclusiveSecondaryVertexV2BJetTags'),\n# qgVariablesInputTag\t\t= cms.InputTag('QGTaggerAK4'),\n minJetPt\t\t\t= cms.untracked.double(20.),\n deltaRcut\t\t\t= cms.untracked.double(0.3),\n)\nprocess.qgMiniTupleAK4chs \t= process.qgMiniTupleAK4.clone(jetsInputTag = 'ak4PFJetsCHS', jec = 'ak4PFCHSL1FastL2L3', csvInputTag = 'ak4CHSCombinedInclusiveSecondaryVertexV2BJetTags')#, qgVariablesInputTag = 'QGTaggerAK4chs')\n\n# The path: jet sequence + b-tagging + (QGTagger) + qgMiniTuple for every jet collection\nprocess.p = cms.Path(process.myRecoPFJets * \n process.ak4BTagging * process.ak4CHSBTagging *\n process.qgMiniTupleAK4 * process.qgMiniTupleAK4chs\n)\n","repo_name":"cms-jet/QGDev","sub_path":"qgMiniTuple/test/qgMiniTuple_cfg.py","file_name":"qgMiniTuple_cfg.py","file_ext":"py","file_size_in_byte":3340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18401823182","text":"class Solution(object):\n def nthUglyNumber(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n\n if n <= 0:\n return -1\n\n res = [1]\n u2 = u3 = u5 = 0\n for i in range(n - 1):\n res.append(min(res[u2] * 2, res[u3] * 3, res[u5] * 5))\n if res[u2] * 2 == res[-1]:\n u2 += 1\n if res[u3] * 3 == res[-1]:\n u3 += 1\n if res[u5] * 5 == res[-1]:\n u5 += 1\n\n return res[-1]\n\n\nif __name__ == '__main__':\n print(Solution().nthUglyNumber(1500))","repo_name":"wbq9224/Leetcode_Python","sub_path":"Leetcode/264_NthUglyNumber.py","file_name":"264_NthUglyNumber.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30183517321","text":"# Konieczne importy\nimport pandas as pd\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom sklearn import model_selection\n\n# Przygotowanie danych\ndata = pd.read_csv(\"vote.csv\")\n\nx = data.iloc[:, 0:-1].to_numpy()\ny = data.iloc[:, -1].to_numpy().reshape(-1, 1)\n\n# Podział danych na zbiory uczący i testowy\nx_train, x_test, y_train, y_test = model_selection.train_test_split(x, y, test_size=0.2)\n\n# Stworzenie modelu\nmodel = keras.Sequential(\n [\n layers.Dense(7, activation=\"sigmoid\"),\n layers.Dropout(rate=0.2),\n layers.Dense(5, activation=\"sigmoid\"),\n layers.Dropout(rate=0.2),\n layers.Dense(1, activation=\"sigmoid\"),\n ]\n)\n\n# Uczenie modelu\nbatch_size = 32\nepochs = 200\n\nmodel.compile(loss=\"binary_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"])\nmodel.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, validation_split=0.1)\n\n# Ewaluacja modelu\nscore = model.evaluate(x_test, y_test, verbose=0)\nprint(\"Test loss:\", score[0])\nprint(\"Test accuracy:\", score[1])\n","repo_name":"AniaSniadek/Machine-learning","sub_path":"lab4/lab4.py","file_name":"lab4.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40773011811","text":"# leuk voorbeeld van een socket verbinding met een Starwars animatie\n# 2017-0719 PePo nieuw\n# source = http://docs.micropython.org/en/latest/esp8266/esp8266/tutorial/network_tcp.html\n\n# pre-condition: device is connected to the web/internet\ndef starwars():\n import socket\n\n #Then get the IP address of the telnet-server\n addr_info = socket.getaddrinfo(\"towel.blinkenlights.nl\", 23)\n\n #The getaddrinfo function actually returns a list of addresses, and each address has more information than we need. We want to get just the first valid address, and then just the IP address and port of the server. To do this use:\n addr = addr_info[0][-1]\n\n #If you type addr_info and addr at the prompt you will see exactly what information they hold.\n #Using the IP address we can make a socket and connect to the server:\n s = socket.socket()\n s.connect(addr)\n\n #Now that we are connected we can download and display the data:\n # Ctrl-C to stop\n while True:\n data = s.recv(500)\n print(str(data, 'utf8'), end='')\n\n# run example\ntry:\n starwars()\nexcept:\n print('Done')\n","repo_name":"flashypepo/myMicropython-Examples","sub_path":"demos-esp32/network/starwars.py","file_name":"starwars.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"37483666218","text":"\"\\n\" #New line\n{\"format\" \"and\" \"f\"} #print concatenate variables or strings\n\"\\t\" #command to tab a text or string\n\ns = \"Es lo que dijo ella\"\nen = \"That's What she said\"\nak = \"I should write something\"\nann = \"What you wanna do\"\nryu = \"For real!!!\"\n\nprint(f\"{ak} before I go to sleep\")\nprint(\"{0} said ryuji after listen {1} from ann\".format(ryu,ann))\nprint(\"burn my dread\\ntoday\")\nprint(s,\"\\t\",en)\n\n #This space is indentation\n ","repo_name":"AngelTahraf/Python_path_byte-of-python","sub_path":"Basics.py","file_name":"Basics.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36127266145","text":"from __future__ import division, print_function, absolute_import\nfrom __future__ import print_function\nfrom utils.functional import quat2euler\nimport numpy as np\nimport torch\nimport cv2\nimport warnings\nwarnings.filterwarnings('ignore', category=RuntimeWarning)\n\n__all__ = ['calculate_diff']\n\ndef calculate_diff(output, target, mean=True):\n _, ypr_or_qua = target.shape\n if ypr_or_qua == 4:\n output = output.detach().cpu().numpy()\n target = target.detach().cpu().numpy()\n\n output_ypr = []\n target_ypr = []\n for i in range(len(output)):\n ypr1 = quat2euler(*output[i])\n ypr2 = quat2euler(*target[i])\n output_ypr.append(ypr1)\n target_ypr.append(ypr2)\n\n dif = np.abs(np.asarray(output_ypr) - np.asarray(target_ypr))\n if mean:\n dif = np.mean(dif)\n else:\n dif = torch.abs(output - target)\n if mean:\n dif = torch.mean(dif).item()\n else:\n dif = dif.detach().cpu().numpy()\n return dif\n\nif __name__=='__main__':\n output = torch.randn((32, 3))\n target = torch.randn((32, 3))\n print(calculate_diff(output, target))","repo_name":"seathiefwang/RankPose","sub_path":"src/utils/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"48"} +{"seq_id":"40805302493","text":"\"\"\" Development of Web Applications and Web Services\n\n\"\"\"\n\n__author__ = \"Dawit Nida (dawit.nida@abo.fi)\"\n__date__ = \"Date: 26.10.2014\"\n__version__ = \"Version: \"\n\nfrom django.core.management.base import NoArgsCommand\nfrom django.core import management\n\n# TR2.3 Automated test for testing concurrency when bidding\nclass Command(NoArgsCommand):\n def handle_noargs(self, **options):\n management.call_command('test', 'yaas.tests.AuctionConcurrencyTest.test_auction_concurrency')\n management.call_command('test', 'yaas.tests.BidConcurrencyTest.test_bid_concurrency')","repo_name":"dawitnida/Pythonidae","sub_path":"YAAS/management/commands/testUC10.py","file_name":"testUC10.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"38935830442","text":"#!/usr/bin/env python\n\n\"\"\"READER.PY - spectral reader\n\n\"\"\"\n\nfrom __future__ import print_function\n\n__authors__ = 'David Nidever '\n__version__ = '20210605' # yyyymmdd\n\nimport os\nimport numpy as np\nimport warnings\nimport astropy\nfrom astropy.io import fits\nfrom astropy.table import Table\nfrom scipy.ndimage.filters import median_filter\nfrom dlnpyutils import utils as dln, bindata\nimport dill as pickle\nimport functools\nfrom . import spec1d,utils\nfrom .spec1d import Spec1D\ntry:\n import __builtin__ as builtins # Python 2\nexcept ImportError:\n import builtins # Python 3\n \n# Ignore these warnings, it's a bug\nwarnings.filterwarnings(\"ignore\", message=\"numpy.dtype size changed\")\nwarnings.filterwarnings(\"ignore\", message=\"numpy.ufunc size changed\")\n\n# Get print function to be used locally, allows for easy logging\nprint = utils.getprintfunc() \n\nastropy.io.fits.Conf.use_memmap = False # load into memory\n\n# Check the data\ndef datacheck(spec=None):\n \"\"\" Check that there aren't any bad values in FLUX or ERR.\"\"\"\n if spec is None:\n return\n nanflux = np.sum(~np.isfinite(spec.flux))\n if nanflux>0:\n print('WARNING: Spectrum has '+str(nanflux)+' NaN/Inf FLUX pixels')\n nanerr = np.sum(~np.isfinite(spec.err))\n if nanerr>0:\n print('WARNING: Spectrum has '+str(nanerr)+' NaN/Inf ERR pixels')\n zeroerr = np.sum(spec.err<=0.0)\n if zeroerr>0:\n print('WARNING: Spectrum has '+str(zeroerr)+' pixels with ERR<=0')\n if np.sum(~spec.mask)==0:\n print('WARNING: Entire Spectrum is MASKED')\n \n\n# Register a new reader\ndef register(format,reader):\n '''\n This registers a new spectral reader for the Doppler reader registry.\n\n Parameters\n ----------\n format : str\n The name of the new format.\n reader : function\n The function for the new reader.\n\n Returns\n -------\n Nothing is returned. The Doppler reader registry is updated.\n\n Example\n -------\n doppler.reader.register('myformat',myformat)\n\n '''\n\n _readers[format] = reader\n\n \n \n# Load a spectrum\ndef read(filename=None,format=None):\n '''\n This reads in a SDSS-IV MWM training set spectrum and returns an\n object that is guaranteed to have certain information.\n\n Parameters\n ----------\n filename : str\n The filename of the spectrum.\n format : str, optional\n The format string, or name of the reader to use.\n\n Returns\n -------\n spec : Spec1D object\n A Spec1D object that always has FLUX, ERR, WAVE, MASK, FILENAME, SPTYPE, WAVEREGIME and INSTRUMENT.\n\n Examples\n --------\n\n Load an APOGEE apStar spectrum.\n\n .. code-block:: python\n\n spec = read(\"apStar-r8-2M00050083+6349330.fits\")\n\n '''\n if filename is None:\n print(\"Please input the filename\")\n return\n\n # Different types of spectra\n # apVisit APOGEE spectra\n # apStar APOGEE spectra\n # SDSS BOSS spectra\n # SDSS MaStar spectra\n # IRAF-style spectra\n base, ext = os.path.splitext(os.path.basename(filename))\n\n # Check that the files exists\n if os.path.exists(filename) is False:\n print(filename+\" NOT FOUND\")\n return None\n \n # Readers dictionary\n try:\n nreaders = len(_readers)\n except:\n # _readers is defined at bottom of readers.py\n raise ValueError(\"No readers defined\")\n # Format input\n if format is not None:\n # check that we have this reader\n if format.lower() not in _readers.keys():\n raise ValueError('reader '+format+' not found')\n # Use the requested reader/format\n out = _readers[format](filename)\n datacheck(out)\n if out is not None: return out\n # Check if it's spec1d\n else:\n head = fits.getheader(filename)\n if head.get('SPECTYPE')=='SPEC1D':\n out = spec1d(filename)\n datacheck(out)\n if out is not None: return out\n \n # Loop over all readers until we get a spectrum out\n for k in _readers.keys():\n try:\n out = _readers[k](filename)\n except:\n out = None\n datacheck(out) \n if out is not None: return out\n # None found\n print('No reader recognized '+filename)\n print('Current list of readers: '+', '.join(_readers.keys()))\n return\n\n\n# read spectrum written with Spec1D.write()\ndef spec1d(filename):\n \"\"\"\n Read a Doppler written spectrum.\n\n Parameters\n ----------\n filename : string\n The name of the spectrum file to load.\n\n Returns\n -------\n spec : Spec1D object\n The spectrum as a Spec1D object.\n\n Examples\n --------\n \n spec = spec1d('spec.fits')\n\n \"\"\"\n\n base, ext = os.path.splitext(os.path.basename(filename))\n\n # Get number of extensions\n hdu = fits.open(filename)\n \n # Check that this has the right format\n if hdu[0].header['SPECTYPE'] != 'SPEC1D':\n return None\n\n # HDU0: header\n wavevac = hdu[0].header['WAVEVAC']\n instrument = hdu[0].header['INSTRMNT']\n normalized = hdu[0].header['NORMLIZD']\n ndim = hdu[0].header['NDIM']\n npix = hdu[0].header['NPIX']\n norder = hdu[0].header['NORDER']\n snr = float(hdu[0].header['SNR'])\n bc = hdu[0].header.get('BC')\n # HDU1: flux\n flux = hdu[1].data\n # HDU2: flux error\n err = hdu[2].data\n # HDU3: wavelength\n wave = hdu[3].data\n # HDU4: mask\n mask = hdu[4].data\n # HDU5: LSF\n lsfsigma = hdu[5].data\n lsfxtype = hdu[5].header['XTYPE']\n lsftype = hdu[5].header['LSFTYPE']\n npars = hdu[5].header['NPARS']\n npars1 = hdu[5].header['NPARS1']\n npars2 = hdu[5].header.get('NPARS2')\n if npars>0:\n lsfpars = np.zeros(npars,float)\n for i in range(npars):\n lsfpars[i] = hdu[5].header['PAR'+str(i)]\n if npars2 is not None:\n lsfpars = lsfpars.reshape(npars1,npars2)\n else:\n lsfpars = lsfpars.reshape(npars1) \n # HDU6: continuum\n cont = hdu[6].data\n # HDU7: continuum function\n cont_func_tab = hdu[7].data\n\n # Create the Spec1D object\n spec = Spec1D(flux,wave=wave,lsfpars=lsfpars,lsftype=lsftype,lsfxtype=lsfxtype)\n spec.reader = 'spec1d'\n spec.filename = filename\n spec.err = err\n if mask is not None:\n spec.mask = mask.astype(bool)\n if cont is not None:\n spec._cont = cont\n spec.continuum_func = pickle.loads(cont_func_tab['func'][0])\n spec.instrument = instrument\n spec.wavevac = True\n if bc is not None: spec.bc = bc\n \n # Add extra attributes\n if len(hdu)>8:\n for i in np.arange(8,len(hdu)):\n val = hdu[i].data\n vector = hdu[i].header.get('vector')\n attribut = hdu[i].header.get('attribut')\n name = hdu[i].header.get('name')\n if attribut==True and vector==False: # scalar table\n tab = hdu[i].data\n for c in tab.dtype.names:\n val = tab[c][0]\n if val=='None': val=None\n setattr(spec,c,val)\n elif attribut==True and vector==True: # vector\n setattr(spec,name,val)\n hdu.close()\n \n return spec\n\n\n# Load APOGEE apVisit/asVisit spectra\ndef apvisit(filename):\n \"\"\"\n Read a SDSS APOGEE apVisit spectrum.\n\n Parameters\n ----------\n filename : string\n The name of the spectrum file to load.\n\n Returns\n -------\n spec : Spec1D object\n The spectrum as a Spec1D object.\n\n Examples\n --------\n \n spec = apvisit('spec.fits')\n\n \"\"\"\n\n base, ext = os.path.splitext(os.path.basename(filename))\n\n # Get number of extensions\n hdulist = fits.open(filename)\n nhdu = len(hdulist)\n hdulist.close()\n \n # Check that this has the right format\n validfile = False\n if (base.find(\"apVisit\") == -1) | (base.find(\"asVisit\") == -1):\n if nhdu>=10:\n gd, = np.where(np.char.array(hdulist[0].header['HISTORY']).astype(str).find('AP1DVISIT') > -1)\n if len(gd)>0: validfile=True\n if validfile is False:\n return None\n \n # APOGEE apVisit, visit-level spectrum\n\n # HISTORY AP1DVISIT: HDU0 = Header only \n # HISTORY AP1DVISIT: HDU1 - Flux (10^-17 ergs/s/cm^2/Ang) \n # HISTORY AP1DVISIT: HDU2 - Error (10^-17 ergs/s/cm^2/Ang) \n # HISTORY AP1DVISIT: HDU3 - Flag mask (bitwise OR combined) \n # HISTORY AP1DVISIT: HDU4 - Wavelength (Ang) \n # HISTORY AP1DVISIT: HDU5 - Sky (10^-17 ergs/s/cm^2/Ang) \n # HISTORY AP1DVISIT: HDU6 - Sky Error (10^-17 ergs/s/cm^2/Ang) \n # HISTORY AP1DVISIT: HDU7 - Telluric \n # HISTORY AP1DVISIT: HDU8 - Telluric Error \n # HISTORY AP1DVISIT: HDU9 - Wavelength coefficients \n # HISTORY AP1DVISIT: HDU10 - LSF coefficients\n # HISTORY AP1DVISIT: HDU11 - RV catalog\n\n # flux, err, sky, skyerr are in units of 1e-17\n flux = fits.getdata(filename,1).T * 1e-17 # [Npix,Norder]\n wave = fits.getdata(filename,4).T\n lsfcoef = fits.getdata(filename,10).T\n spec = Spec1D(flux,wave=wave,lsfpars=lsfcoef,lsftype='Gauss-Hermite',lsfxtype='Pixels')\n spec.reader = 'apvisit'\n spec.filename = filename\n spec.sptype = \"apVisit\"\n spec.waveregime = \"NIR\"\n spec.instrument = \"APOGEE\" \n spec.head = fits.getheader(filename,0)\n spec.err = fits.getdata(filename,2).T * 1e-17 # [Npix,Norder]\n #bad = (spec.err<=0) # fix bad error values\n #if np.sum(bad) > 0:\n # spec.err[bad] = 1e30\n spec.bitmask = fits.getdata(filename,3).T\n spec.sky = fits.getdata(filename,5).T * 1e-17\n spec.skyerr = fits.getdata(filename,6).T * 1e-17\n spec.telluric = fits.getdata(filename,7).T\n spec.telerr = fits.getdata(filename,8).T\n spec.wcoef = fits.getdata(filename,9).T \n # Create the bad pixel mask\n # \"bad\" pixels:\n # flag = ['BADPIX','CRPIX','SATPIX','UNFIXABLE','BADDARK','BADFLAT','BADERR','NOSKY',\n # 'LITTROW_GHOST','PERSIST_HIGH','PERSIST_MED','PERSIST_LOW','SIG_SKYLINE','SIG_TELLURIC','NOT_ENOUGH_PSF','']\n # badflag = [1,1,1,1,1,1,1,1,\n # 0,0,0,0,0,0,1,0]\n mask = (np.bitwise_and(spec.bitmask,16639)!=0) | (np.isfinite(spec.flux)==False)\n # Extra masking for bright skylines\n x = np.arange(spec.npix)\n nsky = 4\n for i in range(spec.norder):\n sky = spec.sky[:,i]\n medsky = median_filter(sky,201,mode='reflect')\n medcoef = dln.poly_fit(x,medsky/np.median(medsky),2)\n medsky2 = dln.poly(x,medcoef)*np.median(medsky)\n skymask1 = (sky>nsky*medsky2) # pixels Nsig above median sky\n mask[:,i] = np.logical_or(mask[:,i],skymask1) # OR combine\n spec.mask = mask\n # Fix NaN pixels\n for i in range(spec.norder):\n bd,nbd = dln.where( (np.isfinite(spec.flux[:,i])==False) | (spec.err[:,i] <= 0) )\n if nbd>0:\n spec.flux[bd,i] = 0.0\n spec.err[bd,i] = 1e30\n spec.mask[bd,i] = True\n if (nhdu>=11):\n spec.meta = fits.getdata(filename,11) # catalog of RV and other meta-data\n # Spectrum, error, sky, skyerr are in units of 1e-17\n #spec.snr = spec.head[\"SNR\"]\n if base.find(\"apVisit\") > -1:\n spec.observatory = 'apo'\n else:\n spec.observatory = 'lco'\n spec.wavevac = True\n return spec\n\n\n# Load APOGEE apStar/asStar spectra \ndef apstar(filename):\n \"\"\"\n Read an SDSS APOGEE apStar spectrum.\n\n Parameters\n ----------\n filename : string\n The name of the spectrum file to load.\n\n Returns\n -------\n spec : Spec1D object\n The spectrum as a Spec1D object.\n\n Examples\n --------\n \n spec = apstar('spec.fits')\n\n \"\"\"\n\n base, ext = os.path.splitext(os.path.basename(filename))\n\n # Get number of extensions\n hdulist = fits.open(filename)\n nhdu = len(hdulist)\n hdulist.close()\n \n # Check that this has the right format\n validfile = False\n if (base.find(\"apStar\") == -1) | (base.find(\"asStar\") == -1):\n if nhdu>=9:\n gd, = np.where(np.char.array(hdulist[0].header['HISTORY']).astype(str).find('APSTAR') > -1)\n if len(gd)>0: validfile=True\n if validfile is False:\n return None\n \n \n # APOGEE apStar, combined spectrum\n\n # HISTORY APSTAR: HDU0 = Header only \n # HISTORY APSTAR: All image extensions have: \n # HISTORY APSTAR: row 1: combined spectrum with individual pixel weighting \n # HISTORY APSTAR: row 2: combined spectrum with global weighting \n # HISTORY APSTAR: row 3-nvisits+2: individual resampled visit spectra \n # HISTORY APSTAR: unless nvisits=1, which only have a single row \n # HISTORY APSTAR: All spectra shifted to rest (vacuum) wavelength scale \n # HISTORY APSTAR: HDU1 - Flux (10^-17 ergs/s/cm^2/Ang) \n # HISTORY APSTAR: HDU2 - Error (10^-17 ergs/s/cm^2/Ang) \n # HISTORY APSTAR: HDU3 - Flag mask: \n # HISTORY APSTAR: row 1: bitwise OR of all visits \n # HISTORY APSTAR: row 2: bitwise AND of all visits \n # HISTORY APSTAR: row 3-nvisits+2: individual visit masks \n # HISTORY APSTAR: HDU4 - Sky (10^-17 ergs/s/cm^2/Ang) \n # HISTORY APSTAR: HDU5 - Sky Error (10^-17 ergs/s/cm^2/Ang) \n # HISTORY APSTAR: HDU6 - Telluric \n # HISTORY APSTAR: HDU7 - Telluric Error \n # HISTORY APSTAR: HDU8 - LSF coefficients \n # HISTORY APSTAR: HDU9 - RV and CCF structure\n\n # Spectrum, error, sky, skyerr are in units of 1e-17\n # these are 2D arrays with [Nvisit+2,Npix]\n # the first two are combined and the rest are the individual spectra\n\n head1 = fits.getheader(filename,1)\n w0 = np.float64(head1[\"CRVAL1\"])\n dw = np.float64(head1[\"CDELT1\"])\n nw = head1[\"NAXIS1\"]\n wave = 10**(np.arange(nw)*dw+w0)\n \n # flux, err, sky, skyerr are in units of 1e-17\n flux = fits.getdata(filename,1).T * 1e-17\n lsfcoef = fits.getdata(filename,8).T\n spec = Spec1D(flux,wave=wave,lsfpars=lsfcoef,lsftype='Gauss-Hermite',lsfxtype='Pixels')\n spec.reader = 'apstar'\n spec.filename = filename\n spec.sptype = \"apStar\"\n spec.waveregime = \"NIR\"\n spec.instrument = \"APOGEE\"\n spec.head = fits.getheader(filename,0)\n spec.err = fits.getdata(filename,2).T * 1e-17\n #bad = (spec.err<=0) # fix bad error values\n #if np.sum(bad) > 0:\n # spec.err[bad] = 1e30\n spec.bitmask = fits.getdata(filename,3)\n spec.sky = fits.getdata(filename,4).T * 1e-17\n spec.skyerr = fits.getdata(filename,5).T * 1e-17\n spec.telluric = fits.getdata(filename,6).T\n spec.telerr = fits.getdata(filename,7).T\n spec.lsf = fits.getdata(filename,8).T\n # Create the bad pixel mask\n # \"bad\" pixels:\n # flag = ['BADPIX','CRPIX','SATPIX','UNFIXABLE','BADDARK','BADFLAT','BADERR','NOSKY',\n # 'LITTROW_GHOST','PERSIST_HIGH','PERSIST_MED','PERSIST_LOW','SIG_SKYLINE','SIG_TELLURIC','NOT_ENOUGH_PSF','']\n # badflag = [1,1,1,1,1,1,1,1,\n # 0,0,0,0,0,0,1,0]\n mask = (np.bitwise_and(spec.bitmask,16639)!=0) | (np.isfinite(spec.flux)==False)\n # Extra masking for bright skylines\n x = np.arange(spec.npix)\n nsky = 4\n medsky = median_filter(spec.sky,201,mode='reflect')\n medcoef = dln.poly_fit(x,medsky/np.median(medsky),2)\n medsky2 = dln.poly(x,medcoef)*np.median(medsky)\n skymask1 = (sky>nsky*medsky2) # pixels Nsig above median sky\n mask[:,i] = np.logical_or(mask[:,i],skymask1) # OR combine\n spec.mask = mask\n # Fix NaN or bad pixels pixels\n bd,nbd = dln.where( (np.isfinite(spec.flux[:,i])==False) | (spec.err[:,i] <= 0.0) )\n if nbd>0:\n spec.flux[bd] = 0.0\n spec.err[bd] = 1e30\n spec.mask[bd] = True\n if nhdu>=9:\n spec.meta = fits.getdata(filename,9) # meta-data\n #spec.snr = spec.head[\"SNR\"]\n if base.find(\"apStar\") > -1:\n spec.observatory = 'apo'\n else:\n spec.observatory = 'lco'\n spec.wavevac = True \n return spec\n\n\n# Load SDSS BOSS spectra \ndef boss(filename):\n \"\"\"\n Read a SDSS BOSS spectrum.\n\n Parameters\n ----------\n filename : string\n The name of the spectrum file to load.\n\n Returns\n -------\n spec : Spec1D object\n The spectrum as a Spec1D object.\n\n Examples\n --------\n \n spec = boss('spec.fits')\n\n \"\"\"\n\n base, ext = os.path.splitext(os.path.basename(filename))\n\n # Get number of extensions\n hdulist = fits.open(filename)\n nhdu = len(hdulist)\n hdulist.close()\n \n # Check that this has the right format\n validfile = False\n if (base.find(\"spec-\") == -1) | (base.find(\"SDSS\") == -1):\n # nothing definitive in the header\n if nhdu>=3:\n validfile = True\n if validfile is False:\n return None\n \n # BOSS spec\n\n # HDU1 - binary table of spectral data\n # HDU2 - table with metadata including S/N\n # HDU3 - table with line measurements\n head = fits.getheader(filename,0)\n tab1 = Table.read(filename,1)\n for c in tab1.colnames: # Make column names all lowercase\n tab1[c].name=c.lower()\n cat1 = Table.read(filename,2)\n for c in cat1.colnames: # Make column names all lowercase \n cat1[c].name=c.lower()\n flux = tab1[\"flux\"].data\n wave = 10**tab1[\"loglam\"].data\n wdisp = tab1[\"wdisp\"].data\n # checking for zeros in IVAR\n ivar = tab1[\"ivar\"].data.copy()\n bad = (ivar<=0)\n if np.sum(bad) > 0:\n ivar[bad] = 1.0\n err = 1.0/np.sqrt(ivar)\n err[bad] = 1e30 #np.nan\n mask = np.zeros(flux.shape,bool)\n mask[bad] = True\n else:\n err = 1.0/np.sqrt(ivar)\n mask = np.zeros(flux.shape,bool)\n spec = Spec1D(flux,err=err,wave=wave,mask=mask,lsfsigma=wdisp,lsfxtype='Wave')\n spec.reader = 'boss'\n spec.lsf.clean() # clean up some bad LSF values\n spec.filename = filename\n spec.sptype = \"spec\"\n spec.waveregime = \"Optical\"\n spec.instrument = \"BOSS\"\n if head.get('DATE-OBS') is None:\n if head.get('INTSTART') is not None:\n head['DATE-OBS'] = head['INTSTART']\n spec.head = head\n spec.ivar = tab1[\"ivar\"].data\n spec.bitmask = tab1[\"or_mask\"].data\n spec.and_mask = tab1[\"and_mask\"].data\n spec.or_mask = tab1[\"or_mask\"].data\n spec.sky = tab1[\"sky\"].data\n if 'model' in np.char.array(tab1.colnames).lower():\n spec.model = tab1[\"model\"].data\n spec.meta = cat1\n # What are the units?\n if 'sn_median_all' in np.char.array(tab1.colnames).lower():\n spec.snr = cat1[\"sn_median_all\"].data[0]\n spec.observatory = 'apo'\n spec.wavevac = True\n return spec \n\n \n# Load SDSS MaStar spectra\ndef mastar(filename):\n \"\"\"\n Read a SDSS MaStar spectrum.\n\n Parameters\n ----------\n filename : string\n The name of the spectrum file to load.\n\n Returns\n -------\n spec : Spec1D object\n The spectrum as a Spec1D object.\n\n Examples\n --------\n \n spec = mastar('spec.fits')\n\n \"\"\"\n\n base, ext = os.path.splitext(os.path.basename(filename))\n\n # Get number of extensions\n hdulist = fits.open(filename)\n nhdu = len(hdulist)\n hdulist.close()\n \n # Check that this has the right format\n validfile = False\n if (base.find(\"mastar-\") == -1):\n # Not much definitive in the header\n if nhdu>=1:\n validfile = True\n if validfile is False:\n return None\n \n # MaStar spec\n\n # HDU1 - table with spectrum and metadata\n tab = Table.read(filename,1)\n flux = tab[\"FLUX\"].data[0]\n # checking for zeros in IVAR\n ivar = tab[\"IVAR\"].data[0].copy()\n bad = (ivar<=0)\n if np.sum(bad) > 0:\n ivar[bad] = 1.0\n err = 1.0/np.sqrt(ivar)\n err[bad] = 1e30 #np.nan\n mask = np.zeros(flux.shape,bool)\n mask[bad] = True\n else:\n err = 1.0/np.sqrt(ivar)\n mask = np.zeros(flux.shape,bool)\n spec = Spec1D(flux,wave=wave,err=err,mask=mask)\n spec.reader = 'mastar'\n spec.filename = filename\n spec.sptype = \"MaStar\"\n spec.waveregime = \"Optical\"\n spec.instrument = \"BOSS\" \n spec.ivar = tab[\"IVAR\"].data[0]\n spec.wave = tab[\"WAVE\"].data[0]\n spec.bitmask = tab[\"MASK\"].data[0]\n spec.disp = tab[\"DISP\"].data[0]\n spec.presdisp = tab[\"PREDISP\"].data[0]\n meta = {'DRPVER':tab[\"DRPVER\"].data,'MPROCVER':tab[\"MPROCVER\"].data,'MANGAID':tab[\"MANGAID\"].data,'PLATE':tab[\"PLATE\"].data,\n 'IFUDESIGN':tab[\"IFUDESIGN\"].data,'MJD':tab[\"MJD\"].data,'IFURA':tab[\"IFURA\"].data,'IFUDEC':tab[\"IFUDEC\"].data,\n 'OBJRA':tab[\"OBJRA\"].data,'OBJDEC':tab[\"OBJDEC\"].data,'PSFMAG':tab[\"PSFMAG\"].data,'MNGTARG2':tab[\"MNGTARG2\"].data,\n 'NEXP':tab[\"NEXP\"].data,'HELIOV':tab[\"HELIOV\"].data,'VERR':tab[\"VERR\"].data,'V_ERRCODE':tab[\"V_ERRCODE\"].data,\n 'MJDQUAL':tab[\"MJDQUAL\"].data,'SNR':tab[\"SNR\"].data,'PARS':tab[\"PARS\"].data,'PARERR':tab[\"PARERR\"].data}\n spec.meta = meta\n # What are the units?\n #spec.snr = tab[\"SNR\"].data\n spec.observatory = 'apo'\n spec.wavevac = True \n return spec \n\n \n# Load IMACS spectra\ndef imacs(filename):\n \"\"\"\n Read IMACS spectrum.\n\n Parameters\n ----------\n filename : string\n The name of the spectrum file to load.\n\n Returns\n -------\n spec : Spec1D object\n The spectrum as a Spec1D object.\n\n Examples\n --------\n \n spec = imacs('spec.fits')\n\n \"\"\"\n\n base, ext = os.path.splitext(os.path.basename(filename))\n \n # Generic IRAF spectrum\n # BANDID1 = 'spectrum: background median, weights variance, clean yes' / \n # BANDID2 = 'sigma - background median, weights variance, clean yes' / \n # BANDID3 = 'mask - 0:good, 1:bad' / \n data,head = fits.getdata(filename,0,header=True)\n ndim = data.ndim\n # often the 2nd dimension is unnecessary, e.g. [3, 1, 1649]\n if (ndim==3):\n if data.shape[1]==1: data = data[:,0,:]\n ndim = data.ndim\n flux = data[0,:]\n npix = len(flux) \n sigma = data[1,:]\n badmask = data[2,:]\n mask = np.zeros(npix,bool)\n mask[badmask==1] = True\n # Get wavelength\n # NWPAR = 4 / Number of Wavelength solution parameters \n # WPAR1 = 4301.64021493 / Wavelength solution parameter \n # WPAR2 = 1.70043816611 / Wavelength solution parameter \n # WPAR3 = -3.92469453122E-06 / Wavelength solution parameter \n # WPAR4 = 1.99202801624E-09 / Wavelength solution parameter \n # WSIG = 0.125175450918 / Sigma of wavelenth solution in Ang \n # WCSDIM = 3 / \n nwpar = head['nwpar']\n wpar = np.zeros(nwpar,np.float64)\n for i in range(nwpar):\n wpar[i] = head['WPAR'+str(i+1)]\n wpar = wpar[::-1] # reverse\n wave = np.poly1d(wpar)(np.arange(npix))\n\n spec = Spec1D(flux,err=sigma,wave=wave,mask=mask)\n spec.reader = 'imacs'\n spec.filename = filename\n spec.sptype = \"IMACS\"\n spec.head = head\n spec.observatory = 'LCO'\n spec.wavevac = False\n \n return spec\n\n# Load HYDRA spectra\ndef hydra(filename):\n \"\"\"\n Read HYDRA spectrum.\n\n Parameters\n ----------\n filename : string\n The name of the spectrum file to load.\n\n Returns\n -------\n spec : Spec1D object\n The spectrum as a Spec1D object.\n\n Examples\n --------\n \n spec = hydra('spec.fits')\n\n \"\"\"\n\n base, ext = os.path.splitext(os.path.basename(filename))\n \n # Generic IRAF spectrum\n # BANDID1 = 'spectrum: background median, weights variance, clean yes' / \n # BANDID2 = 'sigma - background median, weights variance, clean yes' / \n # BANDID3 = 'mask - 0:good, 1:bad' / \n data,head = fits.getdata(filename,0,header=True)\n ndim = data.ndim\n # often the 2nd dimension is unnecessary, e.g. [3, 1, 1649]\n if (ndim==3):\n if data.shape[1]==1: data = data[:,0,:]\n ndim = data.ndim\n if (ndim==2):\n flux = data[0,:]\n npix = len(flux) \n sigma = data[1,:]\n badmask = data[2,:]\n mask = np.zeros(npix,bool)\n mask[badmask==1] = True \n elif (ndim==1):\n flux = data\n npix = len(flux) \n sigma = np.sqrt(np.maximum(flux,1)) # assume gain~1\n mask = np.zeros(npix,bool)\n # Get wavelength\n crval1 = head.get('CRVAL1')\n crpix1 = head.get('CRPIX1')\n cdelt1 = head.get('CDELT1')\n if cdelt1 is None: cdelt1=head.get('CD1_1')\n if (crval1 is not None) & (crpix1 is not None) & (cdelt1 is not None):\n wave = (np.arange(npix)+1-crpix1) * np.float64(cdelt1) + np.float64(crval1)\n wlogflag = head.get('DC-FLAG')\n if (wlogflag is not None):\n if wlogflag==1: wave = 10**wave\n else:\n print('No wavelength information')\n wave = None\n\n spec = Spec1D(flux,err=sigma,wave=wave,mask=mask)\n spec.reader = 'hydra'\n spec.filename = filename\n spec.sptype = \"HYDRA\"\n spec.head = head\n spec.wavevac = False\n observat = head.get('OBSERVAT')\n if observat is not None:\n spec.observatory = observat.lower()\n\n # Deal with bad pixels\n bdpix, = np.where(np.isfinite(spec.flux)==False)\n if len(bdpix)>0:\n spec.flux[bdpix] = 0\n spec.err[bdpix] = 1e30\n spec.mask[bdpix] = True\n \n # Modify continuum parameters\n spec.continuum_func = functools.partial(spec1d.continuum,norder=4,perclevel=75.0,binsize=0.15,interp=True)\n # Mask last 100 pixels and first 75 that are below 0.8 of the continuum\n try:\n cont = spec.continuum_func(spec)\n x = np.arange(spec.npix)\n bd, = np.where((spec.flux/cont < 0.85) & ((x > (spec.npix-100)) | (x<75)))\n if len(bd)>0:\n spec.mask[bd] = True\n spec.err[bd] = 1e30\n except:\n spec.mask[0:100] = True\n spec.err[0:100] = 1e30\n spec.mask[-100:] = True\n spec.err[-100:] = 1e30 \n \n return spec\n\n \n# Load IRAF-style spectra\ndef iraf(filename):\n \"\"\"\n Read an IRAF-style spectrum.\n\n Parameters\n ----------\n filename : string\n The name of the spectrum file to load.\n\n Returns\n -------\n spec : Spec1D object\n The spectrum as a Spec1D object.\n\n Examples\n --------\n \n spec = iraf('spec.fits')\n\n \"\"\"\n\n base, ext = os.path.splitext(os.path.basename(filename))\n \n # Generic IRAF spectrum\n #BANDID1 = 'spectrum: background fit, weights variance, clean no' \n #BANDID2 = 'spectrum: background fit, weights none, clean no' \n #BANDID3 = 'background: background fit' \n #BANDID4 = 'sigma - background fit, weights variance, clean no' \n data,head = fits.getdata(filename,0,header=True)\n ndim = data.ndim\n if ndim==2: \n npix,norder = data.shape\n flux = data[:,0]\n else:\n flux = data\n norder = 1\n npix = len(flux)\n # Get wavelength\n crval1 = head.get('crval1')\n crpix1 = head.get('crpix1')\n cdelt1 = head.get('cdelt1')\n if cdelt1 is None: cdelt1=head.get('cd1_1')\n if (crval1 is not None) & (crpix1 is not None) & (cdelt1 is not None):\n wave = (np.arange(npix,int)+1-crpix1) * np.float64(cdelt1) + np.float64(crval1)\n wlogflag = head.get('DC-FLAG')\n if (wlogflag is not None):\n if wlogflag==1: wave = 10**wave\n else:\n print('No wavelength information')\n wave = None\n spec = Spec1D(flux,wave=wave)\n spec.reader = 'iraf'\n spec.filename = filename\n spec.sptype = \"IRAF\"\n spec.head = head\n # Error/sigma array\n bandid = head.get('BANDID*')\n if bandid is not None:\n for i,key in enumerate(bandid):\n val = bandid[key]\n if 'sigma' in val:\n if (i<=norder):\n spec.err = data[:,k]\n\n return spec\n\n# List of readers\n_readers = {'apvisit':apvisit, 'apstar':apstar, 'boss':boss, 'mastar':mastar, 'iraf':iraf,\n 'spec1d':spec1d, 'imacs':imacs, 'hydra':hydra}\n","repo_name":"dnidever/doppler","sub_path":"doppler/reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":28883,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"18273921673","text":"## Assignment 1 Scarlette Bello c0860234\n\nimport pandas as pd \nimport random\n\n\ntest_grades = [['Rodrigo', 67], ['James', 45], ['John', 56], ['Michael', 90], ['Mary', 89], ['Patricia', 89], ['Jennifer', 99], [ 'Linda', 87], ['David', 45], ['Elizabeth', 78], ['Barbara', 56], ['William', 45], ['Richard', 78], ['Joseph', 61], ['Thomas',37], ['Charles',100], ['Susan',67], ['Jessica', 88], ['Sarah', 53], ['Karen', 87], ['Christopher', 99], ['Daniel', 76], ['Matthew', 41], ['Anthony',99], ['Mark',76], ['Lisa',66], ['Nancy',85], ['Betty', 98], ['Margaret',45], ['Sandra',73], ['Ashley', 100], ['Donald', 76], ['Steven',65], ['Paul', 78], ['Andrew',43], ['Joshua',76], ['Kenneth',35], ['Kevin',89], ['Brian',46], ['George',87], ['Timothy', 89], ['Kimberly',76], ['Emily',65], ['Donna',76], ['Michelle',65], ['Carol',76], ['Amanda',54], ['Dorothy',80], ['Melissa',54], ['Deborah', 38]]\n\ndf = pd.DataFrame(test_grades, columns=['Name', 'Grade'])\nprint(df)\nprint()\n\n\ndef convert_column_to_list():\n grade_list = df.Grade.values.tolist()\n return grade_list \n\n\ndef choosing_random_grades(): \n i = 1\n rd_numbers_dict = {}\n while i < 11:\n i += 1\n numbers_content = random.randint(35,100)\n rd_numbers_dict[numbers_content] = 0\n return rd_numbers_dict\n\n\ndef freq_1(counter_dict, counted_list):\n for element in counted_list:\n if element in counter_dict.keys():\n counter_dict[element] += 1\n return counter_dict\n\n\n\nmy_grades_list = convert_column_to_list()\nmy_random_grades = choosing_random_grades()\nfrequency = freq_1(my_random_grades, my_grades_list)\n\n\ndf_calculation= pd.DataFrame(frequency.items(), columns=['Random grades', 'Frequency'])\ndf_calculation['Cumulative Frequency'] = df_calculation['Frequency'].cumsum()\ndf_calculation['Cumulative Percent'] = 100*(df_calculation['Cumulative Frequency'] / 50)\nprint(df_calculation)\nprint()\n\n\nminimum_grade= df.min()\nprint('Minimum grade')\nprint(minimum_grade)\nprint()\n\nfirst_quartile_grades = df.quantile([0.25])\nprint('First quartile')\nprint(first_quartile_grades)\nprint()\n\nmedian_grades = df['Grade'].median()\nprint('Median')\nprint(median_grades)\nprint()\n\nthird_quartile_grades = df.quantile([0.75])\nprint('Third quartile')\nprint(third_quartile_grades)\nprint()\n\nmaximum_grade = df.max()\nprint('Maximum')\nprint(maximum_grade)\nprint()","repo_name":"ScarletteBel/LearningDataScience-","sub_path":"Statistics/StatisticsGeneral/Assignment1ScarletteBello.py","file_name":"Assignment1ScarletteBello.py","file_ext":"py","file_size_in_byte":2341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8858655295","text":"import boolean.boolean\nfrom colomoto_jupyter.sessionfiles import new_output_file\nfrom pypint.converters.lib.boolean_utils import BoolToAN\nfrom pypint.converters.lib.export_utils import pint_protect\n\nfrom colomoto.minibn import BooleanNetwork, MultiValuedNetwork\n\ndef import_minibn(f):\n if isinstance(f, MultiValuedNetwork):\n raise Exception(\"Direct conversion from MultiValuedNetwork is not supported yet (you should use biolqm instead)\")\n\n assert isinstance(f, BooleanNetwork), \\\n \"{}: only objects of type {} are supported\".format(import_minibn, BooleanNetwork)\n\n ba = f.ba\n\n def ls_of_lit(lit):\n if isinstance(lit, boolean.boolean.NOT):\n return (lit.args[0].obj, 0)\n else:\n return (lit.obj, 1)\n\n anfile = new_output_file(ext=\"an\")\n with open(anfile, \"w\") as outf:\n def out(data):\n print(data, file=outf)\n b2a = BoolToAN(ba, ls_of_lit, out)\n\n for a in sorted(f.keys()):\n out(\"{} [0, 1]\".format(pint_protect(a)))\n\n for a, fa in sorted(f.items()):\n sa = f.vars(a)[0]\n expr_up = fa.subs({sa: ba.FALSE}).literalize().simplify()\n expr_down = (~fa).subs({sa: ba.TRUE}).literalize().simplify()\n b2a.make_transitions([(a, 0, 1)], expr_up)\n b2a.make_transitions([(a, 1, 0)], expr_down)\n\n import pypint\n return pypint.load(anfile)\n\n","repo_name":"pauleve/pypint","sub_path":"pypint/converters/minibn.py","file_name":"minibn.py","file_ext":"py","file_size_in_byte":1403,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"30126037395","text":"import numpy as np\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n#이미지에 변화 주기 -> 증폭\ntrain_datagen = ImageDataGenerator(\n rescale = 1./255,\n horizontal_flip=True,\n vertical_flip=True,\n width_shift_range=0.1,\n height_shift_range=0.1,\n rotation_range=5,\n zoom_range=1.2,\n fill_mode='nearest'\n)\n\ntest_datagen = ImageDataGenerator(\n rescale=1./255\n)\n\nxy_train = train_datagen.flow_from_directory(\n './tmp/horse-or-human',\n target_size=(300, 300),\n batch_size=5,\n class_mode='binary'\n)\n\nxy_test = test_datagen.flow_from_directory(\n './tmp/testdata',\n target_size=(300, 300),\n batch_size=5,\n class_mode='binary'\n)","repo_name":"ahnGeo/keras","sub_path":"Keras/keras32_ImageDataGenerator1.py","file_name":"keras32_ImageDataGenerator1.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"30365458219","text":"import pygame\r\nfrom pygame.locals import *\r\nimport time\r\nimport random\r\n\r\nBLACK = (0, 0, 0)\r\nWHITE = (200, 200, 200)\r\nRED = (255, 0, 0)\r\nWINDOW_HEIGHT = 700\r\nWINDOW_WIDTH = 1400\r\n\r\n\r\nclass Obstacle:\r\n def __init__(self, parent_screen):\r\n self.image = pygame.image.load(\"obstacle.png\").convert()\r\n self.parent_screen = parent_screen\r\n random.seed()\r\n self.x = random.randint(2, 26) * 50\r\n self.y = random.randint(2, 13) * 50\r\n\r\n def draw(self):\r\n self.parent_screen.blit(self.image, (self.x, self.y))\r\n pygame.display.flip()\r\n\r\n def move(self):\r\n random.seed()\r\n self.x = random.randint(2, 26) * 50\r\n self.y = random.randint(2, 13) * 50\r\n\r\n\r\nclass Car:\r\n def __init__(self, parent_screen):\r\n self.parent_screen = parent_screen\r\n self.block = pygame.image.load(\"car-cyan-resize(50).png\").convert()\r\n self.direction = 'right'\r\n self.x = 0\r\n self.y = 50\r\n\r\n def draw(self):\r\n self.parent_screen.blit(self.block, (self.x, self.y))\r\n pygame.display.flip()\r\n\r\n def move_up(self):\r\n self.direction = 'up'\r\n\r\n def move_down(self):\r\n self.direction = 'down'\r\n\r\n def move_right(self):\r\n self.direction = 'right'\r\n\r\n def walk(self):\r\n if self.direction == 'up':\r\n self.y -= 25\r\n\r\n if self.direction == 'down':\r\n self.y += 25\r\n\r\n if self.direction == 'right':\r\n self.x += 50\r\n self.draw()\r\n\r\n\r\nclass Game:\r\n def __init__(self):\r\n pygame.init()\r\n self.surface = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))\r\n self.render_background()\r\n self.car = Car(self.surface)\r\n self.car.draw()\r\n self.obstacle = Obstacle(self.surface)\r\n self.obstacle.draw()\r\n self.obstacle2 = Obstacle(self.surface)\r\n self.obstacle2.draw()\r\n self.obstacle3 = Obstacle(self.surface)\r\n self.obstacle3.draw()\r\n self.obstacle4 = Obstacle(self.surface)\r\n self.obstacle4.draw()\r\n self.obstacle5 = Obstacle(self.surface)\r\n self.obstacle5.draw()\r\n\r\n def draw_grid(self):\r\n blockSize = 50 # Set the size of the grid block\r\n for x in range(0, WINDOW_WIDTH, blockSize):\r\n for y in range(0, WINDOW_HEIGHT, blockSize):\r\n rect = pygame.Rect(x, y, blockSize, blockSize)\r\n pygame.draw.rect(self.surface, WHITE, rect, 1)\r\n\r\n def is_collision(self, x1, y1, x2, y2):\r\n if x2 <= x1 < x2 + 50:\r\n if y2 <= y1 < y2 + 50: # here y will be same\r\n return True\r\n\r\n return False\r\n\r\n def render_background(self):\r\n bg = pygame.image.load(\"background-final.png\")\r\n self.surface.blit(bg, (0, 0))\r\n\r\n def run(self):\r\n\r\n running = True\r\n\r\n while running:\r\n #self.draw_grid()\r\n for event in pygame.event.get():\r\n if event.type == KEYDOWN:\r\n if event.key == K_DOWN:\r\n self.car.move_down()\r\n if event.key == K_UP:\r\n self.car.move_up()\r\n if event.key == K_ESCAPE:\r\n running = False\r\n elif event.type == QUIT:\r\n running = False\r\n else:\r\n self.car.move_right()\r\n try:\r\n self.play()\r\n except Exception as e:\r\n self.crashed()\r\n running = False\r\n\r\n time.sleep(0.2)\r\n\r\n def play(self):\r\n self.render_background()\r\n #self.draw_grid()\r\n self.car.walk()\r\n self.obstacle.draw()\r\n self.obstacle2.draw()\r\n self.obstacle3.draw()\r\n self.obstacle4.draw()\r\n self.obstacle5.draw()\r\n if self.is_collision(self.obstacle.x, self.obstacle.y, self.car.x, self.car.y):\r\n raise \"Collision occurred\"\r\n if self.is_collision(self.obstacle2.x, self.obstacle2.y, self.car.x, self.car.y):\r\n raise \"Collision occurred\"\r\n if self.is_collision(self.obstacle3.x, self.obstacle3.y, self.car.x, self.car.y):\r\n raise \"Collision occurred\"\r\n if self.is_collision(self.obstacle4.x, self.obstacle4.y, self.car.x, self.car.y):\r\n raise \"Collision occurred\"\r\n if self.is_collision(self.obstacle5.x, self.obstacle5.y, self.car.x, self.car.y):\r\n raise \"Collision occurred\"\r\n\r\n def crashed(self):\r\n self.render_background()\r\n font = pygame.font.SysFont('arial', 60)\r\n line = font.render(\"CRASHED!\", True, RED)\r\n self.surface.blit(line, (600, 350))\r\n pygame.display.flip()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n game = Game()\r\n game.run()\r\n","repo_name":"gaurav2699/ACM-Self_Driving_car","sub_path":"self_driving_car/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4794,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23595917286","text":"\"\"\"\r\nDifficulty: Medium\r\n\r\nGiven a doubly linked list, list nodes also have a child property that can point to a separate doubly linked list. These child lists can also have one or more child doubly linked lists of their own and so on.\r\nReturn the list as a single level flattened doubly linked list.\r\n\r\n1->2->3->4->5\r\n |\r\n 6->7->8\r\n\r\nFlattened:\r\n1->2->6->7->8->3->4->5\r\n\r\nConstraints:\r\nCan a doubly linked list have mulitple child list nodes? -Yes\r\nwhat do we do with child property after flattening? -Null\r\n\"\"\"\r\n\r\nfrom random import randint\r\n\r\nclass Node:\r\n def __init__(self, value=None, child=None):\r\n self.value=value\r\n self.next=None\r\n self.prev=None\r\n self.child=child\r\n\r\nclass LinkedList:\r\n def __init__(self):\r\n self.head=None\r\n self.tail=None\r\n \r\n def __iter__(self):\r\n currNode=self.head\r\n while currNode:\r\n yield currNode\r\n currNode=currNode.next\r\n\r\n def add(self, value, child=None):\r\n if self.head is None:\r\n newNode=Node(value)\r\n self.head=newNode\r\n self.tail=newNode\r\n self.child=child\r\n else:\r\n self.tail.next=Node(value)\r\n self.tail.child=child\r\n self.tail=self.tail.next\r\n return(self.tail)\r\n\r\n def generate(self,n,min_value,max_value):\r\n self.head=None\r\n self.tail=None\r\n for _ in range(n):\r\n self.add(randint(min_value,max_value))\r\n return self\r\n \r\n #check\r\n #assign prev\r\n def flattenChildren(self):\r\n currNode=self.head\r\n while currNode.next is not None:\r\n while currNode.child is None:\r\n currNode=currNode.next\r\n nextNode=currNode.next\r\n childNode=currNode.child\r\n currNode.child=None\r\n currNode.next=childNode\r\n while childNode.next is not None:\r\n childNode=childNode.next\r\n childNode.next=nextNode\r\n\r\nLL=LinkedList()\r\nLL.add(1)\r\n\r\nLL2=LinkedList()\r\nLL2.add(8)\r\nLL2.add(9)\r\n\r\nLL1=LinkedList()\r\nLL1.add(6)\r\nLL1.add(7,LL2)\r\n\r\nLL.add(2,LL1)\r\nLL.add(3)\r\nLL.add(4)\r\nLL.add(5)\r\nprint ([x.value for x in LL])\r\nLL.flattenChildren()\r\n# LL.generate(10,1,5)\r\nprint ([x.value for x in LL])\r\n\r\n","repo_name":"Artistic-cat/python_problems_and_notes","sub_path":"Linked_List - Merge_Multi_Level_Doubly_Linked_List - Medium.py","file_name":"Linked_List - Merge_Multi_Level_Doubly_Linked_List - Medium.py","file_ext":"py","file_size_in_byte":2276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26836885691","text":"import os\n\nfrom torch import optim, utils\nfrom torch.utils.data import random_split\nfrom ._model import WaterOnOilVGG16\nfrom torchvision import transforms\nfrom src.utils._data import EmulsionDataset\nfrom src.utils._loss import EDMLoss\n\n\ndef water_on_oil():\n base_path = os.path.abspath(os.path.join(__file__, '../../../',\n 'Filtered water on oil'))\n batch_size = 2\n transform = transforms.Compose([transforms.ToTensor()])\n dataset = EmulsionDataset((base_path + \"/\" + \"óleo_em_água.xlsx\"), base_path, transform=transform)\n\n dataset_train, dataset_test = random_split(dataset, [9, 2])\n\n train_loader = utils.data.DataLoader(dataset_train, batch_size=batch_size, shuffle=False, drop_last=True)\n test_loader = utils.data.DataLoader(dataset_test, batch_size=batch_size, shuffle=False)\n\n network = WaterOnOilVGG16(41)\n\n criterion = EDMLoss()\n optimizer = optim.SGD(network.parameters(), lr=0.001, momentum=0.9)\n\n for epoch in range(10):\n\n for data in train_loader:\n img, metadata, labels = data\n optimizer.zero_grad()\n outputs = network(img)\n loss = criterion(outputs, labels)\n loss.backward()\n optimizer.step()\n","repo_name":"Luca-Machado-uff/ic-emulsoes","sub_path":"src/waterOnOil/water_on_oil.py","file_name":"water_on_oil.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41866862652","text":"#String Validators\r\n#Task :\r\n#You are given a string S.\r\n#Your task is to find out if the string S contains: alphanumeric characters, \r\n#alphabetical characters, digits, lowercase and uppercase characters.\r\n\r\ndef function1(s):\r\n for i in range(len(s)):\r\n if(s[i].isalnum()):\r\n return True;\r\n break;\r\n return False;\r\n\r\ndef function2(s):\r\n for i in range(len(s)):\r\n if(s[i].isalpha()):\r\n return True;\r\n break;\r\n return False;\r\n \r\ndef function3(s):\r\n for i in range(len(s)):\r\n if(s[i].isdigit()):\r\n return True;\r\n break;\r\n return False;\r\n\r\ndef function4(s):\r\n for i in range(len(s)):\r\n if(s[i].islower()):\r\n return True;\r\n break;\r\n return False;\r\n\r\ndef function5(s):\r\n for i in range(len(s)):\r\n if(s[i].isupper()):\r\n return True;\r\n break;\r\n return False;\r\n\r\nif __name__ == '__main__':\r\n s = input()\r\n \r\n alphanumeric=function1(s)\r\n alphabetical=function2(s)\r\n digits= function3(s)\r\n lowercase=function4(s)\r\n uppercase=function5(s)\r\n print(alphanumeric)\r\n print(alphabetical)\r\n print(digits)\r\n print(lowercase)\r\n print(uppercase)","repo_name":"Abhinandberwal/HackerRank-Python-Solutions-","sub_path":"Python (Basic)/String Validators.py","file_name":"String Validators.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21178352269","text":"\"\"\"\n Script for building encodings related to incidence matrices.\n The underlying encoding is a bipartite graph.\n\"\"\"\n\nfrom pysms.graph_builder import *\n\n\ndef getParserIncidence():\n parser = getDefaultParser()\n # Remove required argument vertices\n for action in parser._actions:\n if \"--vertices\" in action.option_strings:\n parser._remove_action(action) # remove vertex option\n break\n parser.add_argument(\"--n1\", type=int, required=True, help=\"Number of rows of the incidence matrix\")\n parser.add_argument(\"--n2\", type=int, required=True, help=\"Number of columns of the incidence matrix\")\n return parser\n\n\nclass IncidenceMatrixBuilder(GraphEncodingBuilder):\n \"\"\"Incidence matrix represented as bipartite graph\"\"\"\n\n def __init__(self, n1, n2, staticInitialPartition=False):\n super().__init__(n=n1 + n2, staticInitialPartition=staticInitialPartition)\n del self.paramsSMS[\"vertices\"]\n self.paramsSMS[\"bipartite\"] = str(n1) + \" \" + str(n2)\n\n self.n1 = n1\n self.n2 = n2\n self.V1 = range(n1)\n self.V2 = range(n1, n1 + n2)\n\n # make bipartite\n for i, j in combinations(self.V1, 2):\n self.append([-self.var_edge(i, j)])\n for i, j in combinations(self.V2, 2):\n self.append([-self.var_edge(i, j)])\n\n def var_incident(self, i, j):\n return self.var_edge(i, j + self.n1)\n\n\nif __name__ == \"__main__\":\n args = getParserIncidence().parse_args()\n b = IncidenceMatrixBuilder(args.n1, args.n2, staticInitialPartition=args.staticInitialPartition)\n b.add_constraints_by_arguments(args)\n b.solveArgs(args)\n","repo_name":"markirch/sat-modulo-symmetries","sub_path":"pysms/incidince_matrix_builder.py","file_name":"incidince_matrix_builder.py","file_ext":"py","file_size_in_byte":1655,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"1054494617","text":"from django.urls import path\nfrom blog import views\n\nurlpatterns = [# blog app 서비스로 요청을 넘겨주는 기능\n\n path('', views.index), # 메인 페이지\n path('', views.single_post_page), # 디테일\n\n path('cbv', views.PostList.as_view()),\n path('cbv/', views.PostDetail.as_view()),\n path('cbv_post', views.NewPostList.as_view()),\n\n\n]\n","repo_name":"youns1121/Django_project","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29395653976","text":"\"\"\"\nGiven a string containing only three types of characters: '(', ')' and '*', write a function to check whether this\nstring is valid. We define the validity of a string by these rules:\n\nAny left parenthesis '(' must have a corresponding right parenthesis ')'.\nAny right parenthesis ')' must have a corresponding left parenthesis '('.\nLeft parenthesis '(' must go before the corresponding right parenthesis ')'.\n'*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string.\nAn empty string is also valid.\n\"\"\"\n\n\ndef checkParentheses(parenthesesString: str):\n Rmin = Rmax = 0\n for c in parenthesesString:\n if c == '(':\n Rmax += 1\n Rmin += 1\n if c == ')':\n Rmax -= 1\n Rmin = max(Rmin - 1, 0)\n if c == '*':\n Rmax += 1\n Rmin = max(Rmin - 1, 0)\n if Rmax < 0:\n return False\n return Rmin == 0\n\n\nif __name__ == '__main__':\n\n parenthesesString = '(*)'\n print(checkParentheses(parenthesesString))\n","repo_name":"SemajDraw/leetcode_solutions","sub_path":"questions/medium/valid_parentheses_string.py","file_name":"valid_parentheses_string.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73062420306","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom spp_layer import spatial_pyramid_pool\n\nclass SPPNet(nn.Module):\n def __init__(self, opt, input_nc, ndf=64, gpu_ids=[]):\n super(SPPNet, self).__init__()\n self.gpu_ids = gpu_ids\n self.output_num = [4, 2, 1]\n \n # ZF-5\n self.features = nn.Sequentail(\n nn.Conv2d(input_nc, 96, filter_size=7, stride=2, bias=False),\n nn.ReLU(inplace=True),\n LRN(local_size=3, alpha=0.0001, beta=0.75),\n nn.Conv2d(96, 256, filter_size=5, stride=2, bias=False),\n nn.ReLU(inplace=True),\n LRN(local_size=3, alpha=0.0001, beta=0.75),\n nn.Conv2d(256, 384, filter_size=3, bias=False),\n nn.ReLU(inplace=True),\n nn.Conv2d(256, 384, filter_size=3, bias=False),\n nn.ReLU(inplace=True),\n nn.Conv2d(256, 384, filter_size=3, bias=False),\n nn.ReLU(inplace=True),\n )\n\n\n def forward(self, x):\n x = self.features(x)\n x = self.ReLU(x)\n","repo_name":"dev-sungman/cnn-model","sub_path":"models/sppnet.py","file_name":"sppnet.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"23739982926","text":"import glob\nimport math\nimport os\nimport re\nimport torch\nfrom utils.io import log\n\ndef resume_training(args, model, optimizer, scheduler):\n \"\"\" Resumes previous training or starts anew\n \"\"\"\n model_files = glob.glob(os.path.join(args['log_dir'], '*.pth'))\n\n if len(model_files) == 0:\n start_epoch = 0\n else:\n log(args.log_file, \"> Resuming previous training\\n\")\n epochs_exist = []\n for model_file in model_files:\n result = re.findall('ckpt_e(.*).pth', model_file)\n epochs_exist.append(int(result[0]))\n max_epoch = max(epochs_exist)\n max_epoch_model_file = os.path.join(args['log_dir'], 'ckpt_e%d.pth' % max_epoch)\n checkpoint = torch.load(max_epoch_model_file)\n model.load_state_dict(checkpoint['state_dict'])\n optimizer.load_state_dict(checkpoint['optimizer'])\n scheduler.load_state_dict(checkpoint['scheduler'])\n\n start_epoch = max_epoch\n\n return start_epoch\n\ndef save_model(args, model, optimizer, scheduler, epoch):\n save_dict = {\n 'args': args,\n 'state_dict': model.state_dict(),\n 'optimizer' : optimizer.state_dict(),\n 'scheduler': scheduler.state_dict()}\n\n torch.save(save_dict, os.path.join(args['log_dir'], 'ckpt_e{}.pth'.format(epoch)))\n\n# the same as skimage.metrics.peak_signal_noise_ratio\ndef batch_psnr(a, b):\n a = torch.clamp(a, 0, 1)\n b = torch.clamp(b, 0, 1)\n x = torch.mean((a - b) ** 2, dim=[-3, -2, -1])\n return 20 * torch.log(1 / torch.sqrt(x)) / math.log(10)\n","repo_name":"nagejacob/FloRNN","sub_path":"train_models/base_functions.py","file_name":"base_functions.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"48"} +{"seq_id":"15670275985","text":"import csv\nimport numpy as np\nimport random\nimport gzip\nimport sklearn.linear_model\nfrom sklearn.linear_model import Lasso, Ridge, ElasticNet\nfrom pandas import DataFrame\nfrom sklearn.metrics import mean_squared_error\nimport math\n\ntrain_filename = 'train.csv.gz'\ntest_filename = 'test.csv.gz'\npred_filename = 'example_mean.csv'\n# Load the data file.\ntrain_subset = []\nwith open('train_subset.csv', 'r') as subset_fh:\n\n # Parse it as a CSV file.\n subset_csv = csv.reader(subset_fh, delimiter=',', quotechar='\"')\n\n # Skip the header row.\n next(subset_csv, None)\n\n # Load the data.\n for row in subset_csv:\n smiles = row[0]#first row, all chemical symbols\n numbers=[float(i) for i in row[1].split(']')[0].split()[1:]]#converts to floats\n features=DataFrame.transpose(DataFrame(numbers))#saves features\n gap=DataFrame(float(row[2]), index=[0], columns=[0])#saves gap, what we want to predict\n\n train_subset.append({ 'smiles': smiles,\n 'features': features,\n 'gap': gap })\n# Load the test file.\ntest_data = []\nwith gzip.open(test_filename, 'r') as test_fh:\n\n # Parse it as a CSV file.\n test_csv = csv.reader(test_fh, delimiter=',', quotechar='\"')\n \n \n # Skip the header row.\n next(test_csv, None)\n\n # Load the data.\n for row in test_csv:\n id = row[0]\n smiles = row[1]\n numbers2 = np.array([float(x) for x in row[2:258]])\n features=DataFrame.transpose(DataFrame(numbers2))#saves features\n \n test_data.append({ 'id': id,\n 'smiles': smiles,\n 'features': features })\n\nfor i in range(10000):#ditto for test features\n if i==0:\n X=train_subset[0]['features']\n y=train_subset[0]['gap']\n else:\n X=X.append(train_subset[i]['features'], ignore_index=True)\n y=y.append(train_subset[i]['gap'], ignore_index=True)\nXtrain=X.as_matrix()\nytrain=y.as_matrix()\n\n#824230\nfor i in range(20000):#ditto for test features\n if i==0:\n X=test_data[0]['features']\n else:\n X=X.append(test_data[i]['features'], ignore_index=True)\nXtest=X.as_matrix()\n\nalpha=.01\n\nridge=Ridge(alpha=alpha)\nridpredictions=ridge.fit(Xtrain, ytrain).predict(Xtest)\nridpredictions=DataFrame(ridpredictions)#changes forms of predictions\n#ytestrid=DataFrame(y.values, index=ridpredictions.index, columns=['Correct Values'])\n#ytestrid['Predictions']=ridpredictions#dataframe with predictions and correct value\n#print ytestrid\nridge.coef_\n\npred_filename = 'predictionsExample.csv'\n\nwith open(pred_filename, 'w') as pred_fh:\n\n # Produce a CSV file.\n pred_csv = csv.writer(pred_fh, delimiter=',', quotechar='\"',lineterminator='\\n')\n\n # Write the header row.\n pred_csv.writerow(['Id', 'Prediction'])\n#824230\n for i in range(20000):\n pred_csv.writerow([i, ridpredictions[i]])\n\n","repo_name":"HeLiHarvard/Team-Sriracha-Appreciators-of-USA","sub_path":"predictFinal.py","file_name":"predictFinal.py","file_ext":"py","file_size_in_byte":2940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73206375185","text":"import datetime\nimport math\nimport os\nimport sys\n\nimport jieba\nimport re\n\ndef getListFromTxt(file):\n with open(file, 'r', encoding='utf-8') as f:\n line = f.readline()\n return line.split(\",\")\n\ndef segment(sentence, cut_all=True):\n sentence = re.sub('[a-zA-Z0-9]', '', sentence.replace('\\n', '')) # 过滤\n sentence = sentence.replace('用户:', '')\n sentence = sentence.replace('点赞数:', '')\n return jieba.lcut(sentence, cut_all=cut_all) # 分词\n\n\ndef getStopWords(path): # 获取停用词表\n swlist = []\n with open(path, 'r', encoding='utf-8') as f:\n for line in f.readlines():\n line = line.strip()\n swlist.append(line)\n return swlist\n\n\ndef calTFIDF(inputdir, dirname): # 根据语料库目录计算每一个词的词频和TF-IDF\n documents = MyDocuments(inputdir)\n stopwords = getStopWords(path='my_stopwords.txt') # 获取停用词表\n # 排除中文标点符号\n ignored = stopwords + ['', ' ', '', '。', ':', ',', ')', '(', '!', '?', '”', '“', '!', '?', '[', ']', '][', '.', '~', '·', '日', \"\\\"\", '”。', ',']\n id_freq = {} # 统计一个词的频数\n txt_freq = {} # 统计一个词是否出现在这个文档里\n isInFile = {} # 用来标记这个词是否出现在文件中\n i = 0 # 总文档数\n wish = getListFromTxt(\"祝福支持.txt\")\n hope = getListFromTxt(\"期盼希望.txt\")\n rationality = getListFromTxt(\"理性.txt\")\n optimism = getListFromTxt(\"乐观快乐.txt\")\n concern = getListFromTxt(\"关注关切.txt\")\n concerninternational = getListFromTxt(\"关注国外.txt\")\n touch = getListFromTxt(\"感动感谢.txt\")\n worry = getListFromTxt(\"担忧焦虑.txt\")\n annoy = getListFromTxt(\"不满无语.txt\")\n for doc in documents:\n # 每次进入一个新文档,isInFile这个标记就要全部置为false\n for key in isInFile:\n if isInFile[key]: #如果不是false的话就置为false\n isInFile[key] = False\n doc = (x for x in doc if x not in ignored)\n for x in doc: # 统计每个词的词频\n if x in hope:\n if not (isInFile.get(\"期盼希望\", False)): #如果这个词是在所有文档中第一次出现,把他加入进去并默认置为false;如果这个词在这个文档中是第一次出现,把他加进去并默认置为false\n isInFile[\"期盼希望\"] = True\n txt_freq[\"期盼希望\"] = txt_freq.get(\"期盼希望\", 0) + 1 # 如果出现在某个文档中这个词在文档中的出现数目+1\n id_freq[\"期盼希望\"] = id_freq.get(\"期盼希望\", 0) + 1\n if x in concern:\n if not (isInFile.get(\"关注关切\", False)):\n isInFile[\"关注关切\"] = True\n txt_freq[\"关注关切\"] = txt_freq.get(\"关注关切\", 0) + 1\n id_freq[\"关注关切\"] = id_freq.get(\"关注关切\", 0) + 1\n if x in worry:\n if not (isInFile.get(\"担忧焦虑\", False)):\n isInFile[\"担忧焦虑\"] = True\n txt_freq[\"担忧焦虑\"] = txt_freq.get(\"担忧焦虑\", 0) + 1\n id_freq[\"担忧焦虑\"] = id_freq.get(\"担忧焦虑\", 0) + 1\n if x in optimism:\n if not (isInFile.get(\"乐观快乐\", False)):\n isInFile[\"乐观快乐\"] = True\n txt_freq[\"乐观快乐\"] = txt_freq.get(\"乐观快乐\", 0) + 1\n id_freq[\"乐观快乐\"] = id_freq.get(\"乐观快乐\", 0) + 1\n if x in wish:\n if not (isInFile.get(\"祝福支持\", False)):\n isInFile[\"祝福支持\"] = True\n txt_freq[\"祝福支持\"] = txt_freq.get(\"祝福支持\", 0) + 1\n id_freq[\"祝福支持\"] = id_freq.get(\"祝福支持\", 0) + 1\n if x in rationality:\n if not (isInFile.get(\"理性\", False)):\n isInFile[\"理性\"] = True\n txt_freq[\"理性\"] = txt_freq.get(\"理性\", 0) + 1\n id_freq[\"理性\"] = id_freq.get(\"理性\", 0) + 1\n if x in touch:\n if not (isInFile.get(\"感动感谢\", False)):\n isInFile[\"感动感谢\"] = True\n txt_freq[\"感动感谢\"] = txt_freq.get(\"感动感谢\", 0) + 1\n id_freq[\"感动感谢\"] = id_freq.get(\"感动感谢\", 0) + 1\n if x in concerninternational:\n if not (isInFile.get(\"关注国外\", False)):\n isInFile[\"关注国外\"] = True\n txt_freq[\"关注国外\"] = txt_freq.get(\"关注国外\", 0) + 1\n id_freq[\"关注国外\"] = id_freq.get(\"关注国外\", 0) + 1\n if x in concerninternational:\n if not (isInFile.get(\"关注国外\", False)):\n isInFile[\"关注国外\"] = True\n txt_freq[\"关注国外\"] = txt_freq.get(\"关注国外\", 0) + 1\n id_freq[\"关注国外\"] = id_freq.get(\"关注国外\", 0) + 1\n if x in annoy:\n if not (isInFile.get(\"不满无语\", False)):\n isInFile[\"不满无语\"] = True\n txt_freq[\"不满无语\"] = txt_freq.get(\"不满无语\", 0) + 1\n id_freq[\"不满无语\"] = id_freq.get(\"不满无语\", 0) + 1\n else:\n pass\n if i % 1000 == 0: # 每隔1000篇输出状态\n print('Documents processed: ', i, ', time: ',\n datetime.datetime.now())\n i += 1\n\n # 计算逆文档频率并且存储\n outputfile = dirname + \".txt\"\n with open(outputfile, 'w', encoding='utf-8') as f:\n total = sum(id_freq.values()) # 所有词的总value数,也就是所有词的总词数\n for key, value in id_freq.items():\n # TF-IDF的log是以二为底\n tf = value / total # tf是对每一个词词频的归一化\n idf = math.log(i / (txt_freq.get(key, 0) + 1), 2) # 注意要在分母上加一个1以避免0的情况\n f.write(key + ' ' + str(value) + ' ' + str(tf) + ' ' + str(idf) + ' ' + str(tf * idf) + '\\n')\n\n\ndef printTopK(tfidf, select_words, topK):\n for i in range(0, topK):\n word = select_words[i]\n freq = tfidf.freq[word]\n tf_freq = tfidf.tf_freq[word]\n idf_freq = tfidf.idf_freq[word]\n tfidf_freq = tfidf.tfidf_freq[word]\n print(word + \" \" + \"Freq = \" + str(freq) + \" \" + \"TF = \" + str(tf_freq) + \" \"\n + \"IDF = \" + str(idf_freq) + \" \" + \"TF-IDF = \" + str(tfidf_freq))\n\n\nclass MyDocuments(object): # 实现高效读取文本并且进行分词\n def __init__(self, dirname):\n self.dirname = dirname\n if not os.path.isdir(dirname):\n print(dirname, '- not a directory!')\n sys.exit()\n\n def __iter__(self):\n for dirfile in os.walk(self.dirname):\n for fname in dirfile[2]:\n try:\n text = open(os.path.join(dirfile[0], fname),\n 'r').read()\n yield segment(text)\n except UnicodeDecodeError as e:\n pass\n\n\n\n\nclass TFIDFLoader(object):\n def __init__(self, idf_path):\n self.idf_path = idf_path\n self.freq = {} # 词频\n self.tf_freq = {} # tf\n self.mean_tf = 0.0 # tf均值\n self.idf_freq = {} # idf\n self.mean_idf = 0.0 # idf均值\n self.tfidf_freq = {} # tfidf\n self.load_idf()\n\n def load_idf(self): # 从文件中载入idf,对这个idf文件的每一行(词语和idf值的一一对应)输入到一个字典中\n # 这个字典就是self.idf_freq这个对象\n cnt = 0\n with open(self.idf_path, 'r', encoding='utf-8') as f:\n for line in f:\n try:\n word, freq, tf, idf, tfidf = line.strip().split(' ')\n cnt += 1\n except Exception as e:\n pass\n self.freq[word] = int(freq)\n self.tf_freq[word] = float(tf)\n self.idf_freq[word] = float(idf)\n self.tfidf_freq[word] = float(tfidf)\n\n print('Vocabularies loaded: %d' % cnt)\n # self.mean_idf = sum(self.idf_freq.values()) / cnt\n\n\nclass TFIDF(object):\n def __init__(self, idf_path):\n # 分别获取Loader的每个属性\n self.idf_loader = TFIDFLoader(idf_path)\n self.freq = self.idf_loader.freq\n self.tf_freq = self.idf_loader.tf_freq\n self.idf_freq = self.idf_loader.idf_freq\n self.tfidf_freq = self.idf_loader.tfidf_freq\n # self.mean_idf = self.idf_loader.mean_idf\n\n def extract_keywordsInSentence(self, sentence, topK=30):\n # 分词\n seg_list = segment(sentence)\n\n freq = {}\n for w in seg_list:\n freq[w] = freq.get(w, 0.0) + 1.0 # 统计词频\n if '' in freq:\n del freq['']\n total = sum(freq.values()) # 总词数\n\n for k in freq: # 计算 TF-IDF\n freq[k] *= self.idf_freq.get(k) / total\n\n tags = sorted(freq, key=freq.__getitem__, reverse=True) # 排序,reverse=true标志着是降序排序\n\n if topK: # 返回topK\n return tags[:topK]\n else:\n return tags\n\n def extract_keywordsInCorpus(self, topK=9):\n tags = sorted(self.tfidf_freq, key=self.tfidf_freq.__getitem__, reverse=True)\n\n return tags[:topK], topK\n\n\nif __name__ == '__main__':\n basedir = \"D:\\\\NJU\\大二上\\数据科学基础\\大作业\\Coding\\评论数据\\评论bilibili\"\n dirname = \"bilibili评论\"\n inputdir = basedir + '\\\\' + dirname\n calTFIDF(inputdir ,dirname)\n idffile = dirname + \".txt\"\n tfidf = TFIDF(idffile)\n select_words, topK = tfidf.extract_keywordsInCorpus(topK=9) # 获得的topK个关键词\n printTopK(tfidf, select_words, topK)\n\n","repo_name":"jiaxinr/ProjectOfDataScience","sub_path":"其他代码/tf-idf/emotion-tfidf(precious).py","file_name":"emotion-tfidf(precious).py","file_ext":"py","file_size_in_byte":9979,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"4913902251","text":"class ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n\nclass Solution:\n def deleteDuplicates(self, head):\n total = list()\n dup = set()\n\n node = head\n while node is not None:\n if node.val in total:\n dup.add(node.val)\n else:\n total.append(node.val)\n\n node = node.next\n\n new = None\n for v in reversed(total):\n if v not in dup:\n new = ListNode(v, new)\n\n return new\n","repo_name":"fzdy1914/leetcode","sub_path":"linkedlist/82-remove-duplicates-2.py","file_name":"82-remove-duplicates-2.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16952028857","text":"import json\nfrom template_engine import TemplateEngine\n# from datastore.sqlite import SqliteStore\n\n# file_name = \"C:\\\\Users\\\\b\\\\Desktop\\\\spc-migrate\\\\mathew\\\\templates\\\\pubs.html\"\n# template_file = open(file_name, 'r')\n# template = template_file.read()\n\n# with SqliteStore('test.data') as data_store:\n# data_store.bootstrap()\n# data = {k: v for k, v in data_store.get_data()}\n\n# def get_data(m):\n# key = m.group(1)\n# return data[key]\n\n# TE = TemplateEngine(\n# templates_dir=\"C:\\\\Users\\\\b\\\\Desktop\\\\spc-migrate\\\\mathew\\\\templates\")\n# result = TE.parse(template, get_data)\n\n# with open('build.html', 'w') as outfile:\n# outfile.write(result)\n\n# template_file.close()\n\nspecimen = \"hello world, i am birnadin erick,\\n here are some { include a.html }\"\ndata = {\n \"a.html\": (\n \"i have a crush on {eval crush.name}, i love her {eval crush.fav}\",\n [\n {\"name\": \"Manuka K\", \"fav\": \"tt\"},\n {\"name\": \"Kaviya S\", \"fav\": \"nose\"},\n ]\n ),\n \"b.html\": (\n \"i have a crush on {eval crush.name}, i hate her {eval crush.hate}\",\n [\n {\"name\": \"Manuka K\", \"hate\": \"jealousy\"},\n {\"name\": \"Kaviya S\", \"hate\": \"ignorance\"},\n ]\n ),\n}\n\nfor k in data.keys():\n agg_res = parse_template(data[k][0], data[k][1])\n\n for i, agg_re in enumerate(agg_res):\n fname, ext = tuple(k.split(\".\"))\n filename = fname + str(i) + '.' + ext\n with open(filename, 'w') as file:\n file.write(eval_include(specimen, agg_re))\n","repo_name":"BirnadinErick/mathew","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1560,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"12744992594","text":"import os\nfrom rest_framework import serializers, viewsets, permissions, status\nfrom rest_framework.response import Response\nfrom ..models import Album\nfrom photos.models import Photo\nfrom .serializers import AlbumSerializers, AlbumhitorySerializers\nfrom django.http import HttpResponseRedirect\nfrom rest_framework.response import Response\nfrom rest_framework.permissions import IsAuthenticated, AllowAny\nfrom google_drive import demo as drive\nfrom django.http import JsonResponse\n\nfrom django.db.models import Q\n\nfrom django.contrib.auth import get_user_model\nUser = get_user_model()\n\nclass AlbumViewSet (viewsets.ModelViewSet):\n\n filter_backends = []\n queryset = Album.objects.all()\n serializer_class = AlbumSerializers\n http_method_names = ['get', 'post', 'put', 'delete','head']\n permission_classes = [IsAuthenticated]\n\n\n\n def list(self, request, *args, **kwargs):\n \n if request.user.id == None:\n \n return Response('no user')\n \n user_albuns = Album.objects.filter(Q(owner = request.user.id) | Q(shared_with = request.user.id))\n serializer = AlbumSerializers(user_albuns, many=True)\n #print(serializer.data, request.user.id, '<<<')\n return Response(serializer.data)\n\n def update(self, request, *args, **kwargs):\n partial = kwargs.pop('partial', True)\n instance = self.get_object()\n serializer = self.get_serializer(instance, data=request.data, partial=partial)\n serializer.is_valid(raise_exception=True)\n \n new_data = request.data\n old_data = instance \n print(new_data['title'], old_data)\n if new_data['title']:\n if new_data['title'] != old_data.title:\n \n print('seaching for', old_data.title)\n drive.change_file_name(str(old_data.owner.email), old_data.title, new_data['title'])\n \n \n self.perform_update(serializer)\n\n if getattr(instance, '_prefetched_objects_cache', None):\n # If 'prefetch_related' has been applied to a queryset, we need to\n # forcibly invalidate the prefetch cache on the instance.\n instance._prefetched_objects_cache = {}\n\n return Response(serializer.data)\n\n def create(self, request, *args, **kwargs):\n\n owner_data= request.user\n \n multiple_image_count = 0\n image = []\n for dados in request.data:\n print(dados)\n if dados == f'photos[{multiple_image_count}][photo]':\n \n name = str()\n print(str(request.data[f'photos[{multiple_image_count}][photo]']))\n image.append(request.data[f'photos[{multiple_image_count}][photo]'])\n multiple_image_count += 1\n \n \n album_request_data = request.data\n print(request.data)\n\n print(request.POST, ' self.value:\n if self.right is None:\n self.right = Node(value)\n else:\n self.right.insert(value)\n else:\n self.value = value\n\n\ndef is_valid_node(node, value):\n if isinstance(int(), type(value)):\n while node is not None:\n if value == node.value:\n return True\n elif value < node.value:\n node = node.left\n elif value > node.value:\n node = node.right\n return False\n","repo_name":"hollymcevoy/Python-LCA","sub_path":"Python/binaryTree.py","file_name":"binaryTree.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"73202619345","text":"import torch\nimport torch.nn as nn\n\nfrom torch.nn.functional import softplus\nfrom torch.nn import functional as F\n\nfrom torch.distributions.uniform import Uniform\nfrom torch.distributions.gamma import Gamma\nfrom torch.distributions.dirichlet import Dirichlet\n\nfrom .helpers import NB_log_prob, ZINB_log_prob, ELBO_collapsed_Categorical\n\nclass BasisDecoder(nn.Module):\n\n \"\"\"\n Core component of BasisVAE: decoder where the last layer contains probabilistic Categorical random variables\n \"\"\"\n\n def __init__(self, data_dim, hidden_dim, z_dim,\n n_basis,\n scale_invariance,\n translation_invariance,\n likelihood=\"Gaussian\",\n nonlinearity=nn.Softplus,\n inference = \"collapsed\",\n alpha=1.0,\n qalpha_init=None,\n max_delta=1.5,\n min_lambda=0.25,\n max_lambda=1.75,\n device=\"cpu\"):\n \"\"\"\n :param data_dim: Data dimensionality\n :param hidden_dim: The number of neurons in the hidden layer (we assume one-hidden-layer NN)\n :param z_dim: Dimensionality of latent space\n :param n_basis: Number of basis functions (K)\n :param scale_invariance: Is BasisVAE scale-invariant?\n :param translation_invariance: Is BasisVAE translation-invariant?\n :param likelihood: Likelihood (options include \"Gaussian\", \"Bernoulli\", and for single-cell applications \"NB\" and \"ZINB\")\n :param nonlinearity: Type of non-linearity in NNs\n :param inference: Inference approach (\"collapsed\" is recommended)\n :param alpha: The Dirichlet alpha parameter (scalar)\n :param qalpha_init: Only relevant for non-collapsed inference\n :param max_delta: The range of delta values can be restricted for identifiability\n :param min_lambda: Lower bound on lambda values\n :param max_lambda: Upper bound on lambda values\n :param device: CPU or GPU\n \"\"\"\n super().__init__()\n\n self.data_dim = data_dim\n self.likelihood = likelihood\n self.inference = inference\n self.device = device\n\n self.scale_invariance = scale_invariance\n self.translation_invariance = translation_invariance\n self.n_basis = n_basis\n self.max_delta = max_delta\n self.min_lambda = min_lambda\n self.max_lambda = max_lambda\n\n # we will set up a neural network with one hidden layer\n if self.translation_invariance:\n # for translation-invariant case, we do the computations manually for computational efficiency\n self.linear1 = nn.Linear(z_dim, hidden_dim)\n self.linear2 = nn.Linear(hidden_dim, self.n_basis)\n self.nonlinearity = nonlinearity()\n else:\n # for non-translation-invariant case\n self.mapping_z = nn.Sequential(\n nn.Linear(z_dim, hidden_dim),\n nonlinearity(),\n nn.Linear(hidden_dim, self.n_basis)\n )\n\n # feature-specific variances\n if self.likelihood == \"Gaussian\":\n self.noise_sd = nn.Parameter(-2.0 * torch.ones(1, data_dim))\n\n elif self.likelihood == \"NB\":\n self.nb_theta = nn.Parameter(torch.zeros(1, data_dim))\n\n elif self.likelihood == \"ZINB\":\n self.nb_theta = nn.Parameter(torch.zeros(1, data_dim))\n\n self.dropout_decoder = nn.Sequential(\n nn.Linear(1, hidden_dim),\n nonlinearity(),\n nn.Linear(hidden_dim, data_dim)\n )\n\n elif self.likelihood == \"Bernoulli\":\n self.noise_sd = None\n else:\n raise ValueError(\"Unknown likelihood\")\n\n self.intercept = nn.Parameter(torch.zeros(1, data_dim))\n\n # we assume vector (alpha, ..., alpha)\n self.alpha_z = alpha * torch.ones(n_basis, device=self.device)\n\n # q(phi) parameters\n self.qphi_logits = nn.Parameter(torch.zeros([self.data_dim, self.n_basis]))\n\n if self.inference == \"non-collapsed\":\n # for non-collapsed inference, q(alpha)\n if qalpha_init is None:\n raise ValueError(\"For non-collapsed inference need to specify q(alpha)\")\n self.qalpha_z = nn.Parameter(torch.Tensor(qalpha_init))\n\n if self.scale_invariance:\n self.scaling_z = nn.Parameter(torch.zeros([self.data_dim, self.n_basis]))\n\n if self.translation_invariance:\n self.shift_z = nn.Parameter(torch.zeros([self.data_dim, self.n_basis, 1]))\n\n def get_delta(self):\n # delta values (constrained within [-max_delta, max_delta]\n return self.max_delta * torch.tanh(self.shift_z)\n\n def get_lambda(self):\n # lambda values\n return self.min_lambda + (self.max_lambda - self.min_lambda) * torch.sigmoid(self.scaling_z)\n\n def get_phi(self):\n return torch.softmax(self.qphi_logits, dim=-1)\n\n def get_basis(self, z):\n\n if self.translation_invariance:\n\n z_tilde = self.get_delta()[None, :, :, :] + z[:, None, None, :]\n # first hidden layer representation, [N, output_dim, n_basis_z, n_hidden_units]\n hidden = self.nonlinearity(self.linear1(z_tilde))\n\n # [N, output_dim, n_basis_z]\n basis0 = torch.sum(hidden * self.linear2.weight, dim=3)\n\n # [output_dim, n_basis_z]\n scaling = self.get_lambda()\n\n # [N, output_dim, n_basis_z]\n basis = basis0 * scaling\n\n else:\n basis0 = self.mapping_z(z)\n\n if self.scale_invariance:\n # shape [output_dim, n_basis_z]\n scaling = self.get_lambda()\n\n # shape [N, output_dim, n_basis_z]\n basis = basis0[:, None, :] * scaling\n else:\n # shape [N, output_dim, n_basis_z]\n basis = basis0[:, None, :].repeat(1, self.data_dim, 1)\n\n return basis\n\n def KL_phi(self):\n\n if self.inference == \"collapsed\":\n return ELBO_collapsed_Categorical(self.qphi_logits, self.alpha_z, K=self.n_basis, N=self.data_dim)\n\n elif self.inference == \"fixed_pi\":\n qphi = self.get_phi()\n pi = torch.ones_like(qphi) / self.n_basis\n KL = (\n qphi * (torch.log(qphi + 1e-16) - torch.log(pi))\n ).sum()\n return KL\n\n elif self.inference == \"non-collapsed\":\n qDir = Dirichlet(concentration=self.qalpha_z)\n pDir = Dirichlet(concentration=self.alpha_z)\n\n # KL(q(pi) || p(pi))\n KL_Dir = torch.distributions.kl_divergence(qDir, pDir)\n\n # E[log q(phi) - log p(phi | pi)] under q(pi)q(phi)\n qpi = qDir.rsample()\n qphi = self.get_phi()\n\n # KL categorical\n KL_Cat = (\n qphi * (torch.log(qphi + 1e-16) - torch.log(qpi[None, :]))\n ).sum()\n return KL_Dir + KL_Cat\n\n def forward(self, z):\n if self.likelihood == \"Bernoulli\":\n pred = self.get_basis(z)\n dropout_prob = None\n theta = None\n\n elif self.likelihood == \"Gaussian\":\n pred = self.get_basis(z)\n dropout_prob = None\n theta = None\n\n elif self.likelihood == \"NB\":\n pred = softplus(self.get_basis(z))\n theta = softplus(self.nb_theta)\n dropout_prob = None\n\n elif self.likelihood == \"ZINB\":\n pred = softplus(self.get_basis(z))\n dropout_prob = self.dropout_decoder(z)\n theta = softplus(self.nb_theta)\n\n return pred, dropout_prob, theta\n\n def loglik(self, y_obs, y_pred, dropout_prob_logit, theta):\n\n if self.likelihood == \"Gaussian\":\n\n sigma = 1e-4 + softplus(self.noise_sd)\n p_data = torch.distributions.normal.Normal(loc=y_pred, scale=sigma[:, :, None])\n log_p = p_data.log_prob(y_obs[:, :, None])\n\n elif self.likelihood == \"NB\":\n\n log_p = NB_log_prob(y_obs[:, :, None], mu=y_pred, theta=theta[:, :, None])\n\n elif self.likelihood == \"ZINB\":\n\n # [batch_size, output_dim, n_basis]\n log_p = ZINB_log_prob(y_obs[:, :, None], y_pred, theta[:, :, None], dropout_prob_logit[:, :, None])\n\n if self.likelihood == \"Bernoulli\":\n\n log_p = -F.binary_cross_entropy_with_logits(y_pred, y_obs[:, :, None].repeat(1, 1, self.n_basis), reduction='none')\n\n phi = self.get_phi()\n\n loglik = (phi * log_p).sum()\n\n return loglik\n\n def loss(self, y_obs, y_pred, dropout_prob_logit, theta, batch_scale=1.0, beta=1.0):\n\n prior_loss = 0.0\n\n if self.translation_invariance:\n prior_loss += self.get_delta().pow(2).sum()\n\n if self.scale_invariance:\n lambdas = self.get_lambda()\n prior_loss -= Gamma(torch.ones_like(lambdas), torch.ones_like(lambdas)).log_prob(lambdas).sum()\n\n loglik = batch_scale * self.loglik(y_obs, y_pred, dropout_prob_logit, theta)\n\n decoder_loss = - loglik + beta * self.KL_phi() + prior_loss\n\n return decoder_loss\n\n def get_similarity_matrix(self):\n with torch.no_grad():\n mat = torch.mm(self.get_phi(), self.get_phi().t())\n return mat\n\n","repo_name":"kasparmartens/BasisVAE","sub_path":"BasisVAE/decoder.py","file_name":"decoder.py","file_ext":"py","file_size_in_byte":9335,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"48"} +{"seq_id":"13000701158","text":"import sys\nsys.stdin = open(\"D4_1251_input.txt\", \"r\")\n\n# 내 풀이 1\n# def make_set(v):\n# parent[v] = v\n# rank[v] = 0\n#\n# def find(v):\n# if parent[v] != v:\n# parent[v] = find(parent[v])\n# return parent[v]\n#\n# def union(v, u):\n# root1 = find(v)\n# root2 = find(u)\n#\n# if root1 != root2:\n# if rank[root1] > rank[root2]:\n# parent[root2] = root1\n# else:\n# parent[root1] = root2\n# if rank[root1] == rank[root2]:\n# rank[root2] += 1\n#\n# def kruskal():\n# for v in range(N):\n# make_set(v)\n# # mst = []\n# mst = 0\n# for edge in edges:\n# if find(edge[1]) != find(edge[2]):\n# union(edge[1], edge[2])\n# # mst.append(edge[0])\n# mst += edge[0]\n# # return sum(mst)\n# return mst\n#\n# T = int(input())\n# for test_case in range(T):\n# N = int(input())\n# data = [list(map(int, input().split())) for _ in range(2)]\n# E = float(input())\n# parent = {}\n# rank = {}\n# edges = [] # 거리, 노드1, 노드2\n#\n# for i in range(N):\n# for j in range(i + 1, N):\n# edges.append((pow(data[0][i] - data[0][j], 2) + pow(data[1][i] - data[1][j], 2), i, j))\n# edges.sort()\n# print(\"#{} {}\".format(test_case + 1, round(kruskal() * E)))\n\n\n#############################################################################\n\n# 다른사람 풀이\n# def find(x):\n# if parent[x] == x:\n# return x\n# else:\n# parent[x] = find(parent[x])\n# return parent[x]\n#\n#\n# def union(x, y):\n# x = find(x)\n# y = find(y)\n# if x != y:\n# parent[y] = x\n# return True\n# else:\n# return False\n#\n#\n# def calc(nxt, now):\n# return (a[nxt][1] - a[now][1]) ** 2 + (a[nxt][0] - a[now][0]) ** 2\n#\n#\n# for t in range(int(input())):\n# n = int(input())\n# a = list(map(int, input().split()))\n# b = list(map(int, input().split()))\n# a = list(zip(a, b))\n# parent = [0] * (n)\n# for i in range(n):\n# parent[i] = i\n#\n# d = []\n# for i in range(n):\n# for j in range(i, n):\n# if i == j:\n# continue\n# d.append((i, j, calc(i, j)))\n# d = sorted(d, key=lambda x: x[2])\n# ans = 0\n# for x, y, cur in d:\n# if not union(x, y):\n# continue\n# else:\n# ans += cur\n# k = float(input())\n# print('#{} {}'.format(t + 1, round(ans * k)))\n\n\n#############################################################################\n\n# 내 풀이 2\ndef find(v):\n if parent[v] == v:\n return v\n else:\n parent[v] = find(parent[v])\n return parent[v]\n\ndef union(v, e):\n v = find(v)\n e = find(e)\n\n if v != e:\n parent[e] = v\n return True\n return False\n\nT = int(input())\nfor test_case in range(T):\n N = int(input())\n data = [list(map(int, input().split())) for _ in range(2)]\n E = float(input())\n parent = list(range(N))\n edges = []\n mat = 0\n\n for i in range(N):\n for j in range(i + 1, N):\n edges.append((pow(data[0][i] - data[0][j], 2) + pow(data[1][i] - data[1][j], 2), i, j))\n # edges.sort()\n edges = sorted(edges, key = lambda x : x[0])\n\n for distance, v, e in edges:\n if not union(v, e):\n continue\n mat += distance\n print(\"#{} {}\".format(test_case + 1, round(mat * E)))","repo_name":"hongyong3/TIL","sub_path":"Algorithm/Swea/D4_1251.py","file_name":"D4_1251.py","file_ext":"py","file_size_in_byte":3432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6667055955","text":"def run_length_encode(string):\n encoded_data = \"\"\n count = 1\n prev_char = string[0]\n\n # Apply Run-Length Encoding\n for char in string[1:]:\n if char == prev_char:\n count += 1\n else:\n encoded_data += str(count) + prev_char\n count = 1\n prev_char = char\n\n encoded_data += str(count) + prev_char\n\n return encoded_data\n\n\ndef compress_string(string):\n compressed_data = \"\"\n count = 1\n prev_char = string[0]\n\n # Compress the string\n for char in string[1:]:\n if char == prev_char:\n count += 1\n else:\n compressed_data += prev_char + str(count)\n count = 1\n prev_char = char\n\n compressed_data += prev_char + str(count)\n\n return compressed_data\n\n\ndef convert_to_ascii(string):\n ascii_data = [ord(char) for char in string]\n return ascii_data\n\n\ndef convert_to_binary(data):\n binary_data = \"\".join(format(byte, \"08b\") for byte in data)\n return binary_data\n\n\ndef run_length_decode(encoded_data):\n decoded_data = \"\"\n i = 0\n while i < len(encoded_data):\n count = \"\"\n while i < len(encoded_data) and encoded_data[i].isdigit():\n count += encoded_data[i]\n i += 1\n char = encoded_data[i]\n decoded_data += char * (int(count) if count else 1)\n i += 1\n return decoded_data\n\n\ndef decompress_string(compressed_string):\n decompressed_data = \"\"\n i = 0\n while i < len(compressed_string):\n char = compressed_string[i]\n count = \"\"\n i += 1\n while i < len(compressed_string) and compressed_string[i].isdigit():\n count += compressed_string[i]\n i += 1\n decompressed_data += char * (int(count) if count else 1)\n return decompressed_data\n\n\ndef decode_binary(binary_data):\n ascii_data = []\n for i in range(0, len(binary_data), 8):\n byte = binary_data[i:i+8]\n ascii_data.append(int(byte, 2))\n return ascii_data\n\n\n# Example usage\noriginal_string = \"ZZZZZZZ\"\nrle_encoded_string = run_length_encode(original_string)\ncompressed_string = compress_string(original_string)\nascii_data = convert_to_ascii(compressed_string)\nbinary_data = convert_to_binary(ascii_data)\ndecoded_string = run_length_decode(rle_encoded_string)\ndecompressed_string = decompress_string(compressed_string)\n\nprint(\"Original string:\", original_string)\nprint(\"RLE encoded string:\", rle_encoded_string)\nprint(\"Compressed string:\", compressed_string)\nprint(\"ASCII representation:\", ascii_data)\nprint(\"Binary representation:\", binary_data)\nprint(\"Decoded string:\", decoded_string)\nprint(\"Decompressed string:\", decompressed_string)\n","repo_name":"Ahmed-Ihsan/Compress_string","sub_path":"compress.py","file_name":"compress.py","file_ext":"py","file_size_in_byte":2683,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13255836895","text":"import tkinter as tk\nimport random as rd\nimport OptionsMenu\nfrom AddCustomerFrame import AddCustomerFrame\nfrom ViewCustomerFrame import ViewCustomerFrame\nfrom AddProductFrame import AddProductFrame\nfrom ViewProductFrame import ViewProductFrame\nfrom AddInvoiceFrame import AddInvoiceFrame\nfrom ViewInvoiceFrame import ViewInvoiceFrame\nfrom OrderBoardFrame import OrderBoardFrame\nfrom StatementsFrame import Statements\nfrom ProductBreakdownFrame import ProductBreakdownFrame\nfrom tkinter import BOTH, LEFT, Menu\n\nclass GPFUI():\n def __init__(self):\n self.root = tk.Tk()\n #self.baseFrame = tk.Frame(self.root,bg = '#FFFFFF')\n self.baseCanvas = tk.Canvas(self.root, bg='#FFFFFF')\n self.baseFrame_2 = tk.Frame(self.baseCanvas, bg='#FFFFFF')\n self.sbHorizontalScrollBar = tk.Scrollbar(self.root)\n self.sbVerticalScrollBar = tk.Scrollbar(self.root)\n\n def create_scrollable_container(self):\n self.baseCanvas.config(xscrollcommand=self.sbHorizontalScrollBar.set,yscrollcommand=self.sbVerticalScrollBar.set, highlightthickness=0)\n self.sbHorizontalScrollBar.config(orient=tk.HORIZONTAL, command=self.baseCanvas.xview)\n self.sbVerticalScrollBar.config(orient=tk.VERTICAL, command=self.baseCanvas.yview)\n\n self.sbHorizontalScrollBar.pack(fill=tk.X, side=tk.BOTTOM, expand=tk.FALSE)\n self.sbVerticalScrollBar.pack(fill=tk.Y, side=tk.RIGHT, expand=tk.FALSE)\n\n self.baseCanvas.pack(fill=tk.BOTH, side=tk.LEFT, expand=tk.TRUE)\n self.baseCanvas.create_window(0, 0, window=self.baseFrame_2, anchor=tk.NW)\n\n def update_scrollable_region(self):\n self.baseCanvas.update_idletasks()\n self.baseCanvas.config(scrollregion=self.baseFrame_2.bbox())\n\n def start(self):\n\n #root = tk.Tk()\n\n self.root.title('Green Paradise Farms')\n self.root.iconbitmap('GPFISHTMLObjects\\Invoices\\imgs\\gpf_logo.ico')\n\n window_width = 700\n window_height = 500\n\n # get the screen dimension\n screen_width = self.root.winfo_screenwidth()\n screen_height = self.root.winfo_screenheight()\n #print(\"SCREEN HEIGHT: \" + str(screen_height) + \" SCREEN WIDTH: \" + str(screen_width))\n\n # find the center point\n center_x = int(screen_width/2 - window_width / 2)\n center_y = int(screen_height/2 - window_height / 2)\n\n #Window controls\n #Fullscreen no top toolbar\n self.root.attributes('-fullscreen', True)\n self.root.update_idletasks()\n #Full screen with right top toolbar\n #root.geometry(\"%dx%d\" % (screen_width, screen_height))\n #Use window geometery and center\n #self.root.geometry(f'{window_width}x{window_height}+{center_x}+{center_y}')\n #baseFrame = tk.Frame(root, bd = 5, bg = 'grey')\n #baseFrame.pack(fill=BOTH, expand=1)\n\n #scrollbar set up\n #baseFrame = tk.Frame(self.root,bg = '#FFFFFF')\n #self.baseFrame.pack()\n self.baseFrame_2.pack()\n\n #baseCanvas = tk.Canvas(self.baseFrame, bg=\"#FFFFFF\")\n #self.baseCanvas.pack(side='left', fill=BOTH, expand=1)\n\n #v_scroll = tk.Scrollbar(self.baseFrame, orient='vertical', command=self.baseCanvas.yview)\n #v_scroll.pack(side='right', fill='y')\n\n #baseFrame_2 = tk.Frame(self.baseCanvas, bg=\"#FFFFFF\")\n\n #Instantiate class objects for each menu option\n #Each object builds and controls UI widgets\n order_board_frame = OrderBoardFrame(self.baseFrame_2)\n add_customer_frame = AddCustomerFrame(self.baseFrame_2)\n view_customer_frame = ViewCustomerFrame(self.baseFrame_2, self.baseCanvas, self.root)\n add_product_frame = AddProductFrame(self.baseFrame_2)\n view_product_frame = ViewProductFrame(self.baseFrame_2, self.baseCanvas, self.root)\n add_invoice_frame = AddInvoiceFrame(self.baseFrame_2, self.baseCanvas)\n view_invoice_frame = ViewInvoiceFrame(self.baseFrame_2, self.baseCanvas, self.root)\n statement_frame = Statements(self.baseFrame_2, self.baseCanvas, self.root)\n product_breakdown_frame = ProductBreakdownFrame(self.baseFrame_2, self.baseCanvas, self.root)\n\n self.baseFrame_2.configure(bg='#cccccc')\n self.baseCanvas.configure(bg='#cccccc')\n\n self.create_scrollable_container()\n self.update_scrollable_region()\n #baseCanvas.configure(yscrollcommand=v_scroll.set)\n #baseCanvas.bind(\"\", lambda e: baseCanvas.configure(scrollregion= baseCanvas.bbox(\"all\")))\n\n #baseCanvas.create_window((0,0), window=baseFrame_2, anchor='nw', tags=\"baseFrame_2\")\n #baseCanvas.itemconfig(\"baseFrame_2\", height=screen_height, width=screen_width)\n\n #baseCanvas = tk.Canvas(baseFrame, scrollregion=(0,0, 1500, 1500))\n #vbar = tk.Scrollbar(baseFrame, orient='vertical')\n #vbar.pack(side='right', fill='y')\n #vbar.config(command=baseCanvas.yview)\n #baseCanvas.config(yscrollcommand=vbar.set)\n #baseCanvas.pack(side='left' ,fill='both', expand=True)\n\n #This class should make an object for all the frames like view customer, add customer, view product, add product etc..\n #each of those objects will have a reference to the base frame and be passed to the menu class.\n #the menu class will have references to those objects, be able to call their methods, and change frames based on the menu action selected.\n #Each of those objects may or may not have imported classes that deal with retrieving or sending data to the databse. Those classes\n #WILL NOT handle any of that themselves, beyond making a call asks for or sends data. Data that is sent or comes in should be in list or tuple form. \n # (possible that it may be lists or tuples of appropriate objects e.g. Product, Customer classes)\n\n baseMenu = OptionsMenu.GPF_OptionsMenu(self.root, \n add_customer_frame = add_customer_frame, \n view_customer_frame= view_customer_frame, \n add_product_frame= add_product_frame, \n view_product_frame= view_product_frame, \n add_invoice_frame= add_invoice_frame, \n view_invoice_frame= view_invoice_frame,\n order_board_frame= order_board_frame,\n statement_frame= statement_frame,\n product_breakdown_frame = product_breakdown_frame)\n self.root.config(menu=baseMenu.getMenuBar())\n\n self.root.mainloop()\n","repo_name":"mower003/GPF","sub_path":"GPFUI.py","file_name":"GPFUI.py","file_ext":"py","file_size_in_byte":6736,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25582861573","text":"\"\"\"Common Info Endpoint.\"\"\"\r\n\r\nimport datetime\r\n\r\nfrom ..config import CONFIG\r\nfrom ..utils.logging import LOG\r\n\r\n\r\nasync def get_info(host):\r\n \"\"\"Return service info of self.\r\n\r\n Service ID is parsed from hostname to ensure that each service has a unique ID.\r\n \"\"\"\r\n LOG.debug(\"Return service info.\")\r\n\r\n service_info = {\r\n \"id\": \".\".join(reversed(host.split(\".\"))),\r\n \"name\": CONFIG.name,\r\n \"type\": {\"group\": CONFIG.type_group, \"artifact\": CONFIG.type_artifact, \"version\": CONFIG.type_version},\r\n \"description\": CONFIG.description,\r\n \"organization\": {\"name\": CONFIG.organization, \"url\": CONFIG.organization_url},\r\n \"contactUrl\": CONFIG.contact_url,\r\n \"documentationUrl\": CONFIG.documentation_url,\r\n \"createdAt\": CONFIG.create_time,\r\n \"updatedAt\": datetime.datetime.now().strftime(\"%Y-%m-%dT%H:%M:%SZ\"),\r\n \"environment\": CONFIG.environment,\r\n \"version\": CONFIG.version,\r\n }\r\n\r\n return service_info\r\n","repo_name":"CSCfi/beacon-network","sub_path":"aggregator/endpoints/info.py","file_name":"info.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"} +{"seq_id":"23447055226","text":"import sys\nfrom heapq import heappop, heappush\ninput = lambda : sys.stdin.readline().rstrip()\n\ndef find(x) :\n if parent[x] != x :\n parent[x] = find(parent[x])\n return parent[x]\n\ndef union(x, y) :\n x = find(x)\n y = find(y)\n if x > y :\n parent[y] = x\n elif x < y :\n parent[x] = y\n\nN = int(input())\nstars = [list(map(float, input().split())) for _ in range(N)]\ndist = []\nparent = [i for i in range(N)]\nfor one in range(N) :\n for two in range(N) :\n if one == two :\n continue\n one_x, one_y = stars[one]\n two_x, two_y = stars[two]\n now_dist = ((two_x - one_x) **2 + (two_y - one_y)**2)**0.5\n heappush(dist, [round(now_dist,2), one, two])\n\nanswer = 0\nwhile dist :\n weight, one, two = heappop(dist)\n if find(one) != find(two) :\n answer += weight\n union(one, two)\nprint(answer)\n","repo_name":"JoungMinJu/PyCodingTest","sub_path":"Reis/mst/BOJ_4386.py","file_name":"BOJ_4386.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6905024114","text":"# 上からスクリプトを読み込むので、関数定義を行ってから関数を呼び出すこと\n\ndef say_something():\n print('Hi')\n\n# say_sometnigはである\nprint(type(say_something)) \n#この様にも実行できる\nf = say_something\nf()\n\n# 戻り値(複数の戻り値を返す)\ndef test_something():\n s = 'hi'\n m = 100\n return s,m\n\nresult = test_something()\nprint(result)\n# 戻り地が複数ある場合はタプル型で返って来る\nprint(type(result))\n\n# 引数\ndef what_is_this(color):\n if color == 'red':\n return 'tomoto'\n elif color == 'green':\n return 'green pepper'\n else:\n return \"I don't know.\"\n\nresult = what_is_this('green')\nprint(result)\n","repo_name":"Kazzuki/study_python","sub_path":"48_function.py","file_name":"48_function.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12148221332","text":"'''\nIl existe 5 types de déplacements, représentés par 5 entiers différents : aller à gauche (1), aller à droite (2), aller tout droit (3), monter (4) et descendre (5).\nLe premier entier à lire est le nombre total de déplacements (1000 au maximum). Ensuite, chaque déplacement (représenté par un entier) est indiqué sur sa propre ligne.\nVous devez afficher la suite des déplacements à faire pour aller de votre position actuelle à la sortie.\n'''\n\ndeplacementInverse = [0, 2, 1, 3, 5, 4]\nnbDeplacements = int(input())\nchemin = [0] * nbDeplacements\nfor numero in range(nbDeplacements):\n chemin[numero] = int(input())\nfor numero in range(nbDeplacements-1, -1, -1):\n deplacement = chemin[numero]\n print(deplacementInverse[deplacement])\n","repo_name":"vogtdale/python","sub_path":"franceIOI/Niveau2/DecouverteTableau/visiteMine.py","file_name":"visiteMine.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17856979681","text":"#dict_main.py\r\nfrom func1 import *\r\nfrom func2 import *\r\nfrom func3 import *\r\nfrom func4 import *\r\nfrom func5 import *\r\n\r\n'''\r\n menu_test.py\r\n'''\r\n\r\nmenu = '''\r\n\r\n1. 단어 입력\r\n\r\n2. 단어 수정\r\n\r\n3. 단어 삭제\r\n\r\n4. 단어 검색\r\n\r\n5. 단어장 전체 출력\r\n\r\n0. 종료\r\n\r\nselect menu : '''\r\n\r\ndef main():\r\n wordbook = {}\r\n func_dict = { 1:func1, 2:func2, 3:func3, 4:func4, 5:func5 }\r\n while True:\r\n print( menu, end = ' ' )\r\n selectMenu = int( input() )\r\n if selectMenu == 0:\r\n break\r\n elif 2 <= selectMenu <= 5:\r\n func_dict[ selectMenu ](wordbook)\r\n elif selectMenu == 1 :\r\n wordbook = func_dict[ selectMenu ](wordbook)\r\n return\r\n\r\nif __name__ == '__main__':\r\n main()","repo_name":"yeonsikC/Bigdata_maestro","sub_path":"Python/dict_main.py","file_name":"dict_main.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15273858901","text":"N = int(input())\n\nword = []\ncomp = []\nfor idx in range(N):\n word.append(input())\nfor idx in range(N - 1):\n comp.append(input())\n\nprint(word)\nprint(comp)\nfor x in word[:]:\n if x in comp:\n word.remove(x)\nprint(word[0])\n'''\n5\nbig\ngood\nsky\nblue\nmouse\nsky\ngood\nmouse\nbig\n'''","repo_name":"gkdbssla97/Python-Coding-Test","sub_path":"CodingProblem/단어_찾기.py","file_name":"단어_찾기.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"16577726033","text":"import datetime\nfrom django.db import models\nfrom django.contrib.auth.models import User\nfrom django.utils import timezone\n\n# Create your models here.\nclass BankAccount(models.Model):\n owner = models.ForeignKey(\n User,\n related_name=\"owner\",\n verbose_name=\"Owner\",\n null=True,\n blank=True,\n on_delete=models.SET_NULL,\n )\n amount = models.FloatField(\n verbose_name=\"Current Amount\", default=0, null=True, blank=True\n )\n created_at = models.DateTimeField(auto_now_add=True)\n\n def __str__(self) -> str:\n return f\"{self.owner.username} {self.amount} $\"\n\n verbose_name = \"Bank Account\"\n verbose_name_plural = \"Bank Accounts\"\n\n\nclass Transaction(models.Model):\n sender = models.ForeignKey(\n User,\n related_name=\"sender\",\n verbose_name=\"Sender\",\n null=True,\n blank=True,\n on_delete=models.SET_NULL,\n )\n recipient = models.ForeignKey(\n User,\n related_name=\"recipient\",\n verbose_name=\"Recipient\",\n null=True,\n blank=True,\n on_delete=models.SET_NULL,\n )\n recipient_bank_account = models.ForeignKey(\n BankAccount,\n related_name=\"recipient_bank_account\",\n verbose_name=\"Recipient bank account\",\n null=True,\n blank=True,\n on_delete=models.SET_NULL,\n )\n bank_account = models.ManyToManyField(\n BankAccount, blank=True, verbose_name=\"Bank Account\"\n )\n amount = models.FloatField(verbose_name=\"Amount\", default=0, null=True, blank=True)\n status = models.BooleanField(default=True)\n created_at = models.DateTimeField(auto_now_add=True)\n\n def __str__(self) -> str:\n return f\"{self.sender.username} {self.amount} {self.recipient.username}\"\n\n verbose_name = \"Transaction\"\n verbose_name_plural = \"Transactions\"\n","repo_name":"Gogee90/Bank-account","sub_path":"bank_account_app/bank_account/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1852,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"2542521996","text":"import pickle\nfrom pathlib import Path\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import GroupKFold, KFold\nfrom tpcp.optimize import GridSearchCV\nfrom tpcp.validate import cross_validate\n\nimport sleep_analysis.classification.utils.scoring as sc\n\n\ndef nested_cv_optimization(pipe, parameters, algorithm, dataset, dataset_name, modality, group_labels):\n \"\"\"\n In this work, nested cv optimization is used for sleep/wake detection using the real-world sleep dataset containing ecg and imu data\n :input_param: pipe: Pipeline of type OptimizablePipeline of tpcp\n :input_param: parameters: Parameters for hyperparameter search via GridSearch\n :input_param: algorithm: Algorithm to optimize (just needed for name of .csv file)\n :input_param: dataset: Data to optimize with (Datasetclass of IMUDataset/ RealWorldDataset)\n :input_param: dataset_name: Which study to optimize (IMU/ Real-World Actigraphy/ Pretrained)\n :input_param: modality: Which input modalities? Actigraphy/HRV/Respiration/Combination of those\n input_param: group_labels: This parameter prevents inter-subject splitting in cross validation splits\n :returns: nothing - result get saved as csv at the end of the function\n \"\"\"\n cv = GroupKFold(n_splits=5)\n\n gs = GridSearchCV(\n pipe,\n parameters,\n scoring=sc.score,\n cv=cv,\n return_optimized=\"kappa\",\n return_train_score=False,\n n_jobs=-1,\n pre_dispatch=\"n_jobs/1.3\",\n verbose=10,\n )\n results = cross_validate(\n gs,\n dataset=dataset,\n groups=group_labels,\n cv=cv,\n scoring=sc.score,\n return_optimizer=True,\n return_train_score=False,\n propagate_groups=True,\n )\n\n file = open(\n Path(__file__)\n .parents[1]\n .joinpath(\n \"exports/results_per_algorithm/\"\n + algorithm\n + \"/\"\n + algorithm\n + \"_results_\"\n + dataset_name\n + \"_\"\n + modality\n + \".pkl\"\n ),\n \"wb\",\n )\n pickle.dump(results, file)\n\n\ndef hold_out_optimization(\n pipe,\n parameters,\n dataset,\n algorithm,\n dataset_name,\n modality,\n classification_type=\"binary\",\n n_jobs=-1,\n pre_dispatch=\"n_jobs/1.7\",\n):\n cv = KFold(n_splits=5)\n train, test = dataset\n\n # optimization parameter for Grid Search\n optimize_param = \"mcc\"\n\n gs = GridSearchCV(\n pipe,\n parameters,\n scoring=sc.score,\n cv=cv,\n return_optimized=optimize_param,\n return_train_score=False,\n n_jobs=n_jobs,\n pre_dispatch=pre_dispatch,\n verbose=10,\n )\n gs = gs.optimize(train)\n\n # save results of Grid Search to .csv file\n pd.DataFrame(gs.cv_results_).to_csv(\n Path(__file__)\n .parents[3]\n .joinpath(\n \"exports/results_per_algorithm/\"\n + algorithm\n + \"/\"\n + algorithm\n + \"_gridsearch_\"\n + dataset_name\n + \"_\"\n + \"_\".join(modality)\n + \"_\"\n + classification_type\n + \".csv\"\n ),\n index=True,\n )\n\n # save optimized pipeline to .obj file\n optimized_pipeline = gs.optimized_pipeline_\n file = open(\n Path(__file__)\n .parents[3]\n .joinpath(\n \"exports/pickle_pipelines/\"\n + algorithm\n + \"_\"\n + dataset_name\n + \"_\"\n + \"_\".join(modality)\n + \"_\"\n + classification_type\n + \".obj\"\n ),\n \"wb\",\n )\n pickle.dump(optimized_pipeline, file)\n\n final_results = {}\n\n # apply pipeline to each subject in test set and get classification performance\n for subj in test:\n final_results[subj.index[\"mesa_id\"][0]] = sc.score(optimized_pipeline, subj)\n\n # compute confusion matrix for all subjects\n sleep_stage_labels, conf_matrix = _get_sleep_stage_labels(classification_type)\n for subj in final_results.keys():\n conf_matrix += final_results[subj][\"confusion_matrix\"].get_value()\n\n # Save subject-wise results as .csv file\n final_results = pd.DataFrame(final_results)\n final_results.index.name = \"metric\"\n final_results.to_csv(\n Path(__file__)\n .parents[3]\n .joinpath(\n \"exports/results_per_algorithm/\"\n + algorithm\n + \"/\"\n + algorithm\n + \"_\"\n + dataset_name\n + \"_\"\n + \"_\".join(modality)\n + \"_\"\n + classification_type\n + \".csv\"\n ),\n index=True,\n )\n\n # Save confusion matrix as .csv file\n conf_matrix = pd.DataFrame(conf_matrix, index=sleep_stage_labels, columns=sleep_stage_labels)\n pd.DataFrame(conf_matrix).to_csv(\n Path(__file__)\n .parents[3]\n .joinpath(\n \"exports/results_per_algorithm/\"\n + algorithm\n + \"/confusion_matrix_\"\n + algorithm\n + \"_\"\n + dataset_name\n + \"_\"\n + \"_\".join(modality)\n + \"_\"\n + classification_type\n + \".csv\"\n ),\n index=True,\n )\n\n\ndef _get_sleep_stage_labels(classification_type):\n \"\"\"Get sleep stage labels and empty confusion matrix dependent on classification type\"\"\"\n if classification_type == \"binary\":\n return [\"wake\", \"sleep\"], np.zeros((2, 2))\n elif classification_type == \"3stage\":\n return [\"wake\", \"nrem\", \"rem\"], np.zeros((3, 3))\n elif classification_type == \"5stage\":\n return [\"wake\", \"n1\", \"n2\", \"n3\", \"rem\"], np.zeros((5, 5))\n elif classification_type == \"4stage\":\n return [\"wake\", \"light\", \"deep\", \"rem\"], np.zeros((4, 4))\n else:\n raise ValueError(\"Classification type not supported\")\n","repo_name":"mad-lab-fau/sleep_analysis","sub_path":"sleep_analysis/classification/ml_algorithms/ml_pipeline_helper.py","file_name":"ml_pipeline_helper.py","file_ext":"py","file_size_in_byte":5892,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"42201124739","text":"from dbco import *\nimport pprint\nimport json\n\ndef testing():\n\n db.qdoc.find().count\n #print(db.entities.find_one())\n db.qdoc.find().limit(1).skip(1000)\n art = list(db.qdoc.find({'entities': {'$exists': True}}).limit(1).skip(10000))[0]\n print('artobject' + str(art))\n '''\n for entity in art['entities']:\n print entity\n '''\n #print(list(db.entities.find({'_id': 'Q1'})))\n #P31\n\n\n#Adds the type field to all entities\ndef addHumanType():\n #numeric-id is \"human\" (Q5)\n #_id is what the entity actually is\n #wdid refers to \"Instance of\"\n humanCount = 0\n entityLookup = list(db.entities.find({'_id': {'$exists': True}}).limit(100))\n for entity in entityLookup:\n #print(entity)\n properties = entity['properties']\n if ('Instance of' in properties.keys()):\n if (properties['Instance of']['value']['numeric-id'] == 5):\n humanCount += 1\n #print(entity['_id'])\n print(entity)\n #Do the actual update\n #db.entities.update( { \"_id\": entity['_id'] },{\"$set\": {\"type\": 'human' }})\n print('found ' + str(humanCount) + ' humans')\n\ndef qdocEntityLookup():\n \n '''\n wdoc = db.qdoc\n article = wdoc.find_one()\n #pprint.pprint(article)\n for entity in article['entities']:\n print(entity)\n break\n\n entities = db.entities\n entity = entities.find_one()\n #pprint.pprint(article)\n print(entity)\n '''\n \n import pymongo\n '''\n import itertools\n\n fullEdges = []\n limit = {'$limit': 10}\n for d in db.qdoc.aggregate([limit]):\n # print(d['entities'])\n wdids = [ent['wdid'] for ent in d['entities'] if ent['wdid'] is not None]\n thisEdges = list(itertools.combinations(wdids, 2))\n fullEdges.extend(thisEdges)\n print fullEdges\n return\n '''\n\n ARTICLE_LIMIT = 10000\n HUMANS_LIMIT = 1500\n\n limit = {\"$limit\": ARTICLE_LIMIT}\n project = {\"$project\": { \"_id\" : 1, \"entities\" : 1, \"title\" : 1 } }\n unwind = {\"$unwind\": '$entities'}\n lookup = {\n \"$lookup\":\n {\n \"from\": \"entities\",\n \"localField\": \"entities.wdid\",\n \"foreignField\": \"_id\",\n \"as\": \"entity_lookup\"\n }\n }\n fakeUnwind = {\"$unwind\": '$entity_lookup'}\n match = {\"$match\": {\"entity_lookup.type\" : \"human\"}}\n group = {'$group': {'_id': '$entities.wdid', 'articleids' : {'$push': '$_id'}, 'title': {'$first': '$entity_lookup.title'}, 'count': {'$sum': 1}}}\n sort = {'$sort': {'count': -1}}\n humansLimit = {'$limit': HUMANS_LIMIT}\n print(\"Fetching articles with aggregation...\")\n results = list(db.qdoc.aggregate([limit, project, unwind, lookup, fakeUnwind, match, group, sort, humansLimit]))\n print(\"Aggregation complete\")\n\n graphInput = {\"nodes\" : [], \"links\" : []}\n\n numberID = 0\n for entry in results:\n print(entry['count'], entry['title'])\n graphInput['nodes'].append({\"name\" : entry['title'], \"group\" : 0})\n entry['numberID'] = numberID\n entry['articleids'] = set([str(x) for x in entry['articleids']])\n numberID += 1\n\n for i in range(len(results)):\n for j in range(i + 1, len(results)):\n numEdges = len(results[i]['articleids'] & results[j]['articleids'])\n #print(numEdges)\n if (int(numEdges) > 3):\n graphInput['links'].append({\"source\" : results[i]['numberID'], \"target\" : results[j]['numberID'], \"value\" : numEdges})\n\n with open('entities.json', 'w') as fp:\n json.dump(graphInput, fp)\n\n ''' \n return\n output_file = open(\"humans.txt\", \"w\")\n\n #Error found: _id can't be trusted in qdoc, text can probably\n\n titleLookup = {}\n for item in result:\n #print(item)\n articleTitle = item['title']\n entityTitle = item['entity_lookup'][0]['title']\n\n if (articleTitle not in titleLookup):\n titleLookup[articleTitle] = set()\n\n titleLookup[articleTitle].add(entityTitle)\n\n print(\"Processed all articles\")\n \n print(\"Constructing adjacency matrix\")\n adjMatrix = {}\n\n personCount = {}\n\n for title, people in titleLookup.items():\n\n for person in people:\n if (person not in adjMatrix):\n adjMatrix[person] = {}\n for subPerson in people:\n if (subPerson != person):\n if (subPerson not in adjMatrix[person]):\n adjMatrix[person][subPerson] = 1\n else:\n adjMatrix[person][subPerson] = adjMatrix[person][subPerson] + 1\n\n\n\n output_file.write(json.dumps(adjMatrix, encoding=\"utf-8\") + '\\n')\n #match = {\"$match\": {\"timestamp\" : {\"$gt\" : startTime, \"$lt\" : endTime}}}\n #qdocLookup = list(db.qdoc.find({'_id': {'$exists': True}}).limit(100))\n\n idLookup = {}\n for id, entry in enumerate(adjMatrix.keys()):\n idLookup[entry] = id\n #print('id' + str(idLookup))\n\n print(\"Constructing d3 JSON\")\n graphInput = {\"nodes\" : [], \"links\" : []}\n #print(adjMatrix)\n for source, otherEntities in adjMatrix.items():\n graphInput['nodes'].append({\"name\" : source, \"group\" : 0})\n for target in otherEntities:\n graphInput['links'].append({\"source\" : idLookup[source], \"target\" : idLookup[target], \"value\" : adjMatrix[source][target]})\n output_file.close()\n\n with open('entities.json', 'w') as fp:\n json.dump(graphInput, fp)\n '''\nqdocEntityLookup()\n#testing()\n\n'''\nprint(\"Constructing d3 JSON\")\n graphInput = {\"nodes\" : [], \"links\" : []}\n #print(adjMatrix)\n for source, otherEntities in adjMatrix.items():\n added = False\n for target in otherEntities:\n if (adjMatrix[source][target] > 2):\n if (not added):\n graphInput['nodes'].append({\"name\" : source, \"group\" : 0})\n added = True\n graphInput['links'].append({\"source\" : idLookup[source], \"target\" : idLookup[target], \"value\" : adjMatrix[source][target]})\n print('graph' + str(graphInput))\n output_file.close()\n'''","repo_name":"gt-big-data/entity-graph","sub_path":"entities.py","file_name":"entities.py","file_ext":"py","file_size_in_byte":6157,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31077783605","text":"import timeit\nimport random\nimport time\nimport array\nimport numpy as np\n\ndef solution_fabi(my_fun):\n #c = 0\n tmp = my_fun[0]\n\n i = len(my_fun) - 1\n\n my_fun[0] = my_fun[i]\n\n while i > 1:\n my_fun[i] = my_fun[i-1]\n i -= 1\n #c += 2\n my_fun[1] = tmp \n\n #print(c)\n #return my_fun\n\n\ndef solution_luca(my_fun):\n i = 0\n tempA = my_fun[0]\n\n while i < len(my_fun) - 1: \n tempB = my_fun[i+1]\n my_fun[i+1] = tempA\n tempA = tempB\n i += 1\n\n my_fun[0] = tempB\n\n #return(my_fun)\n \n#def bla(arr):\n# i = 0\n#def bla2(arr):\n\n\ndef main():\n \n #print(arr)\n #print(solutionB(arr))\n\n N = 5000000\n\n start = time.time()\n #arr = np.array([random.randint(0,1) for i in range(N)], dtype=\"int\")\n arr = np.random.randint(2, size=N)\n #arr = array.array('i',(random.randint(0,1) for i in range(0,N))) #[random.randint(0,1) for i in range(N)]\n #arrB = copy.copy(arr)\n arrB = np.copy(arr)\n\n print(time.time()- start)\n print(\"Finished init\")\n\n start = time.time()\n solution_fabi(arr)\n print(time.time()- start)\n\n start = time.time()\n solution_luca(arrB)\n print(time.time()- start)\n\n\n #print(timeit.timeit('solution_fabi(arr)', globals=globals()))\n #print(timeit.timeit('solution_luca(arr)', globals=globals()))\n #timeit.Timer(\"solutionA(arr)\", 'gc.enable()', setup=\"from __main__ import test\").timeit(number=10)\n\n #timeit.timeit(, number=100)\n #timeit.timeit(\"solutionB(arr)\", number=100)\n\nif __name__ == \"__main__\":\n main()","repo_name":"thaurturion/Practice","sub_path":"codilit_c2.py","file_name":"codilit_c2.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73200265426","text":"import pandas as pd\nimport numpy as np\nfrom scipy.sparse.csgraph import reverse_cuthill_mckee\nfrom scipy.sparse import csr_matrix\nimport matplotlib.pylab as plt\n\n\ndef logger(label, obj):\n print(f'\\n{\"-\" * 20}\\n{label}:\\n{obj}\\n{\"-\" * 20}\\n')\n\n\ndef plot_band_matrix(square_matrix, square_band_matrix, bandwidth_1, bandwidth_2, save_plot=False):\n \"\"\"\n\n :param square_matrix: Square piece extracted from the original sparse transaction data\n :param square_band_matrix: Resulting band matrix after applying RCM to square matrix\n :param bandwidth_1: Original bandwidth\n :param bandwidth_2: Reduced bandwidth after applying RCM\n :param save_plot: Boolean value for saving the plot of band matrix; before-after\n :return:\n \"\"\"\n f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)\n f.set_figheight(8)\n f.set_figwidth(16)\n f.suptitle(\"Before & After RCM Bandwidth Reduction\")\n\n ax1.spy(square_matrix, marker='.', markersize='2')\n ax1.set_title(\"Original Sparse Data\")\n\n ax2.spy(square_band_matrix, marker='.', markersize='2')\n ax2.set_title(\"Data after RCM\")\n\n if save_plot:\n plt.savefig('./Plots/band_matrix_plot.png')\n plt.show()\n\n print(\"Bandwidth before RCM: \", bandwidth_1)\n print(\"Bandwidth after RCM\", bandwidth_2)\n\n\ndef compute_band_matrix(dataset=None, bm_size=1000, num_sensitive=1, plot=False):\n \"\"\"\n Function for creating the band matrix that will be used for sensitive transaction anonymization process\n\n :param dataset: Original dataset (sparse binary matrix)\n :param bm_size: Edge length of the square matrix (soon to be band-matrix)\n :param num_sensitive: Number of sensitive items\n Since there is no way to know which items are sensitive, we tag a chosen number of them as sensitive\n :param plot:\n :return: band-matrix, item list, sensitive items list\n \"\"\"\n # input : unsymmetric matrix A\n # compute symmetric matrix B = AxA.T\n # sigma = RCM(sigma)\n # A'= permutation sigma applied to A\n # return A'\n random_seed = 42\n\n # TODO: Add a zero padding method for the 'matrix slicing' so we can have bigger matrices then len(items)\n if dataset is not None and len(dataset) >= bm_size:\n # logger('Original df head', dataset.head())\n items = None # FIXME: this should probably go in the if else statements, rather than being global\n # logger('Items', items[:10])\n\n # define a random seed for np.random operations\n # np.random.seed(seed=42)\n\n random_column = None\n random_row = None\n\n # check if we need to add zero filler columns\n if len(dataset.columns) >= bm_size:\n np.random.seed(random_seed)\n items = dataset.columns # FIXME: this may need to be converted to a list explicitly, check if it runs correctly\n # random permutation of rows and columns\n random_column = np.random.permutation(dataset.shape[1])[:bm_size]\n # logger('Random columns', random_column[:10])\n\n random_row = np.random.permutation(dataset.shape[0])[:bm_size]\n # logger('Random rows', random_row[:10])\n\n else:\n np.random.seed(random_seed)\n random_row = np.random.permutation(dataset.shape[0])\n dataset = dataset.iloc[random_row][:bm_size]\n dataset = dataset.reset_index()\n dataset.drop('index', axis=1, inplace=True)\n\n columns = dataset.columns\n\n # fill the gap between the features and wanted dimension size with zeros\n zero_data_to_add = np.zeros(shape=(len(dataset), len(dataset) - len(columns)))\n columns_to_add = [f\"temp_{x}\" for x in range(0, len(dataset) - len(columns))]\n\n df_to_add = pd.DataFrame(zero_data_to_add, columns=columns_to_add, index=dataset.index, dtype='uint8')\n\n # add all prepared filler zeros to dataset\n dataset = pd.concat([dataset, df_to_add], axis=1)\n\n # shuffle rows and cols\n np.random.seed(random_seed)\n items = dataset.columns\n\n random_column = np.random.permutation(dataset.shape[1])\n random_row = np.random.permutation(dataset.shape[0])\n\n dataset.columns = [str(i) for i in range(len(dataset.columns))]\n\n items_reordered = [items[i] for i in random_column]\n\n # cut selected size of square piece from the dataset\n df_square = dataset.iloc[random_row, random_column]\n\n # spy method is for plotting sparsity pattern of 2D arrays\n # TODO: Select sensitive items (columns) before populating the matrix with zeros?\n # select sensitive items\n sensitive_items = df_square.columns[-num_sensitive:]\n # sensitive_items = np.random.choice(df_square.columns, num_sensitive)\n\n # Convert df to sparse matrix format\n sparse = csr_matrix(df_square)\n\n # Compute RCM\n # RCM func assumes the input matrix is not symmetric\n # therefore no need to try to create a symmetric matric beforehand\n # TODO: try out preparing a symmetric input matrix to see if anything changes\n order = reverse_cuthill_mckee(sparse)\n\n\n columns_final_order = [df_square.columns[i] for i in order]\n\n # items_final_order = [items_reordered[i] for i in order]\n items_final_order = [items_reordered[i] for i in order]\n\n # Band matrix\n df_square_band = df_square.iloc[order][columns_final_order]\n\n # Band of the initial dataframe\n [i, j] = np.where(df_square == 1)\n bw1 = max(i - j) + 1\n\n # Band after RCM --> it will be reduced\n [i, j] = np.where(df_square_band == 1)\n bw2 = max(i - j) + 1\n\n if plot:\n plot_band_matrix(df_square, df_square_band, bw1, bw2)\n\n return df_square_band, items_final_order, sensitive_items\n\n\nif __name__ == '__main__':\n df = pd.read_csv('./Dataset/BMS1_table.csv', index_col=False)\n df_square, items, sensitive_items = compute_band_matrix(dataset=df, bm_size=1000, num_sensitive=5)\n logger(\"Band matrix shape\", df_square.shape)\n logger(\"band matrix columns\", df_square.columns)\n\n","repo_name":"ilkayalbayrak/CAHD","sub_path":"band_matrix.py","file_name":"band_matrix.py","file_ext":"py","file_size_in_byte":6145,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70870558865","text":"import asyncio\nimport logging\n\nfrom aiohttp import web\n\nimport tgproxy.errors as errors\n\nDEFAULT_LOGGER_NAME = 'tgproxy.app'\n\n\nclass BaseApp:\n def __init__(self, logger_name=DEFAULT_LOGGER_NAME):\n self.app = web.Application(\n middlewares=[\n self._error_middleware,\n ],\n )\n self._log = logging.getLogger(logger_name)\n\n self.app.add_routes([\n web.get('/ping.html', self._on_ping),\n ])\n\n def _success_response(self, status=200, **kwargs):\n return web.json_response(\n data=dict(\n status='success',\n **kwargs\n ),\n status=status,\n )\n\n def _error_response(self, message, status=500, **kwargs):\n return web.json_response(\n dict(\n status='error',\n message=message or 'Unknown error',\n **kwargs\n ),\n status=status,\n )\n\n @web.middleware\n async def _error_middleware(self, request, handler):\n try:\n response = await handler(request)\n except errors.BaseError as e:\n response = self._error_response(\n message=str(e),\n status=e.http_status,\n )\n\n return response\n\n async def _on_ping(self, request):\n return web.Response(\n text='OK',\n )\n\n\nclass HttpAPI(BaseApp):\n def __init__(self, channels):\n super().__init__()\n\n self.channels = dict(channels)\n self.app.add_routes([\n web.get('/', self._on_index),\n web.get('/{channel_name}', self._on_channel_stat),\n web.post('/{channel_name}', self._on_channel_send),\n ])\n self.app.on_startup.append(self.start_background_channels_tasks)\n self.app.on_shutdown.append(self.stop_background_channels_tasks)\n\n self.background_tasks = list()\n\n async def start_background_channels_tasks(self, app):\n self._log.info('Start background tasks')\n for ch in self.channels.values():\n self.background_tasks.append(\n asyncio.create_task(\n ch.process(),\n name=ch,\n ),\n )\n\n async def stop_background_channels_tasks(self, app):\n self._log.info('Stop background tasks')\n for task in self.background_tasks:\n task.cancel()\n await task\n\n def _get_task_state(self, task):\n if task.cancelled():\n return 'cancelled'\n if task.done():\n return 'done'\n return 'active'\n\n def _has_failed_workers(self):\n return any(map(lambda x: x.cancelled() or x.done(), self.background_tasks))\n\n def _workers(self):\n return {\n task.get_name(): self._get_task_state(task) for task in self.background_tasks\n }\n\n async def _on_ping(self, request):\n if self._has_failed_workers():\n return self._error_response(\n status=502,\n message='Background workers canceled',\n workers=self._workers(),\n )\n\n return self._success_response(\n workers=self._workers(),\n )\n\n async def _on_index(self, request):\n return self._success_response(\n channels={\n name: str(ch) for name, ch in self.channels.items()\n },\n )\n\n def _get_channel(self, request):\n channel_name = request.match_info['channel_name']\n channel = self.channels.get(channel_name)\n if not channel:\n raise errors.ChannelNotFound(f'Channel \"{channel_name}\" not found')\n return channel\n\n async def _on_channel_send(self, request):\n channel = self._get_channel(request)\n message = channel.message_class.from_request(\n await request.post(),\n )\n await channel.put(message)\n return self._success_response(\n status=201,\n request_id=message.request_id,\n )\n\n async def _on_channel_stat(self, request):\n channel = self._get_channel(request)\n return self._success_response(\n **channel.stat(),\n )\n","repo_name":"unhandled-exception/tgproxy","sub_path":"tgproxy/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4207,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"69824925906","text":"import requests\nimport json\n\n\nurl = 'https://github.com/pagopa/template-java-spring-microservice/tree/main/.github/workflows'\nurl_raw = 'https://raw.githubusercontent.com/pagopa/template-java-spring-microservice/main/'\n\nresponse = requests.get(url)\n\nfor item in json.loads(response.text)[\"payload\"][\"tree\"][\"items\"]:\n path = item[\"path\"]\n name = item[\"name\"]\n print(name)\n response = requests.get(url_raw+path)\n fo = open(name, \"w\")\n fo.write(response.text)\n fo.close()\n\n\n","repo_name":"pagopa/pagopa-api-config-selfcare-integration","sub_path":".github/workflows/update_gha.py","file_name":"update_gha.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"38108615154","text":"#!/usr/bin/python\nimport sys\nsys.path.append(\"..\")\nfrom pymcda.electre_tri import ElectreTri\nfrom pymcda.ui.graphic import display_electre_tri_models\nfrom datasets import ticino\nfrom datasets import loulouka\n\nif __name__ == \"__main__\":\n etri = ElectreTri(ticino.c, ticino.cv, ticino.ptb,\n ticino.lbda, ticino.cps)\n etri2 = ElectreTri(loulouka.c, loulouka.cv,\n loulouka.ptb, loulouka.lbda,\n loulouka.cps)\n\n worst_ticino = ticino.pt.get_worst(ticino.c)\n worst_loulouka = loulouka.pt.get_worst(loulouka.c)\n\n best_ticino = ticino.pt.get_best(ticino.c)\n best_loulouka = loulouka.pt.get_best(loulouka.c)\n\n display_electre_tri_models([etri, etri2],\n [worst_ticino, worst_loulouka],\n [best_ticino, best_loulouka])\n","repo_name":"minpegdwende/MRSort-jupyter-notebook","sub_path":"oso-pymcda/tests/test_graphic.py","file_name":"test_graphic.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6868706339","text":"from multiprocessing import Process\n\nfrom balder.exceptions import IllegalVDeviceMappingError\nfrom _balder.balder_session import BalderSession\n\n\ndef test_1_setup_illegal_vdevice_cnn(balder_working_dir):\n \"\"\"\n This testcase executes the basic CALCULATOR example. It maps a device to a vDevice, which requires a connection that\n does not exist in the setup class itself. The VDevice<->Device mapping is also done in the setup.\n\n The test expects the throwing of the ``IllegalVDeviceMappingError`` on COLLECTOR level.\n \"\"\"\n proc = Process(target=processed, args=(balder_working_dir, ))\n proc.start()\n proc.join()\n assert proc.exitcode == 0, \"the process terminates with an error\"\n\n\ndef processed(env_dir):\n print(\"\\n\", flush=True)\n session = BalderSession(cmd_args=[], working_dir=env_dir)\n try:\n session.run()\n print(\"\\n\")\n assert False, \"test session terminates without an error\"\n except IllegalVDeviceMappingError as exc:\n assert exc.args[0] == \"the @for_vdevice connection for vDevice `CalculatorDevice` of feature \" \\\n \"`PyAddProvideANumber` (used in `SetupPythonAdd.NumberProvider1`) uses a connection \" \\\n \"that does not fit with the connection defined in setup class `SetupPythonAdd` to \" \\\n \"related device `Calculator`\"\n\n assert session.executor_tree is None, \"test session does not terminates before collector work was done\"\n","repo_name":"balder-dev/balder","sub_path":"tests/vdevice/test_1_setup_illegal_vdevice_cnn/test_1_setup_illegal_vdevice_cnn.py","file_name":"test_1_setup_illegal_vdevice_cnn.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"5260831407","text":"from datetime import timedelta\nfrom os import getlogin\nfrom flask import Flask, redirect, render_template, request, session\nimport requests\nfrom helpers import getToken, getUserData, getBotCommonGuilds\n\napp = Flask(__name__)\napp.secret_key = \"hi\"\nbot = \"\"\n# app.permanent_session_lifetime = timedelta(seconds=60)\n\ndef getLoginStatus(): \n return False if 'token' not in session else True\n\n@app.route('/')\ndef home():\n if getLoginStatus():\n user_data = getUserData(session['token'])\n data = {\n 'username': f\"{user_data['username']}\",\n 'avatar': f\"https://cdn.discordapp.com/avatars/{user_data['id']}/{user_data['avatar']}.png\"\n }\n session['user_data'] = data\n return render_template(\"home/index.jinja\", data=data)\n else:\n return render_template(\"home/index.jinja\")\n\n@app.route(\"/oauth/discord\")\ndef oauth():\n if 'token' not in session:\n code = request.args.get('code')\n token = getToken(code)\n session[\"token\"] = token\n return redirect('/')\n\n@app.route(\"/dashboard\")\ndef dashboard():\n if getLoginStatus():\n args = request.args\n if 'guild_id' in args:\n guild_state = requests.get(f\"http://127.0.0.1:5001/guild/{args['guild_id']}/state\" )\n guild_custom = requests.get(f\"http://127.0.0.1:5001/guild/{args['guild_id']}/customcommands\")\n guild_timed = requests.get(f\"http://127.0.0.1:5001/guild/{args['guild_id']}/timedmessages\")\n \n guild_state.raise_for_status()\n guild_custom.raise_for_status()\n guild_timed.raise_for_status()\n \n guild = {\n 'state': guild_state.json(),\n 'customcommands': guild_custom.json(),\n 'timedmsgs': guild_timed.json()\n }\n\n return guild\n else:\n global bot\n common_guilds = getBotCommonGuilds(bot_token = bot, user_token = session['token'])\n return render_template(\n \"home/dashboard.jinja\", \n guilds=common_guilds, \n data=session['user_data']\n )\n else:\n return redirect('/')\n\n@app.route(\"/dashboard/{guild_id}\")\ndef guildDashboard(guild_id):\n if getLoginStatus():\n return guild_id\n else:\n return redirect('/')\n\n@app.route(\"/logout\")\ndef logout():\n if getLoginStatus():\n session.pop('token')\n \n return redirect('/')\n\n\nif __name__ == '__main__':\n\tapp.run(debug=True, port=8000)","repo_name":"piyushsatti/nonagon","sub_path":"src/dashboard/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2480,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42596847873","text":"import dataclasses\nfrom typing import Any, Callable, Dict, List, Tuple, Union\nimport tensorflow as tf\nimport tensorflow_probability as tfp\n\n\n@dataclasses.dataclass(frozen=True)\nclass OptimizationMetric:\n \"\"\"Container class for a metric to use as the loss for model optimization.\"\"\"\n name: str\n func: Union[tf.keras.losses.Loss, Callable[..., Any]]\n # How to select the best performing checkpoint for the loss ('max', 'min').\n best_checkpoint_mode: str\n\n @property\n def best_checkpoint_metric(self) -> str:\n return f'val_{self.name}'\n\n\ndef tf_pearson(y_true: tf.Tensor, y_pred: tf.Tensor):\n \"\"\"Returns an implementation of Pearson correlation.\"\"\"\n return tfp.stats.correlation(y_pred, y_true)\n\n\ndef _get_metric_key_name(metrics_dict: Dict[str, float]) -> Tuple[str, str]:\n \"\"\"Returns the key and associated text name to use for eval metrics.\n\n This function is used to identify what metric should be used to assess model\n performance across data folds. It is needed because different model types\n (e.g. TF vs XGBoost) sometimes use different names for the same evaluation\n metric (e.g. the area under the receiver operating characteristic curve is\n called 'auroc' for Keras metrics, but 'auc' for XGBoost).\n\n Args:\n metrics_dict: An example metrics dictionary.\n\n Returns:\n A tuple of the dictionary key that should be used to select the metric of\n interest and the corresponding text name of the metric.\n \"\"\"\n if 'tf_pearson' in metrics_dict:\n # TensorFlow metric for a quantitative phenotype.\n return 'tf_pearson', 'correlation'\n elif 'pearson' in metrics_dict:\n # XGBoost metric for a quantitative phenotype.\n return 'pearson', 'correlation'\n elif 'auroc' in metrics_dict:\n # TensorFlow metric for a binary phenotype.\n return 'auroc', 'AUROC'\n elif 'auc' in metrics_dict:\n # XGBoost metric for a binary phenotype.\n return 'auc', 'AUROC'\n else:\n raise ValueError('Unable to find metric to assess model performance: '\n f'{metrics_dict}')\n\n\ndef acceptable_model_performance(eval_metrics: List[Dict[str, float]]) -> bool:\n \"\"\"Returns True if and only if performance across folds is acceptable.\n\n Args:\n eval_metrics: A list of metrics computed on the eval set for multiple data\n folds. `eval_metrics[i]` contains the metrics for data fold `i`, and each\n fold is expected to contain identical keys.\n\n Returns:\n True if and only if the heuristics for model training being consistent\n across data folds are satisfactorily passed.\n \"\"\"\n key, name = _get_metric_key_name(eval_metrics[0])\n\n values = sorted([d[key] for d in eval_metrics])\n if values[0] <= 0:\n print(f'Some {name}s are non-positive: ', values)\n return False\n\n if values[-1] < 0.05:\n print(f'Weak {name}s of covariates to phenotype: ', values)\n return False\n\n delta = (values[-1] - values[0]) / values[0]\n if delta > 0.1:\n print(f'Performance gap in {name} between folds > 10%: ', values)\n return False\n\n return True\n\n\ndef get_optimization_metric(name: str) -> OptimizationMetric:\n \"\"\"Returns the requested OptimizationMetric.\"\"\"\n try:\n return _OPTIMIZATION_METRIC_REGISTRY[name]\n except KeyError:\n raise ValueError(f'Unsupported optimization metric \"{name}\", must be in: '\n f'{sorted(_OPTIMIZATION_METRIC_REGISTRY.keys())}')\n\n\n_OPTIMIZATION_METRIC_REGISTRY = {\n 'mse':\n OptimizationMetric(\n name='mse',\n func=tf.keras.losses.MeanSquaredError(name='mse'),\n best_checkpoint_mode='min'),\n 'crossentropy':\n OptimizationMetric(\n name='crossentropy',\n func=tf.keras.losses.BinaryCrossentropy(name='crossentropy'),\n best_checkpoint_mode='min'),\n 'tf_pearson':\n OptimizationMetric(\n name='tf_pearson', func=tf_pearson, best_checkpoint_mode='max'),\n}\n","repo_name":"Google-Health/genomics-research","sub_path":"nonlinear-covariate-gwas/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":3865,"program_lang":"python","lang":"en","doc_type":"code","stars":103,"dataset":"github-code","pt":"48"} +{"seq_id":"73197466706","text":"from typing import Optional\r\nfrom ratelimit import limits,RateLimitException,sleep_and_retry\r\nimport requests\r\nfrom fastapi import FastAPI\r\nfrom pydantic import BaseModel\r\nimport random\r\n\r\napp = FastAPI()\r\n\r\n\r\nuserList={}\r\n\r\n\r\n@app.get(\"/signup/\")\r\ndef write_item(user_id:str,pas:str):\r\n if user_id in userList:\r\n return {\"User Already exist\"}\r\n else:\r\n userList.update({user_id:pas})\r\n return{\"Signup successful, 5 attempts left !!\"} \r\n\r\n\r\nONE_MINUTE = 60\r\n@sleep_and_retry\r\n@limits(calls=5, period=ONE_MINUTE)\r\ndef call_api():\r\n try:\r\n response = random.randint(0,100000)\r\n return {\"Random number \" + str(response)}\r\n except RateLimitException as e:\r\n print(e)\r\n return {\"Limit exceed , Wait a minute!\"}\r\n\r\n@app.get(\"/login/\")\r\ndef read_item(user_id:str,pas:str):\r\n # print(userList.get(user_id))\r\n if(userList.get(user_id)==pas):\r\n return call_api()\r\n else:\r\n return{\"user not found\"} ","repo_name":"itsbishwa/backendTask","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16837730757","text":"import paddle\nimport paddle.fluid as fluid\nimport unittest\nfrom paddle.fluid.dygraph import to_variable, guard\nimport numpy as np\nfrom paddle.fluid.framework import _test_eager_guard\n\n\nclass TestImperativeUsingNonZeroGpu(unittest.TestCase):\n def run_main(self, np_arr, place):\n with guard(place):\n var = to_variable(np_arr)\n self.assertTrue(np.array_equal(np_arr, var.numpy()))\n\n def func_non_zero_gpu(self):\n if not fluid.is_compiled_with_cuda():\n return\n\n np_arr = np.random.random([11, 13]).astype('float32')\n if paddle.device.cuda.device_count() > 1:\n # should use non zero gpu if there are more than 1 gpu\n self.run_main(np_arr, fluid.CUDAPlace(1))\n else:\n self.run_main(np_arr, fluid.CUDAPlace(0))\n\n def test_non_zero_gpu(self):\n with _test_eager_guard():\n self.func_non_zero_gpu()\n self.func_non_zero_gpu()\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"EnnSou/ooss-paddle2.3","sub_path":"python/paddle/fluid/tests/unittests/test_imperative_using_non_zero_gpu.py","file_name":"test_imperative_using_non_zero_gpu.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"8018425730","text":"#!/bin/python3\n# Enter your code here. Read input from STDIN. Print output to STDOUT\nfrom itertools import product\n\nif __name__ == \"__main__\":\n K, M = list(map(int, input().split()))\n \n lst = [list(map(int, input().split()))[1:] for _ in range(K)]\n \n xPow2 = lambda x: x**2\n \n lst2 = [list(map(xPow2, i)) for i in lst]\n \n print(max([sum(j) % M for j in product(*lst2)]))\n","repo_name":"Chukwudebelu/HackerRank","sub_path":"Python/Itertools/Maximize_It!/MaximizeIt2.py","file_name":"MaximizeIt2.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"12849474802","text":"import tensorflow as tf\nimport pandas as pd\nimport numpy as np\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.layers.experimental import preprocessing\nimport itertools\nimport pathlib\nimport re\nfrom matplotlib import pyplot as plt\n\nnp.set_printoptions(precision = 3 ,suppress = True)\n\n# download data\nabalone_train = pd.read_csv(\n \"https://storage.googleapis.com/download.tensorflow.org/data/abalone_train.csv\",\n names = [\"Length\" ,\"Diameter\" ,\"Height\" ,\"Whole weight\" ,\"Shucked weight\"\n ,\"Viscera weight\" ,\"Shell weight\" ,\"Age\"]\n)\nprint(abalone_train.head())\nabalone_features = abalone_train.copy()\nabalone_labels = abalone_features.pop('Age')\nabalone_features = np.array(abalone_features)\nprint(abalone_labels)\nprint(abalone_features)\n\n# simple train\nabalone_model = tf.keras.Sequential([\n layers.Dense(64),\n layers.Dense(1)\n])\nabalone_model.compile(\n loss = tf.losses.MeanSquaredError(),\n optimizer = tf.optimizers.Adam()\n)\nabalone_model.fit(\n abalone_features,\n abalone_labels,\n epochs = 10\n)\nnormalize = preprocessing.Normalization()\nprint(\"\\n\\n\\n 0:\\n\")\nprint(abalone_features)\nnormalize.adapt(abalone_features)\nnorm_abalone_model = tf.keras.Sequential([\n normalize,\n layers.Dense(64),\n layers.Dense(1)\n])\nnorm_abalone_model.compile(\n loss = tf.losses.MeanSquaredError(),\n optimizer = tf.optimizers.Adam()\n)\nnorm_abalone_model.fit(\n abalone_features,\n abalone_labels,\n epochs = 10\n)\n\n# predict tatanic survivy\ntitanic = pd.read_csv(\"https://storage.googleapis.com/tf-datasets/titanic/train.csv\")\nprint(titanic.head())\ntitanic_features = titanic.copy()\ntitanic_labels = titanic_features.pop(\"survived\")\ninput = tf.keras.Input(shape =() ,dtype = tf.float32)\nresult = 2 * input + 1\nprint(result)\ncalc = tf.keras.Model(inputs = input ,outputs = result)\nprint(calc(1).numpy())\nprint(calc(2).numpy())\n\ninputs = {}\nfor name ,column in titanic_features.items():\n dtype = column.dtype\n if dtype == object:\n dtype = tf.string\n else:\n dtype = tf.float32\n\n inputs[name] = tf.keras.Input(shape = (1 ,) ,name = name ,dtype = dtype)\nprint(inputs)\nnumeric_inputs = {name:input for name ,input in inputs.items()\n if input.dtype == tf.float32}\nx = layers.Concatenate()(list(numeric_inputs.values()))\nnorm = preprocessing.Normalization()\nnorm.adapt(np.array(titanic[numeric_inputs.keys()]))\nall_numeric_inputs = norm(x)\nprint(all_numeric_inputs)\npreprocessed_inputs = [all_numeric_inputs]\n\nfor name ,input in inputs.items():\n if input.dtype == tf.float32:\n continue\n lookup = preprocessing.StringLookup(vocabulary = np.unique(titanic_features[name]))\n one_hot = preprocessing.CategoryEncoding(max_tokens = lookup.vocab_size())\n\n x= lookup(input)\n x = one_hot(x)\n preprocessed_inputs.append(x)\nprint(preprocessed_inputs)\npreprocessed_inputs_cat = layers.Concatenate()(preprocessed_inputs)\ntitanic_preprocessing = tf.keras.Model(inputs ,preprocessed_inputs_cat)\n\n# draw model layer png\ntf.keras.utils.plot_model(model = titanic_preprocessing ,rankdir = \"LR\" ,dpi = 72 ,show_shapes = True)\n\ntitanic_features_dict = {name : np.array(value) \n for name ,value in titanic_features.items()}\ntitanic_preprocessing(titanic_features_dict)\nfeature_dict = {name:values[:1] for name ,values in titanic_features_dict.items()}\nprint(titanic_preprocessing(feature_dict))\n\ndef titanic_model(preprocessing_head ,inputs):\n body = tf.keras.Sequential([\n layers.Dense(64),\n layers.Dense(1)\n ])\n preprocessed_inputs = preprocessing_head(inputs)\n result = body(preprocessed_inputs)\n model = tf.keras.Model(inputs ,result)\n model.compile(loss = tf.losses.BinaryCrossentropy(from_logits = True),\n optimizer = tf.optimizers.Adam())\n return model\ntitanic_model = titanic_model(titanic_preprocessing ,inputs)\ntitanic_model.fit(\n x = titanic_features_dict,\n y = titanic_labels,\n epochs = 10\n)\ntitanic_model.save('titanic_test')\nreloaded = tf.keras.models.load_model('titanic_test')\nfeature_dict = {name:values[:1] for name ,values in titanic_features_dict.items()}\nbefore = titanic_model(feature_dict)\nafter = reloaded(feature_dict)\nassert(before - after) < 1e-3\nprint(before)\nprint(after)\n\n# in memory data\ndef slices(features):\n for i in itertools.count():\n example = {name:values[i] for name ,values in features.items()}\n yield example\nfor example in slices(titanic_features_dict):\n for name ,value in example.items():\n print(f\"{name:19s}:{value}\")\n break\ntitanic_ds = tf.data.Dataset.from_tensor_slices((titanic_features_dict ,titanic_labels))\ntitanic_batchs = titanic_ds.shuffle(len(titanic_labels)).batch(32)\ntitanic_model.fit(\n titanic_batchs,\n epochs = 5\n)\n\ntitanic_file_path = tf.keras.utils.get_file(\"train.csv\" ,\"https://storage.googleapis.com/tf-datasets/titanic/train.csv\")\ntitanic_csv_ds = tf.data.experimental.make_csv_dataset(\n titanic_file_path,\n batch_size = 5,\n label_name = 'survived',\n num_epochs = 1,\n ignore_errors = True,\n)\nfor batch ,label in titanic_csv_ds.take(1):\n for key ,value in batch.items():\n print(f\"{key:20s}:{value}\")\n print()\n print(f\"{'label':20s}:{label}\")\n\ntraffic_volume_csv_gz = tf.keras.utils.get_file(\n 'Metro_Interstate_Traffic_Volume.csv.gz',\n \"https://archive.ics.uci.edu/ml/machine-learning-databases/00492/Metro_Interstate_Traffic_Volume.csv.gz\",\n cache_dir = '.',\n cache_subdir = 'traffic'\n)\ntraffic_volume_csv_gz_ds = tf.data.experimental.make_csv_dataset(\n traffic_volume_csv_gz,\n batch_size = 256,\n label_name = 'traffic_volume',\n num_epochs = 1,\n compression_type = \"GZIP\"\n)\nfor batch ,label in traffic_volume_csv_gz_ds.take(1):\n for key ,value in batch.items():\n print(f\"{key:20s}:{value[:5]}\")\n print()\n print(f\"{'label':20s}:{label[:5]}\")\nfor i ,(batch ,label) in enumerate(traffic_volume_csv_gz_ds.repeat(20)):\n if i % 40 == 0:\n print('.',end = '')\nprint()\nsnapshot = tf.data.experimental.snapshot('titanic.tfsnap')\nsnapshotting = traffic_volume_csv_gz_ds.apply(snapshot).shuffle(1000)\nfor i ,(batch ,label) in enumerate(snapshotting.shuffle(1000).repeat(20)):\n if i % 40 == 0:\n print('.' ,end='')\nprint()\n\n# multiple character\nfont_zip = tf.keras.utils.get_file(\n 'font.zip',\n \"https://archive.ics.uci.edu/ml/machine-learning-databases/00417/fonts.zip\",\n cache_dir = '.',\n cache_subdir = 'fonts',\n extract = True\n)\nfonts_ds = tf.data.experimental.make_csv_dataset(\n file_pattern = \"fonts/*.csv\",\n batch_size = 10,\n num_epochs = 1,\n num_parallel_reads = 20,\n shuffle_buffer_size = 10000\n)\nfont_csvs = sorted(str(p) for p in pathlib.Path('fonts').glob(\"*.csv\"))\nprint(font_csvs[:10])\nprint(len(font_csvs))\nfor features in fonts_ds.take(1):\n for i ,(name ,value) in enumerate(features.items()):\n if i > 15:\n break\n print(f\"{name:20s}:{value}\")\nprint('...')\nprint(f\"[total: {len(features)} features]\")\n\ndef make_images(features):\n image = [None] * 400\n new_feats = {}\n for name ,value in features.items():\n match = re.match('r(\\d+)c(\\d+)' ,name)\n if match:\n image[int(match.group(1)) * 20 + int(match.group(2))] = value\n else:\n new_feats[name] = value\n image = tf.stack(image ,axis = 0)\n image = tf.reshape(image ,[20 ,20 ,-1])\n new_feats['image'] = image\n return new_feats\nfonts_image_ds = fonts_ds.map(make_images)\nfor features in fonts_image_ds.take(1):\n break\nplt.figure(figsize = (6,6) ,dpi = 120)\nfor n in range(9):\n plt.subplot(3 ,3 , n+1)\n plt.imshow(features['image'][... ,n])\n plt.title(chr(features['m_label'][n]))\n plt.axis('off')\nplt.show()\n\n# basic level functions\ntext = pathlib.Path(titanic_file_path).read_text()\nlines = text.split('\\n')[1:-1]\nall_strings = [str()]*10\nprint(all_strings)\nfeatures = tf.io.decode_csv(lines ,record_defaults = all_strings)\nfor f in features:\n print(f\"type: {f.dtype.name} ,shape:{f.shape}\")\nprint(lines[0])\ntitanic_types = [int() ,str() ,float() ,int() ,int() ,float() ,str() ,str() ,str() ,str()]\nprint(titanic_types)\nfeatures = tf.io.decode_csv(lines ,record_defaults = titanic_types)\nfor f in features:\n print(f\"type:{f.dtype.name}, shape{f.shape}\")\nsimple_titanic = tf.data.experimental.CsvDataset(titanic_file_path ,record_defaults = titanic_types ,header = True)\nfor example in simple_titanic.take(1):\n print([e.numpy() for e in example])\ndef decode_titanic_line(line):\n return tf.io.decode_csv(line ,titanic_types)\nmanual_titanic = (\n tf.data.TextLineDataset(titanic_file_path)\n .skip(1)\n .map(decode_titanic_line)\n)\nfor example in manual_titanic.take(1):\n print([e.numpy() for e in example])\nfont_lines = pathlib.Path(font_csvs[0]).read_text().splitlines()[1]\nprint(font_lines)\nnum_font_features = font_lines.count(',')+1\nfont_column_types = [str() ,str()] + [float()] * (num_font_features - 2)\nprint(font_csvs[0])\nsimple_font_ds = tf.data.experimental.CsvDataset(\n font_csvs,\n record_defaults = font_column_types,\n header = True\n)\nfor row in simple_font_ds.take(10):\n print(row[0].numpy())\nfont_files = tf.data.Dataset.list_files(\"fonts/*.csv\")\nprint('Epoch 1:')\nfor f in list(font_files)[:5]:\n print(\" \",f.numpy())\nprint(' ...')\nprint()\nprint('Epoch 2:')\nfor f in list(font_files)[:5]:\n print(\" \",f.numpy())\nprint(' ...')\nprint()\n\ndef make_font_csv_ds(path):\n return tf.data.experimental.CsvDataset(\n path,\n record_defaults = font_column_types,\n header = True\n )\nfont_rows = font_files.interleave(make_font_csv_ds ,cycle_length = 3)\nfonts_dict = {'font_name':[] ,'character':[]}\nfor row in font_rows.take(10):\n fonts_dict['font_name'].append(row[0].numpy().decode())\n fonts_dict['character'].append(chr(row[2].numpy()))\npd.DataFrame(fonts_dict)\n\nBATCH_SIZE = 2048\nfont_ds = tf.data.experimental.make_csv_dataset(\n file_pattern = \"fonts/*.csv\",\n batch_size = BATCH_SIZE,\n num_epochs = 1,\n num_parallel_reads = 100\n)\nfor i ,batch in enumerate(fonts_ds.take(20)):\n print('.' ,end = '')\nprint()\nfonts_files = tf.data.Dataset.list_files(\"fonts/*.csv\")\nfonts_lines = fonts_files.interleave(\n lambda fname:tf.data.TextLineDataset(fname).skip(1),\n cycle_length = 100\n).batch(BATCH_SIZE)\nfonts_fast = fonts_lines.map(lambda x: tf.io.decode_csv(x ,record_defaults =font_column_types))\nfor i ,batch in enumerate(fonts_fast.take(20)):\n print('.' ,end='')\nprint()\n\nprint(\"\\nInput CVS data done.\\n\")\n","repo_name":"ShiKe-And-His-Friends/ComputerVisionDraft","sub_path":"202101/tf/input_cvs.py","file_name":"input_cvs.py","file_ext":"py","file_size_in_byte":10509,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"25207232517","text":"import os\nimport json \nfrom xml.etree import ElementTree as ET\nimport argparse\n\n\"\"\"\n\nformat config :\n\nconfig:\n pos01.json\n pos02.json \n\n\n\"\"\"\n\n\nmapping = {\n \"anchor\": \"anchors\",\n \"field\": \"fields\"\n}\n\n\ndef read_xml(xml_path):\n \"\"\"_summary_\n\n Args:\n xml_path (_type_): _description_\n\n Returns:\n (list): [\n {\n 'filename': xxx.jpg,\n 'metadata': {\n 'label_1': [[xmin, ymin, xmax, ymax], ...],\n 'label_2': ...\n }\n }\n ]\n \"\"\"\n tree = ET.parse(xml_path)\n root = tree.getroot()\n data = []\n for item in root.iter(\"image\"):\n image_info = {}\n filename = item.attrib['name'] # img_path\n \n metadata = {}\n\n anchor_boxes = []\n fields_boxes = []\n for obj in item.iter('box'):\n label = obj.attrib['label']\n\n for att in obj.iter('attribute'):\n text = att.text\n label = label + \"_\" + text\n if label in mapping:\n label = mapping[label]\n\n xmin = int(float(obj.attrib['xtl']))\n ymin = int(float(obj.attrib['ytl']))\n xmax = int(float(obj.attrib['xbr']))\n ymax = int(float(obj.attrib['ybr']))\n box = [xmin, ymin, xmax, ymax]\n\n if label == 'anchors':\n anchor_boxes.append(box)\n else:\n fields_boxes.append(\n {\n 'box': box,\n 'label': label\n }\n )\n\n\n # box_info = {\n # 'box': box,\n # 'label': \n # }\n \n # if label not in metadata:\n # metadata[label] = [box]\n # else:\n # metadata[label].append(box)\n # labels.append(label)\n\n metadata = {\n 'anchors': anchor_boxes,\n 'fields': fields_boxes\n }\n\n image_info['filename'] = filename\n image_info['metadata'] = metadata\n\n data.append(image_info)\n return data\n\ndef write_json(data, out_path):\n with open(out_path, 'w', encoding='utf8') as f:\n json.dump(data, f)\n\n\n\nclass Converter:\n def __init__(self):\n pass \n \n @staticmethod\n def cvat2json(in_path, out_path, template_dir=None):\n \"\"\"convert cvat output format to json format \n\n image name in cvat should have page number, example: filename_page_1.jpg\n\n json format for one document type belike:\n {\n \"page_1\": {\n \"anchors\": [[xmin, ymin, xmax, ymax], ...]\n \"fields\": ...\n },\n \"page_2\": {\n \"anchors\": [[xmin, ymin, xmax, ymax], ...]\n \"fields\": ...\n }\n } \n --> pos01.json\n\n Args:\n in_path (str): path of .xml file\n out_path (_type_): path of output, .json \n \"\"\"\n assert \".xml\" in in_path and \".json\" in out_path\n\n outdir = os.path.dirname(out_path)\n if not os.path.exists(outdir):\n os.makedirs(outdir)\n\n out_data = {}\n\n data = read_xml(in_path)\n \"\"\" data format \n [\n {\n 'filename': xxx.jpg,\n 'metadata': {\n 'label_1': [[xmin, ymin, xmax, ymax], ...],\n 'label_2': ...\n }\n }\n ]\n \"\"\"\n doc_id = os.path.splitext(os.path.basename(out_path))[0]\n \n for item in data:\n filename = item['filename']\n metadata = item['metadata']\n page_number = int(float(os.path.splitext(filename)[0].split(\"_\")[-1]))\n doc_id_with_page = \"{}_page_{}\".format(doc_id, page_number+1)\n metadata['image_path'] = os.path.join(template_dir, filename)\n out_data[doc_id_with_page] = metadata\n \n\n write_json(out_data, out_path)\n print(\"Done!!!\")\n\n\n def cvat2json_with_fields(in_path, out_path, template_dir=None):\n \"\"\"convert cvat output format to json format \n\n image name in cvat should have page number, example: filename_page_1.jpg\n\n json format for one document type belike:\n {\n \"page_1\": {\n \"anchors\": [[xmin, ymin, xmax, ymax], ...]\n \"fields\": ...\n },\n \"page_2\": {\n \"anchors\": [[xmin, ymin, xmax, ymax], ...]\n \"fields\": ...\n }\n } \n --> pos01.json\n\n Args:\n in_path (str): path of .xml file\n out_path (_type_): path of output, .json \n \"\"\"\n assert \".xml\" in in_path and \".json\" in out_path\n\n outdir = os.path.dirname(out_path)\n if not os.path.exists(outdir):\n os.makedirs(outdir)\n\n out_data = {}\n\n data = read_xml(in_path)\n \"\"\" data format \n [\n {\n 'filename': xxx.jpg,\n 'metadata': {\n 'label_1': [[xmin, ymin, xmax, ymax], ...],\n 'label_2': ...\n }\n }\n ]\n \"\"\"\n doc_id = os.path.splitext(os.path.basename(out_path))[0]\n \n for item in data:\n filename = item['filename']\n metadata = item['metadata']\n page_number = int(float(os.path.splitext(filename)[0].split(\"_\")[-1]))\n doc_id_with_page = \"{}_page_{}\".format(doc_id, page_number+1)\n metadata['image_path'] = os.path.join(template_dir, filename)\n out_data[doc_id_with_page] = metadata\n \n\n write_json(out_data, out_path)\n print(\"Done!!!\")\n\n \n\n \nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--in_path\", type=str, required=True, help=\"in path\")\n parser.add_argument(\"--out_path\", type=str, required=True, help=\"out path\")\n parser.add_argument(\"--template_dir\", type=str, required=True)\n\n args = parser.parse_args()\n converter = Converter()\n converter.cvat2json(\n in_path=args.in_path,\n out_path=args.out_path,\n template_dir=args.template_dir\n )","repo_name":"mrlasdt/template-matching","sub_path":"scripts/convert_format_label.py","file_name":"convert_format_label.py","file_ext":"py","file_size_in_byte":6284,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"19628188805","text":"import functions.image_handler as ih\n\ndef process_data(name, flag):\n untranslated_text = ih.image_to_text(name)\n translated_text = translate(untranslated_text, flag)\n\n return translated_text\n\ndef encode_text(text):\n keywords ={\n '%': '%25',\n \",\": '%2C',\n \"/\": '%5C%2F',\n '?': '%3F',\n ':': \"%3A\",\n ';': '%3B',\n \"[\": '%5B',\n ']': \"%5D\",\n '{': '%7B',\n '}': '%7D', \n '+': '%2B',\n '=': '%3D',\n \"\\\\\": '%5C%5C',\n '|': '%5C%7C',\n '&': '%26',\n '^': '%5E',\n '$': '%24',\n '#': '%23',\n \"@\": '%40'\n }\n\n for keyword in keywords:\n if keyword in text:\n text = text.replace(keyword, keywords[keyword])\n\n return text\n\n\n\ndef translate(text, flag):\n if flag:\n to_language = \"pl\"\n else:\n to_language = \"en\"\n\n return_string = f\"https://www.deepl.com/translator#de/{to_language}/{encode_text(text)}\"\n return return_string","repo_name":"ZetrextJG/Auto-Deutsch","sub_path":"functions/translators.py","file_name":"translators.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25410020922","text":"#RL: An Introduction exercise 7.2\r\n#Comparison of n-step bootstrapping error and sum of TD errors\r\n#random walk env\r\n#Solution by Matt Deible\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.metrics import mean_squared_error\r\nimport math\r\nimport random\r\nimport itertools\r\n\r\nSTATES = 19 #any odd number - 19 was used in the book\r\nINITIAL = (STATES // 2)\r\n\r\noptimal_values = np.zeros(STATES)\r\nfor i in range(INITIAL):\r\n optimal_values[INITIAL - 1 - i] = -(i + 1) / (INITIAL + 1)\r\n optimal_values[INITIAL + 1 + i] = (i + 1) / (INITIAL + 1)\r\n\r\npolicy = lambda S: 1 if random.random() < 0.5 else -1 #policy is random step\r\n\r\n#Experiment parameters\r\n#No discount in this environment\r\n#using sampling of all possible alpha and all n shown in figure 7.2 pg. 145\r\nlearning_rates = [0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1]\r\nn_values = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]\r\n\r\nEPISODES = 10 #same episode count used as in figure 7.2\r\nREPITITIONS = 1000 #REPITITIONS was increased to provide a smoother result\r\n\r\nfor n in n_values:\r\n print(\"Running experiment with n =\", n)\r\n error_difference = []\r\n\r\n for ALPHA in learning_rates:\r\n print(\"Testing alpha =\", ALPHA)\r\n if ALPHA == 0:\r\n error_difference.append(0) #won't learn with alpha = 0\r\n continue\r\n\r\n nstep_avg_rms = 0\r\n TD_avg_rms = 0\r\n\r\n for repetition in range(REPITITIONS):\r\n value = np.zeros(STATES)\r\n TD_value = [np.zeros(STATES + 1)] #need to keep history of value function for TD summation, extra state is value of terminal state = 0\r\n\r\n for episode in range(EPISODES):\r\n TD_value = [TD_value[-1].copy()] #clear TD_value history from last episode\r\n S = [INITIAL]\r\n T = math.inf\r\n for t in itertools.count(): #iterate through timesteps t = 0, 1, 2,...\r\n if t < T:\r\n S.append(S[t] + policy(S[t]))\r\n if S[t + 1] == -1 or S[t + 1] == STATES: T = t + 1 #check if state is terminal\r\n\r\n TAU = t - n + 1\r\n if TAU >= 0:\r\n #first do n-step value updating\r\n if T == math.inf: G = value[S[TAU + n]] #if not at terminal state all rewards are 0 so G is just estimate of state\r\n elif S[-1] == -1: G = -1 #terminal state that causes -1 reward\r\n else: G = 1 #terminal state that causes 1 reward\r\n value[S[TAU]] += ALPHA * (G - value[S[TAU]])\r\n\r\n #now do summation of TD(0) updates\r\n #initialize G with reward if terminal state is reached\r\n if S[-1] == -1: update = -1 #far left got reward of -1\r\n elif S[-1] == STATES: update = 1 #far right got reward of 1\r\n else: update = 0 #if haven't reached terminal state, no rewards recieved\r\n for i in range(min(n, T - TAU)): #now add up all TD(0) updates that would have happened (all other rewards were 0, so they are omitted)\r\n update += TD_value[TAU + i][S[TAU + i + 1]] - TD_value[TAU + i][S[TAU + i]]\r\n\r\n TD_value[t][S[TAU]] += (ALPHA * update) #update current TD_value\r\n TD_value[t][S[TAU]] = sorted([-1, TD_value[t][S[TAU]], 1])[1] #Bound new value estimation by max and min returns\r\n\r\n if TAU == T - 1: break\r\n TD_value.append(TD_value[t].copy()) #save history t - 1\r\n\r\n nstep_avg_rms += math.sqrt(mean_squared_error(optimal_values, value))\r\n TD_avg_rms += math.sqrt(mean_squared_error(optimal_values, TD_value[-1][:-1]))\r\n nstep_avg_rms /= REPITITIONS\r\n TD_avg_rms /= REPITITIONS\r\n\r\n error_difference.append(nstep_avg_rms - TD_avg_rms)\r\n\r\n plt.plot(learning_rates, error_difference)\r\n\r\nplt.title(\"n-step vs TD(0) summation updating\")\r\nplt.legend(n_values, title = \"n value\")\r\n\r\nplt.xlabel('Alpha')\r\nplt.ylabel('RMSE difference (n-step - TD(0))')\r\nplt.show()\r\n","repo_name":"mdeib/RL-intro-programming-solutions","sub_path":"ex7-2/ex7-2.py","file_name":"ex7-2.py","file_ext":"py","file_size_in_byte":4213,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"31850924582","text":"class Node:\n def __init__(self, value, pr):\n self.data = value\n self.pr = pr\n self.next = None\n\n\nclass PriorityQueue:\n def __init__(self, size=5):\n self.size = size\n self.len = 0\n self.size = size\n self.head = None\n self.tail = None\n\n def insert(self, value, pro):\n if self.len <= self.size:\n self.len += 1\n node = Node(value, pro)\n if self.head is None:\n self.head = self.tail = node\n elif self.head.pr < node.pr:\n node.next = self.head\n self.head = node\n elif self.tail.pr > node.pr:\n self.tail.next = node\n self.tail = node\n\n else:\n cur = self.head.next\n prev = self.head\n while cur is not None:\n if cur.pr == node.pr:\n node.next = cur.next\n cur.next = node\n break\n elif cur.pr < node.pr:\n node.next = cur\n prev.next = node\n break\n else:\n prev = cur\n cur = cur.next\n\n\n else:\n print(\"Queue is full!\")\n\n def DEL(self):\n if self.head:\n value = self.head.data\n self.head = self.head.next\n return value\n else:\n print(\"PQ is empty!\")\n\n def __str__(self):\n temp = self.head\n s = \"PQ :\"\n while temp:\n s = s + str(temp.data) + \" \"\n temp = temp.next\n return s\n\n\nlist = PriorityQueue(5)\nprint(\"Enter the operation you want to perform:\")\nprint(\"Enter 1 to insertion\")\nprint(\"Enter 2 to deletion\")\nprint(\"Enter 3 to exit\")\nwhile True:\n option = int(input(\"Enter your choice:\"))\n if option == 1:\n list.insert(int(input(\"Enter the value you want to insert: \")),int(input(\"\\nEnter the priority of the element : \")))\n if option == 2:\n list.DEL()\n if option == 3:\n break\n print(\"\\n\", \" \", list)\n","repo_name":"gourishankerJK/DataStructureGKV","sub_path":"PriorityQueue/PriorityQueue.py","file_name":"PriorityQueue.py","file_ext":"py","file_size_in_byte":2150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19467816239","text":"import json\r\nimport eel\r\n\r\n# Load the JSON data from the file\r\nwith open('all_items.json', 'r', encoding='utf-8') as f:\r\n data = json.load(f)\r\n\r\n# Define a function that returns the items as a list of dictionaries\r\n@eel.expose\r\ndef get_items(rate, volume, price_uah, price_uah_max, price_rub):\r\n items = []\r\n for item in data.values():\r\n rate_value = item.get('rate', 0) # Use 0 as the default value if 'rate' is not present\r\n volume_value = item.get('tm_volume', 0) # Use 0 as the default value if 'tm_volume' is not present\r\n price_uah_value = item.get('sale_price_text_uah', 0)\r\n price_rub_value = item.get('sale_price_text_rub', 0)\r\n name = item['market_hash_name']\r\n \r\n if rate_value is not None and float(rate_value) > float(rate) and volume_value is not None and int(volume_value) > int(volume) and price_uah_value is not None and float(price_uah) < float(price_uah_value) < float(price_uah_max) and price_rub_value is not None and float(price_rub_value) > float(price_rub):\r\n items.append({'name': name, 'price': price_uah_value, 'rate': rate_value, 'tm_volume': volume_value, 'rubprice': price_rub_value})\r\n \r\n return items\r\n\r\n# Start the Eel app\r\neel.init('front')\r\neel.start('index.html', size=(1280, 800))","repo_name":"hewwodarkness/MarketCSGOPriceComparison","sub_path":"tradebackclone.py","file_name":"tradebackclone.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"27737018807","text":"# 1. Написать функцию num_translate(), переводящую числительные от 0 до 10 c английского на русский язык.\n\n# ヽ(ˇヘˇ)ノ\n\ndef num_translate(num, dict):\n print(dict.get(num))\n\nword_book = {\n 'zero': 'ноль',\n 'one': 'один',\n 'two': 'два',\n 'three': 'три',\n 'four': 'четыре',\n 'five': 'пять',\n 'six': 'шесть',\n 'seven': 'семь',\n 'eight': 'восемь',\n 'nine': 'девять',\n 'ten': 'десять'\n}\n\ndigit = input('Ввод пользователя: ')\nnum_translate(digit, word_book)","repo_name":"selfish-skunk/gb_homework","sub_path":"Alferov_Aleksandr_dz_3/task_3_1.py","file_name":"task_3_1.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20665199862","text":"import cv2\nimport numpy as np\nimport pyzbar.pyzbar as pyzbar\n\ndef QR_detect():\n camera = cv2.VideoCapture(0)\n #count = 0\n while True:\n camera.read()\n camera.read()\n camera.read()\n camera.read()#先读取4帧,去除延迟\n (reg,img) = camera.read()\n #cv2.imshow('img_1',img)\n img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n barcodes = pyzbar.decode(img_gray)\n if not barcodes:\n #debug\n #count += 1\n #if count % 100 == 0:\n #print('signal\\n')\n continue\n else:\n print(barcodes)\n for barcode in barcodes:\n (x,y,w,h) = barcode.rect\n cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),2)\n barcodeDate = barcode.data.decode(\"utf-8\")\n #print(barcode.data)\n #print(barcodeDate)\n barcodeType = barcode.type\n text = \"{}({})\".format(barcodeDate,barcodeType)\n cv2.putText(img,text,(x,y-10),cv2.FONT_HERSHEY_SIMPLEX,0.5,(255,0,0),2)\n print(\"[INFO] Found {} barcode: {}\".format(barcodeType,barcodeDate))\n cv2.imshow('img_result',img)\n key_num = cv2.waitKey(0)\n if key_num == ord('q'):\n break\n cv2.destroyAllWindows()\n camera.release()\n cv2.destroyAllWindows()\n \ndef main():\n QR_detect()\nmain()","repo_name":"WindowsXp-Beta/intelligent_transporting_robot","sub_path":"raspberry_pi/颜色识别二维码检测/bar_code.py","file_name":"bar_code.py","file_ext":"py","file_size_in_byte":1433,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"71388610066","text":"## This script creates the quickInstall.js file from\n## the main.js and stylesBase.js files\n## Doesn't work in IDLE...\n\nquickInstall = open('quickInstall.js', 'w')\nmain = open('main.js', 'r')\nbase = open('stylesBase.js', 'r')\nlangSelector = open('langSelector.html', 'r')\n\nquickInstall.write('//*******************stylesBases.js**************\\n\\n' +\n base.read() + '\\n\\n'\n '//*******************main.js*********************\\n\\n' +\n main.read())\n","repo_name":"cdrini/DocsSyntaxHighlighting","sub_path":"Update Quick Install.py","file_name":"Update Quick Install.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13271990414","text":"class DisjointSet:\n def __init__(self, n):\n self.fa = [i for i in range(n)]\n self.count = n\n\n def get(self, x):\n if x == self.fa[x]:\n return x\n self.fa[x] = self.get(self.fa[x])\n return self.fa[x]\n\n def merge(self, x, y):\n if self.get(x) == self.get(y):\n return False\n self.fa[self.get(x)] = self.get(y)\n self.count -= 1\n return True\n\nclass Solution:\n def swimInWater(self, grid: List[List[int]]) -> int:\n N = len(grid)\n ds = DisjointSet(N * N)\n location = {}\n for i in range(N):\n for j in range(N):\n location[grid[i][j]] = i * N + j\n \n t = 0\n directions = [\n (1, 0), (0, 1), (-1, 0), (0, -1)\n ]\n while t <= N * N - 1:\n index = location[t]\n i = index // N\n j = index % N\n for d in directions:\n i1 = i + d[0]\n j1 = j + d[1]\n if i1 >= 0 and i1 < N and j1 >= 0 and j1 < N:\n if grid[i1][j1] <= t:\n ds.merge(\n index, i1 * N + j1\n )\n\n if ds.get(0) == ds.get(N * N - 1):\n return t\n t += 1\n return 0\n \n","repo_name":"maxwang967/kick-start","sub_path":"leetcode/778.py","file_name":"778.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18383827001","text":"from django.urls import path\n\nfrom profiles import views\nfrom profiles import innovation_submission as inno_create\n\napp_name = 'profiles'\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('forms/', views.forms, name='form'),\n path('innovations/create/basic/', inno_create.basic_information, name='inno-create-basic'),\n path('innovations/create//basic/', inno_create.basic_info_edit, name='inno-create-basic-edit'),\n path('innovations/create//documentation/', inno_create.images_and_ref, name='inno-create-doc'),\n path('innovations/create//detailed/', inno_create.detailed_information,\n name='inno-create-detailed'),\n path('innovations/create//persons/', inno_create.persons_info, name='inno-create-persons'),\n\n path('innovations//save-ref/', inno_create.save_innovation_url, name='inno-save-ref'),\n path('innovations//save-image/', inno_create.save_innovation_image, name='inno-save-image'),\n path('innovations//save-contact-person/', inno_create.save_contact_person,\n name='inno-save-contact-person'),\n path('innovations//save-contributor/', inno_create.save_contributor,\n name='inno-save-contributor'),\n]\n","repo_name":"phanuelayuka/ilriipsrdemo","sub_path":"profiles/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35880684455","text":"import django_filters\nfrom marvel_world.models import Comic,Character,Power,Alignment,SkinColor,HairColor,EyeColor,Race,Publisher,Gender\n\n\nclass Marvel_comicFilter(django_filters.FilterSet):\n comic_name = django_filters.CharFilter(\n\t\tfield_name='comic_name',\n\t\tlabel='Comic Name',\n\t\tlookup_expr='icontains'\n\t)\n year = django_filters.CharFilter(\n\t\tfield_name='comic_name',\n\t\tlabel='Year(please enter 4 number as year)',\n\t\tlookup_expr='icontains'\n\t)\n description = django_filters.CharFilter(\n\t\tfield_name='description',\n\t\tlabel='Description',\n\t\tlookup_expr='icontains'\n\t)\n \n\n \n \n\n\t# Add description, heritage_site_category, region, sub_region and intermediate_region filters here\n\n Character= django_filters.ModelChoiceFilter(\n\t\tfield_name='characters',\n\t\tlabel='Character in this Comic',\n queryset=Character.objects.all(),\n\t\tlookup_expr='exact'\n\t)\n class Meta:\n\t model =Comic\n\t fields = []\nclass Marvel_worldFilter(django_filters.FilterSet):\n character_name = django_filters.CharFilter(\n\t\tfield_name='character_name',\n\t\tlabel='Character Name',\n\t\tlookup_expr='icontains'\n\t)\n \n\n \n \n\n\t# Add description, heritage_site_category, region, sub_region and intermediate_region filters here\n\n Power= django_filters.ModelChoiceFilter(\n\t\tfield_name='super_power',\n\t\tlabel='super power',\n\t\tqueryset=Power.objects.all(),\n\t\tlookup_expr='exact'\n\t)\n gender= django_filters.ModelChoiceFilter(\n field_name='gender',\n label='Gender',\n queryset=Gender.objects.all(), \n lookup_expr='exact')\n alignment= django_filters.ModelChoiceFilter(\n field_name='alignment',\n label='Alignment',\n queryset=Alignment.objects.all(), \n lookup_expr='exact')\n skin_color= django_filters.ModelChoiceFilter(\n field_name='skin_color',\n label='Skin Color',\n queryset=SkinColor.objects.all(), \n lookup_expr='exact')\n eye_color= django_filters.ModelChoiceFilter(\n field_name='eye_color',\n label='Eye Color',\n queryset=EyeColor.objects.all(), \n lookup_expr='exact')\n hair_color= django_filters.ModelChoiceFilter(\n field_name='hair_color',\n label='Hair Color',\n queryset=HairColor.objects.all(), \n lookup_expr='exact')\n race= django_filters.ModelChoiceFilter(\n field_name='race',\n label='Race',\n queryset=Race.objects.all(), \n lookup_expr='exact')\n Publisher= django_filters.ModelChoiceFilter(\n field_name='publisher',\n label='Publisher',\n queryset=Publisher.objects.all(), \n lookup_expr='exact')\n weight = django_filters.NumberFilter(\n\t\tfield_name='weight',\n\t\tlabel='Weight(kg)',\n\t\tlookup_expr='exact'\n\t)\n height = django_filters.NumberFilter(\n\t\tfield_name='height',\n\t\tlabel='Height(cm)',\n\t\tlookup_expr='exact'\n\t)\n \n \n\t# Add date_inscribed filter here\n\n\n class Meta:\n\t model =Character\n\t # form = SearchForm\n\t # fields [] is required, even if empty.\n\t fields = []","repo_name":"xiaoranppp/si664-final","sub_path":"marvel_world/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":3010,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11765649677","text":"from flask import request, g, current_app\n\nimport jwt\n\nfrom datetime import timedelta\n\n\ndef decode_session_token(token):\n try:\n return jwt.decode(\n token,\n current_app.config['SECRET_KEY'],\n leeway=timedelta(seconds=10),\n algorithms=['HS256']\n )\n except jwt.ExpiredSignatureError:\n return None\n except jwt.InvalidTokenError:\n return None\n\n\ndef get_current_user():\n session_token = request.headers.get('Authorization')\n\n if session_token:\n # Get the token from the header\n session_token = session_token.replace('Bearer ', '')\n decoded_token = decode_session_token(session_token)\n if decoded_token:\n g.current_user = decoded_token\n\n\ndef has_permission(permission, user=None):\n user = user or g.current_user\n if not user:\n return False\n return user.get('permissions') >= permission\n","repo_name":"Porter97/flask-ai-zappa-boilerplate","sub_path":"app/middlewares/auth_middleware.py","file_name":"auth_middleware.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"8126082361","text":"class Solution:\n def maximizeTheProfit(self, n: int, offers: List[List[int]]) -> int:\n dp = [0] * (n + 1)\n m = [[] for _ in range(n)]\n for s, e, g in offers:\n m[e].append([s,g])\n for e in range(1, n + 1):\n dp[e] = dp[e-1]\n for s, g in m[e-1]:\n dp[e] = max(dp[e], dp[s] + g)\n return dp[-1]","repo_name":"YingbingZhu/python_leetcode","sub_path":"dp/2830. Maximize the Profit as the Salesman .py","file_name":"2830. Maximize the Profit as the Salesman .py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25486193657","text":"if '__file__' in globals():\n import os, sys\n sys.path.append(os.path.join(os.path.dirname(__file__), '..'))\nimport dezero\nimport dezero.functions as F\nfrom dezero import optimizers\nfrom dezero import DataLoader\nfrom dezero.models import MLP\n\n\n\n########イテレーションの確認#############\nclass MyIterator:\n def __init__(self, max_cnt):\n self.max_cnt = max_cnt\n self.cnt = 0\n\n def __iter__(self):\n return self\n \n def __next__(self):\n if self.cnt == self.max_cnt:\n raise StopIteration()\n\n self.cnt += 1\n return self.cnt\n\nobj = MyIterator(5)\nfor x in obj:\n print(f\"iterator test : {x}\")\n######################################\n\nmax_epoch = 300\nbatch_size = 30\nhidden_size = 10\nlr = 1.0\n\n#スパイラルデータセットの読み込み(ここでDataLoader生きる!!)\ntrain_set = dezero.datasets.Spiral(train=True)\ntest_set = dezero.datasets.Spiral(train=False)\ntrain_loader = DataLoader(train_set, batch_size)\ntest_loader = DataLoader(test_set, batch_size, shuffle=False)\n\nmodel = MLP((hidden_size, 3))\noptimizer = optimizers.SGD(lr).setup(model)\n\nfor epoch in range(max_epoch):\n sum_loss, sum_acc = 0, 0\n\n for x, t in train_loader: #訓練用ミニバッチデータ\n y = model(x)\n loss = F.softmax_cross_entropy(y, t)\n acc = F.accuracy(y, t) #訓練データの精度確認\n model.cleargrads()\n loss.backward()\n optimizer.update()\n\n sum_loss += float(loss.data) * len(t)\n sum_acc += float(acc.data) * len(t)\n\n print('epoch: {}'.format(epoch+1))\n print('train loss: {:.4f}, accuracy: {:.4f}'.format(\n sum_loss / len(train_set), sum_acc / len(train_set)))\n\n sum_loss, sum_acc = 0, 0\n with dezero.no_grad(): #勾配不要モード\n for x, t in test_loader: #テスト用のミニバッチデータ\n y = model(x)\n loss = F.softmax_cross_entropy(y, t)\n acc = F.accuracy(y, t) #テストデータの認識精度\n sum_loss += float(loss.data) * len(t)\n sum_acc += float(acc.data) * len(t)\n\n print('test loss: {:.4f}, accuracy: {:.4f}'.format(\n sum_loss / len(test_set), sum_acc / len(test_set)))\n","repo_name":"Ryushiro-sa/Dezero","sub_path":"step50.py","file_name":"step50.py","file_ext":"py","file_size_in_byte":2228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5728245813","text":"#Mainly a simplified copy of HET_obs.py\n#https://github.com/sjanowiecki/HET_observability\n#and the ligo skymaps tutorials\n#https://github.com/gw-odw/odw-2018/tree/master/skymaps\n\nimport healpy as hp # for working with HEALPix files\nimport numpy as np # needed for vector operations\nfrom scipy.stats import norm # probability functions\nfrom astropy.utils.data import download_file\nfrom astropy.io import ascii\nimport argparse\nfrom astropy.table import Table\nfrom astropy.table import Column\nfrom astroquery.vizier import Vizier\nfrom scipy.special import gammaincinv\nfrom astropy.cosmology import WMAP9 as cosmo\nimport astropy.units as u\nimport astropy.constants as c\nimport pandas as pd\nfrom ligo.skymap.distance import conditional_pdf\nimport pdb\nimport matplotlib.pyplot as plt\nimport astropy_healpix as ah\nfrom astropy.table import QTable\nfrom astropy.io import fits\n\nmaxhetdec = 74\nminhetdec = -12\n\ndef parseargs():\n\n class GetLoc(argparse.Action):\n def __init__(self, option_strings, dest, nargs=None, **kwargs):\n if nargs is not None:\n raise ValueError(\"nargs not allowed\")\n super(GetLoc, self).__init__(option_strings, dest, **kwargs)\n def __call__(self, parser, namespace, values, option_string=None):\n url = (values)\n filename = download_file(url, cache=True)\n setattr(namespace, self.dest, filename)\n\n parser = argparse.ArgumentParser(description='FIND GALAXIES TO OBSERVE IN TWO CATALOGS')\n parser.add_argument('--http', dest='fits', default='https://dcc.ligo.org/public/0146/G1701985/001/LALInference_v2.fits.gz', action=GetLoc, help='HTTPS link to LIGO event localization. It will download the file if not cached.')\n parser.add_argument('-cat', dest='cat', default='MANGROVE', help='Specify which catalog to use: MANGROVE or GLADE')\n args = parser.parse_args()\n\n return args\n\ndef cdf(pdf):\n #Calculate contour in probability\n sortedpix = np.argsort(pdf)[::-1]\n cumsum = np.cumsum(pdf[sortedpix])\n cls = np.empty_like(pdf)\n cls[sortedpix] = cumsum*100\n return cls\n\ndef get_cumprob(m):\n \"\"\"\n Uses multi-order sky map to get 90% confidence region indices.\n \"\"\"\n level, ipix = ah.uniq_to_level_ipix(m['UNIQ'])\n pixel_area = ah.nside_to_pixel_area(ah.level_to_nside(level))\n prob = pixel_area * m['PROBDENSITY']\n cumprob = np.cumsum(prob)\n return cumprob\n\ndef get_idx_from_ang(ra, dec, lvls, ipix):\n \"\"\"\n Get uniq IDs for set of theta and phi values.\n \"\"\"\n ra = ra * u.deg\n dec = dec * u.deg\n\n nside = ah.level_to_nside(lvls)\n match_ipix = ah.lonlat_to_healpix(ra, dec, nside, order='nested')\n i = np.flatnonzero(ipix == match_ipix)[0]\n \n return i\n \ndef get_probability_index(\n cat,\n mask_now,\n mask_full,\n cumprob,\n distmu,\n distsigma,\n distnorm,\n pixarea,\n lvls,\n ipix,\n probability\n):\n \n '''\n This will take a pandas-read in csv file, and will return a ordered list of galaxies within that catalog that are ordered by probability map\n '''\n \n dec = np.array(cat['DEJ2000']).astype(float)\n ra = np.array(cat['RAJ2000']).astype(float)\n \n gal_i = np.array([get_idx_from_ang(ra[i], dec[i], lvls, ipix) for i in range(len(ra))])\n gal_cls = cumprob[gal_i]\n \n idx_full = np.isin(gal_i, mask_full)\n mask_full_resized = gal_i[idx_full]\n overlap = np.isin(mask_full_resized, mask_now)\n \n dist = cat['d']\n log_term1 = np.log10(conditional_pdf(dist, distmu[gal_i],distsigma[gal_i],distnorm[gal_i]).tolist())\n log_term2 = np.log10(probability[gal_i])\n logdp_dV = log_term1 + log_term2\n\n # observable by HET in next 24 hours\n ra = ra[idx_full]\n dec = dec[idx_full]\n logdp_dV = logdp_dV[idx_full]\n cls = gal_cls[idx_full]\n \n s_lumK = 10**(-0.4*cat['B'])[idx_full]\n s_lumK = s_lumK/s_lumK.sum()\n #s_lumB = 10**(-0.4*cat1['B_Abs'][cls>90])\n #s_lumB = s_lumB/s_lumB.sum()\n \n #only using K for now\n logdp_dV = np.log10(s_lumK) + logdp_dV\n logdp_dV[np.isnan(logdp_dV)] = -np.inf\n \n \n return ra, dec, logdp_dV, cls, overlap\n\ndef write_catalog(params, savedir=''):\n #fits_f = params['skymap_fits']\n event = params['superevent_id']\n m = params['skymap_array']\n mask_full = params['mask_full']\n mask_now = params['mask_now']\n het_ra_edges = params['het_ra_edges']\n \n \"\"\"\n # Reading in the skymap prob and header\n locinfo, header = hp.read_map(fits, field=range(4), h=True)\n probb, distmu, distsigma, distnorm = locinfo\n \"\"\"\n \n distmu = m['DISTMU'].value\n distsigma = m['DISTSIGMA'].value\n distnorm = m['DISTNORM'].value\n probability = m['PROBDENSITY'].value\n \n level, ipix = ah.uniq_to_level_ipix(m['UNIQ'])\n nside = ah.level_to_nside(level)\n pixarea = ah.nside_to_pixel_area(ah.level_to_nside(level))\n UNIQ = m['UNIQ']\n \n cumprob = get_cumprob(m)\n \n print(\"Beginning CSV read to pandas\")\n #working with list of galaxies visble to HET\n reader = pd.read_csv(\"Glade_HET_Visible_Galaxies.csv\", chunksize=10000, sep=',',usecols = [1,2,3,4,5],names=['RAJ2000','DEJ2000','B','K','d'],header=0,dtype=np.float64)\n #plt.show()\n \n now_idxs = np.array([])\n ra_cat = np.array([])\n dec_cat = np.array([])\n logdp_dV = np.array([])\n cls = np.array([])\n \n for chunk in reader:\n chunk_subset = chunk[(chunk['DEJ2000'] >= minhetdec) & (chunk['DEJ2000'] <= maxhetdec)] # speed stuff up\n if len(chunk_subset) == 0:\n continue\n r_ct, d_ct, l, c, n_subset = get_probability_index(\n chunk_subset,\n mask_now,\n mask_full,\n cumprob,\n distmu,\n distsigma,\n distnorm,\n pixarea,\n level,\n ipix,\n probability\n )\n \n ra_cat = np.append(ra_cat, r_ct)\n dec_cat = np.append(dec_cat, d_ct)\n logdp_dV = np.append(logdp_dV, l)\n cls = np.append(cls, c)\n now_idxs = np.append(now_idxs, n_subset)\n \n # get subset of galaxies visible now\n \n \n #Now working only with event with overall probability 99% lower than the most probable\n print(np.max(logdp_dV))\n top99i = (logdp_dV-np.max(logdp_dV)) > np.log10(1/100)\n\n ra_cat = ra_cat[top99i]\n dec_cat = dec_cat[top99i]\n logdp_dV = logdp_dV[top99i]\n cls = cls[top99i]\n now_idxs = now_idxs[top99i]\n\n #sorting by probability\n isort = np.argsort(logdp_dV)[::-1]\n \n ra_cat = ra_cat[isort]\n dec_cat = dec_cat[isort]\n logptop = logdp_dV[isort]\n cls = cls[isort]\n now_idxs = now_idxs[isort]\n \n index = Column(name='index',data=np.arange(len(ra_cat)))\n ra_col = Column(name='RAJ2000',data=ra_cat)\n dec_col = Column(name='DEJ2000',data=dec_cat)\n logprob = Column(name='LogProb',data=logptop)\n exptime = Column(name='exptime',data=60*20*np.ones(len(ra_cat)))\n contour = Column(name='contour',data = cls)\n Nvis = Column(name='Nvis',data=np.ones(len(ra_cat)))\n \n cattop = Table()\n cattop.add_columns([index,ra_col,dec_col, logprob,exptime,Nvis,contour])\n ascii.write(cattop['index','RAJ2000','DEJ2000','exptime','Nvis','LogProb','contour'], savedir+'HET_Visible_Galaxies_prob_list_full.dat', overwrite=True)\n \n now_idx_vals = np.where(now_idxs)[0]\n cattop_now = cattop[now_idx_vals]\n ascii.write(cattop_now['index','RAJ2000','DEJ2000','exptime','Nvis','LogProb','contour'], savedir+'HET_Visible_Galaxies_prob_list_now.dat', overwrite=True)\n #should find the number of galaxies that will be visible to HET, compared to the number of total galaxies within the region\n num_galaxies_visible_HET = len(index)\n \n #divide this number by the number of galaxies within the region corresponding to the skymap\n \n return cattop,logptop,num_galaxies_visible_HET\n\n\ndef main():\n\n args = parseargs()\n prob, header = hp.read_map(args.fits, h=True)\n header = dict(header)\n params = {'skymap_fits':args.fits,'skymap_array':prob,'GraceID':header['OBJECT']}\n if args.cat == 'MANGROVE' or args.cat == 'GLADE':\n write_catalog(params,args.cat)\n else:\n print('Must specify GLADE or MANGROVE as catalog.')\n\nif __name__== \"__main__\":\n main()\n\n","repo_name":"sky5265/LIGHETR_Alert_System","sub_path":"Final Directory/get_galaxies_MOC.py","file_name":"get_galaxies_MOC.py","file_ext":"py","file_size_in_byte":8775,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6998574095","text":"import sys\nfrom collections import deque\n\nsys.stdin = open(\"input.txt\")\n\n# 상 하 우 좌\ndx = [0, 1, 0, -1]\ndy = [1, 0, -1, 0]\n\ndef iswall(nx,ny): # 벽이 되는 조건\n if nx < 0 or ny < 0: # 좌표가 0 미만이 되는 경우\n return False\n if nx >= N or ny >= M: # 리스트를 넘는 경우\n return False\n return True\n\ndef solution(cnt,cctv_list,ans):\n\n if cnt == cctv_n: # 모든 CCTV 탐색했다면 사각지대 개수 세주기\n count = 0\n for i in range(N):\n for j in range(M):\n if matrix[i][j] ==0 and visited[i][j] == 0:\n count += 1\n return count\n\n x, y, c = cctv_list[cnt][0], cctv_list[cnt][1], cctv_list[cnt][2]\n for k in range(4): # CCTV 의 4방향 확인\n new_dir = []\n if c == 1: # 1번 CCTV : 현재 방향\n new_dir.append(k)\n elif c == 2: # 2번 CCTV : 현재 방향 + 반대 방향\n new_dir.append(k)\n new_dir.append((k + 2) % 4)\n elif c == 3: # 3번 CCTV : 현재 방향 + 왼쪽 90도 방향\n new_dir.append(k)\n new_dir.append((k + 3) % 4)\n elif c == 4: # 4번 CCTV : 현재 방향 + 반대 방향 + 왼쪽 90도 방향\n new_dir.append(k)\n new_dir.append((k + 3) % 4)\n new_dir.append((k + 2) % 4)\n elif c == 5: # 5번 CCTV : 4방향\n new_dir.append(k)\n new_dir.append((k + 3) % 4)\n new_dir.append((k + 1) % 4)\n new_dir.append((k + 2) % 4)\n\n q = deque()\n for d in new_dir: # CCTV 방향 개수 만큼 이동\n nx, ny = x + dx[d], y + dy[d]\n while iswall(nx,ny): # 특정 방향으로 끝까지 이동\n if not visited[nx][ny] and matrix[nx][ny] != 6: # 방문하지 않았으며 벽이 아니면\n visited[nx][ny] = 1# 방문\n q.append((nx, ny))\n elif matrix[nx][ny] == 6: break # 벽이면 중단\n nx += dx[d]\n ny += dy[d]\n # 다음 CCTV 호출\n ans = min(ans, solution(cnt + 1,cctv_list,ans ))\n # 방문했던 곳 되돌려주기\n while q:\n qx, qy = q.popleft()\n if matrix[qx][qy] == 0:\n visited[qx][qy] = False\n # 5번 CCTV 는 회전할 필요 없으므로 바로 break\n if matrix[x][y] == 5: break\n return ans\n\nN,M = map(int,input().split()) # N: row 수 / M: col 수\nmatrix = [list(map(int,input().split())) for _ in range(N)]\nvisited = [[0 for _ in range(M)] for _ in range(N)]# 방문 여부 확인\ncctv_list = [] # CCTV 좌표 리스트\ncctv_n = 0 # 전체 CCTV 개수\nans = 0 # 사각지대\n\nfor i in range(N):\n for j in range(M):\n if 0 < matrix[i][j] < 6: # CCTV 발견하는 경우\n cctv_list.append((i, j,matrix[i][j]))\n visited[i][j] = True\n cctv_n += 1\n if matrix[i][j]== 0: # 사각지대 count --> MAX\n ans += 1\nprint(solution(0,cctv_list,ans))\n","repo_name":"wjddn279/ttt","sub_path":"백준 15683/15683_python.py","file_name":"15683_python.py","file_ext":"py","file_size_in_byte":3034,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25016767071","text":"import librosa\nimport numpy as np\n\ndef compute_Power_Spectrogram(y, parameter):\n #S = librosa.stft(y=y,n_fft=parameter.n_fft, hop_length=parameter.hop_length, win_length=parameter.win_length,\n # window = parameter.window, center = parameter.symmetry)\n #S = (np.abs(S) ** 2)/parameter.n_fft\n #S = 20 * np.log10((abs(S)**2)/parameter.dispRef)\n #S = librosa.amplitude_to_db(S, ref=1)#parameter.n_fft)\n\n S = np.abs(librosa.stft(y=y, n_fft=parameter.n_fft, hop_length=parameter.hop_length, win_length=parameter.win_length,\n window=parameter.window, center=parameter.symmetry))\n P = S ** parameter.power\n\n return P\n\ndef compute_Mel_Spectrum(y, parameter):\n #S = computeSpectrum(y, parameter)\n #M = librosa.feature.melspectrogram(S=S, power = parameter.power, n_mels = parameter.n_mels)\n P = compute_Power_Spectrogram(y, parameter)\n M = librosa.feature.melspectrogram(S=P, n_mels=parameter.n_mels)\n return M\n\ndef compute_MFCC(y, parameter):\n M = compute_Mel_Spectrum(y, parameter)\n M = librosa.power_to_db(M, ref=1.0)\n F = librosa.feature.mfcc(S=M, n_mfcc=parameter.mfccs)\n return F\n\n\ndef compute_Normalized_Log_Spectrogram(y, parameter):\n P = compute_Power_Spectrogram(y, parameter)\n P_db = librosa.power_to_db(P, ref=parameter.n_fft )\n return P_db\n\n","repo_name":"mschoeff/cryRecognition","sub_path":"Computation/Spectral_Features.py","file_name":"Spectral_Features.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7579022446","text":"import torch\r\nimport numpy as np\r\nfrom io import BytesIO\r\nfrom PIL import Image\r\nimport struct, cv2\r\nfrom scipy.io import loadmat\r\nfrom collections import defaultdict\r\ndef read_vbb(path):\r\n assert path[-3:] == 'vbb'\r\n vbb = loadmat(path)\r\n nFrame = int(vbb['A'][0][0][0][0][0])\r\n objLists = vbb['A'][0][0][1][0]\r\n maxObj = int(vbb['A'][0][0][2][0][0])\r\n objInit = vbb['A'][0][0][3][0]\r\n objLbl = [str(v[0]) for v in vbb['A'][0][0][4][0]]\r\n objStr = vbb['A'][0][0][5][0]\r\n objEnd = vbb['A'][0][0][6][0]\r\n objHide = vbb['A'][0][0][7][0]\r\n altered = int(vbb['A'][0][0][8][0][0])\r\n log = vbb['A'][0][0][9][0]\r\n logLen = int(vbb['A'][0][0][10][0][0])\r\n\r\n data = {}\r\n data['nFrame'] = nFrame\r\n data['maxObj'] = maxObj\r\n data['log'] = log.tolist()\r\n data['logLen'] = logLen\r\n data['altered'] = altered\r\n data['frames'] = defaultdict(list)\r\n\r\n for frame_id, obj in enumerate(objLists):\r\n if len(obj) > 0:\r\n for id, pos, occl, lock, posv in zip(obj['id'][0],\r\n obj['pos'][0],\r\n obj['occl'][0],\r\n obj['lock'][0],\r\n obj['posv'][0]):\r\n keys = obj.dtype.names\r\n id = int(id[0][0]) - 1 # MATLAB is 1-origin\r\n p = pos[0].tolist()\r\n pos = [p[0] - 1, p[1] - 1, p[2], p[3]] # MATLAB is 1-origin\r\n occl = int(occl[0][0])\r\n lock = int(lock[0][0])\r\n posv = posv[0].tolist()\r\n\r\n datum = dict(zip(keys, [id, pos, occl, lock, posv]))\r\n datum['lbl'] = str(objLbl[datum['id']])\r\n # MATLAB is 1-origin\r\n datum['str'] = int(objStr[datum['id']]) - 1\r\n # MATLAB is 1-origin\r\n datum['end'] = int(objEnd[datum['id']]) - 1\r\n datum['hide'] = int(objHide[datum['id']])\r\n datum['init'] = int(objInit[datum['id']])\r\n\r\n data['frames'][frame_id].append(datum)\r\n\r\n return data\r\ndef read_seq(path):\r\n def read_header(ifile):\r\n feed = ifile.read(4)\r\n norpix = ifile.read(24)\r\n version = struct.unpack('@i', ifile.read(4))\r\n length = struct.unpack('@i', ifile.read(4))\r\n assert(length != 1024)\r\n descr = ifile.read(512)\r\n params = [struct.unpack('@i', ifile.read(4))[0] for i in range(0,9)]\r\n fps = struct.unpack('@d', ifile.read(8))\r\n # skipping the rest\r\n ifile.read(432)\r\n image_ext = {100:'raw', 102:'jpg',201:'jpg',1:'png',2:'png'}\r\n return {'w':params[0],'h':params[1],\r\n 'bdepth':params[2],\r\n 'ext':image_ext[params[5]],\r\n 'format':params[5],\r\n 'size':params[4],\r\n 'true_size':params[8],\r\n 'num_frames':params[6]}\r\n \r\n ifile = open(path, 'rb')\r\n params = read_header(ifile)\r\n bytes = open(path, 'rb').read()\r\n\r\n # this is freaking magic, but it works\r\n extra = 8\r\n s = 1024\r\n seek = [0]*(params['num_frames']+1)\r\n seek[0] = 1024\r\n \r\n images = []\r\n \r\n for i in range(0, params['num_frames']-1):\r\n tmp = struct.unpack_from('@I', bytes[s:s+4])[0]\r\n s = seek[i] + tmp + extra\r\n if i == 0:\r\n val = struct.unpack_from('@B', bytes[s:s+1])[0]\r\n if val != 0:\r\n s -= 4\r\n else:\r\n extra += 8\r\n s += 8\r\n seek[i+1] = s\r\n nbytes = struct.unpack_from('@i', bytes[s:s+4])[0]\r\n I = bytes[s+4:s+nbytes]\r\n \r\n tmp_file = 'H:\\\\Object_detection\\\\person_vehicle\\\\USA\\\\V000\\\\%d.jpg' % i\r\n open(tmp_file, 'wb+').write(I)\r\n \r\n img = cv2.imread(tmp_file)\r\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\r\n images.append(img)\r\n return images\r\n# img = read_seq(\"H:\\\\Object_detection\\\\person_vehicle\\\\USA\\\\V000.seq\")\r\n# for i in img:\r\n# cv2.imshow(\"1\", i)\r\n# cv2.waitKey(1)\r\ndata = read_vbb(\"H:\\\\Object_detection\\\\person_vehicle\\\\USA\\\\V000.vbb\")\r\nprint(data)","repo_name":"Diep-Xuan-Son/Briefcam_dxson","sub_path":"RENDER_V1/make_dataset.py","file_name":"make_dataset.py","file_ext":"py","file_size_in_byte":4201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41543782815","text":"from math import radians, degrees\r\nfrom sympy import *\r\nimport math\r\n\r\n\r\ndef calculate_initial_compass_bearing(pointA, pointB):\r\n\r\n if (type(pointA) != tuple) or (type(pointB) != tuple):\r\n raise TypeError(\"Only tuples are supported as arguments\")\r\n\r\n lat1 = radians(pointA[0])\r\n lat2 = radians(pointB[0])\r\n\r\n diffLong = radians(pointB[1] - pointA[1])\r\n\r\n x = sin(diffLong) * cos(lat2)\r\n y = cos(lat1) * sin(lat2) - (sin(lat1)\r\n * cos(lat2) * cos(diffLong))\r\n\r\n initial_bearing = atan2(x, y)\r\n\r\n initial_bearing = initial_bearing\r\n #print(\"laasafaf\", initial_bearing)\r\n return initial_bearing\r\n\r\n\r\ndef getPlanes(originalOrientation,height):\r\n\r\n posDrone=Point3D(0,0,height)\r\n #pointX = Point3D(cos(originalOrientation + pi) * cos(giroscope[1]),sin(originalOrientation + pi) * cos(giroscope[1]), height + sin(giroscope[1]))\r\n #pointY=Point3D(cos(originalOrientation+pi/2)*cos(giroscope[0]),sin(originalOrientation+pi/2)*cos(giroscope[0]),height+sin(giroscope[0]))\r\n point1=Point3D(cos(originalOrientation),sin(originalOrientation),0)\r\n point2=Point3D(cos(originalOrientation-pi),sin(originalOrientation-pi),0)\r\n point3=Point3D(cos(originalOrientation+pi/2),sin(originalOrientation+pi/2),0)\r\n point4=Point3D(cos(originalOrientation-pi/2),sin(originalOrientation-pi/2),0)\r\n planeX=Plane(posDrone,point3,point4)\r\n #print(planeX)\r\n planeY=Plane(posDrone,point1,point2)\r\n #print(planeY)\r\n #print(1234)\r\n return(planeX,planeY)\r\n\r\ndef getPlanes2(originalOrientation,height):\r\n\r\n pos=Point3D(0,0,1)\r\n point1=Point3D(1,0,0)\r\n point2=Point3D(-1,0,0)\r\n point3=Point3D(0,1,0)\r\n point4=Point3D(0,-1,0)\r\n planeX=Plane(pos,point3,point4)\r\n #print(planeX)\r\n planeY=Plane(pos,point1,point2)\r\n #print(planeY)\r\n return(planeX,planeY)\r\n\r\n\"\"\"\r\ndef getAngles(originalOrientation,height,objectBearing,objectDistance):\r\n planes=getPlanes(originalOrientation,height)\r\n posDrone=Point3D(0,0,height)\r\n posObject=Point3D(objectDistance*cos(objectBearing),objectDistance*sin(objectBearing),0)\r\n line=Line3D(posDrone,posObject)\r\n angleX=planes[0].angle_between(line).evalf()\r\n angleY=planes[1].angle_between(line).evalf()\r\n return(angleX,angleY)\r\n \r\n\"\"\"\r\n\r\ndef getAngles(originalOrientation,height,objectBearing,objectDistance,gyroscope):\r\n planes=getPlanes2(originalOrientation,height)\r\n #gyroscope[0]= -gyroscope[0]\r\n #gyroscope[1] = -gyroscope[1]\r\n posDrone=Point3D(0,0,0)\r\n print(objectDistance)\r\n print(objectBearing)\r\n if(math.isnan(objectBearing)):\r\n posObject=Point3D(0,0,-height)\r\n else:\r\n posObject=Point3D(objectDistance*sin(objectBearing),objectDistance*cos(objectBearing),-height)\r\n #print(posObject.x.evalf(), posObject.y.evalf(), posObject.z.evalf())\r\n\r\n planeZ=Plane(Point3D(0, 1, -height), Point3D(1, 0, -height), Point3D(0, 0, -height))\r\n\r\n rmatrixX = Matrix([[1, 0, 0, 0], [0, cos(gyroscope[0]), sin(gyroscope[0]), 0],\r\n [0, -sin(gyroscope[0]), cos(gyroscope[0]), 0], [0, 0, 0, 1]])\r\n rmatrixY = Matrix([[cos(gyroscope[1]),0, -sin(gyroscope[1]), 0],[0, 1, 0, 0],\r\n [ sin(gyroscope[1]),0, cos(gyroscope[1]), 0], [0, 0, 0, 1]])\r\n posObjectX = posObject.transform(rmatrixY)\r\n object_line = Line3D(posObjectX, Point3D(0, 0, 0))\r\n posObjectX = object_line.intersection(planeZ)[0]\r\n posObjectY = posObjectX.transform(rmatrixX)\r\n object_line = Line3D(posObjectY, Point3D(0, 0, 0))\r\n posObjectY = object_line.intersection(planeZ)[0]\r\n posObject = Point3D(posObjectY.x * (-height / posObjectY.z), posObjectY.y * (-height / posObjectY.z), -height)\r\n\r\n #print(posObject.x.evalf(),posObject.y.evalf(),posObject.z.evalf())\r\n\r\n rmatrix = Matrix(\r\n [[cos(originalOrientation), sin(originalOrientation), 0, 0], [-sin(originalOrientation), cos(originalOrientation), 0, 0],\r\n [0, 0, 1, 0], [0, 0, 0, 1]])\r\n posObject=posObject.transform(rmatrix)\r\n #print(posObject.x.evalf(), posObject.y.evalf(), posObject.z.evalf())\r\n line=Line3D(posDrone,posObject)\r\n #print(\"lele\",line)\r\n angleX=planes[0].angle_between(line).evalf()\r\n angleY=planes[1].angle_between(line).evalf()\r\n angleX=atan2(-posObject.x,height)\r\n angleY=atan2(posObject.y,height)\r\n return(angleX,angleY)\r\n\r\ndef getObjectCameraAngle(gps1,gps2,cameraOrientation,droneHeight,gyroscope):\r\n #dist=geopy.distance.vincenty(gps1, gps2).m\r\n\r\n dlon = radians(gps2[1]) - radians(gps1[1])\r\n dlat = radians(gps2[0])- radians(gps1[0])\r\n\r\n a = sin(dlat / 2) ** 2 + cos(radians(gps1[0])) * cos(radians(gps2[0])) * sin(dlon / 2) ** 2\r\n c = 2 * atan2(sqrt(a), sqrt(1 - a))\r\n\r\n R = 6372795\r\n dist= R * c\r\n #print(\"distance\", dist)\r\n\r\n objectBearing=calculate_initial_compass_bearing(gps1,gps2)\r\n result=getAngles(cameraOrientation,droneHeight,objectBearing,dist,gyroscope)\r\n return result\r\n\r\n\r\n\r\n\r\ndef getObjectCameraPos(objectAngles,cameraAngle):\r\n #print(\"lala\",objectAngles)\r\n #print(degrees(objectAngles[0]),degrees(objectAngles[1]))\r\n return (-degrees(objectAngles[0])/(cameraAngle[0]/2)*250+250,degrees(objectAngles[1])/(cameraAngle[1]/2)*250+250)\r\n\r\ndef getCanvasPosition(gps1, gps2, cameraOrientation, droneHeight, gyroscope, cameraAngles=(62.2, 48.8)):\r\n objectAngles = getObjectCameraAngle(gps1, gps2, cameraOrientation, droneHeight, gyroscope)\r\n objectCameraPos = getObjectCameraPos(objectAngles, cameraAngles)\r\n return objectCameraPos\r\n\r\n\"\"\"\r\ngps1=(40.6329514, -8.6601084)\r\ngps2=(40.633018987427825, -8.660247457207692)\r\ngps2=(40.632951399875445, -8.659938454039345)\r\ncameraOrientation=0\r\ndroneHeight=20\r\ngyroscope=(-radians(-45), -radians(-0))\r\n\r\ncameraAngles=(62.2, 48.8)\r\nobjectAngles=getObjectCameraAngle(gps1,gps2,cameraOrientation,droneHeight,gyroscope)\r\nobjectCameraPos=getObjectCameraPos(objectAngles,cameraAngles)\r\n#print(objectAngles)\r\nprint(123)\r\nprint(objectCameraPos)\r\n\"\"\"\r\n","repo_name":"dimitri-silva/PiDrone","sub_path":"converter.py","file_name":"converter.py","file_ext":"py","file_size_in_byte":5963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34543953517","text":"\nimport torch \nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass VONet(nn.Module):\n def __init__(self, args, network=0, flowNormFactor=1.0, down_scale=True, config=1, fixflow=True):\n super(VONet, self).__init__()\n\n from VOFlowNet import VOFlowRes as FlowPoseNet\n self.flowPoseNet = FlowPoseNet( down_scale=down_scale)\n \n from backbone.select_backbone import select_resnet\n from backbone.convrnn import ConvGRU\n self.preEncoder, _, _, _, _ = select_resnet('resnet18') \n \n if args.pre_train:\n print('Using the pretrained encoder')\n self.init_weights()\n else:\n print('Training from scratch')\n\n def init_weights(self):\n\n ckpt = torch.load('../../preMM_model/memdpc_zy_rotate_multimodal_zip-128_resnet18_mem1024_bs16_lr0.001_seq4_pred1_len1_ds1_segTrue_depthTrue/epoch600.pth.tar')['state_dict']\n ckpt2 = {}\n for key in ckpt:\n if key.startswith('backbone_rgb'):\n ckpt2[key.replace('backbone_rgb.', '')] = ckpt[key]\n\n self.preEncoder.load_state_dict(ckpt2)\n print('load pretrain success')\n \n def forward(self, x, only_flow=False):\n\n feat1, feat2 = self.preEncoder(x[0].unsqueeze(2)), self.preEncoder(x[1].unsqueeze(2))\n feat1, feat2 = feat1.mean(dim=(2,3,4)), feat2.mean(dim=(2,3,4))\n feat = torch.cat([feat1, feat2], dim=1)\n pose = self.flowPoseNet(feat)\n \n return pose\n\n def get_flow_loss(self, netoutput, target, criterion, mask=None, small_scale=False):\n if self.network == 0: # pwc net\n # netoutput 1/4, 1/8, ..., 1/32 size flow\n if mask is not None:\n return self.flowNet.get_loss_w_mask(netoutput, target, criterion, mask, small_scale=small_scale)\n else:\n return self.flowNet.get_loss(netoutput, target, criterion, small_scale=small_scale)\n else: \n if mask is not None:\n valid_mask = mask<128\n valid_mask = valid_mask.expand(target.shape)\n return criterion(netoutput[valid_mask], target[valid_mask])\n else:\n return criterion(netoutput, target)\n\nif __name__ == '__main__':\n \n voflownet = VONet(network=0, intrinsic=True, flowNormFactor=1.0, down_scale=True, config=1, fixflow=True) # \n voflownet.cuda()\n voflownet.eval()\n print(voflownet)\n import numpy as np\n import matplotlib.pyplot as plt\n import time\n\n x, y = np.ogrid[:448, :640]\n # print x, y, (x+y)\n img = np.repeat((x + y)[..., np.newaxis], 3, 2) / float(512 + 384)\n img = img.astype(np.float32)\n print(img.dtype)\n imgInput = img[np.newaxis,...].transpose(0, 3, 1, 2)\n intrin = imgInput[:,:2,:112,:160].copy()\n\n imgTensor = torch.from_numpy(imgInput)\n intrinTensor = torch.from_numpy(intrin)\n print(imgTensor.shape)\n stime = time.time()\n for k in range(100):\n flow, pose = voflownet((imgTensor.cuda(), imgTensor.cuda(), intrinTensor.cuda()))\n print(flow.data.shape, pose.data.shape)\n print(pose.data.cpu().numpy())\n print(time.time()-stime)\n print((time.time()-stime)/100)\n\n","repo_name":"microsoft/COMPASS","sub_path":"vo/VONet.py","file_name":"VONet.py","file_ext":"py","file_size_in_byte":3218,"program_lang":"python","lang":"en","doc_type":"code","stars":44,"dataset":"github-code","pt":"48"} +{"seq_id":"1138570642","text":"from typing import Final\nfrom pyteal import (\n abi,\n InnerTxn,\n InnerTxnBuilder,\n Int,\n Seq,\n TealType,\n TxnField,\n TxnType,\n)\nfrom beaker import *\nfrom beaker.precompile import AppPrecompile, LSigPrecompile\n\n\nclass LSig(LogicSignature):\n pass\n\n\nclass Child1(Application):\n counter: Final[ApplicationStateValue] = ApplicationStateValue(\n stack_type=TealType.uint64,\n default=Int(0),\n )\n\n @create\n def create(self):\n return Seq(\n self.initialize_application_state(),\n )\n\n @external\n def increment_counter(self, *, output: abi.Uint64):\n \"\"\"Increment the counter global state.\"\"\"\n return Seq(\n self.counter.increment(),\n output.set(self.counter.get()),\n )\n\n\nclass Child2(Application):\n lsig: LSigPrecompile = LSigPrecompile(LSig())\n\n @external(read_only=True)\n def get_lsig_addr(self, *, output: abi.Address):\n return output.set(self.lsig.logic.hash())\n\n\nclass Parent(Application):\n child_1: AppPrecompile = AppPrecompile(Child1())\n child_2: AppPrecompile = AppPrecompile(Child2())\n\n @external\n def create_child_1(self, *, output: abi.Uint64):\n \"\"\"Create a new child app.\"\"\"\n return Seq(\n InnerTxnBuilder.Execute(\n {\n TxnField.type_enum: TxnType.ApplicationCall,\n TxnField.approval_program: self.child_1.approval.binary,\n TxnField.clear_state_program: self.child_1.clear.binary,\n TxnField.global_num_uints: Int(1),\n }\n ),\n output.set(InnerTxn.created_application_id()),\n )\n\n @external\n def create_child_2(self, *, output: abi.Uint64):\n \"\"\"Create a new child app.\"\"\"\n return Seq(\n InnerTxnBuilder.Execute(\n {\n TxnField.type_enum: TxnType.ApplicationCall,\n TxnField.approval_program: self.child_2.approval.binary,\n TxnField.clear_state_program: self.child_2.clear.binary,\n TxnField.global_num_uints: Int(1),\n }\n ),\n output.set(InnerTxn.created_application_id()),\n )\n\n\nclass Grandparent(Application):\n parent: AppPrecompile = AppPrecompile(Parent())\n\n @external\n def create_parent(self, *, output: abi.Uint64):\n \"\"\"Create a new parent app.\"\"\"\n return Seq(\n InnerTxnBuilder.Execute(\n {\n TxnField.type_enum: TxnType.ApplicationCall,\n TxnField.approval_program: self.parent.approval.binary,\n TxnField.clear_state_program: self.parent.clear.binary,\n }\n ),\n output.set(InnerTxn.created_application_id()),\n )\n","repo_name":"cusma/beaker","sub_path":"examples/nested_precompile/nested_application.py","file_name":"nested_application.py","file_ext":"py","file_size_in_byte":2828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"34580206790","text":"from models.Item import Item\n\npotion = Item('Poção simples', Item.TYPE_HEALING, 10, 'Recupera poucos pontos de vida')\nsuperPotion = Item('Poção média', Item.TYPE_HEALING, 20, 'Recupera uma quantidade razoável de vida')\nhyperPotion = Item('Poção avançada', Item.TYPE_HEALING, 50, 'Recupera muitos pontos de vida')\n\nrock = Item('Pedra pequena', Item.TYPE_DAMAGE, 10, 'Inflinge uma pequena quantia de dano')\n\ndataItems = { 'potion' : potion, \n 'superPotion' : superPotion, \n 'hyperPotion' : hyperPotion,\n 'rock' : rock}","repo_name":"thalessahd/mesc","sub_path":"Extra/my_oo_rpg/dataBase/items/items.py","file_name":"items.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38463388495","text":"from typing import Any, MutableMapping\n\nimport pytest\nfrom airbyte_cdk.sources.file_based.config.file_based_stream_config import FileBasedStreamConfig\nfrom source_s3.v4.cursor import Cursor\n\n\n@pytest.mark.parametrize(\n \"input_state, expected_state\",\n [\n pytest.param({}, {\"history\": {}, \"_ab_source_file_last_modified\": None}, id=\"empty-history\"),\n pytest.param(\n {\"history\": {\"2023-08-01\": [\"file1.txt\"]}, \"_ab_source_file_last_modified\": \"2023-08-01T00:00:00Z\"},\n {\n \"history\": {\n \"file1.txt\": \"2023-08-01T00:00:00.000000Z\",\n },\n \"_ab_source_file_last_modified\": \"2023-08-01T00:00:00.000000Z_file1.txt\",\n },\n id=\"single-date-single-file\",\n ),\n pytest.param(\n {\"history\": {\"2023-08-01\": [\"file1.txt\", \"file2.txt\"]}, \"_ab_source_file_last_modified\": \"2023-08-01T00:00:00Z\"},\n {\n \"history\": {\n \"file1.txt\": \"2023-08-01T00:00:00.000000Z\",\n \"file2.txt\": \"2023-08-01T00:00:00.000000Z\",\n },\n \"_ab_source_file_last_modified\": \"2023-08-01T00:00:00.000000Z_file2.txt\",\n },\n id=\"single-date-multiple-files\",\n ),\n pytest.param(\n {\n \"history\": {\n \"2023-08-01\": [\"file1.txt\", \"file2.txt\"],\n \"2023-07-31\": [\"file1.txt\", \"file3.txt\"],\n \"2023-07-30\": [\"file3.txt\"],\n },\n \"_ab_source_file_last_modified\": \"2023-08-01T00:00:00Z\",\n },\n {\n \"history\": {\n \"file1.txt\": \"2023-08-01T00:00:00.000000Z\",\n \"file2.txt\": \"2023-08-01T00:00:00.000000Z\",\n \"file3.txt\": \"2023-07-31T00:00:00.000000Z\",\n },\n \"_ab_source_file_last_modified\": \"2023-08-01T00:00:00.000000Z_file2.txt\",\n },\n id=\"multiple-dates-multiple-files\",\n ),\n ],\n)\ndef test_set_initial_state_with_v3_state(input_state: MutableMapping[str, Any], expected_state: MutableMapping[str, Any]) -> None:\n cursor = Cursor(stream_config=FileBasedStreamConfig(file_type=\"csv\", name=\"test\", validation_policy=\"Emit Records\"))\n cursor.set_initial_state(input_state)\n assert cursor.get_state() == expected_state\n","repo_name":"luisfernandezbr/airbyte","sub_path":"airbyte-integrations/connectors/source-s3/unit_tests/v4/test_cursor.py","file_name":"test_cursor.py","file_ext":"py","file_size_in_byte":2393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"31033425572","text":"from returing.nn_old.operation import Operation\nfrom returing.nn_old.tensor import Tensor\n\nfrom returing.nn_old.operation.base import Sum, BatchElementWiseMul, Add, \\\n GetSubTensor, SetSubTensor, Reshape, Repeat\nfrom returing.nn_old.operation.base.pad import Padding2D\nfrom returing.nn_old.operation.base.slide import Sliding2D\n\nfrom returing.nn_old.utils import safe_read_dict, initialization\n\nimport numpy as np\nnp.random.seed(20170430)\n\n\nclass ConvCore2D(Operation):\n # The basic one-time Convolutional Operation.\n\n def __init__(self, *args, **kwargs):\n super(ConvCore2D, self).__init__()\n self.op_name = 'cross_correlation_2d'\n #self.name = name\n #self.kwargs = kwargs['kwargs']\n\n \"\"\"\n self.input_width = safe_read_dict(self.kwargs, 'input_width', -1)\n self.input_height = safe_read_dict(self.kwargs, 'input_height', -1)\n self.kernel_size = safe_read_dict(self.kwargs, 'kernel_size', -1)\n self.stride = safe_read_dict(self.kwargs, 'stride', -1)\n self.padding = safe_read_dict(self.kwargs, 'padding', -1)\n\n self.W = safe_read_dict(self.kwargs, 'W', None) # weights, [K, K]\n \"\"\"\n\n self.input_width = safe_read_dict(kwargs, 'input_width', -1)\n self.input_height = safe_read_dict(kwargs, 'input_height', -1)\n self.kernel_size = safe_read_dict(kwargs, 'kernel_size', -1)\n self.stride = safe_read_dict(kwargs, 'stride', -1)\n self.padding = safe_read_dict(kwargs, 'padding', -1)\n\n self.W = safe_read_dict(kwargs, 'W', None) # weights, [K, K]\n\n\n def set_weights(self, W):\n # Weights, Kernels, Filters\n assert isinstance(W, Tensor)\n assert W.data.shape == (self.K, self.K)\n\n self.W = W\n\n def forward(self, *args, **kwargs):\n \"\"\"\n # ConvCore2D (Convolution on a 2-D array of X.data, By a kernel W)\n ## Input: X, [n_samples, input_width, input_height],\n ## Output: Y [n_samples, output_width, output_height]\n\n W [K, K], weights of one channel.\n\n padding_X = Padding2D(padding, channel_idx)(X)\n [n_samples, input_width + 2P, input_height + 2P]\n\n Y_ij = Sliding2D(i, j, stride, channel_idx)(padding_X)\n [K, K]\n\n Y = SetSubTensor(i, j)(Y_ij)\n \"\"\"\n\n assert len(args) == 1\n assert isinstance(args[0], Tensor)\n\n X = args[0]\n #assert X.data.shape[1:] == (self.input_width, self.input_height)\n assert isinstance(self.W, Tensor)\n assert isinstance(self.W.data, np.ndarray)\n assert self.W.data.shape == (self.kernel_size, self.kernel_size)\n\n output_width = int((self.input_width - self.kernel_size + 2 * self.padding) \\\n / self.stride + 1)\n output_height = int((self.input_height - self.kernel_size + 2 * self.padding) \\\n / self.stride + 1)\n\n n_samples = X.data.shape[0]\n\n # Y_pred: [n_samples, output_width, output_height]\n Y_pred = Tensor(np.zeros((n_samples, output_width, output_height)))\n\n # X: [n_samples, input_width, input_height]\n # padding_X: [n_samples, input_width+2P, input_weight+2P]\n padding_X = Padding2D(padding=self.padding)(X)\n\n assert padding_X.data.shape == (n_samples,\n self.input_width + 2 * self.padding,\n self.input_height + 2 * self.padding)\n\n for i in range(output_width):\n for j in range(output_height):\n\n # sub_X: [n_samples, K, K]\n sub_X = Sliding2D(\n width_idx=i,\n height_idx=j,\n stride=self.stride,\n kernel_size=self.kernel_size)(padding_X)\n\n assert sub_X.data.shape == (n_samples, self.kernel_size, self.kernel_size)\n\n # sub_X: [n_samples, K, K]\n # W: [K, K]\n # Y_pred_ij: [n_samples, K, K]\n # Rely on Right-align Broadcast of numpy in `ElementWiseMul`.\n Y_pred_ij = BatchElementWiseMul()(sub_X, self.W)\n\n assert Y_pred_ij.data.shape == (n_samples, self.kernel_size, self.kernel_size)\n\n # Y_pred_ij: [n_samples, 1, 1]\n target_shape = (n_samples, 1, 1)\n Y_pred_ij = Sum(axis=(1, 2), target_shape=target_shape)(Y_pred_ij)\n\n assert Y_pred_ij.data.shape == (n_samples, 1, 1)\n\n # Y_pred: [n_samples, output_width, output_height]\n # Y_pred_ij: [n_samples, 1, 1]\n coord_tuple = ((0, n_samples),\n (i, i+1),\n (j, j+1))\n Y_pred = SetSubTensor(coord_tuple)(Y_pred, Y_pred_ij)\n\n assert Y_pred.data.shape == (n_samples, output_width, output_height)\n\n return Y_pred\n\n\nclass Conv2D(Operation):\n def __init__(self, **kwargs):\n super(Conv2D, self).__init__()\n self.op_name = 'conv2d'\n self.name = None\n #self.kwargs = kwargs\n\n self.n_input_channel = safe_read_dict(kwargs, 'n_input_channel', -1)\n self.input_width = safe_read_dict(kwargs, 'input_width', -1)\n self.input_height = safe_read_dict(kwargs, 'input_height', -1)\n self.n_output_channel = safe_read_dict(kwargs, 'n_output_channel', -1)\n self.kernel_size = safe_read_dict(kwargs, 'kernel_size', -1)\n self.stride = safe_read_dict(kwargs, 'stride', -1)\n self.padding = safe_read_dict(kwargs, 'padding', -1)\n\n self.initialization = safe_read_dict(kwargs, 'initialization', None)\n self.is_bias = safe_read_dict(kwargs, 'is_bias', True)\n\n # Initialization\n self.W = initialization.random_init_tensor(\n (self.n_output_channel,\n self.kernel_size,\n self.kernel_size))\n\n if self.is_bias:\n self.b = initialization.random_init_tensor(\n (self.n_output_channel, 1))\n\n def forward(self, *args):\n \"\"\"\n # Dimension Computation Rule\n > output_dim = (N - K + 2P) / S + 1\n > output_dim: output width or height\n > N: input_dim (input width or height)\n > K: filter_size, kernel_size\n > S: stride\n > P: padding\n\n # Input\n X: [n_samples, n_input_channel, input_width, input_height]\n\n # Output\n Y: [n_samples, n_output_channel, output_width, output_height]\n\n # Parameters\n\n W = n_output_channel * (K * K) [n_output_channel, K, K]\n b = n_output_channel * 1 [n_output, 1]\n\n total_n_parameters =\n n_output_channel(n_filters) *\n (kernel_size * kernel_size + 1 if is_bias else 0)\n\n output_width = (input_width - K + 2P) / S + 1\n output_height = (input_height - K + 2P) / S + 1\n\n\n # ===============================Important!!!================================\n # ===== Generated Process\n Y = SetSubTensor(i)([Y_i]),\n i = 0, 1, ..., n_output_channel-1,\n\n Y_i = ListAdd()([ A_j ]) + b_i\n j = 0, 1, ..., n_input_channel-1,\n ListAdd iterate over input channels.\n\n A_j = ConvCore2D ( X_j, W_i ), See Wikipedia for cross-correlation.\n\n # ===== Forward Rule\n\n \"\"\"\n\n assert len(args) == 1\n assert isinstance(args[0], Tensor)\n\n X = args[0] #[n_samples, n_input_channel, input_width, input_height]\n\n self.n_samples = X.data.shape[0]\n\n self.output_width = int((self.input_width - self.kernel_size + 2 * self.padding) \\\n / self.stride + 1)\n self.output_height = int((self.input_height - self.kernel_size + 2 * self.padding) \\\n / self.stride + 1)\n\n # [n_samples, n_output_channel, output_width, output_height]\n Y_pred = Tensor(np.zeros((self.n_samples,\n self.n_output_channel,\n self.output_width,\n self.output_height)), requires_grad=True)\n\n for i in range(self.n_output_channel):\n\n Y_i = Tensor(np.zeros((self.n_samples,\n self.output_width,\n self.output_height)), requires_grad=True)\n\n for j in range(self.n_input_channel):\n # X: [n_samples, n_input_channel, input_width, input_height]\n # X_j: [n_samples, 1, input_width, input_height]\n coord_tuple = ((0, self.n_samples),\n (j, j+1),\n (0, self.input_width),\n (0, self.input_height))\n X_j = GetSubTensor(coord_tuple)(X)\n\n # X_j: [n_samples, 1, input_width, input_height]\n # X_j(Reshaped): [n_samples, input_width, input_height]\n target_shape = (self.n_samples, self.input_width, self.input_height)\n X_j = Reshape(target_shape=target_shape)(X_j)\n\n # W: [n_output_channel, K, K]\n # W_i: [1, K, K]\n coord_tuple = ((i, i+1),\n (0, self.kernel_size),\n (0, self.kernel_size))\n W_i = GetSubTensor(coord_tuple)(self.W)\n\n # W_i: [K, K]\n target_shape = (self.kernel_size, self.kernel_size)\n W_i = Reshape(target_shape=target_shape)(W_i)\n\n assert W_i.data.shape == (self.kernel_size, self.kernel_size)\n\n # A_j: [n_samples, output_width, output_height]\n # W_i: [K, K]\n A_j = ConvCore2D(W=W_i,\n input_width=self.input_width,\n input_height=self.input_height,\n kernel_size=self.kernel_size,\n stride=self.stride,\n padding=self.padding\n )(X_j)\n\n assert A_j.data.shape == (self.n_samples,\n self.output_width,\n self.output_height)\n\n # Y_i: [n_samples, output_width, output_height]\n # A_j: [n_samples, output_width, output_height]\n Y_i = Add()(Y_i, A_j)\n\n \"\"\"\n # Actually, bias can be added in the very end of the \n # output_chanel. \n \n if self.is_bias:\n # b: [n_output_channel, 1]\n # b_i: [1, 1]\n coord_tuple = ((i, i+1),\n (0, 1))\n b_i = GetSubTensor(coord_tuple)(self.b)\n\n # Y_i: [n_samples, output_width, output_height]\n # b_i: [1, 1]\n # Rely on broadcast of numpy in `Add`.\n # Here b_i is [1, 1], `Reshape` is not needed.\n Y_i = Add()(Y_i, b_i)\n \"\"\"\n\n # Y_pred = [n_sample, n_output_channel, output_width, output_height]\n # Y_i: [n_samples, output_width, output_height]\n coord_tuple = ((0, self.n_samples),\n (i, i+1),\n (0, self.output_width),\n (0, self.output_height))\n\n target_shape = (self.n_samples, 1, self.output_width, self.output_height)\n Y_i = Reshape(target_shape=target_shape)(Y_i)\n\n assert Y_i.data.shape == target_shape\n\n Y_pred = SetSubTensor(coord_tuple)(Y_pred, Y_i)\n\n if self.is_bias:\n # Y_pred: [n_samples, n_output_channel, output_width, output_height]\n # b: [n_output_channel, 1]\n\n repeat_time = self.output_width * self.output_height\n target_shape = (self.n_output_channel,\n self.output_width,\n self.output_height)\n\n b = Repeat(repeat_time = repeat_time,\n target_shape = target_shape)(self.b)\n\n assert b.data.shape == (self.n_output_channel,\n self.output_width,\n self.output_height)\n\n # Note: Rely on Broadcast of numpy.\n Y_pred = Add()(Y_pred, b)\n\n assert Y_pred.data.shape == (self.n_samples,\n self.n_output_channel,\n self.output_width,\n self.output_height)\n\n return Y_pred\n","repo_name":"feynmanma7/machine_learning","sub_path":"returing/returing/nn_old/operation/base/conv.py","file_name":"conv.py","file_ext":"py","file_size_in_byte":12634,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"16831199288","text":"import json\n\n\nclass Validator:\n def __init__():\n pass\n\n def validate(fileName):\n try:\n f = open(fileName)\n data = json.load(f)\n f.close()\n\n tasks = data[\"tasks\"]\n days = {\n \"0\": \"Sun\",\n \"1\": \"Mon\",\n \"2\": \"Tue\",\n \"3\": \"Wednes\",\n \"4\": \"Thurs\",\n \"5\": \"Fri\",\n \"6\": \"Satur\",\n \"*\": \"any \",\n }\n months = {\n \"1\": \"January\",\n \"2\": \"February\",\n \"3\": \"March\",\n \"4\": \"April\",\n \"5\": \"May\",\n \"6\": \"June\",\n \"7\": \"July\",\n \"8\": \"August\",\n \"9\": \"September\",\n \"10\": \"October\",\n \"11\": \"November\",\n \"12\": \"December\",\n \"*\": \"any month\",\n }\n\n out = \"\"\n for task in tasks:\n start = task[0].split()\n command = task[1]\n args = task[2]\n preposition = task[3]\n end = task[4].split()\n out += f\"Execute command `{command} {args}` at {start[1].zfill(2) if start[1] != '*' else 'any'}:{start[0].zfill(2) if start[0] != '*' else 'any'}\"\n out += f\" on day {start[2].zfill(2) if start[2] != '*' else 'any'} of {months[start[3]]} if it is {days[start[4]]}day\\n\"\n\n if preposition == \"until\":\n out += f\" Revert command `{command} {args}` at {end[1].zfill(2) if end[1] != '*' else 'any'}:{end[0].zfill(2) if end[0] != '*' else 'any'}\"\n out += f\" on day {end[2].zfill(2) if end[2] != '*' else 'any'} of {months[end[3]]} if it is {days[end[4]]}day\\n\\n\"\n\n # Add custom EOL character to split on in output command\n out += chr(255)\n\n return (\n True,\n \"File is valid. Tasks will run at the following times:\\n\\n\" + out,\n )\n except Exception as e:\n return False, \"File is not valid. See below:\\n\\n\" + str(e)\n","repo_name":"LachlanCourt/rainbowBot","sub_path":"cogs/helpers/_taskValidator.py","file_name":"_taskValidator.py","file_ext":"py","file_size_in_byte":2167,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"9493882719","text":"# Import\r\nimport numpy as np\r\nimport pandas as pd\r\nimport pickle\r\n\r\nfrom tqdm import tqdm\r\nfrom transformers import BertTokenizer\r\nfrom tensorflow.data import Dataset\r\n\r\n# Data needed\r\nwith open('data/data_encoder.obj', 'rb') as f:\r\n Encoder=pickle.load(f)\r\nmax_len= Encoder.max_len\r\n\r\n# Preprocessing data\r\ntokenizer = BertTokenizer.from_pretrained('bert-base-cased')\r\n\r\ndef map_dataset(input_ids, attn_masks, e1_position, e2_position, grammar_relation, shortest_path, labels):\r\n return {\r\n 'input_ids': input_ids,\r\n 'attention_mask': attn_masks,\r\n 'e1_position': e1_position,\r\n 'e2_position': e2_position,\r\n 'grammar_relation': grammar_relation,\r\n 'shortest_path': shortest_path\r\n }, labels\r\n\r\ndef empty_matrix(data, max_len=max_len):\r\n return np.zeros((len(data), max_len))\r\n\r\n# Class for preprocessing data\r\nclass preprocess_data_BERT():\r\n def __init__(self, data, X, y):\r\n self.data = data\r\n self.X = X\r\n self.y = y\r\n \r\n def generate_data(self, ids, masks, tokenizer=tokenizer):\r\n for i, text in tqdm(enumerate(self.data['sentence'])):\r\n tokenized_text = tokenizer.encode_plus(text,\r\n max_length=max_len,\r\n truncation=True,\r\n padding='max_length',\r\n add_special_tokens=True,\r\n return_tensors='tf')\r\n ids[i, :] = tokenized_text.input_ids\r\n masks[i, :] = tokenized_text.attention_mask\r\n ids_data, attn_data = empty_matrix(self.data), empty_matrix(self.data)\r\n ids_data, attn_data = ids, masks\r\n dataset = Dataset.from_tensor_slices((ids_data, attn_data, self.X[1], self.X[2], self.X[3], self.X[4], self.y))\r\n dataset = dataset.map(map_dataset)\r\n dataset = dataset.shuffle(100).batch(16, drop_remainder=True)\r\n return dataset\r\n\r\n","repo_name":"hellofromtheothersky/Relation-extraction","sub_path":"relation_extraction/generate_bert_data.py","file_name":"generate_bert_data.py","file_ext":"py","file_size_in_byte":2047,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"8555807027","text":"#!/usr/bin/python3\nimport hardline \n\n#Just a quick demo test script\n\nif __name__==\"__main__\":\n import argparse\n\n parser = argparse.ArgumentParser(description='P2P Tunneling proxy on the LAN')\n\n\n parser.add_argument('--localport', help='Pages will be proxied at .localhost:. Set to 0 to disable proxying.',default=\"7009\")\n parser.add_argument('--p2pport', help='Port used for secure P2P',default=\"7008\")\n parser.add_argument('--service', help='hostname of a service you want to make available. Requires --certfile',default=\"\")\n parser.add_argument('--serviceport', help='port of a service you want to make available.',default=\"80\")\n parser.add_argument('--certfile', help='Certificate file for publishing a service. Created if nonexistant.',default=\"foo.cert\")\n parser.add_argument('--servicetitle', help='title of a service you want to make available.',default=\"Title here\")\n\n args = vars(parser.parse_args())\n\n print(\"Local port: \"+args['localport'])\n print(\"P2P port: \"+args['p2pport'])\n hardline.P2P_PORT= int(args['p2pport'])\n\n if args['service']:\n print(\"Serving a service from \"+args['service'])\n s = hardline.Service(args['certfile'], args['service'], args['serviceport'], {'title':args['servicetitle']} )\n\n hardline.start(int(args['localport']))\n","repo_name":"EternityForest/hardlinep2p","sub_path":"hardline.py","file_name":"hardline.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"48"} +{"seq_id":"38313832566","text":"def mine_sweeper(grid):\r\n # Create a new grid to store the counts\r\n rows = len(grid)\r\n columns = len(grid[0])\r\n counts = [[0] * columns for _ in range(rows)]\r\n\r\n # Loop over each position in the grid\r\n for i, row in enumerate(grid):\r\n for j, value in enumerate(row):\r\n if value == '#':\r\n # Mark the mine\r\n counts[i][j] = '#'\r\n else:\r\n # Count the adjacent mines\r\n mine_count = 0\r\n for ii in range(max(0, i-1), min(rows, i+2)):\r\n for jj in range(max(0, j-1), min(columns, j+2)):\r\n if (ii, jj) == (i, j):\r\n continue # skip current cell\r\n if grid[ii][jj] == '#':\r\n mine_count += 1\r\n\r\n counts[i][j] = str(mine_count)\r\n\r\n # Create a new array with the same dimensions as the input grid\r\n return [[str(counts[i][j]) if grid[i][j] == '-' else grid[i][j] for j in range(len(row))] for i, row in enumerate(grid)]\r\n\r\n\r\n# sample grid\r\ngrid = [[\"-\", \"-\", \"-\", \"-\", \"#\"],\r\n [\"-\", \"#\", \"-\", \"#\", \"-\"],\r\n [\"-\", \"-\", \"#\", \"-\", \"-\"],\r\n [\"-\", \"#\", \"#\", \"-\", \"-\"],\r\n [\"-\", \"#\", \"-\", \"-\", \"-\"]]\r\nresult = mine_sweeper(grid)\r\nfor row in result:\r\n print(' '.join(row))\r\n","repo_name":"serganzha/projects","sub_path":"minesweeper.py","file_name":"minesweeper.py","file_ext":"py","file_size_in_byte":1342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2687900350","text":"import os\nimport cv2\nimport sys\nimport json\nimport shutil\nfrom tqdm import tqdm\nfrom glob import glob\nimport numpy as np\n\n\nif 0:\n b0 = r'/home/data/lwb/data/20220629'\n b1 = r'/home/data/lwb/data/20220629_fev'\n for dname in tqdm(os.listdir(b0)):\n dir1 = b0 + '/' + dname\n for fname in os.listdir(dir1):\n path1 = dir1 + '/' + fname\n path2 = path1.replace('0629/', '0629_fev/')\n if 'json' in fname:\n ind = path2.rfind('/')\n os.makedirs(path2[:ind], exist_ok=True)\n shutil.copy(path1, path2)\n continue\n path2 = path2.replace('.mp4', '_fev')\n cap = cv2.VideoCapture(path1)\n frames_len = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))\n print(path2, '\\t\\t', frames_len)\n os.makedirs(path2, exist_ok=True)\n for k in tqdm(range(frames_len)):\n ret, img = cap.read()\n if ret:\n save_path = path2 + rf'/{k+1:05d}.jpg'\n try:\n cv2.imwrite(save_path, img)\n except:\n print(f'imwrite error: {save_path}')\n print(f'frames_length: {frames_len}')\n cap.release()\n\n\nif 0:\n b0 = '/home/qwe/data/20220629_bev'\n ds = sorted(os.listdir(b0))\n for dcnt in [10, 5]:\n bn = 'bev2' if dcnt == 10 else 'bev1'\n for k in range(dcnt):\n for d in tqdm(ds):\n b1 = b0 + '/' + d\n l = b1 + '/left_bev'\n r = b1 + '/right_bev'\n os.makedirs(l.replace('20220629_bev', f'{bn}/bev_v{k+1}'))\n os.makedirs(r.replace('20220629_bev', f'{bn}/bev_v{k+1}'))\n src = b1 + '/front.json'\n dst = b1.replace('20220629_bev', f'{bn}/bev_v{k+1}') + '/front.json'\n shutil.copy(src, dst)\n for e in [l, r]:\n fs = sorted(os.listdir(e))\n for i in range(0, len(fs), dcnt):\n i += k\n if i > len(fs)-1: break\n src = e + '/' + fs[i]\n dst = src.replace('20220629_bev', f'{bn}/bev_v{k+1}')\n shutil.copy(src, dst)\n\n\nif 0:\n b = r'D:\\dataset\\fev_bev'\n b1 = b + '/bev_v5'\n b2 = b + '/bev_v5_r'\n for n1 in tqdm(os.listdir(b1)):\n d1 = b1 + '/' + n1\n os.makedirs(d1.replace('v5', 'v5_r'), exist_ok=True)\n os.makedirs(d1.replace('v5', 'json'), exist_ok=True)\n for n2 in os.listdir(d1):\n d2 = d1 + '/' + n2\n if 'json' in d2:\n with open(d2, 'r') as f:\n js1 = json.load(f)\n sensor = []\n for e in js1['sensor_info']:\n e = [float(ele) for ele in e]\n sensor.append(e)\n js1['sensor_info'] = sensor\n sv_js1 = d2.replace('v5', 'v5_r')\n sv_js2 = d2.replace('v5', 'json')\n with open(sv_js1, 'w') as f:\n json.dump(js1, f, indent=4)\n with open(sv_js2, 'w') as f:\n json.dump(js1, f, indent=4)\n else:\n # continue\n os.makedirs(d2.replace('v5', 'v5_r'), exist_ok=True)\n for n3 in os.listdir(d2):\n ip = d2 + '/' + n3\n img = cv2.imread(ip)\n if 'left' in ip:\n img = cv2.flip(img, -1)\n svp = ip.replace('v5', 'v5_r')\n pad = np.zeros([85, 350, 3], np.uint8)\n img = np.concatenate([pad, img, pad], axis=0)\n img = cv2.resize(img, (128, 384), interpolation=cv2.INTER_AREA)\n cv2.imwrite(svp, img)\n\n\n\n","repo_name":"huapohen/general_parking_slot_detection","sub_path":"dataset/tools/ds_0629.py","file_name":"ds_0629.py","file_ext":"py","file_size_in_byte":3860,"program_lang":"python","lang":"en","doc_type":"code","stars":46,"dataset":"github-code","pt":"48"} +{"seq_id":"72325799185","text":"import torch\r\nimport torch.nn as nn\r\nfrom Dropout_new import DropPath\r\nfrom functools import partial\r\n\r\n#定义一个模型初始的Patch Embedding\r\nclass Patch_Embedding(nn.Module):\r\n def __init__(self, img_size=224, patch_size=16, in_channel=3, embed_dim=768, norm_Layer=None):\r\n super().__init__()\r\n img_size = (img_size,img_size)\r\n patch_size = (patch_size,patch_size)\r\n stride = patch_size\r\n self.img_size = img_size\r\n self.patch_size = patch_size\r\n self.grid_size = (img_size[0] // patch_size[0], img_size[1] // patch_size[1])\r\n self.num_patches = self.grid_size[0] * self.grid_size[1]\r\n #第一步为完成Patch Embedding的映射从224*224*3通过卷积操作到14*14*768,相当于映射\r\n self.proj = nn.Conv2d(in_channel,embed_dim,stride=stride,kernel_size=patch_size)\r\n #第二步Flatten展开操作,直接使用flatten函数\r\n #第三步进行归一化结束,为下面的一个额外添加的分类的class token准备.\r\n self.norm = norm_Layer(embed_dim) if norm_Layer else nn.Identity()\r\n\r\n def forward(self,x):\r\n B,C,H,W = x.shape#(B--Batchsize--也就是一次处理多少张图像,C--RGB图像--3,H,W--图像高,宽(224,224)\r\n x = self.proj(x)#(B, C--768, H--14,W--14)其中的14可以通过卷积计算公式可得\r\n x = x.flatten(2)#展开HW完成合并操作(B, C, HW)\r\n x = x.transpose(1,2)#换个位置(B,HW,C)为了后面的注意力机制的计算\r\n x = self.norm(x)#对x进行归一化(B,HW,C)---(B,num_patches,C)---(B,196,768)\r\n #至此Patch_Embedding结束\r\n return x\r\n\r\n\r\n\r\nclass Attention_Score(nn.Module):\r\n def __init__(self,\r\n dim,#数据总维度\r\n num_heads=8,#注意力头数,通俗来说就是将X到W(注意力里的权重)到q之后直接划分成几个小q就是几头注意力\r\n qkv_bias=False,#进行线性投影时候的偏置\r\n attn_drop_ratio=0.,#Dropout的失效率,一种有效的正则化和防止神经元共同适应的办法\r\n proj_drop_ratio=0.,\r\n qk_scale=None):\r\n super(Attention_Score,self).__init__()\r\n self.num_heads = num_heads\r\n head_dim = dim//num_heads\r\n self.scale = qk_scale or head_dim**-0.5\r\n self.qkv = nn.Linear(dim, 3*dim, bias=qkv_bias)\r\n self.attn_drop = nn.Dropout(attn_drop_ratio)\r\n self.proj = nn.Linear(dim, dim)\r\n self.proj_drop = nn.Dropout(proj_drop_ratio)\r\n\r\n def forward(self,x):\r\n B, N, C = x.shape#经过外添加的分类的class token后,num_patches+1--(B,num_patches+1,C)--(B,197,768)\r\n x = self.qkv(x)#准备从x中映射出三个QKV出来(B,3*(num_patches+1),C)--(B,3*197,768)\r\n x = x.reshape(B, N, 3, self.num_heads, C//self.num_heads)#重新建立结构(B,197,3,8,96)\r\n qkv = x.permute(2, 0, 3, 1, 4)#(3,B,8,197,96)\r\n q, k, v = qkv[0], qkv[1], qkv[2] #x中映射出三个QKV\r\n\r\n #注意力计算公式操作\r\n attn = (q @ k.transpose(-2,-1)) * self.scale#(B,8,197,96)*(B,8,96,197)=(B,8,197,197)\r\n #这里就可以看出为什么之前要换位置,因为我们多维相乘,我们只进行最后两维,因此我们将num_heads=8,放在倒数第三列\r\n #这样也能保证不同的head之间不会进行交叉计算,保证稳定\r\n attn = attn.softmax(dim=-1)#最后一维其中 就是按行进行softmax--(B,8,197,197)\r\n attn = self.attn_drop(attn)#(B,8,197,197)\r\n\r\n x = (attn @ v)#继续计算(B,8,197,197)*(B,8,197,96)=(B,8,197,96)\r\n x = x.transpose(1, 2)#1,2维换个位置(B,197,8,96)\r\n x = x.reshape(B, N, C)#重新变回x初始样子--(B,197,768)\r\n x = self.proj(x)#在进行一次线性映射--(B,197,768)\r\n x = self.proj_drop(x)#Dropout有效的正则化和防止神经元共同适应\r\n return x\r\n\r\n\r\nclass Mlp(nn.Module):\r\n def __init__(self, in_feature, hidden_features=None, out_features=None, act_layer=nn.GELU,drop=0.):\r\n super().__init__()\r\n self.fc1 = nn.Linear(in_feature,hidden_features)\r\n self.act = act_layer()\r\n self.fc2 = nn.Linear(hidden_features,out_features)\r\n self.drop = nn.Dropout(drop)\r\n#定义一个熟悉的Mlp结果\r\n def forward(self,x):\r\n x = self.fc1(x)\r\n x = self.act(x)\r\n x = self.drop(x)\r\n x = self.fc2(x)\r\n x = self.drop(x)\r\n return x\r\n\r\nclass Vision_Transformer_Block(nn.Module):\r\n def __init__(self,\r\n dim, # 数据总维度\r\n num_heads=8, # 注意力头数,通俗来说就是将X到W(注意力里的权重)到q之后直接划分成几个小q就是几头注意力\r\n qkv_bias=False, # 进行线性投影时候的偏置\r\n qk_scale=None,\r\n drop_ratio=0.,#注意力计算模块中的Dropout的失效率--后\r\n attn_drop_ratio=0., # #注意力计算模块中的Dropout的失效率--前\r\n Dropout_ratio=0.,\r\n mlp_ratio=4,\r\n act_layer=nn.GELU,\r\n norm_layer=nn.Linear):\r\n super(Vision_Transformer_Block,self).__init__()\r\n self.norm1 = norm_layer(dim)\r\n self.attn = Attention_Score(\r\n dim,#数据总维度\r\n num_heads=num_heads,#注意力头数,通俗来说就是将X到W(注意力里的权重)到q之后直接划分成几个小q就是几头注意力\r\n qkv_bias=qkv_bias,#进行线性投影时候的偏置\r\n attn_drop_ratio=attn_drop_ratio,#Dropout的失效率,一种有效的正则化和防止神经元共同适应的办法\r\n proj_drop_ratio=drop_ratio,\r\n qk_scale =qk_scale)\r\n # 作者说这里用这个nn.dropout效果要好,虽然这里并没有使用Dropout_ratio=0.,可以进行对比实验\r\n self.drop_path = DropPath(Dropout_ratio) if Dropout_ratio else nn.Identity()\r\n self.norm2 = norm_layer(dim)\r\n mlp_hidden_features = int(dim * mlp_ratio)#中间的hidden_features设计为4*dim\r\n self.Mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_features, act_layer=act_layer, drop=drop_ratio)\r\n\r\n def forward(self, x):\r\n x = self.drop_path(self.attn(self.norm1(x))) + x#残差连接\r\n x = self.drop_path(self.mlp(self.norm2(x)))+ x\r\n return x\r\n\r\n\r\nclass Vision_Transformer(nn.Module):\r\n def __init__(self, img_size=224, patch_size=16, in_channel=3, num_classes=1000,\r\n embed_dim=768, depth=12, num_heads=12, mlp_ratio=4.0, qkv_bias=True,\r\n qk_scale=None, representation_size=None, distilled=False, drop_ratio=0.,\r\n attn_drop_ratio=0., drop_path_ratio=0., embed_layer=Patch_Embedding, norm_layer=None,\r\n act_layer=None):\r\n super(Vision_Transformer,self).__init__()\r\n self.num_classes = num_classes\r\n self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models\r\n self.num_tokens = 2 if distilled else 1\r\n norm_layer = norm_layer or partial(nn.LayerNorm, eps=1e-6)\r\n act_layer = act_layer or nn.GELU\r\n\r\n self.patch_embed = embed_layer(img_size=img_size, patch_size=patch_size,\r\n in_channel=in_channel, embed_dim=embed_dim)\r\n num_patches = self.patch_embed.num_patches#N---14*14=196\r\n\r\n self.cls_token = nn.Parameter(torch.zero(1,1,embed_dim))\r\n self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + self.num_tokens, embed_dim))\r\n self.pos_drop = nn.Dropout(p=drop_ratio)\r\n\r\n dpr = [x.item() for x in torch.linspace(0, drop_path_ratio, depth)] # stochastic depth decay rule\r\n self.blocks = nn.Sequential(*[\r\n Vision_Transformer_Block(dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,\r\n drop_ratio=drop_ratio, attn_drop_ratio=attn_drop_ratio, drop_path_ratio=dpr[i],\r\n norm_layer=norm_layer, act_layer=act_layer)\r\n for i in range(depth)\r\n ])\r\n\r\n self.norm = norm_layer(embed_dim)\r\n\r\n self.pre_logits = nn.Identity()\r\n self.head = nn.Linear(self.num_features, num_classes)\r\n\r\n # Weight init\r\n nn.init.trunc_normal_(self.pos_embed, std=0.02)\r\n nn.init.trunc_normal_(self.cls_token, std=0.02)\r\n self.apply(_init_vit_weights)\r\n\r\n\r\n def forward(self, x):\r\n # [B, C, H, W] -> [B, num_patches, embed_dim]\r\n x = self.patch_embed(x) # [B, 196, 768]\r\n # [1, 1, 768] -> [B, 1, 768]\r\n cls_token = self.cls_token.expand(x.shape[0], -1, -1)\r\n x = torch.cat((cls_token,x), dim=1)\r\n x = self.pos_drop(x + self.pos_embed)\r\n x = self.blocks(x)\r\n x = self.norm(x)\r\n x = x[:, 0]\r\n x = self.head(x)\r\n return x\r\n\r\n#初始化nn.Conv2d,nn.Linear,nn.LayerNorm\r\ndef _init_vit_weights(m):\r\n if isinstance(m, nn.Linear):\r\n nn.init.trunc_normal_(m.weight, std=.01)\r\n if m.bias is not None:\r\n nn.init.zeros_(m.bias)\r\n elif isinstance(m, nn.Conv2d):\r\n nn.init.kaiming_normal_(m.weight, mode=\"fan_out\")\r\n if m.bias is not None:\r\n nn.init.zeros_(m.bias)\r\n elif isinstance(m, nn.LayerNorm):\r\n nn.init.zeros_(m.bias)\r\n nn.init.ones_(m.weight)\r\n\r\n\r\ndef vit_base_patch16_224(num_classes: int = 1000):\r\n \"\"\"\r\n ViT-Base model (ViT-B/16) from original paper (https://arxiv.org/abs/2010.11929).\r\n ImageNet-1k weights @ 224x224, source https://github.com/google-research/vision_transformer.\r\n weights ported from official Google JAX impl:\r\n 链接: https://pan.baidu.com/s/1zqb08naP0RPqqfSXfkB2EA 密码: eu9f\r\n 代码来自bilibili up主:\r\n vedio:https://www.bilibili.com/video/BV1AL411W7dT/?spm_id_from=333.1007.top_right_bar_window_history.content.click&vd_source=bbb6fff63daa8014a7dbb0710681db68\r\n \"\"\"\r\n model = Vision_Transformer(img_size=224,\r\n patch_size=16,\r\n embed_dim=768,\r\n depth=12,\r\n num_heads=12,\r\n representation_size=None,\r\n num_classes=num_classes)\r\n return model\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"Westbrone/vision_Transformer_network_chinese","sub_path":"vision_transformer_network.py","file_name":"vision_transformer_network.py","file_ext":"py","file_size_in_byte":10541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1556532002","text":"\r\nfrom datetime import datetime as dtdt\r\nfrom datetime import timedelta\r\nimport pytz\r\n\r\ntz_suffix = ' %Z%z'\r\ndatetime_us_fmt = '%m/%d/%Y %H:%M:%S'\r\n# datetime_w_tz_us_fmt = datetime_us_fmt + tz_suffix\r\ndatetime_us_precise_fmt = '%m/%d/%Y %H:%M:%S.%f'\r\n# datetime_w_tz_us_precise_fmt = datetime_us_precise_fmt + tz_suffix\r\ndate_us_fmt = '%m/%d/%Y'\r\ntime_us_fmt = '%H:%M:%S'\r\n# time_w_tz_us_fmt = time_us_fmt + tz_suffix\r\ntime_us_precise_fmt = '%H:%M:%S.%f'\r\n# time_w_tz_us_precise_fmt = time_us_precise_fmt + tz_suffix\r\ndatetime_filename_fmt = '%Y%m%d_%H%M%S'\r\n# datetime_w_tz_filename_fmt = datetime_filename_fmt + tz_suffix\r\ndatetime_filename_precise_fmt = '%Y%m%d_%H%M%S%f'\r\n\r\n# Add to a datetime.\r\nprint('Add to a datetime')\r\nprint( dtdt(2021, 9, 28, 13, 45) + timedelta(days=0, weeks=0, hours=0,\r\n minutes=0, seconds=0) )\r\n\r\n\r\n# Convert to string\r\nprint('Convert datetime to str')\r\nprint( dtdt(2021, 9, 28, 13, 45).strftime('%m/%d/%Y %H:%M:%S') )\r\n\r\n\r\n# Convert from string\r\nprint('Convert str to datetime')\r\nprint(dtdt.strptime('01/03/2021 04:05:06.789012', '%m/%d/%Y %H:%M:%S.%f'))\r\n\r\n\r\n# Now to string to put in filename\r\nprint('Convert str to datetime')\r\ndate_str = dtdt.now().strftime('%Y%m%d_%H%M%S')\r\nprint(date_str)\r\nfp = f'stem_{date_str}.suffix'\r\nprint(fp)\r\n\r\n\r\n# Convert EPT / UTC\r\n\r\n# Timezones\r\nept = pytz.timezone('US/Eastern')\r\nutc = pytz.utc\r\n# str format\r\nfmt = '%Y-%m-%d %H:%M:%S %Z%z'\r\n\r\nprint(\"\\nEPT/UTC examples:\")\r\nprint(\"\\nWinter (EST) example:\")\r\n# Create a UTC time in the winter\r\nwinter_utc = dtdt(2016, 1, 24, 18, 0, 0, tzinfo=utc)\r\nprint(\" UTC: \", winter_utc.strftime(fmt))\r\n# Convert from UTC to eastern prevailing time. Since, the timestamp is in the\r\n# winter, prevailing time is standard time.\r\nwinter_ept = winter_utc.astimezone(ept)\r\nprint(\" EPT: \", winter_ept.strftime(fmt))\r\n# Let's convert back to UTC to show we get back to the original value.\r\nwinter_utc2 = winter_ept.astimezone(utc)\r\nprint(\" UTC: \", winter_utc2.strftime(fmt))\r\n\r\n# Let's do that again for a summer datetime.\r\nprint(\"\\nSummer (EDT) example:\")\r\nsummer_utc = dtdt(2016, 7, 24, 18, 0, 0, tzinfo=utc)\r\nprint(\" UTC: \", summer_utc.strftime(fmt))\r\n# Convert from UTC to eastern prevailing time. Since, the timestamp is in the\r\n# winter, prevailing time is daylight saving time.\r\nsummer_ept = summer_utc.astimezone(ept)\r\nprint(\" EPT: \", summer_ept.strftime(fmt))\r\n# Let's convert back to UTC to show we get back to the original value.\r\nsummer_utc2 = summer_ept.astimezone(utc)\r\nprint(\" UTC: \", summer_utc2.strftime(fmt))\r\n\r\ndef this_month():\r\n now = dtdt.now()\r\n result = dtdt(year=now.year, month=now.month, day=1)\r\n return result\r\n","repo_name":"cadvena/toolbox","sub_path":"cookbook/datetime_recipies.py","file_name":"datetime_recipies.py","file_ext":"py","file_size_in_byte":2709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73520917587","text":"print(\"Enter first operand: \", end=\"\")\n# spot for user to enter first operand\n\noperand_1 = float(input())\n# stores input as new variable\n\nprint(\"Enter second operand: \", end=\"\")\n# spot for user to enter second operand\n\noperand_2 = float(input())\n# stores input as new variable than before\n\nprint(\"Calculator Menu\", \"---------------\", \"1. Addition\", \"2. Subtraction\", \"3. Multiplication\", \"4. Division\", sep=\"\\n\")\n# prints out the menu for the user to see\n\nprint(\"Which operation do you want to perform?\")\n# asks the user what they want to do with the operands\n\noperation = int(input())\n# allows input for which operation the user wants to perform\n\nif operation < 1 or operation > 4:\n print(\"Error: Invalid selection! Terminating program.\")\n# when the user does not choose a number from the menu then they will receive an error message\n\nelse:\n if operation == 1:\n result = operand_1 + operand_2\n # addition operation\n\n if operation == 2:\n result = operand_1 - operand_2\n # subtraction operation\n\n if operation == 3:\n result = operand_1 * operand_2\n # multiplication operation\n\n if operation == 4:\n result = operand_1 / operand_2\n # division operation\n\n print(f\"The result of the operation is {result}. Goodbye!\")\n# shows the user the final calculation\n","repo_name":"dylon-wetzel/Calculator","sub_path":"calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33683731936","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom libnn.kd.kd_utils import Embed, ContrastLoss, ContrastMemory\n\n\nclass SoftTarget(nn.Module):\n \"\"\"\n Distilling the Knowledge in a Neural Network\n https://arxiv.org/pdf/1503.02531.pdf\n \"\"\"\n\n def __init__(self, temperature):\n \"\"\"\n :param temperature: Temperature term which used in soft target\n \"\"\"\n super(SoftTarget, self).__init__()\n self.T = temperature\n\n def forward(self, out_s, out_t):\n loss = F.kl_div(F.log_softmax(out_s / self.T, dim=1),\n F.softmax(out_t / self.T, dim=1),\n reduction='batchmean') * self.T * self.T\n return loss\n\n\nclass Logits(nn.Module):\n \"\"\"\n Do Deep Nets Really Need to be Deep?\n http://papers.nips.cc/paper/5484-do-deep-nets-really-need-to-be-deep.pdf\n \"\"\"\n\n def __init__(self):\n super(Logits, self).__init__()\n\n def forward(self, out_s, out_t):\n loss = F.mse_loss(out_s, out_t)\n return loss\n\n\nclass AT(nn.Module):\n \"\"\"\n Paying More Attention to Attention: Improving the Performance of Convolutional\n Neural Netkworks wia Attention Transfer\n https://arxiv.org/pdf/1612.03928.pdf\n \"\"\"\n\n def __init__(self, p):\n super(AT, self).__init__()\n self.p = p\n\n def forward(self, fm_s, fm_t):\n loss = F.mse_loss(self.attention_map(fm_s), self.attention_map(fm_t))\n return loss\n\n def attention_map(self, fm, eps=1e-6):\n am = torch.pow(torch.abs(fm), self.p)\n am = torch.sum(am, dim=1, keepdim=True)\n norm = torch.norm(am, dim=[2, 3], keepdim=True)\n am = torch.div(am, norm + eps)\n return am\n\n\nclass AFD(nn.Module):\n \"\"\"\n In the original paper, AFD is one of components of AFDS.\n AFDS: Attention Feature Distillation and Selection\n AFD: Attention Feature Distillation\n AFS: Attention Feature Selection\n\n We (not me) find the original implementation of attention is unstable, thus we replace it with a SE block.\n\n Pay Attention to Features, Transfer Learn Faster CNNs\n https://openreview.net/pdf?id=ryxyCeHtPB\n \"\"\"\n\n def __init__(self, in_channels, att_f):\n super(AFD, self).__init__()\n mid_channels = int(in_channels * att_f)\n\n self.attention = nn.Sequential(*[\n nn.Conv2d(in_channels, mid_channels, 1, 1, 0, bias=True),\n nn.ReLU(inplace=True),\n nn.Conv2d(mid_channels, in_channels, 1, 1, 0, bias=True)\n ])\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n if m.bias is not None:\n nn.init.constant_(m.bias, 0)\n\n def forward(self, fm_s, fm_t, eps=1e-6):\n fm_t_pooled = F.adaptive_avg_pool2d(fm_t, 1)\n rho = self.attention(fm_t_pooled)\n # rho = F.softmax(rho.squeeze(), dim=-1)\n rho = torch.sigmoid(rho.squeeze())\n rho = rho / torch.sum(rho, dim=1, keepdim=True) # Looks like an average here\n\n fm_s_norm = torch.norm(fm_s, dim=[2, 3], keepdim=True)\n fm_s = torch.div(fm_s, fm_s_norm + eps)\n fm_t_norm = torch.norm(fm_t, dim=[2, 3], keepdim=True)\n fm_t = torch.div(fm_t, fm_t_norm + eps)\n\n loss = rho * torch.pow(fm_s - fm_t, 2).mean(dim=(2, 3))\n loss = loss.sum(1).mean(0)\n\n return loss\n\n\n'''\n\n'''\n\n\nclass CRD(nn.Module):\n \"\"\"\n Both CRD and it's component are modified from\n -> https://github.com/HobbitLong/RepDistiller/tree/master/crd\n\n Contrastive Representation Distillation\n -> https://openreview.net/pdf?id=SkgpBJrtvS\n\n includes two symmetric parts:\n (a) using teacher as anchor, choose positive and negatives over the student side\n (b) using student as anchor, choose positive and negatives over the teacher side\n\n Args:\n s_dim: the dimension of student's feature\n t_dim: the dimension of teacher's feature\n feat_dim: the dimension of the projection space\n nce_n: number of negatives paired with each positive\n nce_t: the temperature\n nce_mom: the momentum for updating the memory buffer\n n_data: the number of samples in the training set, which is the M in Eq.(19)\n \"\"\"\n\n def __init__(self, s_dim, t_dim, feat_dim, nce_n, nce_t, nce_mom, n_data):\n super(CRD, self).__init__()\n self.embed_s = Embed(s_dim, feat_dim)\n self.embed_t = Embed(t_dim, feat_dim)\n self.contrast = ContrastMemory(feat_dim, n_data, nce_n, nce_t, nce_mom)\n self.criterion_s = ContrastLoss(n_data)\n self.criterion_t = ContrastLoss(n_data)\n\n def forward(self, feat_s, feat_t, idx, sample_idx):\n feat_s = self.embed_s(feat_s)\n feat_t = self.embed_t(feat_t)\n out_s, out_t = self.contrast(feat_s, feat_t, idx, sample_idx)\n loss_s = self.criterion_s(out_s)\n loss_t = self.criterion_t(out_t)\n loss = loss_s + loss_t\n\n return loss\n","repo_name":"nopphonyel/WGANs-CrossModal-KD","sub_path":"libnn/kd/kd_func.py","file_name":"kd_func.py","file_ext":"py","file_size_in_byte":5027,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10066371294","text":"import copy\r\nfrom parsers2 import *\r\nfrom transforming import *\r\nimport re\r\n\r\nHEALTHY = [('white rice','quinoa','quinoa',[],[]),\r\n ('vegetable oil','olive oil','oil',[],[]),\r\n ('butter','coconut oil','oil',[],[]),\r\n ('sour cream','greek yogurt','yogurt',[],[]),\r\n ('flour','coconut flour','flour',[],[]),\r\n ('sugar','stevia','stevia',[],[]),\r\n #('salt','himalayan salt','himalayan salt',[],[]),\r\n ('butter','margarine','margarine',[],[]),\r\n ('bacon', 'lean ham', 'ham',[],[]),\r\n ('pork','lean chicken breast','chicken',[],[]),\r\n ('pasta','spaghetti squash','pasta',[],[]),\r\n ('potatoes','yams','yams',[],[]),\r\n ('dressing', 'dressing','dressing',[],[])]\r\n\r\n\r\n\r\ndef to_healthy(mappings, ingredients, steps):\r\n avocado = 0\r\n for i in ingredients:\r\n if re.search('salt', i.item):\r\n i.item = re.sub('salt','himalayan salt', i.item)\r\n if re.search('iceberg', i.item):\r\n i.item = re.sub('iceberg','romaine',i.item)\r\n if re.search('milk', i.item):\r\n i.item = re.sub('milk','almond milk',i.item)\r\n if re.search('flour', i.item):\r\n i.item = re.sub('flour','coconut flour',i.item)\r\n if re.search('avocado',i.item):\r\n avocado = 1\r\n for s in steps:\r\n for ss in s.substeps:\r\n if re.search('salt', ss.source):\r\n ss.source = re.sub('salt','himalayan salt', ss.source)\r\n if re.search('iceberg', ss.source):\r\n ss.source = re.sub('iceberg','romaine',ss.source)\r\n if re.search('milk', ss.source):\r\n ss.source = re.sub('milk','almond milk',ss.source)\r\n if re.search('flour', ss.source):\r\n ss.source = re.sub('flour','coconut flour', ss.source)\r\n\r\n if avocado == 0:\r\n steps = add_finishing_steps(steps,['Serve with sliced avocado'])\r\n ingredients.append(Ingredient(1,'','avocado'))\r\n\r\n sauce = HEALTHY[-1]\r\n #find the sauces\r\n transform = 0\r\n ingred_sauces = []\r\n for i in ingredients:\r\n if fuzz.partial_ratio(sauce[0], i.item.lower()) > 90: #matches first word of template to an ingredient\r\n transform = 1\r\n ingred_sauces.append(i)\r\n for m in mappings:\r\n if fuzz.partial_ratio(sauce[0], m[1].lower()) > 90: #matches long name in mappings\r\n steps = swap_ingredient(sauce[2], m[0], steps) #swap short names in directions\r\n for i in ingred_sauces:\r\n ingredients.remove(i)\r\n if transform == 1:\r\n ingredients.append(Ingredient(1,'cup','olive oil'))\r\n ingredients.append(Ingredient(.5,'cup','balsamic vinegar'))\r\n ingredients.append(Ingredient(1,'sprig','parsley'))\r\n steps = add_prep_steps(steps, ['Prepare dressing by slowly mixing olive oil, balsamic vinegar, and parsley'])\r\n\r\n for template in HEALTHY[:-1]:\r\n for i in ingredients:\r\n if fuzz.partial_ratio(template[0], i.item.lower()) > 90: #matches first word of template to an ingredient\r\n transform = 1\r\n #print(i.item)\r\n i.item = template[1]\r\n for m in mappings:\r\n if fuzz.partial_ratio(template[0], m[1].lower()) > 90: #matches long name in mappings\r\n steps = swap_ingredient(template[2], m[0], steps) #swap short names in directions\r\n steps = add_prep_steps(steps, template[3])\r\n steps = add_finishing_steps(steps, template[4])\r\n\r\n\r\n return(ingredients,steps)\r\n\r\n\r\nVEGETABLES = list(set(['romaine lettuce','spinach','cauliflower','broccoli','cucumber','squash','corn','onion','bell pepper','carrot','zucchini','iceberg lettuce','asparagus','bean','bamboo','beet','bok choy']))\r\nUNHEALTHY = [('olive oil','melted butter','butter',['Melt butter by heating in pan or microwave until liquid'],[]),\r\n ('butter','pork fat','fat',[],[]),\r\n\r\n]\r\n\r\n#unhealthy\r\ndef to_unhealthy(mappings, ingredients, steps):\r\n ranch = 0\r\n transform = 0\r\n veggies = []\r\n for i in ingredients:\r\n #print(i.item)\r\n if re.search('ranch',i.item):\r\n ranch == 1\r\n if re.search('salt', i.item):\r\n i.item = 'msg'\r\n transform = 1\r\n if re.search('lean', i.item):\r\n i.item = re.sub('lean','fatty',i.item)\r\n transform = 1\r\n for veg in VEGETABLES:\r\n if fuzz.partial_ratio(i.item, veg.lower()) > 90:\r\n veggies.append(i)\r\n\r\n for s in steps:\r\n for ss in s.substeps:\r\n if re.search('salt', ss.source):\r\n ss.source = re.sub('salt', 'msg', ss.source)\r\n if re.search('lean', ss.source):\r\n ss.source = re.sub('lean', 'fatty', ss.source)\r\n\r\n vegg = copy.deepcopy(veggies)\r\n veg = [remove_descriptors(i).item.strip() for i in vegg]\r\n veg = list(set(veg))\r\n if len(veg) > 0:\r\n if len(veg) > 1:\r\n last = veg[-1]\r\n rest = veg[:-1]\r\n if len(rest) > 1:\r\n rest = [i + ',' for i in rest]\r\n veg = rest + ['and'] + [last]\r\n\r\n veg_str = ' '.join(veg)\r\n steps = add_prep_steps(steps, ['Deep fry ' + veg_str + ' until crispy in deep fryer'])\r\n transform = 1\r\n\r\n for template in UNHEALTHY:\r\n for i in ingredients:\r\n if fuzz.partial_ratio(template[0], i.item.lower()) > 90: #matches first word of template to an ingredient\r\n transform = 1\r\n #print(i.item)\r\n i.item = template[1]\r\n for m in mappings:\r\n if fuzz.partial_ratio(template[0], m[1].lower()) > 90: #matches long name in mappings\r\n steps = swap_ingredient(template[2], m[0], steps) #swap short names in directions\r\n steps = add_prep_steps(steps, template[3])\r\n steps = add_finishing_steps(steps, template[4])\r\n\r\n #if ranch == 0:\r\n # steps = add_finishing_steps(steps, ['Top with ranch dressing'])\r\n # ingredients.append(Ingredient(1, \"bottle\",'ranch'))\r\n #if ranch == 1:\r\n # steps = add_finishing_steps(steps, ['Top with instant ramen flavor packet and mix'])\r\n # ingredients.append(Ingredient(1, \"packet\",'instant ramen soup base'))\r\n if transform == 0:\r\n steps = add_prep_steps(steps, ['Place frozen french fries in microwave and heat on high for 5 minutes.'])\r\n steps = add_finishing_steps(steps, ['Serve with french fries on the side'])\r\n ingredients.append(Ingredient(1, 'bag', 'store bought frozen french fries'))\r\n\r\n\r\n return(ingredients,steps)\r\n","repo_name":"sdobon/NLP-recipe-transformer","sub_path":"healthy.py","file_name":"healthy.py","file_ext":"py","file_size_in_byte":6735,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37810945212","text":"n = int(input())\n# 각 수를 표현하기에 가장 큰 개수\ndp = list(i for i in range(n+1))\n\nfor i in range(1, n+1):\n for j in range(1, i):\n if(j * j > i):\n break\n # 아래 조건을 한다면, 제곱수라면 1을 넣을 수 있고 표현하기에 가장 작은 개수를 구할 수 있음\n if(dp[i] > dp[i - j * j] + 1):\n dp[i] = dp[i - j * j] + 1\n\nprint(dp[n])","repo_name":"KoKwanwun/Algorithm","sub_path":"Baekjoon/Silver/Silver 2/1699. 제곱수의 합.py","file_name":"1699. 제곱수의 합.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35628298045","text":"# This sample verifies that the type checker allows access\n# to instance variables provided by a metaclass.\n\nfrom typing import Any\n\n\nclass MetaA(type):\n var0 = 3\n\n def __init__(cls, name, bases, dct):\n cls.var1 = \"hi\"\n\n\nclass ClassA(metaclass=MetaA):\n pass\n\n\n# This should generate an error because var0 isn't\n# accessible via an instance of this class.\nClassA().var0\nreveal_type(ClassA.var0, expected_text=\"int\")\nClassA.var0 = 1\n\nreveal_type(ClassA().var1, expected_text=\"str\")\nreveal_type(ClassA.var1, expected_text=\"str\")\n\nClassA.var1 = \"hi\"\nClassA().var1 = \"hi\"\n\n\nclass MetaB(type):\n def __setattr__(cls, key: str, value: Any) -> None:\n ...\n\n\nclass ClassB(metaclass=MetaB):\n var0: int\n\n\n# This should generate an error\nClassB.var0 = \"\"\nClassB.var1 = \"\"\n\nClassB().var0 = 1\n\n# This should generate an error\nClassB().var0 = \"\"\n\n# This should generate an error\nClassB().var1 = \"\"\n","repo_name":"microsoft/pyright","sub_path":"packages/pyright-internal/src/tests/samples/metaclass11.py","file_name":"metaclass11.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","stars":11208,"dataset":"github-code","pt":"48"} +{"seq_id":"20276268900","text":"__title__ = 'Renderable Box'\n__version__ = '1.0.0'\n__description__ = 'Renderable container image application.'\n__author__ = 'Danilo Peixoto'\n__email__ = 'danilopeixoto@outlook.com'\n__license__ = 'BSD-3-Clause'\n__copyright__ = 'Copyright (c) 2020, Renderable, Inc. All rights reserved.'\n\n\n__all__ = [\n '__title__',\n '__version__',\n '__description__',\n '__author__',\n '__email__',\n '__license__',\n '__copyright__'\n]\n","repo_name":"therenderable/renderable-box","sub_path":"renderable_box/package.py","file_name":"package.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14645391437","text":"from dataclasses import field, fields\nfrom django import forms\nfrom .models import ContactProfile, Skill\n\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.models import User\n\n\n\nclass ContactForm(forms.ModelForm):\n\n\tname = forms.CharField(max_length=100, required=True,\n\t\twidget=forms.TextInput(attrs={\n\t\t\t'placeholder': '*Full name..',\n\t\t\t}))\n\temail = forms.EmailField(max_length=254, required=True, \n\t\twidget=forms.TextInput(attrs={\n\t\t\t'placeholder': '*Email..',\n\t\t\t}))\n\tmessage = forms.CharField(max_length=1000, required=True, \n\t\twidget=forms.Textarea(attrs={\n\t\t\t'placeholder': '*Message..',\n\t\t\t'rows': 6,\n\t\t\t}))\n\n\n\tclass Meta:\n\t\tmodel = ContactProfile\n\t\tfields = ('name', 'email', 'message',)\n\nclass CreateUserForm(UserCreationForm):\n\tclass Meta:\n\t\tmodel = User\n\t\tfields = ['username','email','password1','password2']\n\n\nclass SkillForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = Skill\n\t\tfields = ['name', 'score', 'image', 'is_key_skill']","repo_name":"NikolaiGuerra25/Portafolio-Django","sub_path":"main/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40052740100","text":"import cc\nimport bpy\nimport bgl\nimport bmesh\nimport math\nimport mathutils\nimport mathutils as mu\nfrom bpy_extras import view3d_utils\n\nbl_info = {\n 'name': 'Tool: Gradient',\n 'author': 'Cardboard Computer',\n 'blender': (2, 69, 0),\n 'description': 'Apply gradients on lines/polygon colors',\n 'category': 'Cardboard'\n}\n\ndef apply_gradient(gra, obj, select=None):\n point_a = gra.location\n point_b = gra.matrix_world * mu.Vector((0, 0, 1))\n\n g = gra.data.gradient_settings\n\n if select is None:\n select = g.select\n\n gradient_colors(\n obj, point_a, point_b,\n g.color_a, g.alpha_a,\n g.color_b, g.alpha_b,\n g.blend_type, g.blend_method, g.blend_falloff,\n g.bias, g.scale, g.mirror,\n select\n )\n\ndef gen_mesh_directional(bm, res=32):\n bm.clear()\n\n for i in range(res + 1):\n t = i / float(res)\n bm.verts.new(mu.Vector((0, 0, t)))\n for i in range(res):\n v1 = bm.verts[i]\n v2 = bm.verts[i + 1]\n e = bm.edges.new((v1, v2))\n tip = v2\n v1 = bm.verts.new(mu.Vector((0.05, 0, 0.9)))\n v2 = bm.verts.new(mu.Vector((-0.05, 0, 0.9)))\n e = bm.edges.new((tip, v1))\n e = bm.edges.new((tip, v2))\n\ndef gen_mesh_radial(bm, res=64):\n bm.clear()\n\n for i in range(res):\n t = i / float(res)\n x = math.cos(t * math.pi * 2)\n y = math.sin(t * math.pi * 2)\n bm.verts.new(mu.Vector((x, 0, y)))\n for i in range(res - 1):\n v1 = bm.verts[i]\n v2 = bm.verts[i + 1]\n e = bm.edges.new((v1, v2))\n v1 = v2\n v2 = bm.verts[0]\n e = bm.edges.new((v1, v2))\n\n for i in range(res):\n t = i / float(res)\n x = math.cos(t * math.pi * 2)\n y = math.sin(t * math.pi * 2)\n bm.verts.new(mu.Vector((x, y, 0)))\n for i in range(res, res * 2 - 1):\n v1 = bm.verts[i]\n v2 = bm.verts[i + 1]\n e = bm.edges.new((v1, v2))\n v1 = v2\n v2 = bm.verts[res]\n e = bm.edges.new((v1, v2))\n\n for i in range(res):\n t = i / float(res)\n x = math.cos(t * math.pi * 2)\n y = math.sin(t * math.pi * 2)\n bm.verts.new(mu.Vector((0, x, y)))\n for i in range(res * 2, res * 3 - 1):\n v1 = bm.verts[i]\n v2 = bm.verts[i + 1]\n e = bm.edges.new((v1, v2))\n v1 = v2\n v2 = bm.verts[res * 2]\n e = bm.edges.new((v1, v2))\n\n for i in range(res + 1):\n t = i / float(res) * 2 - 1\n bm.verts.new(mu.Vector((0, 0, t)))\n for i in range(res * 3, res * 4):\n v1 = bm.verts[i]\n v2 = bm.verts[i + 1]\n e = bm.edges.new((v1, v2))\n\n@cc.ops.editmode\ndef sample_color(context, event, ray_max=1000.0):\n result = cc.utils.find(context, event, 10000)\n if result is not None:\n obj, origin, target = result\n if obj.data.vertex_colors.active:\n with cc.colors.Sampler(obj) as sampler:\n return sampler.raycast(origin, target)\n return mathutils.Color((0, 0, 0))\n\n@cc.ops.editmode\ndef gradient_colors(\n obj,\n point_a,\n point_b,\n color_a,\n alpha_a,\n color_b,\n alpha_b,\n blend_type,\n blend_method,\n blend_falloff,\n bias, scale, mirror,\n select='POLYGON'):\n\n colors = cc.colors.layer(obj)\n\n m = mathutils\n to_obj = obj.matrix_world.inverted()\n p1 = to_obj * m.Vector(point_a)\n p2 = to_obj * m.Vector(point_b)\n direction = p2 - p1\n\n for s in colors.itersamples():\n if not s.is_selected(select.lower()):\n continue\n\n vert = s.vertex.co\n delta = vert - p1\n\n if blend_type == 'DIRECTIONAL':\n distance = delta.dot(direction.normalized())\n atten = max(min(distance / direction.length, 1), 0)\n if blend_type == 'RADIAL':\n distance = cc.utils.magnitude(delta)\n atten = max(min(distance / direction.length, 1), 0)\n\n atten = max(min((atten - bias) / scale, 1), 0)\n\n if mirror:\n atten = 1 - abs(atten % 1 * 2 - 1)\n\n if blend_falloff == 'SHARP':\n atten = atten * atten\n if blend_falloff == 'ROOT':\n atten = math.sqrt(atten)\n if blend_falloff == 'SMOOTH':\n atten = math.cos(atten * math.pi + math.pi) / 2 + .5\n\n color_ab = cc.utils.lerp(color_a, color_b, atten)\n alpha_ab = cc.utils.lerp(alpha_a, alpha_b, atten)\n\n if blend_method == 'REPLACE':\n s.color = color_ab\n\n if blend_method == 'MIX':\n s.color = cc.utils.lerp(s.color, color_ab, alpha_ab)\n\n if blend_method == 'MULTIPLY':\n s.color.r *= color_ab.r;\n s.color.g *= color_ab.g;\n s.color.b *= color_ab.b;\n\n if blend_method == 'ADD':\n s.color.r += color_ab.r;\n s.color.g += color_ab.g;\n s.color.b += color_ab.b;\n\n if blend_method == 'SUBTRACT':\n s.color.r -= color_ab.r;\n s.color.g -= color_ab.g;\n s.color.b -= color_ab.b;\n\n@cc.ops.editmode\ndef set_gradient_object(\n obj,\n point_a,\n point_b,\n color_a,\n alpha_a,\n color_b,\n alpha_b,\n blend_type,\n blend_method,\n blend_falloff,\n bias, scale, mirror,\n select='ALL'):\n\n mesh = obj.data\n g = mesh.gradient_settings\n\n if not obj.is_gradient or g.blend_type != blend_type:\n bm = bmesh.new()\n bm.from_mesh(mesh)\n if blend_type == 'DIRECTIONAL':\n gen_mesh_directional(bm)\n elif blend_type == 'RADIAL':\n gen_mesh_radial(bm)\n bm.to_mesh(mesh)\n bm.free()\n\n obj.is_gradient = True\n\n g.color_a = color_a\n g.alpha_a = alpha_a\n g.color_b = color_b\n g.alpha_b = alpha_b\n g.blend_type = blend_type\n g.blend_method = blend_method\n g.blend_falloff = blend_falloff\n g.bias = bias\n g.scale = scale\n g.mirror = mirror\n g.select = select\n\n line = mu.Vector(point_b - point_a)\n quat = line.normalized().to_track_quat('Z', 'Y')\n length = line.length\n\n obj.rotation_mode = 'QUATERNION'\n obj.rotation_quaternion = quat\n obj.location = point_a\n obj.scale = mu.Vector((length, length, length))\n\n mesh.update()\n obj.update_tag()\n bpy.context.scene.update()\n\n colors = cc.colors.layer(obj)\n\n for s in colors.itersamples():\n vert = s.vertex.co\n if blend_type == 'DIRECTIONAL':\n atten = vert.z\n if blend_type == 'RADIAL':\n atten = vert.length\n atten = max(min((atten - bias) / scale, 1), 0)\n if mirror:\n atten = 1 - abs(atten % 1 * 2 - 1)\n if blend_falloff == 'SHARP':\n atten = atten * atten\n if blend_falloff == 'ROOT':\n atten = math.sqrt(atten)\n if blend_falloff == 'SMOOTH':\n atten = math.cos(atten * math.pi + math.pi) / 2 + .5\n s.color = cc.utils.lerp(color_a, color_b, atten)\n\n return obj\n\n@cc.ops.editmode\ndef gen_gradient_object(*args, **kwargs):\n mesh = bpy.data.meshes.new('Gradient')\n obj = bpy.data.objects.new('Gradient', mesh)\n set_gradient_object(obj, *args, **kwargs)\n return obj\n\nPROP_SELECT = bpy.props.EnumProperty(\n items=cc.ops.ENUM_SELECT,\n name='Select', default='POLYGON')\n\nPROP_BLEND_TYPE = bpy.props.EnumProperty(\n items=(\n ('DIRECTIONAL', 'Directional', 'Directional', 'CURVE_PATH', 0),\n ('RADIAL', 'Radial', 'Radial', 'MESH_UVSPHERE', 1),),\n name='Type', default='DIRECTIONAL')\n\nPROP_BLEND_METHOD = bpy.props.EnumProperty(\n items=(\n ('SUBTRACT', 'Subtract', 'Subtract'),\n ('ADD', 'Add', 'Add'),\n ('MULTIPLY', 'Multiply', 'Multiply'),\n ('MIX', 'Mix', 'Mix'),\n ('REPLACE', 'Replace', 'Replace'),),\n name='Method', default='REPLACE')\n\nPROP_BLEND_FALLOFF = bpy.props.EnumProperty(\n items=(\n ('LINEAR', 'Linear', 'Linear', 'LINCURVE', 0),\n ('SHARP', 'Sharp', 'Add', 'SHARPCURVE', 1),\n ('ROOT', 'Root', 'Root', 'ROOTCURVE', 2),\n ('SMOOTH', 'Smooth', 'Smooth', 'SMOOTHCURVE', 3),),\n name='Fallof', default='LINEAR')\n\nPROP_COLOR_A = bpy.props.FloatVectorProperty(\n name=\"Start Color\", subtype='COLOR_GAMMA',\n min=0, max=1, step=1,)\n\nPROP_ALPHA_A = bpy.props.FloatProperty(\n name=\"Start Alpha\", min=0, max=1, step=0.1, default=1)\n\nPROP_COLOR_B = bpy.props.FloatVectorProperty(\n name=\"End Color\", subtype='COLOR_GAMMA',\n min=0, max=1, step=1, default=(1, 1, 1),)\n\nPROP_ALPHA_B = bpy.props.FloatProperty(\n name=\"End Alpha\", min=0, max=1, step=0.1, default=1)\n\nPROP_BIAS = bpy.props.FloatProperty(\n name=\"Bias\", min=0, max=1, step=0.1, default=0)\n\nPROP_SCALE = bpy.props.FloatProperty(\n name=\"Scale\", min=0, max=1, step=0.1, default=1)\n\nPROP_MIRROR = bpy.props.BoolProperty(\n name='Mirror', default=False)\n\nclass GradientSettings(bpy.types.PropertyGroup):\n select = PROP_SELECT\n blend_type = PROP_BLEND_TYPE\n blend_method = PROP_BLEND_METHOD\n blend_falloff = PROP_BLEND_FALLOFF\n color_a = PROP_COLOR_A\n alpha_a = PROP_ALPHA_A\n color_b = PROP_COLOR_B\n alpha_b = PROP_ALPHA_B\n bias = PROP_BIAS\n scale = PROP_SCALE\n mirror = PROP_MIRROR\n\ndef gradient_preset_selected(self, context):\n s = context.scene\n if s.gradient_active_preset:\n preset = s.gradient_presets[s.gradient_active_preset]\n for prop in s.gradient_settings.keys():\n setattr(s.gradient_settings, prop, getattr(preset, prop))\n\nPROP_GRADIENT_SETTINGS = bpy.props.PointerProperty(type=GradientSettings)\n\nPROP_GRADIENT_PRESETS = bpy.props.CollectionProperty(type=GradientSettings)\n\nPROP_GRADIENT_ACTIVE_PRESET = bpy.props.StringProperty(name='Preset', default='', update=gradient_preset_selected)\n\nPROP_IS_GRADIENT = bpy.props.BoolProperty()\n\ndef draw_gradient_settings(context, layout, data):\n s = context.scene\n\n layout.prop(data, 'select', '')\n\n col = layout.column(align=True)\n\n col.prop(data, 'blend_method', '', icon='COLOR')\n col.prop(data, 'blend_type', '')\n col.prop(data, 'blend_falloff', '')\n\n col.prop(data, 'bias')\n col.prop(data, 'scale')\n col.prop(data, 'mirror', toggle=True)\n\n col = layout.column(align=True)\n\n row = col.row(align=True)\n row.prop(data, 'color_a', '')\n row.prop(data, 'color_b', '')\n\n row = col.row(align=True)\n row.prop(data, 'alpha_a', '')\n row.prop(data, 'alpha_b', '')\n\n return col\n\nclass GradientPanel(bpy.types.Panel):\n bl_label = \"Gradient\"\n bl_space_type = 'VIEW_3D'\n bl_region_type = 'TOOLS'\n\n def draw(self, context):\n l = self.layout\n s = context.scene\n\n c = l.column(align=True)\n r = c.row(align=True)\n r.prop_search(s, 'gradient_active_preset', s, 'gradient_presets', '', icon='SETTINGS')\n r.operator('cc.gradient_preset_add', '', icon='ZOOMIN')\n r.operator('cc.gradient_preset_remove', '', icon='X')\n if s.gradient_active_preset:\n r = c.row(align=True)\n r.operator('cc.gradient_preset_update', 'Update', icon='COPYDOWN')\n r.operator('cc.gradient_preset_revert', 'Revert', icon='PASTEDOWN')\n\n c = draw_gradient_settings(context, self.layout, context.scene.gradient_settings)\n c.operator('cc.gradient_swap', '', icon='ARROW_LEFTRIGHT')\n\n l.operator('cc.gradient_default', 'Reset')\n\n op = l.operator('cc.gradient_object', 'Create')\n op.create = True\n op.override = False\n\n obj = context.active_object\n if obj and obj.is_gradient:\n c = l.row(align=True)\n op = c.operator('cc.gradient_object', 'Update')\n op.override = True\n op.create = False\n op = c.operator('cc.gradient_object', 'Adjust')\n op.override = False\n op.create = False\n c.operator('cc.gradient_load', 'Load')\n\n if len(context.selected_objects) > 1:\n l.operator('cc.gradient_apply', 'Apply')\n\nclass GradientPresetAdd(bpy.types.Operator):\n bl_idname = 'cc.gradient_preset_add'\n bl_label = 'Add Preset'\n bl_options = {'UNDO'}\n\n name = bpy.props.StringProperty(name='Name')\n\n def invoke(self, context, event):\n wm = context.window_manager\n return wm.invoke_props_dialog(self)\n\n def execute(self, context):\n s = context.scene\n preset = s.gradient_presets.add()\n for prop in s.gradient_settings.keys():\n setattr(preset, prop, getattr(s.gradient_settings, prop))\n preset.name = self.name\n s.gradient_active_preset = preset.name\n return {'FINISHED'}\n\nclass GradientPresetRemove(bpy.types.Operator):\n bl_idname = 'cc.gradient_preset_remove'\n bl_label = 'Remove Preset'\n bl_options = {'UNDO'}\n\n def execute(self, context):\n s = context.scene\n if s.gradient_active_preset:\n idx = s.gradient_presets.find(s.gradient_active_preset)\n s.gradient_presets.remove(idx)\n s.gradient_active_preset = ''\n self.report({'INFO'}, 'Preset removed.')\n return {'FINISHED'}\n\nclass GradientPresetUpdate(bpy.types.Operator):\n bl_idname = 'cc.gradient_preset_update'\n bl_label = 'Update Preset'\n bl_options = {'UNDO'}\n\n def execute(self, context):\n s = context.scene\n if not s.gradient_active_preset:\n self.report({'ERROR'}, 'No preset active.')\n return {'CANCELLED'}\n preset = s.gradient_presets[s.gradient_active_preset]\n for prop in s.gradient_settings.keys():\n setattr(preset, prop, getattr(s.gradient_settings, prop))\n self.report({'INFO'}, 'Preset updated.')\n return {'FINISHED'}\n\nclass GradientPresetRevert(bpy.types.Operator):\n bl_idname = 'cc.gradient_preset_revert'\n bl_label = 'Load Preset'\n bl_options = {'UNDO'}\n\n def execute(self, context):\n s = context.scene\n if not s.gradient_active_preset:\n self.report({'ERROR'}, 'No preset active.')\n return {'CANCELLED'}\n preset = s.gradient_presets[s.gradient_active_preset]\n for prop in s.gradient_settings.keys():\n setattr(s.gradient_settings, prop, getattr(preset, prop))\n self.report({'INFO'}, 'Reverted to preset.')\n return {'FINISHED'}\n\nclass GradientObject(bpy.types.Operator):\n bl_idname = 'cc.gradient_object'\n bl_label = 'Add/Set Gradient'\n bl_options = {'REGISTER', 'UNDO'}\n\n select = PROP_SELECT\n blend_type = PROP_BLEND_TYPE\n blend_method = PROP_BLEND_METHOD\n blend_falloff = PROP_BLEND_FALLOFF\n color_a = PROP_COLOR_A\n alpha_a = PROP_ALPHA_A\n color_b = PROP_COLOR_B\n alpha_b = PROP_ALPHA_B\n bias = PROP_BIAS\n scale = PROP_SCALE\n mirror = PROP_MIRROR\n\n create = bpy.props.BoolProperty()\n override = bpy.props.BoolProperty()\n\n @classmethod\n def poll(cls, context):\n return context.mode == 'OBJECT'\n\n def draw(self, context):\n draw_gradient_settings(context, self.layout, self)\n\n def execute(self, context):\n obj = context.active_object\n\n args = (\n self.color_a, self.alpha_a,\n self.color_b, self.alpha_b,\n self.blend_type, self.blend_method, self.blend_falloff,\n self.bias, self.scale, self.mirror,\n self.select\n )\n\n if obj and obj.is_gradient and not self.create:\n point_a = obj.location\n point_b = obj.matrix_world * mu.Vector((0, 0, 1))\n set_gradient_object(obj, point_a, point_b, *args)\n else:\n point_a = context.scene.cursor_location\n point_b = point_a + mu.Vector((0, 0, 1))\n obj = gen_gradient_object(point_a, point_b, *args)\n context.scene.objects.link(obj)\n\n bpy.ops.object.select_all(action='DESELECT')\n obj.select = True\n context.scene.objects.active = obj\n context.scene.update()\n\n return {'FINISHED'}\n\n def invoke(self, context, event):\n obj = context.active_object\n scene = context.scene\n\n context.space_data.viewport_shade = 'TEXTURED'\n\n if obj and obj.is_gradient and not self.override:\n g = obj.data.gradient_settings\n else:\n g = scene.gradient_settings\n\n self.select = g.select\n self.blend_type = g.blend_type\n self.blend_method = g.blend_method\n self.blend_falloff = g.blend_falloff\n self.color_a = g.color_a\n self.alpha_a = g.alpha_a\n self.color_b = g.color_b\n self.alpha_b = g.alpha_b\n self.bias = g.bias\n self.scale = g.scale\n self.mirror = g.mirror\n\n return self.execute(context)\n\nclass GradientLoad(bpy.types.Operator):\n bl_idname = 'cc.gradient_load'\n bl_label = 'Load Gradient'\n bl_options = {'REGISTER', 'UNDO'}\n\n @classmethod\n def poll(cls, context):\n obj = context.active_object\n return context.mode == 'OBJECT' and obj and obj.is_gradient\n\n def execute(self, context):\n obj = context.active_object.data.gradient_settings\n scene = context.scene.gradient_settings\n\n scene.select = obj.select\n scene.blend_type = obj.blend_type\n scene.blend_method = obj.blend_method\n scene.blend_falloff = obj.blend_falloff\n scene.color_a = obj.color_a\n scene.alpha_a = obj.alpha_a\n scene.color_b = obj.color_b\n scene.alpha_b = obj.alpha_b\n scene.bias = obj.bias\n scene.scale = obj.scale\n scene.mirror = obj.mirror\n\n return {'FINISHED'}\n\nclass GradientApply(bpy.types.Operator):\n bl_idname = 'cc.gradient_apply'\n bl_label = 'Apply Gradient'\n bl_options = {'REGISTER', 'UNDO'}\n\n @classmethod\n def poll(cls, context):\n return len(context.selected_objects) > 0\n\n def execute(self, context):\n objects = context.selected_objects\n meshes = []\n gradients = []\n\n for obj in objects:\n if obj.is_gradient:\n gradients.append(obj)\n elif obj.type == 'MESH':\n meshes.append(obj)\n\n gradients.sort(key=lambda o: o.name)\n\n for gra in gradients:\n for obj in meshes:\n gra.apply_gradient(obj)\n\n return {'FINISHED'}\n\nclass GradientSwap(bpy.types.Operator):\n bl_idname = 'cc.gradient_swap'\n bl_label = 'Swap Gradient Colors'\n bl_options = {'REGISTER'}\n\n def execute(self, context):\n g = context.scene.gradient_settings\n\n color_a = g.color_a.copy()\n alpha_a = g.alpha_a\n color_b = g.color_b.copy()\n alpha_b = g.alpha_b\n\n g.color_a = color_b\n g.alpha_a = alpha_b\n g.color_b = color_a\n g.alpha_b = alpha_a\n\n return {'FINISHED'}\n\ndef reset_gradient_props(obj):\n setattr(obj, 'blend_type', 'DIRECTIONAL')\n setattr(obj, 'blend_method', 'REPLACE')\n setattr(obj, 'blend_falloff', 'LINEAR')\n setattr(obj, 'bias', 0)\n setattr(obj, 'scale', 1)\n setattr(obj, 'mirror', False)\n setattr(obj, 'color_a', mu.Color((0, 0, 0)))\n setattr(obj, 'alpha_a', 1)\n setattr(obj, 'color_b', mu.Color((1, 1, 1)))\n setattr(obj, 'alpha_b', 1)\n\nclass GradientDefault(bpy.types.Operator):\n bl_idname = 'cc.gradient_default'\n bl_label = 'Reset Gradient Colors'\n bl_options = {'REGISTER'}\n\n def execute(self, context):\n g = context.scene.gradient_settings\n reset_gradient_props(g)\n return {'FINISHED'}\n\nclass GradientTool(bpy.types.Operator):\n bl_idname = 'cc.gradient_tool'\n bl_label = 'Gradient Tool'\n bl_options = {'REGISTER', 'UNDO'}\n\n select = PROP_SELECT\n blend_type = PROP_BLEND_TYPE\n blend_method = PROP_BLEND_METHOD\n blend_falloff = PROP_BLEND_FALLOFF\n color_a = PROP_COLOR_A\n alpha_a = PROP_ALPHA_A\n color_b = PROP_COLOR_B\n alpha_b = PROP_ALPHA_B\n bias = PROP_BIAS\n scale = PROP_SCALE\n mirror = PROP_MIRROR\n\n def reset_func(self, context):\n if self.reset:\n reset_gradient_props(self)\n self.reset = False\n\n reset = bpy.props.BoolProperty(name='Reset', update=reset_func)\n\n point_a = bpy.props.FloatVectorProperty(\n name='Start Point', default=(0.0, 0.0, 0.0))\n point_b = bpy.props.FloatVectorProperty(\n name='End Point', default=(0.0, 0.0, 0.0))\n\n create = bpy.props.BoolProperty()\n\n @classmethod\n def poll(cls, context):\n obj = context.active_object\n return obj and obj.type == 'MESH'\n\n def __init__(self):\n self._draw_3d = None\n self._draw_2d = None\n self.mouse_a = (0, 0)\n self.mouse_b = (0, 0)\n self.mouse_now = (0, 0)\n self.started = False\n\n def __del__(self):\n self.del_viewport_handler()\n\n def draw(self, context):\n draw_gradient_settings(context, self.layout, self)\n self.layout.prop(self, 'reset', toggle=True)\n\n def execute(self, context):\n args = (\n mu.Vector(self.point_a), mu.Vector(self.point_b),\n self.color_a, self.alpha_a,\n self.color_b, self.alpha_b,\n self.blend_type, self.blend_method, self.blend_falloff,\n self.bias, self.scale, self.mirror,\n self.select,\n )\n\n gradient_colors(context.active_object, *args)\n if self.create:\n obj = gen_gradient_object(*args)\n context.scene.objects.link(obj)\n context.scene.update()\n\n theme = context.user_preferences.themes[0].view_3d\n theme.face_select[3] = self.face_select\n theme.editmesh_active[3] = self.editmesh_active\n context.area.tag_redraw()\n\n g = context.scene.gradient_settings\n g.select = self.select\n g.blend_type = self.blend_type\n g.blend_method = self.blend_method\n g.blend_falloff = self.blend_falloff\n g.color_a = self.color_a\n g.alpha_a = self.alpha_a\n g.color_b = self.color_b\n g.alpha_b = self.alpha_b\n g.bias = self.bias\n g.scale = self.scale\n g.mirror = self.mirror\n\n return {'FINISHED'}\n\n def invoke(self, context, event):\n scene = context.scene\n\n context.space_data.viewport_shade = 'TEXTURED'\n\n self.select = scene.gradient_settings.select\n self.blend_type = scene.gradient_settings.blend_type\n self.blend_method = scene.gradient_settings.blend_method\n self.blend_falloff = scene.gradient_settings.blend_falloff\n self.color_a = scene.gradient_settings.color_a\n self.alpha_a = scene.gradient_settings.alpha_a\n self.color_b = scene.gradient_settings.color_b\n self.alpha_b = scene.gradient_settings.alpha_b\n self.bias = scene.gradient_settings.bias\n self.scale = scene.gradient_settings.scale\n self.mirror = scene.gradient_settings.mirror\n\n theme = context.user_preferences.themes[0].view_3d\n self.face_select = theme.face_select[3]\n self.editmesh_active = theme.editmesh_active[3]\n theme.face_select[3] = 0\n theme.editmesh_active[3] = 0\n context.area.tag_redraw()\n\n context.window_manager.modal_handler_add(self)\n\n return {'RUNNING_MODAL'}\n\n def modal(self, context, event):\n ret = {'PASS_THROUGH'}\n\n if self._draw_3d is None:\n self.add_viewport_handler(context)\n\n context.area.tag_redraw()\n context.window.cursor_set('CROSSHAIR')\n\n region = bpy.context.region\n region_3d = bpy.context.space_data.region_3d\n mouse_pos = (event.mouse_region_x, event.mouse_region_y)\n\n self.mouse_now = mouse_pos\n\n direction = view3d_utils.region_2d_to_vector_3d(region, region_3d, mouse_pos)\n endpoint = view3d_utils.region_2d_to_location_3d(region, region_3d, mouse_pos, region_3d.view_location)\n\n if region_3d.is_perspective:\n origin = endpoint - direction * region_3d.view_distance\n farpoint = origin + direction * 1000\n else:\n origin = endpoint + direction * region_3d.view_distance\n farpoint = origin - direction * 1000\n\n if event.ctrl:\n result, obj, matrix, location, normal = context.scene.ray_cast(origin, farpoint)\n if result:\n endpoint = location\n ret = {'RUNNING_MODAL'}\n\n if event.type == 'LEFTMOUSE' and event.value == 'PRESS':\n self.started = True\n self.point_a = endpoint\n self.mouse_a = mouse_pos\n self.mouse_b = mouse_pos\n ret = {'RUNNING_MODAL'}\n\n if event.type == 'MOUSEMOVE':\n self.point_b = endpoint\n self.mouse_b = mouse_pos\n\n if event.type == 'RIGHTMOUSE' and event.value == 'PRESS':\n if event.shift:\n self.color_b = sample_color(context, event)\n else:\n self.color_a = sample_color(context, event)\n return {'RUNNING_MODAL'}\n\n if event.type == 'LEFTMOUSE' and event.value == 'RELEASE':\n self.point_b = endpoint\n self.mouse_b = mouse_pos\n self.create = event.alt\n if self.mouse_a != self.mouse_b:\n self.execute(context)\n self.modal_cleanup(context, event)\n return {'FINISHED'}\n\n if event.type == 'ESC':\n self.modal_cleanup(context, event)\n return {'CANCELLED'}\n\n return ret\n\n def modal_cleanup(self, context, event):\n self.del_viewport_handler()\n context.window.cursor_set('DEFAULT')\n\n theme = context.user_preferences.themes[0].view_3d\n theme.face_select[3] = self.face_select\n theme.editmesh_active[3] = self.editmesh_active\n context.area.tag_redraw()\n\n def draw_viewport_2d(self, context):\n bgl.glPushAttrib(\n bgl.GL_DEPTH_BUFFER_BIT |\n bgl.GL_LINE_BIT |\n bgl.GL_COLOR_BUFFER_BIT |\n bgl.GL_CURRENT_BIT)\n\n bgl.glEnable(bgl.GL_BLEND)\n bgl.glDepthFunc(bgl.GL_ALWAYS)\n bgl.glLineWidth(1)\n\n if self.started:\n ax, ay = self.mouse_a\n bx, by = self.mouse_b\n\n bgl.glBegin(bgl.GL_LINES)\n\n bgl.glColor4f(0, 0, 0, 1)\n bgl.glVertex2f(ax + 1, ay)\n bgl.glVertex2f(bx + 1, by)\n bgl.glVertex2f(ax - 1, ay)\n bgl.glVertex2f(bx - 1, by)\n bgl.glVertex2f(ax, ay + 1)\n bgl.glVertex2f(bx, by + 1)\n bgl.glVertex2f(ax, ay - 1)\n bgl.glVertex2f(bx, by - 1)\n\n bgl.glColor4f(1, 1, 1, 1)\n bgl.glVertex2f(ax, ay)\n bgl.glVertex2f(bx, by)\n\n bgl.glEnd()\n\n mx, my = self.mouse_now\n my -= 16\n\n bgl.glBegin(bgl.GL_QUADS)\n bgl.glColor3f(0, 0, 0)\n bgl.glVertex2f(mx - 9, my - 8)\n bgl.glVertex2f(mx, my + 1)\n bgl.glVertex2f(mx + 9, my - 8)\n bgl.glVertex2f(mx, my - 17)\n bgl.glEnd()\n\n bgl.glBegin(bgl.GL_TRIANGLES)\n bgl.glColor3f(*self.color_a)\n bgl.glVertex2f(mx - 8, my - 8)\n bgl.glVertex2f(mx, my)\n bgl.glVertex2f(mx, my - 16)\n bgl.glEnd()\n\n bgl.glBegin(bgl.GL_TRIANGLES)\n bgl.glColor3f(*self.color_b)\n bgl.glVertex2f(mx, my)\n bgl.glVertex2f(mx + 8, my - 8)\n bgl.glVertex2f(mx, my - 16)\n bgl.glEnd()\n\n bgl.glPopAttrib();\n\n def draw_viewport_3d(self, context):\n pass\n\n def add_viewport_handler(self, context):\n self._draw_3d = bpy.types.SpaceView3D.draw_handler_add(\n self.draw_viewport_3d, (context,), 'WINDOW', 'POST_VIEW')\n self._draw_2d = bpy.types.SpaceView3D.draw_handler_add(\n self.draw_viewport_2d, (context,), 'WINDOW', 'POST_PIXEL')\n\n def del_viewport_handler(self):\n if self._draw_3d:\n bpy.types.SpaceView3D.draw_handler_remove(self._draw_3d, 'WINDOW')\n self._draw_3d = None\n if self._draw_2d:\n bpy.types.SpaceView3D.draw_handler_remove(self._draw_2d, 'WINDOW')\n self._draw_2d = None\n\ndef register():\n cc.utils.register(__REGISTER__)\n\ndef unregister():\n cc.utils.unregister(__REGISTER__)\n\n__REGISTER__ = (\n GradientSettings,\n GradientPanel,\n GradientPresetAdd,\n GradientPresetRemove,\n GradientPresetUpdate,\n GradientPresetRevert,\n GradientObject,\n GradientLoad,\n GradientApply,\n GradientSwap,\n GradientDefault,\n GradientTool,\n (bpy.types.Scene, 'gradient_settings', PROP_GRADIENT_SETTINGS),\n (bpy.types.Scene, 'gradient_presets', PROP_GRADIENT_PRESETS),\n (bpy.types.Scene, 'gradient_active_preset', PROP_GRADIENT_ACTIVE_PRESET),\n (bpy.types.Mesh, 'gradient_settings', PROP_GRADIENT_SETTINGS),\n (bpy.types.Object, 'is_gradient', PROP_IS_GRADIENT),\n (bpy.types.Object, 'apply_gradient', apply_gradient),\n)\n","repo_name":"cardboardcomputer/Blender-Middleware","sub_path":"Blender/2.69/scripts/addons/cc_tool_gradient.py","file_name":"cc_tool_gradient.py","file_ext":"py","file_size_in_byte":28680,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"48"} +{"seq_id":"9438415004","text":"from bs4 import BeautifulSoup\nfrom datetime import datetime\n\n\ndef parse_xml(file_name):\n \"\"\" Using bs4, the case document is parsed. Three parts are extracted: the rdf; containing mostly meta-information,\n the case summary, and the case description. Returns a dictionary of all relevant pieces of information of the case.\n \"\"\"\n # Passing the stored data inside the beautifulsoup parser\n file_xml = BeautifulSoup(file_name, 'xml')\n\n # Find the RDF info, case summary and case description\n case_rdf = file_xml.find('rdf:RDF')\n case_summary = file_xml.find('inhoudsindicatie')\n case_description = file_xml.find('uitspraak')\n\n # For some cases the element 'conclusie' is used instead of 'uitspraak'\n if case_description is None:\n case_description = file_xml.find('conclusie')\n\n # Parse case_rdf to get document meta attributes\n case_content = get_document_attributes(case_rdf)\n\n # Will tell us whether summary, description, or both are missing\n missing = tuple()\n\n # Extract the summary text\n if case_summary is not None:\n case_content['summary'] = case_summary.get_text(separator=' ', strip=True)\n else:\n case_content['summary'] = 'none'\n missing = missing + ('summary',)\n\n # Extract the description text\n if case_description is not None:\n case_content['description'] = case_description.get_text(separator=' ', strip=True)\n else:\n case_content['description'] = 'none'\n missing = missing + ('description',)\n\n # Tuples can't be stored in a parquet\n missing = 'none' if len(missing) == 0 else '|'.join(missing)\n\n # Add information about missing parts to meta df\n case_content['missing_parts'] = missing\n\n return case_content\n\n\ndef get_document_attributes(case_rdf):\n \"\"\" Parses case information that is contained in the rdf tag of the XML file, returning a dictionary containing\n the relevant pieces of (meta) information of a case.\n \"\"\"\n rdf_tags = {}\n\n # Tag pointer dictionary for single tag items\n # Cardinalities are taken from chapter 12 of the pdf 'Technische documentatie Open Data van de Rechtspraak'\n # found at: https://www.rechtspraak.nl/Uitspraken/paginas/open-data.aspx\n # Cardinality: 0/1 - 1\n tag_pointer_dict = {\n 'identifier': 'dcterms:identifier', # 1 - 1\n 'seat_location': 'dcterms:spatial', # 0 - 1\n # 'publisher': 'dcterms:publisher', # 1 - 1, omit because always equal to 'Raad voor de Rechtspraak'\n 'creator': 'dcterms:creator', # 1 - 1\n 'case_type': 'dcterms:type', # 1 - 1\n # 'language':'dcterms:language', # 1 - 1, omit because always equal to NL\n # 'format':'dcterms:format', # 1 - 1, omit because always equal to text/xml\n }\n\n # Tag pointer dictionary for multi tag items\n # Cardinality 0/1 - many\n multi_tag_pointer_dict = {\n 'jurisdiction': 'dcterms:subject', # 0 - many\n 'case_number': 'psi:zaaknummer', # 1 - many\n 'procedures': 'psi:procedure', # 0 - many\n 'references': 'dcterms:references', # 0 - many\n 'relation': 'dcterms:relation' # 0 - many\n }\n\n # Date type cases\n date_tag_pointer_dict = {\n 'issue_date': 'dcterms:issued', # 1 - 1\n 'judgment_date': 'dcterms:date' # 1 - 1\n }\n\n # Datetime type cases\n datetime_tag_pointer_dict = {\n 'modified': 'dcterms:modified' # 1 - 1\n }\n\n # Start with the single tag items\n for tag, pointer in tag_pointer_dict.items():\n found_tag = case_rdf.find(pointer)\n if found_tag is not None:\n rdf_tags[tag] = str(found_tag.text)\n else:\n rdf_tags[tag] = 'none'\n\n # Lets do the multi tags\n for tag, pointer in multi_tag_pointer_dict.items():\n found_tags = ()\n tag_mentions = case_rdf.find_all(pointer)\n for mention in tag_mentions:\n found_tags += (mention.text,)\n\n rdf_tags[tag] = 'none' if len(found_tags) == 0 else '|'.join(found_tags)\n\n # Date tags (%Y-%m-%d)\n for tag, pointer in date_tag_pointer_dict.items():\n found_tag = case_rdf.find(pointer)\n if found_tag is not None:\n rdf_tags[tag] = datetime.strptime(found_tag.text, '%Y-%m-%d') # .date()\n else:\n rdf_tags[tag] = 'none'\n\n # Datetime tags (%Y-%m-%dT%H:%M:%S)\n for tag, pointer in datetime_tag_pointer_dict.items():\n found_tag = case_rdf.find(pointer)\n if found_tag is not None:\n rdf_tags[tag] = datetime.strptime(found_tag.text, '%Y-%m-%dT%H:%M:%S')\n else:\n rdf_tags[tag] = 'none'\n\n return rdf_tags\n","repo_name":"PrijsDF/dutch-legal-summarization","sub_path":"src/data/parse_xml_functions.py","file_name":"parse_xml_functions.py","file_ext":"py","file_size_in_byte":4621,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"11200235802","text":"def add_key(module, sheet):\n INVENTORY['module'] = module\n INVENTORY['sheet'] = sheet\n return INVENTORY\n\n\n# 根据module的key值来读取相应的在ArgumentAdmin.yaml中相应的子dict内容\nfocus = 'focus'\nimg = 'img'\ninvite = 'invite'\nsecKill = 'secKill'\nmutually = 'mutually'\npromote = 'promote'\nreceive = 'receive'\nredpacket = 'redpacket'\nfeedback = 'feedback'\nentrance = 'entrance'\nrelation = 'relation'\nqrcode=\"qrcode\"\n\n# 根据sheet的value值来读取ArgumentAdmin.yaml中,用例的标签名\ncity = 'city'\npage = 'page'\noperate = 'operate'\ncontrast = 'contrast'\npreview = 'preview'\nrules = 'rules'\ntabs = 'tabs'\nselect = 'select'\ndefault = \"default\"\nadd = \"add\"\n\n# 更新此处的key时,需要把ArgumentAdmin.yaml的key值也进行修改\nINVENTORY = {\n 'menu': 'generalize', # 菜单标识符的定义\n 'module': 'no data', # 菜单中模块标识符的定义\n 'sheet': 'no data', # 模块所对应的用例标签名\n 'yaml': 'expression/GeneralizeAssist.yaml' # 菜单所对应的yaml路径\n}\n","repo_name":"namexiaohuihui/operating","sub_path":"CenterBackground/GeneralizeAssist/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42260912535","text":"# from unicodedata import name\nfrom flask import Flask, render_template, request, redirect\nfrom flask import Blueprint\n\nfrom models.product import Product\nfrom models.maker import Maker\n\nimport repositories.maker_repository as maker_repository\nimport repositories.product_repository as product_repository # Keep an eye on the order\n\nproducts_blueprint = Blueprint(\"products\", __name__)\n\n\n@products_blueprint.route(\"/products\")\ndef products():\n products = product_repository.select_all()\n return render_template(\"products/index.html\", products = products) # this could go into / and homepage\n\n################################################################\n\n@products_blueprint.route(\"/products/new\", methods=['GET']) \ndef new_product():\n products = product_repository.select_all()\n makers = maker_repository.select_all() \n return render_template(\"products/new.html\", products = products, makers = makers)\n\n@products_blueprint.route(\"/products\", methods=['POST'])\ndef add_product():\n ### would ID be in here? isnt ID automatically generated? \n name = request.form['name']\n purchase = request.form['purchase']\n sell = request.form['sell']\n description = request.form['description']\n stock_qty = request.form['stock_qty']\n\n maker_id = request.form['maker_id']\n maker = maker_repository.select(maker_id)\n product = Product(name, purchase, sell, description, stock_qty, maker)\n product_repository.save(product)\n return redirect(\"/products\")\n\n################################################################\n\n@products_blueprint.route(\"/products/\", methods=['GET'])\ndef show_product(id):\n product = product_repository.select(id)\n return render_template(\"products/show.html\", product=product)\n\n@products_blueprint.route(\"/products//edit\", methods=['GET'])\ndef edit_product(id):\n# products = product_repository.select(id)\n# maker = maker_repository.select_all()\n return render_template(\"products/edit.html\", \n product = product_repository.select(id),\n makers = maker_repository.select_all())\n\n@products_blueprint.route(\"/products//delete\", methods=['POST'])\ndef delete_product(id):\n product_repository.delete(id)\n return redirect('/products')\n\n@products_blueprint.route(\"/products/\", methods=['POST'])\ndef update_product(id):\n name = request.form['name']\n purchase = request.form['purchase']\n sell = request.form['sell']\n description = request.form['description']\n stock_qty = request.form['stock_qty']\n maker = maker_repository.select(request.form['maker_id'])\n product = Product(name, purchase, sell, description, stock_qty, maker, id) # sus\n # product = product_repository.select(maker)\n product_repository.update(product)\n return redirect(\"/products\")\n\n\n","repo_name":"EFXHK/cc_shopkeeper_project","sub_path":"controllers/product_controller.py","file_name":"product_controller.py","file_ext":"py","file_size_in_byte":2845,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"19155746646","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom palmiche.utils import tools, xvg\nimport argparse \n\n\nclass POT:\n \"\"\"\n This class is used to calculate the flat bottom potential of a trajectory where this kind of potential was used. See:\n https://manual.gromacs.org/documentation/2019/reference-manual/functions/restraints.html\n \"\"\"\n def __init__(self, typepot, coords,**keywords):#force\n self.typepot = typepot\n #self.force = force\n self.coords = coords\n self.keywords = keywords\n POTENTIALS = {\"flat_bottom\": np.vectorize(self.flat_bottom)}\n self.pot = POTENTIALS[self.typepot](self.coords)\n def flat_bottom(self, array):\n if array < self.keywords['ref']:\n return 0.0\n else:\n return 0.5*self.keywords['k']*(array - self.keywords['ref'])**2\n\n #self.pot = [-0.5*(item[0] - self.keywords['ref'])*item[1] for item in zip(self.coord, self.force)]\n\n def plot(self, time):\n plt.plot(time, self.pot)\n plt.title(f\"Potential.\")\n plt.xlabel(\"Time\")\n plt.ylabel(\"V(t)\")\n plt.show()\n \n \nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser(description='A test program.')\n parser.add_argument(\"coord\", help = \"The index of the coord (column index in the cvg file).\", type = int)\n # parser.add_argument(\"-f\", \n # dest=\"pullf\",\n # default = \"pull_pullf.xvg\",\n # help = \"The pullf file. Default is pull_pullf.xvg\",\n # type = str)\n parser.add_argument(\"-x\", \n dest=\"pullx\",\n default = \"pull_pullx.xvg\",\n help = \"The pullx file. Default is pull_pullx.xvg\",\n type = str) \n parser.add_argument(\"-r\", \n dest=\"ref\",\n default = 0,\n help = \"The reference value for the potential. Default is 0\",\n type = float)\n parser.add_argument(\"-k\", \n dest=\"k\",\n default = 0,\n help = \"The reference value for the potential. Default is 0\",\n type = float)\n parser.add_argument(\"-p\", \n dest=\"pot\",\n default = \"flat_bottom\",\n help = \"The potential name. Default is flat_bottom. Could be selected: flat_bottom, ...\",\n type = str) \n args = parser.parse_args()\n\n #f = xvg.XVG(args.pullf).data[:,args.coord]\n x = xvg.XVG(args.pullx).data[:,args.coord]\n t = xvg.XVG(args.pullx).data[:,0]\n k = POT(args.pot, x, ref = args.ref, k = args.k).plot(t)\n","repo_name":"ale94mleon/Palmiche","sub_path":"src/palmiche/utils/potentials.py","file_name":"potentials.py","file_ext":"py","file_size_in_byte":2814,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"43979965111","text":"import glob\nimport os\nimport re\nimport datetime\n\nimport netCDF4\nimport numpy as np\nimport pandas as pd\nfrom scipy.interpolate import interp2d, interpn\n\n\nfrom .proj.grids import RotatedGrid\n\n\nclass COSMOnetCDFDataset(object):\n def __init__(self, path_to_files, analysis_file=\"lfff00000000c.nc\"):\n self._date_time_regex = re.compile(\n \"(\\d{4})-(\\d{2})-(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2})\")\n self._variables = None\n self._init_time = None\n self._history_interval = None\n self._timesteps = None\n self._lats = None\n self._lons = None\n self._rlats = None\n self._rlons = None\n self._xshape = None\n self._yshape = None\n self._last_time = None\n self._grid_north_pole_lat = None\n self._grid_north_pole_lon = None\n self._rotated_grid = None\n self._analysis_file = analysis_file\n self._cosmo_file_path = os.path.join(path_to_files, '')\n self._files_in_path = list(set(glob.glob(self._cosmo_file_path + \"lfff*.nc\")) -\n set(glob.glob(self._cosmo_file_path + self._analysis_file)))\n self._files_in_path.sort()\n self._num_of_files = len(self._files_in_path)\n if self._num_of_files < 1:\n raise ValueError(\n \"COSMOPython Lib: No COSMO netCDF dataset found. Check the path\")\n try:\n self._cosmo_multifile = netCDF4.MFDataset(self._files_in_path)\n except:\n raise ValueError(\n \"COSMOPythonLib: netCDF File(s) could not be opened. Corrupt file(s)?\")\n self.__create_meta_data()\n\n def __create_meta_data(self):\n self._variables = self._cosmo_multifile.variables.keys()\n __init_string = self._cosmo_multifile['time'].units\n __date_match = self._date_time_regex.findall(__init_string)\n self._init_time = datetime.datetime(int(__date_match[0][0]), int(__date_match[0][1]), int(__date_match[0][2]),\n int(__date_match[0][3]), int(__date_match[0][4]), int(__date_match[0][5]))\n self.__extract_coordinates(self._cosmo_multifile)\n __delta_T = self._cosmo_multifile['time'][:][1]\n self._history_interval = datetime.timedelta(seconds=int(__delta_T))\n __delta_T = self._cosmo_multifile['time'][:][-1]\n __delta_T_timedelta = datetime.timedelta(seconds=int(__delta_T))\n self._last_time = self._init_time + __delta_T_timedelta\n self._timesteps = len(self._cosmo_multifile['time'][:])\n self._initialize_Rotated_Grid()\n\n def __extract_coordinates(self, cosmofile):\n self._lons = cosmofile['lon'][:]\n self._lats = cosmofile['lat'][:]\n self._rlats = cosmofile['rlat'][:]\n self._rlons = cosmofile['rlon'][:]\n self._xshape = len(self._rlons)\n self._yshape = len(self._rlats)\n\n def get_variables(self, vars, start=None, end=None, order_by='date'):\n if vars is None:\n raise ValueError(\"Please choose variables\")\n if not isinstance(vars, list):\n vars = [vars]\n if start is None:\n start = self._init_time\n if end is None:\n end = self._last_time\n if start > end:\n raise ValueError(\n \"start {} > end {}, choose a correct date range\".format(start, end))\n __res_dict = {}\n if order_by == 'date':\n for i in range(0, self._timesteps):\n _delta_t = datetime.timedelta(seconds=int(\n self._cosmo_multifile['time'][:][i]))\n _file_date = self._init_time + _delta_t\n if _file_date >= start and _file_date <= end:\n __res_dict[_file_date] = {}\n for arg in vars:\n try:\n __res_dict[_file_date][arg] = self._cosmo_multifile[arg][i][:]\n except:\n raise ValueError(\n \"Could not load variable {}. Is it available?\".format(arg))\n elif order_by == 'variable':\n for arg in vars:\n __res_dict[arg] = {}\n for i in range(0, self._timesteps):\n _delta_t = datetime.timedelta(seconds=int(\n self._cosmo_multifile['time'][:][i]))\n _file_date = self._init_time + _delta_t\n if _file_date >= start and _file_date <= end:\n for arg in vars:\n try:\n __res_dict[arg][_file_date] = self._cosmo_multifile[arg][i][:]\n except:\n raise ValueError(\n \"Could not load variable {}. Is it available?\".format(arg))\n else:\n raise ValueError(\"Please specify ordering...\")\n return __res_dict\n\n def get_timeseries_at_latlon(self, vars, lat, lon, typ='latlon', start=None, end=None):\n if vars is None:\n raise ValueError(\"Please choose variables\")\n if not isinstance(vars, list):\n vars = [vars]\n if start is None:\n start = self._init_time\n if end is None:\n end = self._last_time\n if start > end:\n raise ValueError(\n \"start {} > end {}, choose a correct date range\".format(start, end))\n if lat is None or lon is None:\n raise ValueError(\n \"lat or lon not given. PLease provide coordinates\"\n )\n self.checkCoordinates(lat, lon)\n _dims = {}\n _columns = ['datetime']\n for var in vars:\n _columns.append(var)\n try:\n dim = self._cosmo_multifile[var].dimensions\n except:\n raise ValueError(\n \"Could not load variable {}. Is it available?\".format(var))\n if len(dim) == 4:\n _dims[var] = \"XYZT\"\n elif len(dim) == 3:\n _dims[var] = \"XYT\"\n else:\n raise ValueError(\"Something is strange, dims not 4 or 3..\")\n if typ == 'latlon':\n lat, lon = self._rotated_grid.transformToRot(lats=lat, lons=lon)\n __res_list = []\n for i in range(0, self._timesteps):\n _delta_t = datetime.timedelta(seconds=int(\n self._cosmo_multifile['time'][:][i]))\n _file_date = self._init_time + _delta_t\n if _file_date >= start and _file_date <= end:\n __rec_list = []\n _delta_t = datetime.timedelta(seconds=int(\n self._cosmo_multifile['time'][:][i]))\n _file_date = self._init_time + _delta_t\n __rec_list.append(_file_date)\n for arg in vars:\n _raw = self._cosmo_multifile[arg][i][:]\n _inteprolator = interp2d(\n self._rlons, self._rlats, _raw)\n _res = float(_inteprolator(lon, lat))\n __rec_list.append(_res)\n __res_list.append(__rec_list)\n df = pd.DataFrame.from_records(__res_list, columns=_columns)\n df.index = df['datetime']\n df.drop('datetime', axis=1, inplace=True)\n print(df) \n\n\n def checkCoordinates(self, lon, lat):\n if not -90 <= lat <= 90:\n raise ValueError(\n \"Using latlon coordinates, lat not between -90 and 90N\")\n if not -180 <= lon <= 180:\n raise ValueError(\n \"Using latlon coordinates, lon not between -180 and 180W\")\n \n def _initialize_Rotated_Grid(self):\n self._grid_north_pole_lat = self._cosmo_multifile['rotated_pole'].grid_north_pole_latitude\n self._grid_north_pole_lon = self._cosmo_multifile['rotated_pole'].grid_north_pole_longitude\n self._rotated_grid = RotatedGrid(pollon=self._grid_north_pole_lon, pollat=self._grid_north_pole_lat)\n\n def transformToRot(self, lats, lons):\n return self._rotated_grid.transformToRot(lons=lons, lats=lats)\n \n\n def transformToReg(self, rlats, rlons):\n return self._rotated_grid.transformToReg(rlons=rlons, rlats=rlats)\n\n @property\n def variables(self):\n return self._variables\n\n @property\n def num_of_files(self):\n return self._num_of_files\n\n @property\n def init_time(self):\n return self._init_time\n\n @property\n def rotated_coordinates(self):\n return np.array([self._rlons, self._rlats])\n\n @property\n def regular_meshgrid(self):\n return np.array([self._lons, self._lats])\n\n @property\n def last_date(self):\n return self._last_time\n\n @property\n def history_interval(self):\n return self._history_interval\n\n\n","repo_name":"pick2510/COSMOPythonLib","sub_path":"COSMOPythonLib/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":8791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28056736133","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 14 22:40:18 2019\n\n@author: TrevorMorrisey\n\"\"\"\n\nimport peUtilities\n\ndef highlyDivisibleTriangularNumber():\n index = 1\n counter = 0\n while True:\n counter = index\n currentSum = 0\n while counter > 0:\n currentSum += counter\n counter -= 1\n if len(peUtilities.getFactors(currentSum)) > 500:\n return currentSum\n else:\n index += 1","repo_name":"TrevorMorrisey/Project-Euler","sub_path":"Python/pe012.py","file_name":"pe012.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70567706385","text":"# -*- coding: utf-8 -*-\nfrom django.conf.urls import url\nfrom django_notify import views\n\nurlpatterns = [\n url('^json/get/$', views.get_notifications, name='json_get', kwargs={}),\n url('^json/mark-read/$', views.mark_read, name='json_mark_read_base', kwargs={}),\n url('^json/mark-read/(\\d+)/$', views.mark_read, name='json_mark_read', kwargs={}),\n url('^goto/(?P\\d+)/$', views.goto, name='goto', kwargs={}),\n url('^goto/$', views.goto, name='goto_base', kwargs={}),\n]\n\ndef get_pattern(app_name=\"notify\", namespace=\"notify\"):\n \"\"\"Every url resolution takes place as \"notify:view_name\".\n https://docs.djangoproject.com/en/dev/topics/http/urls/#topics-http-reversing-url-namespaces\n \"\"\"\n return urlpatterns, app_name, namespace","repo_name":"AlaaSwedan/edx","sub_path":"edx/app/edxapp/venvs/edxapp/lib/python2.7/site-packages/django_notify/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37500400703","text":"import pygame\nfrom pygame.locals import *\n\nclass Playeur:\n\n\tdef __init__(self,typeP):\n\t\tif typeP == 1:\n\t\t\tself.x=10\n\t\t\tself.y = 10\n\t\t\tself.sprite = pygame.image.load(\"bluePlayeur.png\").convert_alpha()\n\t\telif typeP == 2:\n\t\t\tself.x=10\n\t\t\tself.y=860\n\t\t\tself.sprite = pygame.image.load(\"yellowPlayeur.png\").convert_alpha()\n\t\tself.sprite = pygame.transform.scale(self.sprite, (30,60))\n\t\n\tdef move(self, direction):\n\t\tif self.x < direction:\n\t\t\tself.x = self.x + 1\n\t\telif self.x > direction:\n\t\t\tself.x = self.x - 1\n\t\n\tdef moveKeyboard(self, key):\n\t\tself.x = self.x + key\n\t\tprint(self.x,self.y)\n","repo_name":"chaudois/coursESGI","sub_path":"Cours Python/pong game/classs.py","file_name":"classs.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29170641005","text":"#! /usr/bin/env python\n\n__author__ = 'bbowman@pacificbiosciences.com'\n\nfrom setuptools import setup, Extension, find_packages\nimport sys\n\ndesc = 'Tools for analyzing large metagenomic contigs'\n\nif (\"install\" in sys.argv) and sys.version_info < (2, 7, 0):\n raise SystemExit(\"MetagenomicsTools requires Python 2.7\")\n\nsetup(\n name = 'MetagenomicTools',\n version='0.1',\n author='Brett Bowman',\n author_email='bbowman@pacificbiosciences.com',\n url='https://github.com/bnbowman/MetagenomicTools',\n description=desc,\n license=open('LICENSES.txt').read(),\n packages = find_packages('src'),\n package_dir = {'':'src'},\n zip_safe = False,\n install_requires=[\n 'h5py >= 2.0.1',\n 'numpy >= 1.8.0',\n 'pbcore >= 0.8.0',\n ]\n )","repo_name":"bnbowman/MetagenomicTools","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21561064096","text":"import json\nimport boto3\nfrom boto3.dynamodb.conditions import Key, Attr\nimport datetime\n\n# ローカルで開発する場合は、\"\"http://dynamodb-local:8000\"\"で良いが、AWSにデプロイする場合は、実際のdynamodbのエンドポイントを指定する必要がある\n# TODO : -> endpoint_url不要(削除したら動いた、なぜ?)→ ローカルでの開発時も不要??\n#\n# 東京リージョンの場合、「dynamodb.ap-northeast-1.amazonaws.com」\n# 参考:https://docs.aws.amazon.com/ja_jp/general/latest/gr/ddb.html\n# client = boto3.client('dynamodb', endpoint_url = \"http://dynamodb-local:8000\")\nclient = boto3.client('dynamodb')\ndynamodb = boto3.resource('dynamodb')\ntable = dynamodb.Table('project_info')\n\n# API Gatewayのルールに則った成功の response を生成する\ndef create_success_response(body, **kwargs):\n origin = '*'\n methods = 'GET'\n\n for k, v in kwargs.items():\n if k == 'origin' : origin = v\n if k == 'methods' : methods = v \n\n headers = {\n 'Access-Control-Allow-Headers' : 'Content-Type',\n 'Access-Control-Allow-Origin' : origin,\n 'Access-Control-Allow-Methods' : methods\n }\n\n # Logger.info(\n # 'return values headers = {}, body = {}, origin = {}, methods = {}'\n # .format(headers, body, origin, methods)\n # )\n\n return {\n 'isBase64Encoded': False,\n 'statusCode' : 200,\n 'headers' : headers,\n 'body' : json.dumps(body)\n }\n\n# API Gatewayのルールに則った失敗の response を生成する\ndef create_error_response(body, **kwargs):\n origin = '*'\n methods = 'GET'\n\n for k, v in kwargs.items():\n if k == 'origin' : origin = v\n if k == 'methods' : methods = v \n\n headers = {\n 'Access-Control-Allow-Headers' : 'Content-Type',\n 'Access-Control-Allow-Origin' : origin,\n 'Access-Control-Allow-Methods' : methods\n }\n\n return {\n 'isBase64Encoded': False,\n 'statusCode': 599,\n 'headers': headers,\n 'body': json.dumps(body)\n }\n\n\n'''\n# フロントからのリクエスト\n{\n \"industries\": \"1\",\n \"systemName\": \"テスト\",\n \"period\": \"20230201\",\n \"businessOverview\": \"test\",\n \"language\": [\n \"C#\",\n \"Python3.9\",\n \"Java\",\n \"TypeScript\"\n ],\n \"tools\": [\n \"VSCode\"\n ],\n \"infra\": [\n \"AWS Lambda\"\n ],\n \"workProcess\": {\n \"rd\": true,\n \"bd\": true,\n \"dd\": true,\n \"cd\": true,\n \"ut\": false,\n \"it\": false,\n \"op\": false\n },\n \"role\": \"0\"\n}\n# 上記にプラスして、\nuser_id, \nproject_info_id(システム日付など)を付与\n'''\ndef post_handler(event, context):\n if event['httpMethod'] == 'OPTIONS':\n return create_success_response(\n { 'message': 'successfully: called options method.' },\n methods='GET,OPTIONS,PUT,POST,DELETE'\n )\n \n # リクエストbody取得\n body = json.loads(event[\"body\"])\n print(body)\n\n user_id = body[\"user_id\"]\n data = body[\"data\"]\n t_delta = datetime.timedelta(hours=9)\n JST = datetime.timezone(t_delta, 'JST')\n now = datetime.datetime.now(JST)\n # # db登録\n result = client.put_item(TableName=\"project_info\",\n Item={\n \"user_id\": {\"S\": user_id},\n \"project_id\": {\"S\": f'{now:%Y%m%d%H%M%S}' },\n \"industries\": {\"S\": data['industries']},\n \"systemName\": {\"S\": data['systemName']},\n \"period\": {\"S\": data['period']},\n \"businessOverview\": {\"S\": data['businessOverview']},\n \"language\": {\"S\": ','.join(data['language'])},\n \"tools\": {\"S\": ','.join(data['tools'])},\n \"infra\": {\"S\": ','.join(data['infra'])},\n \"workProcess\": {\"S\": json.dumps(data['workProcess'])},\n \"role\": {\"S\": data['role']},\n })\n\n response = {\n \"statusCode\": 200,\n \"body\": json.dumps(result)\n }\n\n return response\n\n\n'''\n'''\n\ndef get_handler(event, context):\n print(\"========================\")\n print(\"call project_info API\")\n print(\"========================\")\n print(event[\"queryStringParameters\"][\"user_id\"])\n user_id = event[\"queryStringParameters\"][\"user_id\"]\n print(user_id)\n if not user_id == \"\":\n res = table.query(KeyConditionExpression=Key('user_id').eq(user_id))\n else:\n print(\"else\")\n res = client.scan(TableName=\"project_info\") \n print(res['Items'])\n print(\"else\")\n\n headers = {\n 'Access-Control-Allow-Headers' : 'Content-Type',\n 'Access-Control-Allow-Origin' : '*',\n 'Access-Control-Allow-Methods' : 'GET'\n }\n\n response = {\n \"statusCode\": 200,\n 'headers': headers,\n \"body\": json.dumps(res['Items'])\n }\n\n return response\n","repo_name":"myantyuWorld/stackies-app-api","sub_path":"aws-sam-api/project_info/src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5116,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"69904440146","text":"from django.db import IntegrityError\n\nfrom django_otp.oath import totp\nfrom django_otp.tests import TestCase\n\n\nclass TestTwilioSMS(TestCase):\n def setUp(self):\n try:\n self.alice = self.create_user('alice', 'password')\n self.bob = self.create_user('bob', 'password')\n except IntegrityError:\n self.skipTest(\"Unable to create test users.\")\n else:\n self.alice.twiliosmsdevice_set.create(number='test',\n key='01234567890123456789')\n self.bob.twiliosmsdevice_set.create(number='test',\n key='98765432109876543210')\n\n def test_current(self):\n device = self.alice.twiliosmsdevice_set.get()\n token = device.generate_challenge()\n ok = device.verify_token(token)\n\n self.assertTrue(ok)\n\n def test_previous(self):\n device = self.alice.twiliosmsdevice_set.get()\n token = totp(device.bin_key, t0=30)\n ok = device.verify_token(token)\n\n self.assertTrue(ok)\n\n def test_past(self):\n device = self.alice.twiliosmsdevice_set.get()\n token = totp(device.bin_key, t0=60)\n ok = device.verify_token(token)\n\n self.assertTrue(not ok)\n\n def test_future(self):\n device = self.alice.twiliosmsdevice_set.get()\n token = totp(device.bin_key, t0=-30)\n ok = device.verify_token(token)\n\n self.assertTrue(not ok)\n\n def test_cross_user(self):\n device = self.alice.twiliosmsdevice_set.get()\n token = device.generate_challenge()\n ok = self.bob.twiliosmsdevice_set.get().verify_token(token)\n\n self.assertTrue(not ok)\n","repo_name":"L1NT/django-otp-project","sub_path":"django-otp-twilio/otp_twilio/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16835616417","text":"from __future__ import print_function\n\nimport unittest\nimport numpy as np\nimport sys\nsys.path.append(\"..\")\nfrom op_test import OpTest\nimport paddle\nimport paddle.fluid as fluid\nfrom paddle.fluid import compiler, Program, program_guard\nfrom paddle.fluid import core\n\npaddle.enable_static()\nnp.random.seed(10)\n\n\n#Situation 1: repeat_times is a list (without tensor)\nclass TestTileOpRank1(OpTest):\n def setUp(self):\n self.set_npu()\n self.place = paddle.NPUPlace(0)\n self.op_type = \"tile\"\n self.init_data()\n\n self.inputs = {'X': np.random.random(self.ori_shape).astype(\"float32\")}\n self.attrs = {'repeat_times': self.repeat_times}\n output = np.tile(self.inputs['X'], self.repeat_times)\n self.outputs = {'Out': output}\n\n def set_npu(self):\n self.__class__.use_npu = True\n\n def init_data(self):\n self.ori_shape = [100]\n self.repeat_times = [2]\n\n def test_check_output(self):\n self.check_output_with_place(self.place)\n\n def test_check_grad(self):\n pass\n\n\n#with dimension expanding\nclass TestTileOpRank2Expanding(TestTileOpRank1):\n def init_data(self):\n self.ori_shape = [120]\n self.repeat_times = [2, 2]\n\n\nclass TestTileOpRank2(TestTileOpRank1):\n def init_data(self):\n self.ori_shape = [12, 14]\n self.repeat_times = [2, 3]\n\n\nclass TestTileOpRank3_Corner(TestTileOpRank1):\n def init_data(self):\n self.ori_shape = (2, 10, 5)\n self.repeat_times = (1, 1, 1)\n\n\nclass TestTileOpRank3_Corner2(TestTileOpRank1):\n def init_data(self):\n self.ori_shape = (2, 10, 5)\n self.repeat_times = (2, 2)\n\n\nclass TestTileOpRank3(TestTileOpRank1):\n def init_data(self):\n self.ori_shape = (2, 4, 15)\n self.repeat_times = (2, 1, 4)\n\n\nclass TestTileOpRank4(TestTileOpRank1):\n def init_data(self):\n self.ori_shape = (2, 4, 5, 7)\n self.repeat_times = (3, 2, 1, 2)\n\n\n# Situation 2: repeat_times is a list (with tensor)\nclass TestTileOpRank1_tensor_attr(OpTest):\n def setUp(self):\n self.set_npu()\n self.place = paddle.NPUPlace(0)\n self.op_type = \"tile\"\n self.init_data()\n repeat_times_tensor = []\n for index, ele in enumerate(self.repeat_times):\n repeat_times_tensor.append((\"x\" + str(index), np.ones(\n (1)).astype('int32') * ele))\n\n self.inputs = {\n 'X': np.random.random(self.ori_shape).astype(\"float32\"),\n 'repeat_times_tensor': repeat_times_tensor,\n }\n self.attrs = {\"repeat_times\": self.infer_repeat_times}\n output = np.tile(self.inputs['X'], self.repeat_times)\n self.outputs = {'Out': output}\n\n def set_npu(self):\n self.__class__.use_npu = True\n\n def init_data(self):\n self.ori_shape = [100]\n self.repeat_times = [2]\n self.infer_repeat_times = [-1]\n\n def test_check_output(self):\n self.check_output_with_place(self.place)\n\n def test_check_grad(self):\n pass\n\n\nclass TestTileOpRank2_Corner_tensor_attr(TestTileOpRank1_tensor_attr):\n def init_data(self):\n self.ori_shape = [12, 14]\n self.repeat_times = [1, 1]\n self.infer_repeat_times = [1, -1]\n\n\nclass TestTileOpRank2_attr_tensor(TestTileOpRank1_tensor_attr):\n def init_data(self):\n self.ori_shape = [12, 14]\n self.repeat_times = [2, 3]\n self.infer_repeat_times = [-1, 3]\n\n\n# Situation 3: repeat_times is a tensor\nclass TestTileOpRank1_tensor(OpTest):\n def setUp(self):\n self.set_npu()\n self.place = paddle.NPUPlace(0)\n self.op_type = \"tile\"\n self.init_data()\n\n self.inputs = {\n 'X': np.random.random(self.ori_shape).astype(\"float32\"),\n 'RepeatTimes': np.array(self.repeat_times).astype(\"int32\"),\n }\n self.attrs = {}\n output = np.tile(self.inputs['X'], self.repeat_times)\n self.outputs = {'Out': output}\n\n def set_npu(self):\n self.__class__.use_npu = True\n\n def init_data(self):\n self.ori_shape = [100]\n self.repeat_times = [2]\n\n def test_check_output(self):\n self.check_output_with_place(self.place)\n\n def test_check_grad(self):\n pass\n\n\nclass TestTileOpRank2_tensor(TestTileOpRank1_tensor):\n def init_data(self):\n self.ori_shape = [12, 14]\n self.repeat_times = [2, 3]\n\n\n# Situation 4: input x is Integer\nclass TestTileOpInteger(OpTest):\n def setUp(self):\n self.set_npu()\n self.place = paddle.NPUPlace(0)\n self.op_type = \"tile\"\n self.inputs = {\n 'X': np.random.randint(\n 10, size=(4, 4, 5)).astype(\"int32\")\n }\n self.attrs = {'repeat_times': [2, 1, 4]}\n output = np.tile(self.inputs['X'], (2, 1, 4))\n self.outputs = {'Out': output}\n\n def set_npu(self):\n self.__class__.use_npu = True\n\n def test_check_output(self):\n self.check_output_with_place(self.place)\n\n\n# Situation 5: input x is Integer\nclass TestTileOpInt64_t(OpTest):\n def setUp(self):\n self.set_npu()\n self.place = paddle.NPUPlace(0)\n self.op_type = \"tile\"\n self.inputs = {\n 'X': np.random.randint(\n 10, size=(2, 4, 5)).astype(\"int64\")\n }\n self.attrs = {'repeat_times': [2, 1, 4]}\n output = np.tile(self.inputs['X'], (2, 1, 4))\n self.outputs = {'Out': output}\n\n def set_npu(self):\n self.__class__.use_npu = True\n\n def test_check_output(self):\n self.check_output_with_place(self.place)\n\n\n# Situation 6: input x is Bool\nclass TestTileOpBool(OpTest):\n def setUp(self):\n self.set_npu()\n self.place = paddle.NPUPlace(0)\n self.op_type = \"tile\"\n self.inputs = {'X': np.random.randint(1, size=(2, 4, 5)).astype(\"bool\")}\n self.attrs = {'repeat_times': [2, 1, 4]}\n output = np.tile(self.inputs['X'], (2, 1, 4))\n self.outputs = {'Out': output}\n\n def set_npu(self):\n self.__class__.use_npu = True\n\n def test_check_output(self):\n self.check_output_with_place(self.place)\n\n\n# Test python API\nclass TestTileAPI(unittest.TestCase):\n def test_api(self):\n with fluid.dygraph.guard(paddle.NPUPlace(0)):\n np_x = np.random.random([12, 14]).astype(\"float32\")\n x = paddle.to_tensor(np_x)\n\n positive_2 = np.array([2]).astype(\"int32\")\n positive_2 = paddle.to_tensor(positive_2)\n\n repeat_times = np.array([2, 3]).astype(\"int32\")\n repeat_times = paddle.to_tensor(repeat_times)\n\n out_1 = paddle.tile(x, repeat_times=[2, 3])\n out_2 = paddle.tile(x, repeat_times=[positive_2, 3])\n out_3 = paddle.tile(x, repeat_times=repeat_times)\n\n assert np.array_equal(out_1.numpy(), np.tile(np_x, (2, 3)))\n assert np.array_equal(out_2.numpy(), np.tile(np_x, (2, 3)))\n assert np.array_equal(out_3.numpy(), np.tile(np_x, (2, 3)))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"EnnSou/ooss-paddle2.3","sub_path":"python/paddle/fluid/tests/unittests/npu/test_tile_op_npu.py","file_name":"test_tile_op_npu.py","file_ext":"py","file_size_in_byte":7023,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"13271874744","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Codec:\n\n def serialize(self, root):\n \"\"\"Encodes a tree to a single string.\n \n :type root: TreeNode\n :rtype: str\n \"\"\"\n result = \"\"\n if root is None:\n return result\n q = [root]\n while q:\n n = len(q)\n for _ in range(n):\n node = q.pop(0)\n result += str(node.val) + \",\"\n if node.val == -2000:\n continue\n if node.left:\n q.append(node.left)\n else:\n q.append(TreeNode(-2000))\n if node.right:\n q.append(node.right)\n else:\n q.append(TreeNode(-2000))\n # result += \";\"\n return result\n \n\n def deserialize(self, data):\n \"\"\"Decodes your encoded data to tree.\n \n :type data: str\n :rtype: TreeNode\n \"\"\"\n if data == \"\":\n return None\n level_vals = data.split(\",\")[:-1]\n # print(level_vals)\n root = TreeNode(level_vals[0])\n q = [root]\n i = 1\n while q and i < len(level_vals):\n cur = q.pop(0)\n if cur is None:\n continue\n # print(i)\n cur.left = TreeNode(int(level_vals[i])) if level_vals[i] != \"-2000\" else None\n cur.right = TreeNode(int(level_vals[i + 1])) if level_vals[i + 1] != \"-2000\" else None\n q.append(cur.left)\n q.append(cur.right)\n i += 2\n return root\n\n \n\n \n\n# Your Codec object will be instantiated and called as such:\n# ser = Codec()\n# deser = Codec()\n# ans = deser.deserialize(ser.serialize(root))","repo_name":"maxwang967/kick-start","sub_path":"leetcode/297.py","file_name":"297.py","file_ext":"py","file_size_in_byte":1911,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23898816663","text":"n=int(input())\n\ngrade=list(map(float,input().split())) # 실수형(float)으로 저장\navg=sum(grade)/len(grade)\nprint(f'{avg:.1f}')\n\nif avg>=4.0:\n print('A')\nelif avg>=3.0:\n print('B')\nelse:\n print('C')\n","repo_name":"KimDongHyun0907/python-study","sub_path":"list/gpa_calculator.py","file_name":"gpa_calculator.py","file_ext":"py","file_size_in_byte":213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29689684425","text":"from heapq import heappush,heappop\n\ndef solution(n, k, enemy):\n answer = 0\n h = []\n for i,e_n in enumerate(enemy):\n heappush(h,-e_n)\n n-=e_n\n \n if n < 0:\n if k<=0:\n return i\n else:\n n -= heappop(h)\n k -= 1\n return len(enemy)","repo_name":"SonJinHYo/CodingTest","sub_path":"프로그래머스/unrated/142085. 디펜스 게임/디펜스 게임.py","file_name":"디펜스 게임.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22594392479","text":"import json\nimport matplotlib\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\n \n\ndef parse_file(file_name):\n \n history = {}\n\n with open (file_name) as file:\n \n for line in file:\n parser = line.rstrip(\"\\n\").split(\",\")\n name = parser[1]\n\n if name in history:\n history[name].append({\n \"date\": parser[0],\n \"weight\": parser[2] \n })\n else:\n history[name] = [{\n \"date\": parser[0],\n \"weight\": parser[2] \n }]\n\n for name in history:\n x = []\n y = []\n for workout in history[name]:\n x.append(workout[\"date\"])\n y.append(workout[\"weight\"])\n\n plt.plot(x, y, label=name)\n\n plt.legend(loc=1)\n plt.ylabel('Weight')\n plt.xlabel('Date')\n plt.savefig(\"workout.png\")\n plt.show()\n\n\n\n","repo_name":"RjDrury/WorkoutProgress","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26467551385","text":"# coding=utf-8\nimport pandas as pd\nimport datetime\nfrom selenium import webdriver\nfrom bs4 import BeautifulSoup\nfrom selenium.webdriver.firefox.options import Options as FirefoxOptions\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\n\nsearch_keywords = [\n \"junior+data+scientist\",\n \"junior+data+science\",\n \"junior+data+analyst\",\n \"junior+data+analysis\",\n]\nsearch_url = \"https://www.gehalt.de/einkommen/suche/\"\n\n\ndef next_page():\n global end_reached\n if duplicate_count <= 20 and end_reached is not True:\n # Überprüfen, ob es einen \"Next\"-Button gibt\n if (\n len(\n driver.find_elements(\n By.CSS_SELECTOR, \".next.icon.icon--right.chevron-right\"\n )\n )\n > 0\n ):\n # Scrollen, um den \"Next\"-Button sichtbar zu machen\n driver.execute_script(\n \"arguments[0].scrollIntoView();\",\n driver.find_element(\n By.CSS_SELECTOR, \".next.icon.icon--right.chevron-right\"\n ),\n )\n\n # Überprüfen, ob \"Next\"-Button unverfügbar ist\n if (\n len(\n driver.find_elements(\n By.CSS_SELECTOR, \".next.icon.icon--right.chevron-right.disabled\"\n )\n )\n == 0\n ):\n # Überprüfen, ob ein Newsletter-Modal angezeigt wird\n if (\n len(\n driver.find_elements(\n By.CSS_SELECTOR, \".jobletter.jobletterModal.show\"\n )\n )\n > 0\n ):\n # Schließe Newsletter-Modal\n driver.find_element(\n By.CSS_SELECTOR, \".simplemodal-close.icon.close\"\n ).click()\n\n wait.until(\n lambda driver: len(\n driver.find_elements(\n By.CSS_SELECTOR,\n \".jobletter.jobletterModal.show\",\n )\n )\n == 0\n )\n\n # Klicke \"Next\"- Button\n driver.find_element(\n By.CSS_SELECTOR, \".next.icon.icon--right.chevron-right\"\n ).click()\n else:\n end_reached = True\n\n\n# Lese bestehende Daten\njobs_df = pd.read_pickle(\"../data/jobs.pkl\")\nix_jobs = jobs_df.shape[0]\n\nstatistics = pd.read_pickle(\"../data/statistics.pkl\")\nix_stats = statistics.shape[0]\n\n# Konfigurieren des Firefox-Browsers\noptions = FirefoxOptions()\noptions.add_argument(\"--headless\")\n# driver = webdriver.Firefox()\n\nwith webdriver.Firefox(options=options) as driver:\n wait = WebDriverWait(driver, 20)\n first = True\n\n # Durchlaufen der Suchbegriffe\n for keywords in search_keywords:\n new_entries = 0\n duplicates_found = 0\n duplicate_count = 0\n end_reached = False\n\n driver.get(search_url + keywords)\n # Überprüfen, ob es einen \"Next\"-Button gibt\n # if (\n # len(\n # driver.find_elements(\n # By.CSS_SELECTOR, \".next.icon.icon--right.chevron-right\"\n # )\n # )\n # > 0\n # ):\n # # Scrollen, um den \"Next\"-Button sichtbar zu machen\n # driver.execute_script(\n # \"arguments[0].scrollIntoView();\",\n # driver.find_element(\n # By.CSS_SELECTOR, \".next.icon.icon--right.chevron-right\"\n # ),\n # )\n\n # Beim ersten Durchlauf, Cookie Banner schließen\n if first:\n # Überprüfen, ob es einen Cookie-Banner gibt\n wait.until(\n lambda driver: len(\n driver.find_elements(\n By.CSS_SELECTOR,\n \"#ccmgt_explicit_preferences.privacy-prompt-button.secondary-button.options-button\",\n )\n )\n > 0\n )\n # Klicke ersten Teil des Cookie Banners\n driver.find_element(\n By.CSS_SELECTOR,\n \"#ccmgt_explicit_preferences.privacy-prompt-button.secondary-button.options-button\",\n ).click()\n\n # Klicke zweiten Teil des Cookie Banners\n wait.until(\n lambda driver: len(\n driver.find_elements(\n By.CSS_SELECTOR,\n \".secondary-button.ccmgt_reject_button\",\n )\n )\n > 0\n )\n driver.find_element(\n By.CSS_SELECTOR, \".secondary-button.ccmgt_reject_button\"\n ).click()\n first = False\n\n # # Wenn Newsletter-Modal, klicken\n # if (\n # len(driver.find_elements(By.CSS_SELECTOR, \".jobletter.jobletterModal.show\"))\n # > 0\n # ):\n # driver.find_element(\n # By.CSS_SELECTOR, \".simplemodal-close.icon.close\"\n # ).click()\n\n # Solange suchen, bis genug Duplikate gefunden oder Ende erreicht ist\n while duplicate_count < 20 and end_reached is not True:\n wait.until(\n lambda driver: len(\n driver.find_elements(\n By.CSS_SELECTOR, \"ul#joblist.joblist.copy-default:not(.hidden)\"\n )\n )\n > 0\n )\n\n response = driver.page_source\n soup_object = BeautifulSoup(response, features=\"lxml\")\n\n joblist_container = soup_object.find_all(\n id=\"joblist\", class_=\"joblist copy-default\"\n )[0]\n joblist = joblist_container.find_all(\n \"li\", attrs={\"data-hidesalarydata\": True}\n )\n\n for job in joblist:\n link = job.find(class_=\"jobListLink\")[\"href\"]\n job_id = job.find(class_=\"jobListLink\")[\"href\"].split(\"jobId=\")[1]\n titel = job.find(class_=\"text title textlink-default\").text\n unternehmen = job.find(class_=\"company\").text\n ort = job.find(class_=\"location textlink-default\").text\n datum = datetime.datetime.now().strftime(\"%Y-%m-%d\")\n if job.find(class_=\"salary month textlink-default\") is not None:\n gehalt_min = (\n job.find(class_=\"salary month textlink-default\")\n .text.split(\" – \")[0]\n .replace(\".\", \"\")\n )\n gehalt_max = (\n job.find(class_=\"salary month textlink-default\")\n .text.split(\" – \")[1]\n .replace(\".\", \"\")\n )\n else:\n gehalt_min = \"\"\n gehalt_max = \"\"\n if ~jobs_df[\"JobID\"].isin([job_id]).any():\n jobs_df.loc[\n ix_jobs,\n [\n \"Titel\",\n \"Unternehmen\",\n \"Ort\",\n \"Gehalt_min\",\n \"Gehalt_max\",\n \"JobID\",\n \"Link\",\n \"Datum\",\n ],\n ] = [\n titel,\n unternehmen,\n ort,\n gehalt_min,\n gehalt_max,\n job_id,\n link,\n datum,\n ]\n ix_jobs += 1\n duplicate_count = 0\n new_entries += 1\n else:\n duplicate_count += 1\n duplicates_found += 1\n\n next_page()\n\n statistics.loc[ix_stats, [\"Date\", keywords]] = [\n datetime.datetime.now().strftime(\"%d.%m.%Y\"),\n new_entries,\n ]\n\njobs_df.to_pickle(\"../data/jobs.pkl\")\nstatistics.to_pickle(\"../data/statistics.pkl\")\n","repo_name":"tim-hilde/Data-Science-Jobs","sub_path":"scripts/scraping.py","file_name":"scraping.py","file_ext":"py","file_size_in_byte":8203,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14096330237","text":"from collections import deque\n\nclass RecentCounter(object):\n def __init__(self):\n self.queue = deque()\n\n def ping(self, t):\n range_of_t = (t - 3000, t)\n self.queue.append(t)\n count = 0\n new_queue = deque()\n count = 0\n\n while self.queue:\n item = self.queue.popleft()\n if range_of_t[0] <= item <= range_of_t[1]:\n count += 1\n new_queue.append(item)\n\n self.queue = new_queue\n\n return count\n\n","repo_name":"dvc0310/Interview-prep-stuff","sub_path":"leetcode/recent_counter.py","file_name":"recent_counter.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73088614224","text":"import numpy as np\r\nimport cv2\r\n\r\n\r\n# intersection_points is a list with pixel points of intersections on x-axis, and pixel points of intersection points on y axis\r\n# Similarly for line_points\r\n# Grid size is a tuple of the mapped grid (x,y)\r\n# robot_coord, and goal_coord are pixel coordinates of the start and goal positions and are also in (x,y) format\r\ndef MakeGrid(image, intersection_thresh, line_thresh, X_points, Y_points, grid_size, kernel_size, robot_coord,\r\n goal_coord):\r\n if len(image.shape) > 2:\r\n print(\"Image must be black and white.\\n\")\r\n\r\n x_inter_pts = X_points[::2]\r\n y_inter_pts = Y_points[::2]\r\n\r\n x_line_pts = X_points[1::2]\r\n y_line_pts = Y_points[1::2]\r\n\r\n grid = np.zeros((grid_size[1], grid_size[0]))\r\n\r\n i = 0 # iterating in X dirn for intersections\r\n j = 0 # iterating in Y dirn for intersections\r\n for y in y_inter_pts:\r\n\r\n for x in x_inter_pts:\r\n\r\n sliced_img = image[y - kernel_size // 2:y + kernel_size // 2,\r\n x - kernel_size // 2:x + kernel_size // 2]\r\n\r\n num_white_pix = np.count_nonzero(sliced_img)\r\n # print(\"for \", j, i, \"num_pix is: \", num_white_pix)\r\n\r\n if num_white_pix < intersection_thresh:\r\n grid[j][i] = 1\r\n\r\n i += 2\r\n i=0\r\n j += 2\r\n\r\n i = 0 # iterating in X dirn for vertical lines\r\n j = 1 # iterating in Y dirn for vertical lines\r\n\r\n for y in y_line_pts:\r\n\r\n for x in x_inter_pts:\r\n\r\n sliced_img = image[y - kernel_size // 2:y + kernel_size // 2,\r\n x - kernel_size // 2:x + kernel_size // 2]\r\n\r\n num_white_pix = np.count_nonzero(sliced_img)\r\n # print(\"for \", j, i, \"num_pix is: \", num_white_pix)\r\n\r\n if num_white_pix < line_thresh:\r\n grid[j][i] = 1\r\n\r\n i += 2\r\n\r\n i=0\r\n j += 2\r\n\r\n i = 1 # iterating in X dirn for horizontal lines\r\n j = 0 # iterating in Y dirn for horizontal lines\r\n\r\n for y in y_inter_pts:\r\n\r\n for x in x_line_pts:\r\n\r\n sliced_img = image[y - kernel_size // 2:y + kernel_size // 2,\r\n x - kernel_size // 2:x + kernel_size // 2]\r\n\r\n num_white_pix = np.count_nonzero(sliced_img)\r\n # print(\"for \", j, i, \"num_pix is: \", num_white_pix)\r\n\r\n if num_white_pix < line_thresh:\r\n grid[j][i] = 1\r\n\r\n i += 2\r\n\r\n i=1\r\n j += 2\r\n\r\n # In the grid 9 blocks represent the block on the image. The 4 corners represent intersection points, the 4 edges represent lines on the image\r\n # however there is the middle block in the grid which represents nothing but empty space in the image. These blocks in the grid need to blocked out.\r\n\r\n for j in range(1, grid_size[1], 2):\r\n\r\n for i in range(1, grid_size[0], 2):\r\n grid[j][i] = 1\r\n #print(\"values are: \", j, i, \"\\n\")\r\n\r\n y_robot_diff = [abs(point - robot_coord[1]) for point in Y_points]\r\n x_robot_diff = [abs(point - robot_coord[0]) for point in X_points]\r\n\r\n robot_grid = [x_robot_diff.index(min(x_robot_diff)), y_robot_diff.index(min(y_robot_diff))]\r\n\r\n y_goal_diff = [abs(point - goal_coord[1]) for point in Y_points]\r\n x_goal_diff = [abs(point - goal_coord[0]) for point in X_points]\r\n\r\n goal_grid = [x_goal_diff.index(min(x_goal_diff)), y_goal_diff.index(min(y_goal_diff))]\r\n\r\n return (grid, robot_grid, goal_grid)\r\n","repo_name":"SiddharthSingi/Driving_Blind","sub_path":"Grid.py","file_name":"Grid.py","file_ext":"py","file_size_in_byte":3487,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"4658997855","text":"import sqlite3\nimport datetime\nimport os\nimport logging\nfrom shutil import copyfile\n\n\nclass Student:\n def __init__(self, db_row=None):\n if db_row is None:\n self.found = False\n else:\n self.found = True\n self.id = db_row['id']\n self.first_name = db_row['first_name']\n self.last_name = db_row['last_name']\n self.classgroup = db_row['classgroup']\n self.badgecode = db_row['badgecode']\n self.studentnumber = db_row['studentnumber']\n self.time_ran = db_row['time_ran']\n self.starttime = db_row['starttime']\n\nclass RR_DB :\n def __init__(self, log_handle):\n self.cnx = sqlite3.connect(self.DB_DEST, detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)\n self.cnx.row_factory = sqlite3.Row\n self.csr = self.cnx.cursor()\n self.log = logging.getLogger('{}.Database'.format(log_handle))\n\n #create tables, if they do not exist yet\n for name, ddl in self.TABLES.items():\n self.log.info(\"Creating table {}: \".format(name))\n self.csr.execute(ddl)\n\n #make e backup\n self.backup_database()\n\n DB_FILE = 'rr.db'\n DB_LOCATION = 'resources'\n DB_DEST = os.path.join(DB_LOCATION, DB_FILE)\n DB_BACKUP_LOCATION = os.path.join(DB_LOCATION, 'backup')\n\n TABLES = {}\n TABLES['students'] = (\n \"CREATE TABLE IF NOT EXISTS students (\"\n \" id INTEGER PRIMARY KEY UNIQUE NOT NULL,\"\n \" badgecode TEXT UNIQUE NOT NULL,\"\n \" studentnumber INTEGER, \"\n \" first_name TEXT,\"\n \" last_name TEXT,\"\n \" classgroup TEXT,\"\n \" time_ran INTEGER,\"\n \" starttime timestamp \"\n \")\")\n\n ADD_STUDENT = (\"INSERT INTO students \"\n \"(last_name, first_name, classgroup, studentnumber, badgecode)\"\n \"VALUES (?, ?, ?, ?, ?)\")\n\n UPDATE_GUEST = (\"UPDATE students SET \"\n \"time_ran=?,\"\n \"starttime=?,\"\n \"WHERE id=?;\")\n\n #student_list.append((l['NAAM'], l['VOORNAAM'], l['KLAS'], l['LEERLINGNUMMER'], l['RFID']))\n def add_students(self, student_list):\n rslt = True\n try:\n for s in student_list:\n try:\n self.csr.execute(self.ADD_STUDENT, (s[0], s[1], s[2], s[3], s[4]))\n except sqlite3.Error as e:\n self.log.error('Could not add to database : {} {} from {}'.format(s[0], s[1], s[2]))\n except sqlite3.Error as e:\n rslt = False\n self.cnx.commit()\n self.log.info('Added students to database')\n return rslt\n\n def find_student_from_badge(self, badgecode):\n badgecode = badgecode.upper()\n self.csr.execute('SELECT * FROM students WHERE badgecode=?', (badgecode,))\n r = self.csr.fetchone()\n return Student(r)\n\n def find_student_from_number(self, studentnumber):\n self.csr.execute('SELECT * FROM students WHERE studentnumber=?', (studentnumber,))\n r = self.csr.fetchone()\n return Student(r)\n\n def find_student_from_id(self, id):\n self.csr.execute('SELECT * FROM students WHERE id=?', (id,))\n r = self.csr.fetchone()\n return Student(r)\n\n #return a list of student ids\n def get_students_id(self):\n self.csr.execute('SELECT * FROM students')\n rows = self.csr.fetchall()\n students_id = []\n for r in rows:\n students_id.append(r['id'])\n return students_id\n\n #return all students\n def get_students_sorted_on_time_ran(self):\n self.csr.execute('SELECT * FROM students ORDER BY time_ran ASC, classgroup ASC, last_name ASC, first_name ASC')\n return self.csr.fetchall()\n\n def update_student(self, id, time_ran, starttime):\n try:\n self.csr.execute('UPDATE students SET time_ran=?, starttime=? WHERE id=?;', (time_ran, starttime, id))\n self.cnx.commit()\n self.log.info('Update student {} {} {}'.format(id, time_ran, starttime))\n except sqlite3.Error as e:\n self.log.error('Could not update student {} {} {}'.format(id, time_ran, starttime))\n\n def clear_database(self):\n try:\n self.csr.execute('DELETE FROM students;')\n self.cnx.commit()\n except sqlite3.Error as e:\n self.log.error('Could clear database : {}'.format(e))\n\n def close(self):\n self.cnx.close()\n\n def backup_database(self):\n try:\n absolute_backup_path = os.path.join(os.getcwd(), self.DB_BACKUP_LOCATION)\n if not os.path.isdir(absolute_backup_path):\n os.mkdir(absolute_backup_path)\n backup_dest = os.path.join(self.DB_BACKUP_LOCATION, datetime.datetime.now().strftime('%Y%m%d%H%M%S') + ' ' + self.DB_FILE )\n copyfile(self.DB_DEST, backup_dest)\n except:\n self.log.info(\"Could not backup database\")\n","repo_name":"manuelborowski/RegistreerLopers","sub_path":"Database.py","file_name":"Database.py","file_ext":"py","file_size_in_byte":4968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"3874432377","text":"from datetime import datetime\nfrom typing import List\n\nfrom marshmallow import fields\n\nfrom .field_set import FieldSet, FieldSetSchema\n\n\nclass Process(FieldSet):\n\n def __init__(self,\n args: List[str] = None,\n executable: str = None,\n name: str = None,\n pid: int = None,\n ppid: int = None,\n start: datetime = None,\n thread_id: int = None,\n title: str = None,\n working_directory: str = None,\n *aargs, **kwargs):\n super().__init__(*aargs, **kwargs)\n self.args = args\n self.executable = executable\n self.name = name\n self.pid = pid\n self.ppid = ppid\n self.start = start\n self.thread_id = thread_id\n self.title = title\n self.working_directory = working_directory\n\n\nclass ProcessSchema(FieldSetSchema):\n args = fields.List(fields.String())\n executable = fields.String()\n name = fields.String()\n pid = fields.Integer()\n ppid = fields.Integer()\n start = fields.DateTime(format=\"iso\")\n thread_id = fields.Integer()\n title = fields.String()\n working_directory = fields.String()\n","repo_name":"kumina/kubi_ecs_logger","sub_path":"kubi_ecs_logger/models/fields/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"44224722895","text":"# Author: Sang Ok Suh\r\n# Date: 08/08/2020\r\n# Description: Minesweeper game with User Interface\r\n\r\n# Followed these pygame tutorials for reference:\r\n# http://programarcadegames.com/index.php?lang=en&chapter=array_backed_grids\r\n# https://www.youtube.com/watch?v=zMN9kRLD1DA&list=PLQVvvaa0QuDdLkP8MrOXLe_rKuf6r80KO&index=6\r\n\r\nimport pygame\r\nimport random\r\nimport pygame.font\r\nimport math\r\nimport sys\r\n\r\n# --------------------IMAGES---------------------------------\r\n# Img for bombs, flag\r\nbomb_img = pygame.image.load('images/bomb.png')\r\nbomb_img = pygame.transform.scale(bomb_img, (17, 17))\r\n\r\nbombx_img = pygame.image.load(\"images/bombx.png\")\r\nbombx_img = pygame.transform.scale(bombx_img, (17, 17))\r\n\r\nflag_img = pygame.image.load('images/flag.png')\r\nflag_img = pygame.transform.scale(flag_img, (20, 20))\r\n\r\nthumbs_up = pygame.image.load('images/thumbsup.png')\r\nthumbs_up = pygame.transform.scale(thumbs_up, (27, 27))\r\n\r\nthumbs_down = pygame.image.load('images/thumbsdown.png')\r\nthumbs_down = pygame.transform.scale(thumbs_down, (27, 27))\r\n\r\ncrown = pygame.image.load('images/crown.png')\r\ncrown = pygame.transform.scale(crown, (27, 27))\r\n# ---------------------------------------------------------\r\n\r\n\r\n# -----------COLORS------------\r\nwhite = (255, 255, 255)\r\ngray = (211, 211, 211)\r\nred = (255, 0, 0)\r\nblack = (0, 0, 0)\r\nblue = (65, 105, 225)\r\nbrightred = (240, 128, 128)\r\nbrightblue = (135, 206, 250)\r\ngray = (192, 192, 192)\r\ngreen = (0, 255, 0)\r\nlight_green = (173,255,47)\r\n# ------------------------------\r\n\r\n\r\n# -----------Grid Dimensions----------------\r\nwidth = 20\r\nheight = 20\r\nmargin = 5\r\n# -------------------------------------------\r\n\r\n\r\n# ----------Pygame Initialization----------------------\r\n# Initialize pygame\r\npygame.init()\r\n\r\n# Title of Game\r\npygame.display.set_caption(\"Minesweeper by Sang Ok Suh\")\r\n\r\n# Size of Screen\r\ndisplay_width = 600\r\ndisplay_height = 500\r\nsize = (display_width, display_height)\r\nscreen = pygame.display.set_mode(size)\r\n\r\n# Manage Screen Updates\r\nclock = pygame.time.Clock()\r\n# ------------------------------------------------------\r\n\r\n# -----------FONTS---------------\r\nlargeText = pygame.font.SysFont('Arial.ttf', 80)\r\nchoiceText = pygame.font.SysFont('Arial.ttf', 30)\r\ndescriptionText = pygame.font.SysFont('Arial.ttf', 18)\r\nfont = pygame.font.SysFont('Arial', 15, True)\r\n# -------------------------------\r\n\r\n\r\ndef screen_size(page):\r\n\r\n if page == \"Intro\":\r\n display_width = 600\r\n display_height = 500\r\n\r\n elif page == \"Easy\":\r\n display_width = 232\r\n display_height = 330\r\n\r\n elif page == \"Hard\":\r\n display_width = 410\r\n display_height = 500\r\n\r\n size = (display_width, display_height)\r\n screen = pygame.display.set_mode(size)\r\n\r\n\r\n# Intro Button Function\r\ndef button(msg, x, y, w, h, i, a, fontsize, xcorrection, ycorrection):\r\n\r\n difficultyText = pygame.font.SysFont('Arial.ttf', fontsize)\r\n\r\n mouse = pygame.mouse.get_pos()\r\n\r\n click = pygame.mouse.get_pressed()\r\n\r\n if (x <= mouse[0] <= x + w) and (y <= mouse[1] <= y + h):\r\n pygame.draw.rect(screen, a, [x, y, w, h])\r\n if click[0] == 1:\r\n\r\n if msg == \"Easy\" or msg == \"Hard\":\r\n start_game(msg)\r\n\r\n elif msg == \"Menu\":\r\n screen_size(\"Intro\")\r\n game_intro()\r\n\r\n elif msg == \"Exit\":\r\n sys.exit()\r\n\r\n else:\r\n pygame.draw.rect(screen, i, [x, y, w, h])\r\n\r\n screen.blit(difficultyText.render(msg, True, white), (x + xcorrection, y + ycorrection))\r\n\r\n\r\n# Intro Screen\r\ndef game_intro():\r\n\r\n intro = True\r\n\r\n while intro:\r\n for event in pygame.event.get():\r\n\r\n if event.type == pygame.QUIT:\r\n sys.exit()\r\n\r\n screen.fill(white)\r\n screen.blit(largeText.render(\"Minesweeper\", True, black), (130, 50))\r\n\r\n screen.blit(choiceText.render(\"Choose a difficulty\", True, black), (210, 260))\r\n\r\n button(\"Easy\", 100, 300, 150, 50, blue, brightblue, 50, 35, 10)\r\n button(\"Hard\", 350, 300, 150, 50, red, brightred, 50, 35, 10)\r\n\r\n screen.blit(descriptionText.render(\"9x9, 10 bombs\", True, black), (135, 355))\r\n screen.blit(descriptionText.render(\"16x16, 40 bombs\", True, black), (380, 355))\r\n\r\n pygame.display.update()\r\n clock.tick(60)\r\n\r\n\r\n# Grid Creation\r\ndef create_grid(difficulty):\r\n\r\n if difficulty == \"Easy\":\r\n grid_coordinates = (0, 1, 2, 3, 4, 5, 6, 7, 8)\r\n bomb = 10\r\n elif difficulty == \"Hard\":\r\n grid_coordinates = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)\r\n bomb = 40\r\n\r\n grid = []\r\n for row in range(len(grid_coordinates)):\r\n grid.append([])\r\n for column in range(len(grid_coordinates)):\r\n grid[row].append(0)\r\n\r\n while bomb != 0:\r\n bomb_x = random.randint(0,len(grid_coordinates)-1)\r\n bomb_y = random.randint(0, len(grid_coordinates)-1)\r\n\r\n if grid[bomb_x][bomb_y] != \"b\":\r\n grid[bomb_x][bomb_y] = \"b\"\r\n bomb -= 1\r\n\r\n return grid\r\n\r\n\r\n# Getting the coordinates of all adjacent cells\r\ndef get_adjacent_cells(i, j):\r\n\r\n adjacent_indices = [(i - 1, j - 1), (i - 1, j), (i - 1, j + 1), (i, j - 1), (i, j + 1), (i + 1, j - 1), (i + 1, j),\r\n (i + 1, j + 1)]\r\n\r\n return adjacent_indices\r\n\r\n\r\n# Counter for the number of adjacent cell with bombs\r\ndef bomb_counter(x, y, grid, grid_coordinates):\r\n\r\n # Bomb Counter set to 0\r\n bomb_cell = 0\r\n\r\n # Get All Adjacent Cells\r\n adjacent_cells = get_adjacent_cells(x, y)\r\n\r\n # Loop through all 8 adjacent cells\r\n for i in range(8):\r\n\r\n # Store row and col\r\n adjacent_row = adjacent_cells[i][0]\r\n adjacent_col = adjacent_cells[i][1]\r\n\r\n # If row and column are within grid\r\n if adjacent_row in grid_coordinates and adjacent_col in grid_coordinates:\r\n\r\n # If bomb is in adjacent cell\r\n if grid[adjacent_row][adjacent_col] == \"b\" or grid[adjacent_row][adjacent_col] == \"bf\":\r\n\r\n # Increment bomb counter\r\n bomb_cell += 1\r\n\r\n # return the number of adjacent cells with bombs\r\n return bomb_cell\r\n\r\n\r\n# Function that searches adjacent cells when an empty cell without bomb is clicked.\r\n# Also assigns empty (no adjacent bomb cells) or # of adjacent bomb cells.\r\ndef assign_empty_cell_value(row, col, grid, grid_coordinates):\r\n\r\n bomb_count = bomb_counter(row, col, grid, grid_coordinates)\r\n\r\n # If there are adjacent bomb cells\r\n if bomb_count != 0:\r\n\r\n # Assign bomb_count value to cell location\r\n grid[row][col] = bomb_count\r\n\r\n # If no adjacent bomb cells\r\n if bomb_count == 0:\r\n\r\n # Assign value \"e\" for empty\r\n grid[row][col] = \"e\"\r\n\r\n # Get adjacent cells for \"e\" cells\r\n empty_adjacent = get_adjacent_cells(row, col)\r\n\r\n # Loop through adjacent cells\r\n for i in range(8):\r\n\r\n # Store row and col\r\n adjacent_row = empty_adjacent[i][0]\r\n adjacent_col = empty_adjacent[i][1]\r\n\r\n # If row and column are within grid and cell value is not-clicked\r\n if (adjacent_row in grid_coordinates) and (adjacent_col in grid_coordinates):\r\n if grid[adjacent_row][adjacent_col] == 0 or grid[adjacent_row][adjacent_col] == \"f\":\r\n assign_empty_cell_value(adjacent_row, adjacent_col, grid, grid_coordinates)\r\n\r\n\r\n# Start game function\r\ndef start_game(difficulty):\r\n\r\n extra_xmargin = 0\r\n extra_ymargin = 0\r\n\r\n # Set new screen_size depending on difficulty\r\n screen_size(difficulty)\r\n\r\n # Status\r\n status = \"current\"\r\n\r\n # Create Grid Based on Difficulty\r\n grid = create_grid(difficulty)\r\n\r\n # Flags based on difficulty\r\n if difficulty == \"Easy\":\r\n flags = 10\r\n grid_coordinates = (0, 1, 2, 3, 4, 5, 6, 7, 8)\r\n extra_margin = 0\r\n\r\n elif difficulty == \"Hard\":\r\n flags = 40\r\n grid_coordinates = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)\r\n extra_xmargin = 100\r\n extra_ymargin = 170\r\n\r\n # Timer to track time\r\n timer = 0\r\n dt = 0\r\n\r\n # Loop Counter\r\n done = False\r\n\r\n # Main Game Loop\r\n while not done:\r\n\r\n # Get user event\r\n for event in pygame.event.get():\r\n\r\n # If user clicks close\r\n if event.type == pygame.QUIT:\r\n\r\n sys.exit()\r\n\r\n # If user clicks the mouse\r\n elif event.type == pygame.MOUSEBUTTONDOWN:\r\n\r\n # Get the position of mouse click\r\n pos = pygame.mouse.get_pos()\r\n\r\n # Change the x/y coordinates to grid coordinates\r\n column = pos[0] // (width + margin)\r\n row = (pos[1] // (height + margin)) - 2\r\n\r\n # Reset Game\r\n if 95 + extra_xmargin <= pos[0] <= 120 and 10 <= pos[1] <= 45:\r\n start_game(difficulty)\r\n\r\n # If game is going\r\n if status == \"current\" and row in grid_coordinates and column in grid_coordinates:\r\n\r\n # Start timer\r\n if timer == 0:\r\n timer = 0.001\r\n\r\n # If click was left click\r\n if event.button == 1:\r\n # If clicked cell is bomb\r\n if grid[row][column] == \"b\":\r\n\r\n # Change value to b_found\r\n grid[row][column] = \"b_found\"\r\n\r\n # If clicked on un-clicked space without bomb\r\n elif grid[row][column] == 0:\r\n\r\n assign_empty_cell_value(row, column, grid, grid_coordinates)\r\n\r\n # If player right clicks to mark flag\r\n elif event.button == 3:\r\n\r\n # If player marked empty cell\r\n if grid[row][column] == 0:\r\n\r\n # Assign f\r\n grid[row][column] = \"f\"\r\n flags -= 1\r\n\r\n # Reversing flag to empty\r\n elif grid[row][column] == \"f\":\r\n grid[row][column] = 0\r\n flags += 1\r\n\r\n # If player right clicked bomb location\r\n elif grid[row][column] == \"b\":\r\n\r\n # Assign bf\r\n grid[row][column] = \"bf\"\r\n flags -= 1\r\n\r\n # Reverse bf to b\r\n elif grid[row][column] == \"bf\":\r\n grid[row][column] = \"b\"\r\n flags += 1\r\n\r\n # --------- Game Design -----------------\r\n\r\n if timer != 0 and status == \"current\":\r\n timer += dt\r\n\r\n # Empty Cell Counter\r\n empty_cell_counter = 0\r\n\r\n # Set Screen Background\r\n screen.fill(black)\r\n\r\n # Remaining Flags Display\r\n pygame.draw.rect(screen, gray, [10+extra_xmargin, 10, 65, 35])\r\n flagfont = pygame.font.SysFont('arialblack', 30)\r\n screen.blit(flagfont.render(str(flags), True, red), (25+extra_xmargin, 6))\r\n\r\n # Reset/Game Status Button Display\r\n pygame.draw.rect(screen, gray, [95+extra_xmargin, 10, 35, 35])\r\n if status == \"current\":\r\n screen.blit(thumbs_up, (99+extra_xmargin, 13))\r\n elif status == \"Lost\":\r\n screen.blit(thumbs_down, (99+extra_xmargin, 13))\r\n elif status == \"Won\":\r\n screen.blit(crown, (99+extra_xmargin, 13))\r\n\r\n # Time Display\r\n pygame.draw.rect(screen, gray, [150+extra_xmargin, 10, 65, 35])\r\n flagfont = pygame.font.SysFont('arialblack', 25)\r\n screen.blit(flagfont.render(str(math.floor(timer)), True, red), (155+extra_xmargin, 9))\r\n\r\n # Menu Button\r\n button(\"Menu\", 10+extra_xmargin, 290+extra_ymargin, 90, 30, green, light_green, 35, 12, 5)\r\n\r\n # Exit Button\r\n button(\"Exit\", 130+extra_xmargin, 290+extra_ymargin, 90, 30, red, brightred, 35, 18, 5)\r\n\r\n # Check if won\r\n for row in range(len(grid_coordinates)):\r\n for column in range(len(grid_coordinates)):\r\n\r\n if grid[row][column] == 0 or grid[row][column] == \"f\":\r\n empty_cell_counter += 1\r\n\r\n if empty_cell_counter == 0:\r\n status = \"Won\"\r\n\r\n # Draw grid\r\n for row in range(len(grid_coordinates)):\r\n for column in range(len(grid_coordinates)):\r\n color = gray\r\n\r\n # If bomb is found, set color to red\r\n if grid[row][column] == \"b_found\":\r\n color = red\r\n status = \"Lost\"\r\n\r\n # If empty was clicked, set color to white\r\n elif grid[row][column] == \"e\":\r\n color = white\r\n\r\n pygame.draw.rect(screen, color, [(margin + width) * column + margin,\r\n (margin + height) * row + margin + 50,\r\n width,\r\n height])\r\n\r\n # Number of adjacent bomb cells\r\n if grid[row][column] in (1, 2, 3, 4, 5, 6, 7, 8):\r\n screen.blit(font.render(str(grid[row][column]), True, blue), ((margin + width) * column + 11,\r\n (margin + height) * row + 6 + 50))\r\n\r\n # Flag Graphics\r\n if grid[row][column] == \"f\" or grid[row][column] == \"bf\":\r\n screen.blit(flag_img, ((margin + width) * column + 7, (margin + height) * row + 6 + 50))\r\n\r\n # If game over\r\n if status == \"Lost\":\r\n\r\n # Reveal all bombs\r\n if grid[row][column] == \"b_found\" or grid[row][column] == \"b\":\r\n screen.blit(bomb_img, ((margin + width) * column + 7, (margin + height) * row + 6 + 50))\r\n\r\n # Reveal all incorrect flags\r\n if grid[row][column] == \"f\":\r\n screen.blit(bombx_img, ((margin + width) * column + 7, (margin + height) * row + 6 + 50))\r\n\r\n if status == \"Won\":\r\n\r\n if grid[row][column] == \"b\":\r\n screen.blit(flag_img, ((margin + width) * column + 7, (margin + height) * row + 6 + 50))\r\n\r\n dt = clock.tick(60) / 1000\r\n\r\n # --- Update the screen ---\r\n pygame.display.flip()\r\n\r\n\r\ngame_intro()\r\npygame.quit()\r\nquit()","repo_name":"sangokey/minesweeper","sub_path":"minesweeper.py","file_name":"minesweeper.py","file_ext":"py","file_size_in_byte":14684,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20233960663","text":"from easydict import EasyDict as edict\nfrom torchvision import transforms\n\nC = edict()\n\n# Alias\ncfg = C\n\n# Model name\nC.MODEL = \"BasicModel\"\n\n# Learner to use\nC.LEARNER = \"Learner\"\n\n# GPU to use\nC.GPU = 0\n\n# conf\nC.ARCH = [1000, 1000, 500, 200, 10]\n\n# Train options\nC.TRAIN = edict()\n\n# Dataset for training\nC.TRAIN.DATASET = edict()\nC.TRAIN.DATASET.NAME = \"MNIST\"\nC.TRAIN.DATASET.TRANSFORM = transforms.Compose([\n # transforms.Resize((224, 224)),\n # transforms.CenterCrop(224),\n transforms.ToTensor()\n # transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) (0.1307,), (0.3081,))\n])\n\n# Step period to write summaries to tensorboard\nC.TRAIN.SUMMARY_FREQ = 10\n# Step period to perform validation\nC.TRAIN.VAL_FREQ = 200\n# Train batch size\nC.TRAIN.BATCH_SIZE = 20\n# Number of epochs\nC.TRAIN.NUM_EPOCHS = 2\n# Restore from wandb or local\nC.TRAIN.RESTORE_STORAGE = 'local'\n# Path to checkpoint from which to be restored\nC.TRAIN.RESTORE_FILE = ''\n# Learning rate\nC.TRAIN.LR = 1e-4\n# save checkpoint model frequency\nC.TRAIN.SAVE_MODEL_FREQ = 5000\n\n# # Validation options.\nC.VAL = edict()\n# Validation batch size\nC.VAL.BATCH_SIZE = 20\n\n# Test options\nC.TEST = edict()\n# Test batch size\nC.TEST.BATCH_SIZE = 20\n# Path to checkpoint from which to be restored\nC.TEST.RESTORE_FILE = \"andrijazz/pruning/2w6vyy0x/basicmodel-5600.pth\"\n# Restore from wandb or local\nC.TEST.RESTORE_STORAGE = 'wandb'\n# percentage of weights/units to be pruned\nC.TEST.PRUNING_K = [0, 25, 50, 60, 70, 80, 90, 95, 97, 99]\n# Dataset for testing\nC.TEST.DATASET = edict()\nC.TEST.DATASET.NAME = \"MNIST\"\nC.TEST.DATASET.TRANSFORM = transforms.Compose([\n # transforms.Resize((224, 224)),\n # transforms.CenterCrop(224),\n transforms.ToTensor()\n # transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) (0.1307,), (0.3081,))\n])\n# Path to h5 file to save results\nC.TEST.OUTPUT_FILE = \"\"\n","repo_name":"andrijazz/pruning","sub_path":"models/basic_config.py","file_name":"basic_config.py","file_ext":"py","file_size_in_byte":1888,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"612648600","text":"import streamlit as st\nimport pandas as pd\nfrom PIL import Image\nfrom model import open_data, preprocess_data, get_X_y_data, load_model_and_predict\n\n\ndef process_main_page():\n show_main_page()\n process_side_bar_inputs()\n\n\ndef show_main_page():\n image = Image.open(\n \"data/page_icon_car.png\")\n\n st.set_page_config(\n layout=\"wide\",\n initial_sidebar_state=\"auto\",\n page_title=\"Demo Cars\",\n page_icon=image,\n\n )\n\n st.write(\n \"\"\"\n # Предсказание цены автомобиля\n Определение цены автомобиля с использованием линейной регрессии \n \"\"\"\n )\n\n st.image(image)\n\n\ndef write_user_data(df):\n st.write(\"## Ваши данные\")\n st.write(df)\n\n\ndef write_prediction(prediction):\n st.write(\"## Предсказание\")\n st.write(prediction)\n\n\ndef process_side_bar_inputs():\n st.sidebar.header(\n \"Задайте параметры автомобиля\")\n user_input_df = sidebar_input_features()\n write_user_data(user_input_df)\n\n data = open_data()\n X_df, _ = get_X_y_data(data)\n full_X_df = pd.concat((user_input_df, X_df), axis=0)\n preprocessed_X_df = preprocess_data(full_X_df, test=False)\n\n user_X_df = preprocessed_X_df[:1]\n\n prediction = load_model_and_predict(user_X_df)\n write_prediction(prediction)\n\n\ndef sidebar_input_features():\n year = st.sidebar.slider(\"Год выпуска\",\n min_value=1950, max_value=2015, step=1)\n km_driven = st.sidebar.number_input(\n \"Пробег на дату продажи\")\n fuel = st.sidebar.selectbox(\n \"Тип используемого топлива\", (\"Дизель\", \"Бензин\"))\n transmission = st.sidebar.selectbox(\n \"Тип трансмиссии\", (\"Ручная\", \"Автоматическая\"))\n seller_type = st.sidebar.selectbox(\n \"Продавец\", (\"Официальный дилер\", \"Физ. лицо\", \"Дилер\",))\n owner = st.sidebar.selectbox(\"Количество владельцев\", (\n \"Один\", \"Два\", \"Три\", \"Четыре и более\"))\n mileage = st.sidebar.number_input(\"Текущий пробег\")\n engine = st.sidebar.number_input(\"Объем двигателя\")\n max_power = st.sidebar.number_input(\n \"Пиковая мощность двигателя\")\n seats = st.sidebar.slider(\n \"Количество мест\", min_value=1, max_value=10, step=1)\n\n translatetion = {\n \"Дизель\": \"Diesel\",\n \"Бензин\": \"Fuel\",\n \"Ручная\": \"Manual\",\n \"Официальный дилер\": \"Trustmark Dealer\",\n \"Физ. лицо\": \"Individual\",\n \"Дилер\": \"Dealer\",\n \"Автоматическая\": \"Automatic\",\n \"Один\": \"First Owner\",\n \"Два\": \"Second Owner\",\n \"Три\": \"Third Owner\",\n \"Четыре и более\": \"Fourth & Above Onwer\",\n }\n\n data = {\n \"year\": year,\n \"km_driven\": km_driven,\n \"fuel\": translatetion[fuel],\n \"transmission\": translatetion[transmission],\n \"seller_type\": translatetion[seller_type],\n \"owner\": translatetion[owner],\n \"mileage\": mileage,\n \"engine\": engine,\n \"max_power\": max_power,\n \"seats\": seats\n }\n\n df = pd.DataFrame(data, index=[0])\n\n return df\n\n\nif __name__ == \"__main__\":\n process_main_page()\n","repo_name":"mmjoke/from-idea-to-project-ml","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3518,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22024750151","text":"import functools\nimport math\nimport random\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\ntry:\n import deepspeed\n from deepspeed.ops.transformer.inference import DeepSpeedTransformerInferenceKernel\nexcept ImportError:\n pass\n\nimport dlas.codes.torch_intermediary as ml\nfrom dlas.codes.models.arch_util import AttentionBlock\nfrom dlas.codes.trainer.networks import register_model\nfrom dlas.codes.utils.transformers.stream_generator import init_stream_support\nfrom dlas.codes.utils.util import opt_get\nfrom transformers import GPT2Config, GPT2PreTrainedModel\nfrom transformers.modeling_outputs import CausalLMOutputWithCrossAttentions\n\ninit_stream_support()\n\n\ndef null_position_embeddings(range, dim):\n return torch.zeros((range.shape[0], range.shape[1], dim), device=range.device)\n\n\nclass ResBlock(nn.Module):\n \"\"\"\n Basic residual convolutional block that uses GroupNorm.\n \"\"\"\n\n def __init__(self, chan):\n super().__init__()\n self.net = nn.Sequential(\n nn.Conv1d(chan, chan, kernel_size=3, padding=1),\n nn.GroupNorm(chan // 8, chan),\n nn.ReLU(),\n nn.Conv1d(chan, chan, kernel_size=3, padding=1),\n nn.GroupNorm(chan // 8, chan),\n )\n\n def forward(self, x):\n return F.relu(self.net(x) + x)\n\n\nclass GPT2InferenceModel(GPT2PreTrainedModel):\n \"\"\"Override GPT2LMHeadModel to allow for prefix conditioning.\"\"\"\n\n def __init__(self, config, gpt, pos_emb, embeddings, norm, linear, kv_cache):\n super().__init__(config)\n self.transformer = gpt\n self.pos_embedding = pos_emb\n self.embeddings = embeddings\n self.final_norm = norm\n self.lm_head = nn.Sequential(norm, linear)\n self.kv_cache = kv_cache\n\n def store_prefix_emb(self, prefix_emb):\n self.cached_prefix_emb = prefix_emb\n\n def prepare_inputs_for_generation(self, input_ids, past_key_values=None, **kwargs):\n token_type_ids = kwargs.get(\"token_type_ids\", None) # usually None\n if not self.kv_cache:\n past_key_values = None\n\n # only last token for inputs_ids if past is defined in kwargs\n if past_key_values is not None:\n input_ids = input_ids[:, -1].unsqueeze(-1)\n if token_type_ids is not None:\n token_type_ids = token_type_ids[:, -1].unsqueeze(-1)\n\n attention_mask = kwargs.get(\"attention_mask\", None)\n position_ids = kwargs.get(\"position_ids\", None)\n\n if attention_mask is not None and position_ids is None:\n # create position_ids on the fly for batch generation\n position_ids = attention_mask.long().cumsum(-1) - 1\n position_ids.masked_fill_(attention_mask == 0, 1)\n if past_key_values is not None:\n position_ids = position_ids[:, -1].unsqueeze(-1)\n else:\n position_ids = None\n return {\n \"input_ids\": input_ids,\n \"past_key_values\": past_key_values,\n \"use_cache\": kwargs.get(\"use_cache\"),\n \"position_ids\": position_ids,\n \"attention_mask\": attention_mask,\n \"token_type_ids\": token_type_ids,\n }\n\n def forward(\n self,\n input_ids=None,\n past_key_values=None,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n inputs_embeds=None,\n encoder_hidden_states=None,\n encoder_attention_mask=None,\n labels=None,\n use_cache=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n ):\n assert self.cached_prefix_emb is not None\n assert inputs_embeds is None # Not supported by this inference model.\n assert labels is None # Training not supported by this inference model.\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n # assert len(past_key_values) + len(input_ids) == attention_mask.shape[1]\n\n # Create embedding\n prefix_len = self.cached_prefix_emb.shape[1]\n if input_ids.shape[1] != 1:\n gen_inputs = input_ids[:, prefix_len:]\n gen_emb = self.embeddings(gen_inputs)\n gen_emb = gen_emb + self.pos_embedding(gen_emb)\n if self.cached_prefix_emb.shape[0] != gen_emb.shape[0]:\n prefix_emb = self.cached_prefix_emb.repeat_interleave(\n gen_emb.shape[0] // self.cached_prefix_emb.shape[0], 0\n )\n else:\n prefix_emb = self.cached_prefix_emb.to(gen_emb.dtype)\n emb = torch.cat([prefix_emb, gen_emb], dim=1)\n else:\n emb = self.embeddings(input_ids)\n emb = emb + self.pos_embedding.get_fixed_embedding(\n attention_mask.shape[1] - (prefix_len + 1), attention_mask.device\n )\n transformer_outputs = self.transformer(\n inputs_embeds=emb,\n past_key_values=past_key_values,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n hidden_states = transformer_outputs[0]\n lm_logits = self.lm_head(hidden_states)\n\n if not return_dict:\n return (lm_logits,) + transformer_outputs[1:]\n\n return CausalLMOutputWithCrossAttentions(\n loss=None,\n logits=lm_logits,\n past_key_values=transformer_outputs.past_key_values,\n hidden_states=transformer_outputs.hidden_states,\n attentions=transformer_outputs.attentions,\n cross_attentions=transformer_outputs.cross_attentions,\n )\n\n @staticmethod\n def _reorder_cache(past, beam_idx):\n \"\"\"\n This function is used to re-order the :obj:`past_key_values` cache if\n :meth:`~transformers.PreTrainedModel.beam_search` or :meth:`~transformers.PreTrainedModel.beam_sample` is\n called. This is required to match :obj:`past_key_values` with the correct beam_idx at every generation step.\n \"\"\"\n return tuple(\n tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past)\n for layer_past in past\n )\n\n\nclass ConditioningEncoder(nn.Module):\n def __init__(\n self,\n spec_dim,\n embedding_dim,\n attn_blocks=6,\n num_attn_heads=4,\n do_checkpointing=False,\n mean=False,\n ):\n super().__init__()\n attn = []\n self.init = nn.Conv1d(spec_dim, embedding_dim, kernel_size=1)\n for a in range(attn_blocks):\n attn.append(AttentionBlock(embedding_dim, num_attn_heads, do_checkpoint=do_checkpointing))\n self.attn = nn.Sequential(*attn)\n self.dim = embedding_dim\n self.do_checkpointing = do_checkpointing\n self.mean = mean\n\n def forward(self, x):\n h = self.init(x)\n h = self.attn(h)\n if self.mean:\n return h.mean(dim=2)\n else:\n return h[:, :, 0]\n\n\nclass LearnedPositionEmbeddings(nn.Module):\n def __init__(self, seq_len, model_dim, init=0.02, relative=False):\n super().__init__()\n # nn.Embedding\n self.emb = torch.nn.Embedding(seq_len, model_dim)\n # Initializing this way is standard for GPT-2\n self.emb.weight.data.normal_(mean=0.0, std=init)\n self.relative = relative\n self.seq_len = seq_len\n\n def forward(self, x):\n sl = x.shape[1]\n if self.relative:\n start = random.randint(sl, self.seq_len) - sl\n return self.emb(torch.arange(start, start + sl, device=x.device))\n else:\n return self.emb(torch.arange(0, sl, device=x.device))\n\n def get_fixed_embedding(self, ind, dev):\n return self.emb(torch.tensor([ind], device=dev)).unsqueeze(0)\n\n\ndef build_hf_gpt_transformer(\n layers,\n model_dim,\n heads,\n max_mel_seq_len,\n max_text_seq_len,\n max_prompt_len,\n checkpointing,\n):\n \"\"\"\n GPT-2 implemented by the HuggingFace library.\n \"\"\"\n from transformers import GPT2Config, GPT2Model\n\n gpt_config = GPT2Config(\n vocab_size=256, # Unused.\n n_positions=max_mel_seq_len + max_text_seq_len + max_prompt_len,\n n_ctx=max_mel_seq_len + max_text_seq_len + max_prompt_len,\n n_embd=model_dim,\n n_layer=layers,\n n_head=heads,\n gradient_checkpointing=checkpointing,\n use_cache=not checkpointing,\n )\n gpt = GPT2Model(gpt_config)\n # Override the built in positional embeddings\n del gpt.wpe\n gpt.wpe = functools.partial(null_position_embeddings, dim=model_dim)\n # Built-in token embeddings are unused.\n del gpt.wte\n\n # def _attn(self, query, key, value, attention_mask=None, head_mask=None):\n # attn_output = torch.nn.functional.scaled_dot_product_attention(\n # query, key, value, dropout_p=self.attn_dropout.p, is_causal=True\n # )\n # return attn_output, None\n\n # for i in range(len(gpt.h)):\n # gpt.h[i].attn._attn = types.MethodType(\n # _attn, gpt.h[i].attn\n # )\n\n mel_pos_emb = (\n LearnedPositionEmbeddings(max_mel_seq_len, model_dim)\n if max_mel_seq_len != -1\n else functools.partial(null_position_embeddings, dim=model_dim)\n )\n text_pos_emb = (\n LearnedPositionEmbeddings(max_text_seq_len, model_dim)\n if max_mel_seq_len != -1\n else functools.partial(null_position_embeddings, dim=model_dim)\n )\n # gpt = torch.compile(gpt, mode=\"reduce-overhead\", fullgraph=True)\n return gpt, mel_pos_emb, text_pos_emb, None, None\n\n\nclass MelEncoder(nn.Module):\n def __init__(self, channels, mel_channels=80, resblocks_per_reduction=2):\n super().__init__()\n self.channels = channels\n self.encoder = nn.Sequential(\n nn.Conv1d(mel_channels, channels // 4, kernel_size=3, padding=1),\n nn.Sequential(*[ResBlock(channels // 4) for _ in range(resblocks_per_reduction)]),\n nn.Conv1d(channels // 4, channels // 2, kernel_size=3, stride=2, padding=1),\n nn.GroupNorm(channels // 16, channels // 2),\n nn.ReLU(),\n nn.Sequential(*[ResBlock(channels // 2) for _ in range(resblocks_per_reduction)]),\n nn.Conv1d(channels // 2, channels, kernel_size=3, stride=2, padding=1),\n nn.GroupNorm(channels // 8, channels),\n nn.ReLU(),\n nn.Sequential(*[ResBlock(channels) for _ in range(resblocks_per_reduction)]),\n )\n self.reduction = 4\n\n def forward(self, x):\n for e in self.encoder:\n x = e(x)\n return x.permute(0, 2, 1)\n\n\nclass UnifiedVoice(nn.Module):\n def __init__(\n self,\n start_text_token=261,\n stop_text_token=0,\n layers=8,\n model_dim=512,\n heads=8,\n max_text_tokens=120,\n max_mel_tokens=250,\n max_prompt_tokens=70,\n max_conditioning_inputs=1,\n mel_length_compression=1024,\n number_text_tokens=256,\n number_mel_codes=8194,\n start_mel_token=8192,\n stop_mel_token=8193,\n train_solo_embeddings=False,\n use_mel_codes_as_input=True,\n checkpointing=True,\n average_conditioning_embeddings=False,\n freeze_everything_but_position_embeddings=False,\n freeze_conditioning_encoder=False,\n tortoise_compat=True,\n label_smoothing=0.0,\n ):\n \"\"\"\n Args:\n layers: Number of layers in transformer stack.\n model_dim: Operating dimensions of the transformer\n heads: Number of transformer heads. Must be divisible by model_dim. Recommend model_dim//64\n max_text_tokens: Maximum number of text tokens that will be encountered by model.\n max_mel_tokens: Maximum number of MEL tokens that will be encountered by model.\n max_conditioning_inputs: Maximum number of conditioning inputs provided to the model. If (1), conditioning input can be of format (b,80,s), otherwise (b,n,80,s).\n mel_length_compression: The factor between and . Used to compute MEL code padding given wav input length.\n number_text_tokens:\n start_text_token:\n stop_text_token:\n number_mel_codes:\n start_mel_token:\n stop_mel_token:\n train_solo_embeddings:\n use_mel_codes_as_input:\n checkpointing:\n average_conditioning_embeddings: Whether or not conditioning embeddings should be averaged, instead of fed piecewise into the model.\n \"\"\"\n super().__init__()\n\n self.label_smoothing = label_smoothing\n self.number_text_tokens = number_text_tokens\n self.start_text_token = start_text_token\n self.stop_text_token = stop_text_token\n self.number_mel_codes = number_mel_codes\n self.start_mel_token = start_mel_token\n self.stop_mel_token = stop_mel_token\n self.start_prompt_token = start_mel_token\n self.stop_prompt_token = stop_mel_token\n self.layers = layers\n self.heads = heads\n self.model_dim = model_dim\n self.max_conditioning_inputs = max_conditioning_inputs\n self.max_mel_tokens = -1 if max_mel_tokens == -1 else max_mel_tokens + 2 + self.max_conditioning_inputs\n self.max_text_tokens = -1 if max_text_tokens == -1 else max_text_tokens + 2\n self.max_prompt_tokens = max_prompt_tokens\n self.mel_length_compression = mel_length_compression\n # self.conditioning_encoder = ConditioningEncoder(\n # 80, model_dim, num_attn_heads=heads\n # )\n self.average_conditioning_embeddings = average_conditioning_embeddings\n self.tortoise_compat = tortoise_compat # credit to https://github.com/152334H/DL-Art-School/commit/ae80992817059acf6eef38a680efa5124cee570b\n # nn.Embedding\n self.text_embedding = ml.Embedding(self.number_text_tokens, model_dim)\n if use_mel_codes_as_input:\n # nn.Embedding\n self.mel_embedding = ml.Embedding(self.number_mel_codes, model_dim)\n else:\n self.mel_embedding = MelEncoder(model_dim, resblocks_per_reduction=1)\n (\n self.gpt,\n self.mel_pos_embedding,\n self.text_pos_embedding,\n self.mel_layer_pos_embedding,\n self.text_layer_pos_embedding,\n ) = build_hf_gpt_transformer(\n layers,\n model_dim,\n heads,\n self.max_mel_tokens,\n self.max_text_tokens,\n self.max_prompt_tokens,\n checkpointing,\n )\n if train_solo_embeddings:\n self.mel_solo_embedding = nn.Parameter(torch.randn(1, 1, model_dim) * 0.02, requires_grad=True)\n self.text_solo_embedding = nn.Parameter(torch.randn(1, 1, model_dim) * 0.02, requires_grad=True)\n else:\n self.mel_solo_embedding = 0\n self.text_solo_embedding = 0\n\n self.final_norm = nn.LayerNorm(model_dim)\n self.text_head = ml.Linear(model_dim, self.number_text_tokens)\n self.mel_head = ml.Linear(model_dim, self.number_mel_codes)\n\n # Initialize the embeddings per the GPT-2 scheme\n embeddings = [self.text_embedding]\n if use_mel_codes_as_input:\n embeddings.append(self.mel_embedding)\n for module in embeddings:\n module.weight.data.normal_(mean=0.0, std=0.02)\n\n if freeze_conditioning_encoder:\n print(\" > Freezing conditioning encoder.\")\n for p in self.conditioning_encoder.parameters():\n p.requires_grad = False\n p.DO_NOT_TRAIN = True\n\n if freeze_everything_but_position_embeddings:\n for p in self.parameters():\n p.requires_grad = False\n p.DO_NOT_TRAIN = True\n for m in [self.mel_pos_embedding, self.text_pos_embedding]:\n for p in m.parameters():\n del p.DO_NOT_TRAIN\n p.requires_grad = True\n\n def get_grad_norm_parameter_groups(self):\n return {\n \"conditioning_encoder\": list(self.conditioning_encoder.parameters()),\n \"gpt\": list(self.gpt.parameters()),\n \"heads\": list(self.text_head.parameters()) + list(self.mel_head.parameters()),\n }\n\n def post_init_gpt2_config(self, kv_cache=True, use_deepspeed=False, use_deepspeed_f16=False):\n seq_length = self.max_prompt_tokens + self.max_mel_tokens + self.max_text_tokens + 1\n gpt_config = GPT2Config(\n vocab_size=self.max_mel_tokens,\n n_positions=seq_length,\n n_ctx=seq_length,\n n_embd=self.model_dim,\n n_layer=self.layers,\n n_head=self.heads,\n gradient_checkpointing=False,\n use_cache=True,\n )\n self.inference_model = GPT2InferenceModel(\n gpt_config,\n self.gpt,\n self.mel_pos_embedding,\n self.mel_embedding,\n self.final_norm,\n self.mel_head,\n kv_cache=kv_cache,\n )\n # self.inference_model = PrunedGPT2InferenceModel(gpt_config, self.gpt, self.mel_pos_embedding, self.mel_embedding, self.final_norm, self.mel_head)\n self.gpt.wte = self.mel_embedding\n\n if use_deepspeed:\n # init deepspeed inference engine\n if use_deepspeed_f16:\n self.gpt.wte = self.mel_embedding.half()\n self.gpt.wpe = self.mel_pos_embedding.half()\n self.ds_engine = deepspeed.init_inference(\n model=self.inference_model.half(), # Transformers models\n mp_size=1, # Number of GPU\n dtype=torch.float16 if use_deepspeed_f16 else torch.float32, # desired data type of output\n replace_method=\"auto\", # Lets DS autmatically identify the layer to replace\n replace_with_kernel_inject=True, # replace the model with the kernel injector\n )\n self.inference_model = self.ds_engine.module.eval()\n\n def build_aligned_inputs_and_targets(self, input, start_token, stop_token):\n inp = F.pad(input, (1, 0), value=start_token)\n tar = F.pad(input, (0, 1), value=stop_token)\n return inp, tar\n\n def set_mel_padding(self, mel_input_tokens, mel_lengths):\n \"\"\"\n Given mel tokens that are derived from a padded audio clip and the actual lengths of each batch element in\n that audio clip, reformats the tokens with STOP_MEL_TOKEN in place of the zero padding. This is required\n preformatting to create a working TTS model.\n \"\"\"\n # Set padding areas within MEL (currently it is coded with the MEL code for ).\n for b in range(len(mel_lengths)):\n actual_end = mel_lengths[b]\n if actual_end < mel_input_tokens.shape[-1]:\n mel_input_tokens[b, actual_end:] = self.stop_mel_token\n return mel_input_tokens\n\n def get_logits(\n self,\n speech_conditioning_inputs,\n first_inputs,\n first_head,\n second_inputs=None,\n second_head=None,\n prompt=None,\n get_attns=False,\n return_latent=False,\n attn_mask_text=None,\n attn_mask_mel=None,\n ):\n if prompt is not None and speech_conditioning_inputs is not None:\n offset = speech_conditioning_inputs.shape[1] + prompt.shape[1]\n if second_inputs is not None:\n emb = torch.cat(\n [speech_conditioning_inputs, prompt, first_inputs, second_inputs],\n dim=1,\n )\n else:\n emb = torch.cat([speech_conditioning_inputs, prompt, first_inputs], dim=1)\n elif speech_conditioning_inputs is not None:\n offset = speech_conditioning_inputs.shape[1]\n if second_inputs is not None:\n emb = torch.cat([speech_conditioning_inputs, first_inputs, second_inputs], dim=1)\n else:\n emb = torch.cat([speech_conditioning_inputs, first_inputs], dim=1)\n elif prompt is not None:\n offset = prompt.shape[1]\n if second_inputs is not None:\n emb = torch.cat([prompt, first_inputs, second_inputs], dim=1)\n else:\n emb = torch.cat([prompt, first_inputs], dim=1)\n\n # with torch.backends.cuda.sdp_kernel(enable_flash=True, enable_math=False, enable_mem_efficient=False):\n attn_mask = None\n if attn_mask_text is not None:\n attn_mask = torch.cat([attn_mask_text, attn_mask_mel], dim=1)\n if prompt is not None:\n attn_mask_prompt = torch.ones(prompt.shape[0], offset, dtype=torch.bool, device=emb.device)\n attn_mask = torch.cat([attn_mask_prompt, attn_mask], dim=1)\n\n gpt_out = self.gpt(\n inputs_embeds=emb,\n return_dict=True,\n output_attentions=get_attns,\n attention_mask=attn_mask,\n )\n\n if get_attns:\n return gpt_out.attentions\n\n enc = gpt_out.last_hidden_state[:, offset:]\n enc = self.final_norm(enc)\n\n if return_latent:\n return enc[:, : first_inputs.shape[1]], enc[:, -second_inputs.shape[1] :]\n\n first_logits = enc[:, : first_inputs.shape[1]]\n first_logits = first_head(first_logits)\n first_logits = first_logits.permute(0, 2, 1)\n if second_inputs is not None:\n second_logits = enc[:, -second_inputs.shape[1] :]\n second_logits = second_head(second_logits)\n second_logits = second_logits.permute(0, 2, 1)\n return first_logits, second_logits\n else:\n return first_logits\n\n def get_conditioning(self, speech_conditioning_input):\n speech_conditioning_input = (\n speech_conditioning_input.unsqueeze(1)\n if len(speech_conditioning_input.shape) == 3\n else speech_conditioning_input\n )\n conds = []\n for j in range(speech_conditioning_input.shape[1]):\n conds.append(self.conditioning_encoder(speech_conditioning_input[:, j]))\n conds = torch.stack(conds, dim=1)\n conds = conds.mean(dim=1)\n return conds\n\n def get_prompts(self, prompt_codes):\n \"\"\"\n Create a prompt from the mel codes. This is used to condition the model on the mel codes.\n Pad the prompt with start and stop mel tokens.\n \"\"\"\n prompt = prompt_codes\n if self.training:\n prompt_len = random.randint(1, 9) # in secs\n prompt_len = prompt_len * 24 # in frames\n\n if prompt_codes.shape[1] < prompt_len:\n prompt_len = prompt_codes.shape[-1]\n start = 0\n else:\n start = random.randint(0, prompt_codes.shape[-1] - prompt_len)\n\n prompt = prompt_codes[:, start : start + prompt_len]\n\n # add start and stop tokens\n prompt = F.pad(prompt, (1, 0), value=self.start_prompt_token)\n prompt = F.pad(prompt, (0, 1), value=self.stop_prompt_token)\n return prompt\n\n # def get_prompts(self, prompt_codes):\n # \"\"\"\n # Create a prompt from the mel codes. This is used to condition the model on the mel codes.\n # Pad the prompt with start and stop mel tokens.\n # \"\"\"\n # prompt = prompt_codes\n # if self.training:\n # max_prompt_len = 9 * 24\n # if prompt_codes.shape[1] < max_prompt_len:\n # prompt = prompt_codes\n # else:\n # start = random.randint(0, prompt_codes.shape[1] - max_prompt_len)\n # prompt = prompt_codes[:, start : start + max_prompt_len]\n\n # # add start and stop tokens\n # prompt = F.pad(prompt, (1, 0), value=self.start_prompt_token)\n # prompt = F.pad(prompt, (0, 1), value=self.stop_prompt_token)\n # return prompt\n\n def forward(\n self,\n speech_conditioning_input,\n text_inputs,\n text_lengths,\n mel_codes,\n wav_lengths,\n prompt_codes,\n loss_weights=None,\n text_first=True,\n return_attentions=False,\n return_latent=False,\n ):\n \"\"\"\n Forward pass that uses both text and voice in either text conditioning mode or voice conditioning mode\n (actuated by `text_first`).\n\n speech_conditioning_input: MEL float tensor, (b,80,s)\n text_inputs: long tensor, (b,t)\n text_lengths: long tensor, (b,)\n mel_inputs: long tensor, (b,m)\n wav_lengths: long tensor, (b,)\n\n If return_attentions is specified, only logits are returned.\n If return_latent is specified, loss & logits are not computed or returned. Only the predicted latents are returned.\n \"\"\"\n\n # ❗ FIXIT\n speech_conditioning_input = None\n if self.max_conditioning_inputs == 0:\n assert (\n speech_conditioning_input is None\n ), \" ❗ speech_conditioning_input is not None, but max_conditioning_inputs == 0\"\n\n max_text_len = text_lengths.max()\n # Due to the convolution in DVAE, codes do not end with silence at the right place. Rather it predicts some intermediate values\n # Like [..., 186, 45, 45, 83] where actually it should end with 186.\n # We take last 3 codes to prevent abrupt ending of the audio.\n # TODO: This is might need some testing.\n mel_lengths = torch.ceil(wav_lengths / self.mel_length_compression).long() + 3\n\n # If len(codes) + 3 is larger than maxiumum allowed length, we truncate the codes.\n max_mel_len = mel_lengths.max()\n\n if max_mel_len > mel_codes.shape[-1]:\n mel_codes = F.pad(mel_codes, (0, max_mel_len - mel_codes.shape[-1]))\n\n # mel_lengths[mel_lengths >= max_mel_len] = max_mel_len\n\n # silence aware lengths, skip the silence tokens at the end of the mel codes.\n silence = True\n for idx, l in enumerate(mel_lengths):\n length = l.item()\n while silence:\n if mel_codes[idx, length - 1] != 83:\n break\n length -= 1\n mel_lengths[idx] = length\n\n # Lovely assertions\n assert (\n max_mel_len <= mel_codes.shape[-1]\n ), f\" ❗ max_mel_len ({max_mel_len}) > mel_codes.shape[-1] ({mel_codes.shape[-1]})\"\n assert (\n max_text_len <= text_inputs.shape[-1]\n ), f\" ❗ max_text_len ({max_text_len}) > text_inputs.shape[-1] ({text_inputs.shape[-1]})\"\n\n # Append stop token to text inputs\n text_inputs = F.pad(text_inputs[:, :max_text_len], (0, 1), value=self.stop_text_token)\n\n # Append silence token to mel codes\n mel_codes = F.pad(mel_codes[:, :max_mel_len], (0, 1), value=self.stop_mel_token)\n\n # Pad mel codes with STOP_MEL_TOKEN\n mel_codes = self.set_mel_padding(mel_codes, mel_lengths)\n\n # Compute speech conditioning input\n conds = None\n if speech_conditioning_input is not None:\n if not return_latent:\n # Compute speech conditioning input\n speech_conditioning_input = (\n speech_conditioning_input.unsqueeze(1)\n if len(speech_conditioning_input.shape) == 3\n else speech_conditioning_input\n )\n\n conds = []\n for j in range(speech_conditioning_input.shape[1]):\n conds.append(self.conditioning_encoder(speech_conditioning_input[:, j]))\n conds = torch.stack(conds, dim=1)\n if self.average_conditioning_embeddings:\n conds = conds.mean(dim=1).unsqueeze(1)\n else:\n # already computed\n conds = speech_conditioning_input.unsqueeze(1)\n\n # Build input and target tensors\n # Prepend start token to inputs and append stop token to targets\n text_inputs, text_targets = self.build_aligned_inputs_and_targets(\n text_inputs, self.start_text_token, self.stop_text_token\n )\n mel_codes, mel_targets = self.build_aligned_inputs_and_targets(\n mel_codes, self.start_mel_token, self.stop_mel_token\n )\n\n # Set attn_mask\n attn_mask_text = None\n attn_mask_mel = None\n if not return_latent:\n attn_mask_text = torch.ones(\n text_inputs.shape[0],\n text_inputs.shape[1],\n dtype=torch.bool,\n device=text_inputs.device,\n )\n attn_mask_mel = torch.ones(\n mel_codes.shape[0],\n mel_codes.shape[1],\n dtype=torch.bool,\n device=mel_codes.device,\n )\n\n for idx, l in enumerate(text_lengths):\n attn_mask_text[idx, l + 1 :] = 0.0\n\n for idx, l in enumerate(mel_lengths):\n attn_mask_mel[idx, l + 1 :] = 0.0\n\n # Compute text embeddings + positional embeddings\n # print(\" > text input latent:\", text_inputs)\n text_emb = self.text_embedding(text_inputs) + self.text_pos_embedding(text_inputs)\n\n # Compute mel embeddings + positional embeddings\n mel_emb = self.mel_embedding(mel_codes) + self.mel_pos_embedding(mel_codes)\n\n # Compute prompt embeddings + positional embeddings\n prompt = self.get_prompts(prompt_codes)\n\n prompt_emb = self.mel_embedding(prompt).detach() + self.mel_pos_embedding(prompt).detach()\n\n # Get logits\n sub = -4 # don't ask me why 😄\n if self.training:\n sub = -1\n text_logits, mel_logits = self.get_logits(\n conds,\n text_emb,\n self.text_head,\n mel_emb,\n self.mel_head,\n prompt=prompt_emb,\n get_attns=return_attentions,\n return_latent=return_latent,\n attn_mask_text=attn_mask_text,\n attn_mask_mel=attn_mask_mel,\n )\n if return_latent:\n return mel_logits[:, :sub] # sub to prevent bla.\n\n if return_attentions:\n return mel_logits\n\n # Set paddings to -1 to ignore them in loss\n for idx, l in enumerate(text_lengths):\n text_targets[idx, l + 1 :] = -1\n\n for idx, l in enumerate(mel_lengths):\n mel_targets[idx, l + 1 :] = -1\n\n # check if stoptoken is in every row of mel_targets\n assert (mel_targets == self.stop_mel_token).sum() >= mel_targets.shape[\n 0\n ], f\" ❗ mel_targets does not contain stop token ({self.stop_mel_token}) in every row.\"\n\n # Compute losses\n loss_text = F.cross_entropy(\n text_logits, text_targets.long(), ignore_index=-1, label_smoothing=self.label_smoothing\n )\n loss_mel = F.cross_entropy(\n mel_logits, mel_targets.long(), ignore_index=-1, label_smoothing=self.label_smoothing\n )\n\n # if loss_weights is not None:\n # loss_text = loss_text * loss_weights[:, None]\n # loss_mel = loss_mel * loss_weights[:, None]\n return loss_text.mean(), loss_mel.mean(), mel_logits\n\n def text_forward(self, speech_conditioning_input, text_inputs, text_lengths):\n \"\"\"\n Performs autoregressive modeling on only text. Still requires a speech_conditioning_input due to the way the\n model inputs are formatted. Just provide any audio clip (arguably, zeros could be provided).\n \"\"\"\n # This model will receive micro-batches with a ton of padding for both the text and MELs. Ameliorate this by\n # chopping the inputs by the maximum actual length.\n max_text_len = text_lengths.max()\n text_inputs = F.pad(text_inputs[:, :max_text_len], (0, 1), value=self.stop_text_token)\n\n speech_conditioning_input = (\n speech_conditioning_input.unsqueeze(1)\n if len(speech_conditioning_input.shape) == 3\n else speech_conditioning_input\n )\n conds = []\n for j in range(speech_conditioning_input.shape[1]):\n conds.append(self.conditioning_encoder(speech_conditioning_input[:, j]))\n conds = torch.stack(conds, dim=1)\n if self.average_conditioning_embeddings:\n conds = conds.mean(dim=1).unsqueeze(1)\n\n text_inputs, text_targets = self.build_aligned_inputs_and_targets(\n text_inputs, self.start_text_token, self.stop_text_token\n )\n text_emb = self.text_embedding(text_inputs) + self.text_pos_embedding(text_inputs) + self.text_solo_embedding\n text_logits = self.get_logits(conds, text_emb, self.text_head)\n loss_text = F.cross_entropy(text_logits, text_targets.long())\n return loss_text.mean()\n\n def speech_forward(self, speech_conditioning_input, mel_codes, wav_lengths, raw_mels=None):\n \"\"\"\n Performs autoregressive modeling on only speech data.\n \"\"\"\n assert self.max_mel_tokens >= mel_codes.shape[1], f\"{mel_codes.shape[1]}\"\n\n # This model will receive micro-batches with a ton of padding for both the text and MELs. Ameliorate this by\n # chopping the inputs by the maximum actual length.\n max_mel_len = wav_lengths.max() // self.mel_length_compression\n mel_codes = F.pad(mel_codes[:, :max_mel_len], (0, 1), value=self.stop_mel_token)\n mel_codes = self.set_mel_padding(mel_codes, wav_lengths)\n if raw_mels is not None:\n raw_mels = raw_mels[:, :, : max_mel_len * 4]\n\n speech_conditioning_input = (\n speech_conditioning_input.unsqueeze(1)\n if len(speech_conditioning_input.shape) == 3\n else speech_conditioning_input\n )\n conds = []\n for j in range(speech_conditioning_input.shape[1]):\n conds.append(self.conditioning_encoder(speech_conditioning_input[:, j]))\n conds = torch.stack(conds, dim=1)\n if self.average_conditioning_embeddings:\n conds = conds.mean(dim=1).unsqueeze(1)\n\n mel_codes, mel_targets = self.build_aligned_inputs_and_targets(\n mel_codes, self.start_mel_token, self.stop_mel_token\n )\n if raw_mels is not None:\n mel_inp = F.pad(raw_mels, (0, 4))\n else:\n mel_inp = mel_codes\n mel_emb = self.mel_embedding(mel_inp)\n mel_emb = mel_emb + self.mel_pos_embedding(mel_codes) + self.mel_solo_embedding\n mel_logits = self.get_logits(conds, mel_emb, self.mel_head)\n loss_mel = F.cross_entropy(mel_logits, mel_targets.long())\n return loss_mel.mean()\n\n def get_generator(self, fake_inputs, **hf_generate_kwargs):\n return self.inference_model.generate_stream(\n fake_inputs,\n bos_token_id=self.start_mel_token,\n pad_token_id=self.stop_mel_token,\n eos_token_id=self.stop_mel_token,\n max_length=self.max_mel_tokens * 2 + self.max_prompt_tokens + self.max_text_tokens,\n do_stream=True,\n **hf_generate_kwargs,\n )\n\n def compute_embeddings(\n self,\n speech_conditioning_latent,\n text_inputs,\n input_tokens=None,\n prompt_codes=None,\n pad_input_text=False,\n ):\n if pad_input_text and text_inputs.shape[1] < 250:\n text_inputs = F.pad(text_inputs, (0, 250 - text_inputs.shape[1]), value=self.stop_text_token)\n else:\n text_inputs = F.pad(text_inputs, (0, 1), value=self.stop_text_token)\n text_inputs = F.pad(text_inputs, (1, 0), value=self.start_text_token)\n\n emb = self.text_embedding(text_inputs) + self.text_pos_embedding(text_inputs)\n\n print(\" > Text inputs:\", text_inputs)\n if prompt_codes is not None:\n prompt_codes = self.get_prompts(prompt_codes)\n prompt_emb = self.mel_embedding(prompt_codes) + self.mel_pos_embedding(prompt_codes)\n print(\" > Prompt inputs:\", prompt_codes)\n print(\" > Prompt inputs shape:\", prompt_codes.shape)\n emb = torch.cat([prompt_emb, emb], dim=1)\n\n if speech_conditioning_latent is not None:\n conds = speech_conditioning_latent.unsqueeze(1)\n emb = torch.cat([conds, emb], dim=1)\n\n self.inference_model.store_prefix_emb(emb)\n\n fake_inputs = torch.full(\n (\n emb.shape[0],\n emb.shape[1] + 1, # +1 for the start_mel_token\n ),\n fill_value=1,\n dtype=torch.long,\n device=text_inputs.device,\n )\n fake_inputs[:, -1] = self.start_mel_token\n\n if input_tokens is not None:\n fake_inputs = torch.cat([fake_inputs, input_tokens], dim=1)\n return fake_inputs\n\n def inference_speech(\n self,\n speech_conditioning_latent,\n text_inputs,\n input_tokens=None,\n prompt_codes=None,\n pad_input_text=False,\n **hf_generate_kwargs,\n ):\n if pad_input_text and text_inputs.shape[1] < 250:\n text_inputs = F.pad(text_inputs, (0, 250 - text_inputs.shape[1]), value=self.stop_text_token)\n else:\n text_inputs = F.pad(text_inputs, (0, 1), value=self.stop_text_token)\n text_inputs = F.pad(text_inputs, (1, 0), value=self.start_text_token)\n\n emb = self.text_embedding(text_inputs) + self.text_pos_embedding(text_inputs)\n\n print(\" > Text inputs:\", text_inputs)\n if prompt_codes is not None:\n prompt_codes = self.get_prompts(prompt_codes)\n prompt_emb = self.mel_embedding(prompt_codes) + self.mel_pos_embedding(prompt_codes)\n print(\" > Prompt inputs:\", prompt_codes)\n print(\" > Prompt inputs shape:\", prompt_codes.shape)\n emb = torch.cat([prompt_emb, emb], dim=1)\n\n if speech_conditioning_latent is not None:\n conds = speech_conditioning_latent.unsqueeze(1)\n emb = torch.cat([conds, emb], dim=1)\n\n self.inference_model.store_prefix_emb(emb)\n\n fake_inputs = torch.full(\n (\n emb.shape[0],\n emb.shape[1] + 1, # +1 for the start_mel_token\n ),\n fill_value=1,\n dtype=torch.long,\n device=text_inputs.device,\n )\n fake_inputs[:, -1] = self.start_mel_token\n\n if input_tokens is not None:\n fake_inputs = torch.cat([fake_inputs, input_tokens], dim=1)\n\n gen = self.inference_model.generate(\n fake_inputs,\n bos_token_id=self.start_mel_token,\n pad_token_id=self.stop_mel_token,\n eos_token_id=self.stop_mel_token,\n max_length=self.max_mel_tokens * 2 + self.max_prompt_tokens + self.max_text_tokens,\n **hf_generate_kwargs,\n )\n if \"return_dict_in_generate\" in hf_generate_kwargs:\n return gen.sequences[:, fake_inputs.shape[1] :], gen\n return gen[:, fake_inputs.shape[1] :]\n\n # Turns the (utterly insane) output of HF.generate() into a far more sane output:\n # [tensors(B,H,S,S)]. Outer=layers, B=batch,H=head,S=sequence\n def make_hf_generate_attentions_sane(self, attentions):\n layers = [[] for _ in range(len(attentions[0]))]\n full_attention_size = attentions[-1][0].shape[-1]\n for i, gen in enumerate(attentions):\n for j, lyr in enumerate(gen):\n layers[j].append(F.pad(lyr, (0, full_attention_size - lyr.shape[-1])))\n catted = []\n for lyr in layers:\n catted.append(torch.cat(lyr, dim=2))\n return catted\n\n def convert_attentions_to_aligned_codes(self, text, attentions, codes, num_conds):\n \"\"\"\n This was an attempt to make some sense out of the attention matrix retrieved from the unified_voice model. Unfortunately, I can't use it for aligning text & voice.\n \"\"\"\n text_padding = num_conds + 2\n num_text = text.shape[-1]\n num_context = num_text + text_padding\n assert num_context + 1 == attentions[0][0].shape[-1]\n attentions = self.make_hf_generate_attentions_sane(attentions)\n results = [torch.empty_like(codes) for _ in range(len(attentions))]\n for l, layer in enumerate(attentions):\n dec_context = layer[:, :, num_context:, :]\n # Mask out everything that isn't text (including the start token, which gets a LOT of attention)\n dec_context[:, :, :, : text_padding + 1] = 0\n dec_context[:, :, :, num_context:] = 0\n for h in range(dec_context.shape[1]):\n dec_context_indices = torch.argmax(dec_context[0, h], dim=-1)\n print(f\"layer_{l};head_{h}: \" + str(dec_context_indices))\n for t, att_tok in enumerate(attentions):\n combined_attention_weights = torch.zeros((codes.shape[0], num_text), device=codes.device)\n for lyr in att_tok:\n token_to_text_attentions = lyr[:, :, -1, text_padding : (text_padding + num_text)].sum(dim=1)\n combined_attention_weights = combined_attention_weights + token_to_text_attentions\n break\n most_attended_text_token = combined_attention_weights.argmax(dim=-1)\n results[:, t] = most_attended_text_token\n eos_token_mask = codes != self.stop_mel_token\n return results * eos_token_mask\n\n\n@register_model\ndef register_unified_voice_prompt(opt_net, opt):\n return UnifiedVoice(**opt_get(opt_net, [\"kwargs\"], {}))\n\n\nif __name__ == \"__main__\":\n gpt = UnifiedVoice(\n model_dim=256,\n heads=4,\n train_solo_embeddings=True,\n use_mel_codes_as_input=True,\n max_conditioning_inputs=4,\n freeze_everything_but_position_embeddings=True,\n )\n l = gpt(\n torch.randn(2, 3, 80, 800),\n torch.randint(high=256, size=(2, 120)),\n torch.tensor([32, 120]),\n torch.randint(high=8192, size=(2, 250)),\n torch.tensor([250 * 256, 195 * 256]),\n )\n # gpt.text_forward(torch.randn(2,80,800), torch.randint(high=50, size=(2,80)), torch.tensor([32, 80]))\n","repo_name":"camenduru/video-dubbing-hf","sub_path":"TTS/TTS/tts/layers/xtts/gpt_encoder_old.py","file_name":"gpt_encoder_old.py","file_ext":"py","file_size_in_byte":42597,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"74179087184","text":"#!/usr/bin/env python\n# coding=utf-8\n\nimport logging\n\n\ndef show_logger():\n logger = logging.getLogger(__name__)\n logger.setLevel(logging.WARNING)\n handler = logging.StreamHandler()\n logger.addHandler(handler)\n\n logger.debug('I am DEBUG')\n logger.info('I am INFO')\n logger.warning('I am WARNING')\n logger.error('I am ERROR')\n try:\n 1 / 0\n except ZeroDivisionError:\n logger.exception('I am EXCEPTION')\n logger.critical('I am CRITICAL')\n","repo_name":"akun/pycon2015","sub_path":"pycon2015/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"48"} +{"seq_id":"29059439096","text":"import time\nc = time.time()\nraw_nb = open(\"input.txt\").read().split('\\n')[:-1]\n#raw_nb= open(\"input_test.txt\").read().split('\\n')[:-1]\n\n\nlst_nb = [int(k) for k in raw_nb]\n\nif len(raw_nb) > 50:\n n = 25\n N = 3199139634\n iN = 683\nelse :\n n = 5\n N = 127\n iN = 14\n\n\ndef recherche_somme(candidats, goal):\n for k in candidats :\n if (goal - k) in candidats :\n return True\n return False\n\n\ndef test_glissant(i):\n candidats = lst_nb[i-n:i]\n return recherche_somme(candidats, lst_nb[i])\n\ndef intrus():\n for i in range(n, len(lst_nb)):\n if test_glissant(i) == False :\n return lst_nb[i], i\n\ndef recherche_somme():\n for i in range(iN):\n somme = 0\n for k in range(iN-i):\n somme += lst_nb[i+k]\n if somme > N:\n break\n if somme == N:\n vals = lst_nb[i:i+k+1]\n return min(vals) + max(vals)\n return None\n\n#part 1\n#print(intrus())\n\nprint(recherche_somme())\nprint(time.time()-c)","repo_name":"glassus/aoc2020","sub_path":"day09/09_01_02.py","file_name":"09_01_02.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34415091760","text":"import binascii\nimport logging\nfrom copy import deepcopy\nfrom typing import Optional, Union # for type hinting\n\nfrom lxml import etree\nfrom scapy.all import UDP, Ether\n\n\ndef _find_docking_parameters(server_address, new_docking):\n _docking_params = _get_docking_parameters_from_server(\n server_address, new_docking\n )\n\n if _docking_params is not None:\n # it worked, return those\n return _docking_params\n\n logging.warning(\n \"Guessing interface parameters for {} {}. \"\n \"Install the ByteBlower python API to resolve this warning\".format(\n server_address, new_docking\n )\n )\n\n # We couldn't ask the ByteBlower Server for the port.\n # Let's take an educated guess.\n return _guess_docking_parameters(new_docking)\n\n\ndef _guess_docking_parameters(interface_name):\n logging.warning(\n \"Guessing interface '%s' docking parameters\" % interface_name\n )\n\n if 'nontrunk' in interface_name:\n port_id = -1\n splitted = interface_name.split('-')\n if len(splitted) == 2:\n interface_id = splitted[1]\n else:\n interface_id = -1\n\n elif 'trunk' in interface_name:\n splitted = interface_name.split('-')\n port_id = interface_id = -1\n if len(splitted) == 3:\n interface_id = int(splitted[1]) - 1\n port_id = int(splitted[2]) - 1\n else:\n logging.error(\"Unknown interface type '%s'\" % interface_name)\n return None\n\n return interface_id, port_id\n\n\ndef _get_docking_parameters_from_server(server_address, interface_name):\n try:\n from byteblowerll import byteblower\n except ImportError:\n # Aargh, no API available, we can't do our job!\n logging.warning(\"could not find the ByteBlower API\")\n return None\n\n connect_timeout_ns = int(1e9) # one second\n\n try:\n with AutoCleanupServer(server_address,\n timeout=connect_timeout_ns) as server:\n byteblower_interface = server.InterfaceGetByName(interface_name)\n\n physical_interface = byteblower_interface.GetPhysicalInterface()\n\n physical_id = physical_interface.IdGet()\n interface_id = byteblower_interface.PortIdGet() - 1\n\n except byteblower.ConfigError:\n logging.warning(\n \"The ByteBlower server does not know interface '%s'\" %\n interface_name\n )\n return None\n\n except byteblower.ByteBlowerAPIException:\n logging.warning(\"Could not connect to the ByteBlower server\")\n return None\n\n return physical_id, interface_id\n\n\nclass ProjectParseError(Exception):\n\n def __init__(self, message):\n Exception.__init__(self, message)\n\n\nclass ElementNotFound(Exception):\n\n def __init__(self, message):\n Exception.__init__(self, message)\n\n\nclass PortNotFound(Exception):\n\n def __init__(self, message):\n Exception.__init__(self, message)\n\n\nclass FrameNotFound(Exception):\n\n def __init__(self, message):\n Exception.__init__(self, message)\n\n\nclass DockFailed(Exception):\n\n def __init__(self, message):\n super().__init__(message)\n\n\nclass FormatError(Exception):\n\n def __init__(self, message):\n super().__init__(message)\n\n\nclass AutoCleanupServer(object):\n \"\"\" Contextmanager which automatically removes the server when the object goes out of scope\n :param address: The address on which the ByteBlower server is reachable\n :type address: str\n :param port: The TCP port number on which the server listens. 9002 is the default\n :type port: int\n :param timeout: Number of nanoseconds to wait for the server to respond\n :type timeout: int\n :return: A server object\n :rtype: :class:`byteblowerll.byteblower.ByteBlowerServer`\n\n \"\"\"\n\n def __init__(self, address, port=9002, timeout=int(1e9)):\n self._address = address\n self._server = None\n self._port = port\n self._timeout = timeout\n\n def __enter__(self):\n from byteblowerll import byteblower\n instance = byteblower.ByteBlower.InstanceGet()\n self._server = instance.ServerAdd(\n self._address, self._port, self._timeout\n )\n return self._server\n\n def __exit__(self, *args, **kwargs):\n from byteblowerll import byteblower\n instance = byteblower.ByteBlower.InstanceGet()\n try:\n instance.ServerRemove(self._server)\n except byteblower.ByteBlowerAPIException:\n pass\n self._server = None\n\n\nclass Frame(object):\n\n def __init__(self, frame_tree):\n self._tree = frame_tree\n\n @property\n def name(self):\n return self._tree.get('name')\n\n @name.setter\n def name(self, name):\n self._tree.set('name', name)\n\n def copy(self, name):\n parent = self._tree.getparent()\n\n new_tree = deepcopy(self._tree)\n new_frame = Frame(new_tree)\n parent.append(new_tree)\n\n new_frame.name = name\n\n return new_frame\n\n @property\n def udp_src_port(self):\n content = self._tree.get('bytesHexString')\n scapy_content = Ether(binascii.a2b_hex(content))\n return scapy_content[UDP].sport\n\n @udp_src_port.setter\n def udp_src_port(self, value):\n content = self._tree.get('bytesHexString')\n scapy_content = Ether(binascii.a2b_hex(content))\n scapy_content[UDP].sport = value\n self._tree.set(\n 'bytesHexString', binascii.hexlify(bytes(scapy_content))\n )\n\n @property\n def udp_dst_port(self):\n content = self._tree.get('bytesHexString')\n scapy_content = Ether(binascii.a2b_hex(content))\n return scapy_content[UDP].dport\n\n @udp_dst_port.setter\n def udp_dst_port(self, value):\n content = self._tree.get('bytesHexString')\n scapy_content = Ether(binascii.a2b_hex(content))\n scapy_content[UDP].dport = value\n self._tree.set(\n 'bytesHexString', binascii.hexlify(bytes(scapy_content))\n )\n\n @property\n def size(self):\n content = self._tree.get('bytesHexString')\n scapy_content = Ether(binascii.a2b_hex(content))\n return len(scapy_content)\n\n\nclass FlowTemplate(object):\n \"\"\"Interface to a flow template configuration.\"\"\"\n\n def __init__(self, flow_template_tree) -> None:\n self._tree = flow_template_tree\n\n @property\n def name(self):\n return self._tree.get('name')\n\n @property\n def frame_interval(self):\n return self._tree.get(\"frameInterval\")\n\n @frame_interval.setter\n def frame_interval(self, new_value: Union[float, int]):\n \"\"\"\n Set the new frame interval.\n\n .. :param new_value: Interval in nanoseconds\n\n .. note::\n The value will be truncated to the nearest integer value.\n \"\"\"\n # ByteBlower GUI only accepts integer value (nanoseconds)\n self._tree.set(\"frameInterval\", str(int(new_value)))\n\n\nclass Scenario(object):\n \"\"\"Interface to a scenario configuration.\"\"\"\n\n def __init__(self, scenario_tree) -> None:\n self._tree = scenario_tree\n\n @property\n def name(self):\n return self._tree.get('name')\n\n @property\n def duration(self) -> Optional[int]:\n max_scheduled_stop: int = None\n for measurements in self._tree.iterfind(\"measurements\"):\n flow_stop_event = next(measurements.iterfind(\"flowStopEvent\"))\n scheduled_stop: Optional[str] = flow_stop_event.get(\n \"scheduledTime\"\n )\n if scheduled_stop is not None:\n scheduled_stop = int(scheduled_stop)\n if max_scheduled_stop is None or scheduled_stop > max_scheduled_stop:\n max_scheduled_stop = scheduled_stop\n return max_scheduled_stop\n\n @duration.setter\n def duration(self, new_value: Union[float, int]):\n \"\"\"\n Set the new duration.\n\n .. :param new_value: Duration in nanoseconds\n\n .. note::\n The value will be truncated to the nearest integer value.\n \"\"\"\n # ByteBlower GUI only accepts integer value (nanoseconds)\n new_scheduled_stop = int(new_value)\n for measurements in self._tree.iterfind(\"measurements\"):\n flow_stop_event = next(measurements.iterfind(\"flowStopEvent\"))\n scheduled_stop: Optional[str] = flow_stop_event.get(\n \"scheduledTime\"\n )\n if scheduled_stop is not None:\n flow_stop_event.set(\"scheduledTime\", str(new_scheduled_stop))\n\n\nclass ByteBlowerGUIPort(object):\n \"\"\"A port object.\"\"\"\n\n def __init__(self, port_tree):\n self._tree = port_tree\n\n def _dock_to(\n self, server_address, physical_interface_id, byteblower_interface_id,\n server_type\n ):\n for portConfig in self._tree.iterfind('ByteBlowerGuiPortConfiguration'\n ):\n attributes = portConfig.attrib\n new_server_address = server_address or attributes[\n 'physicalServerAddress']\n\n attributes['physicalInterfaceId'] = str(physical_interface_id)\n attributes['physicalPortId'] = str(byteblower_interface_id)\n attributes['physicalServerAddress'] = new_server_address\n attributes['physicalServerType'] = server_type\n\n def dock_to_interface(self, server_address, interface_name):\n \"\"\"Docks a ByteBlower Port to a ByteBlower Interface\n\n :param server_address: The address of the ByteBlower server to dock the port to\n :type server_address: str\n :param interface_name: Name of the interface to dock the port to. E.g. trunk-1-1\n :type interface_name: str\n \"\"\"\n docking_parameters = _find_docking_parameters(\n server_address, interface_name\n )\n\n if docking_parameters is None:\n # something went wrong\n raise DockFailed(\"Unable to resolve dock parameters\")\n\n physical_id, interface_id = docking_parameters\n self._dock_to(server_address, physical_id, interface_id, 'ByteBlower')\n\n def dock_to_wireless_endpoint(self, meetingpoint_address, device_uuid):\n \"\"\"Docks a ByteBlower Port to a ByteBlower Interface\n\n :param meetingpoint_address: The address of the ByteBlower MeetingPoint to dock the port to\n :type meetingpoint_address: str\n :param device_uuid: UUID of the device to dock to.\n :type device_uuid: str\n \"\"\"\n self._dock_to(meetingpoint_address, device_uuid, '-1', 'MeetingPoint')\n\n def set_mac(self, new_mac):\n if ':' not in new_mac:\n raise FormatError(\n \"Unknown MAC Address Format, provide mac as 00:11:22:33:44:55\"\n )\n\n mac_list = new_mac.split(':')\n\n for l2 in self._tree.iterfind('layer2Configuration'):\n for macaddress in l2.iterfind('MacAddress'):\n for i in range(6):\n new_val = int(mac_list[i], 16)\n if new_val > 127:\n new_val = (256 - new_val) * -1\n\n macaddress[i].text = str(new_val)\n\n @staticmethod\n def _set_address(obj, new_address):\n address_list = new_address.split('.')\n\n for i in range(4):\n new_val = int(address_list[i])\n if new_val > 127:\n new_val = (256 - new_val) * -1\n\n obj[i].text = str(new_val)\n\n def set_ip(self, ip):\n \"\"\" Sets the IPv4 address for a ByteBlower Port\n\n :param ip: The IP address for the ByteBlower Port in the form of \"10.4.8.200\"\n :type ip: str\n \"\"\"\n for l3config in self._tree.iterfind(\"ipv4Configuration\"):\n l3config.attrib['addressConfiguration'] = \"Fixed\"\n\n for ip_obj in l3config.iterfind(\"IpAddress\"):\n self._set_address(ip_obj, ip)\n\n def set_netmask(self, netmask):\n \"\"\" Sets the IPv4 netmask for a ByteBlower Port\n\n :param netmask: The netmask for the ByteBlower Port in the form of \"255.255.255.0\"\n :type netmask: str\n \"\"\"\n for l3config in self._tree.iterfind(\"ipv4Configuration\"):\n l3config.attrib['addressConfiguration'] = \"Fixed\"\n\n for netmask_obj in l3config.iterfind(\"Netmask\"):\n self._set_address(netmask_obj, netmask)\n\n def set_gateway(self, gateway):\n \"\"\" Sets the IPv4 gateway for a ByteBlower Port\n\n :param gateway: The gateway for the ByteBlower Port in the form of \"10.4.8.1\"\n :type gateway: str\n \"\"\"\n for l3config in self._tree.iterfind(\"ipv4Configuration\"):\n l3config.attrib['addressConfiguration'] = \"Fixed\"\n\n for gateway_obj in l3config.iterfind(\"DefaultGateway\"):\n self._set_address(gateway_obj, gateway)\n\n\nclass ByteBlowerProjectFile(object):\n \"\"\"Simple class representing a ByteBlower project file.\"\"\"\n\n def __init__(self, filename):\n self._filename = filename\n self._tree = None\n\n def load(self):\n \"\"\" Reads the file from disk and parses it\n :raises: :class:`.ProjectParseError` when the project could not be parsed\n :raises: :class:`FileNotFoundException` when the project cannot be found\n \"\"\"\n try:\n with open(self._filename, 'r') as f:\n self._tree = etree.parse(f)\n\n if self._tree is None:\n raise ProjectParseError(f\"Can't parse {self._filename!r}\")\n except etree.ParseError as pe:\n raise ProjectParseError(f\"Can't parse {self._filename!r}\") from pe\n\n def save(self):\n self.save_as(self._filename)\n\n def save_as(self, new_filename):\n self._tree.write(new_filename)\n\n def get_port(self, name):\n return ByteBlowerGUIPort(self._find_port(name))\n\n def get_port_docking(self, port_name):\n \"\"\"Gets the current port docking information\n :return: The current docking information (server_address, physical_interface_id, byteblower_interface_id)\n :rtype: tuple\n \"\"\"\n port = self._find_port(port_name)\n\n for portConfig in port.iterfind('ByteBlowerGuiPortConfiguration'):\n attributes = portConfig.attrib\n\n return (\n attributes['physicalServerAddress'],\n attributes['physicalInterfaceId'], attributes['physicalPortId']\n )\n\n return None\n\n def _find_port(self, port_name):\n for port in self._tree.iterfind(\"ByteBlowerGuiPort\"):\n if port.attrib['name'] == port_name:\n return port\n\n raise PortNotFound(\n \"Could not find a port named '{}' in project '{}'\".format(\n port_name, self._filename\n )\n )\n\n def list_port_names(self):\n ports = []\n for port in self._tree.iterfind(\"ByteBlowerGuiPort\"):\n ports.append(port.attrib['name'])\n return ports\n\n def list_flow_names(self):\n flows = []\n for flow in self._tree.iterfind(\"Flow\"):\n flows.append(flow.attrib['name'])\n return flows\n\n def _find_flow_template(self, name):\n for template in self._tree.iterfind(\"FlowTemplate\"):\n if template.attrib['name'] == name:\n return template\n\n raise ElementNotFound(\n f\"Could not find a flow template named '{name}'\"\n f\" in project '{self._filename}'\"\n )\n\n def get_flow_template(self, name):\n return FlowTemplate(self._find_flow_template(name))\n\n def list_flow_template_names(self):\n flow_templates = []\n for flow in self._tree.iterfind(\"FlowTemplate\"):\n flow_templates.append(flow.attrib['name'])\n return flow_templates\n\n def _find_scenario(self, name):\n for scenario in self._tree.iterfind(\"Scenario\"):\n if scenario.attrib['name'] == name:\n return scenario\n\n raise ElementNotFound(\n f\"Could not find a scenario named '{name}'\"\n f\" in project '{self._filename}'\"\n )\n\n def get_scenario(self, name):\n return Scenario(self._find_scenario(name))\n\n def list_scenario_names(self):\n scenarios = []\n for scenario in self._tree.iterfind(\"Scenario\"):\n scenarios.append(scenario.attrib['name'])\n return scenarios\n\n def list_frame_names(self):\n frames = []\n for frame in self._tree.iterfind('Frame'):\n frames.append(frame.attrib['name'])\n return frames\n\n def _find_frame(self, name):\n for frame in self._tree.iterfind('Frame'):\n if frame.get('name') == name:\n return frame\n raise FrameNotFound(\n \"Could not find a port named '{}' in project '{}'\".format(\n name, self._filename\n )\n )\n\n def get_frame(self, name):\n \"\"\"Gets a frame with a specified name\n\n :param name: Name to search.\n :type name: str\n\n :raises: :class:`.FrameNotFound` when a frame cannot be found.\n\n :return: The Frame specified by the name param\n :rtype: :class:`.Frame`\n \"\"\"\n return Frame(self._find_frame(name))\n\n def copy_frame(\n self, name, copies, increment_source_port, increment_destination_port\n ):\n frame = self.get_frame(name)\n\n for i in range(1, copies + 1):\n new_frame = frame.copy(name + \"_\" + str(i))\n if increment_source_port:\n new_frame.udp_src_port += i\n\n if increment_destination_port:\n new_frame.udp_dst_port += i\n","repo_name":"excentis/byteblower_bbp_tools","sub_path":"src/byteblower_bbp_tools/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":17675,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"35943313035","text":"import datetime as dt\nfrom random import choice\nfrom gmail_to_ymail import send_from_gmail_ymail\n\nwith open('quotes.txt') as quotes_file:\n quotes = quotes_file.readlines()\n # special_quote = \"Try quote\"\n special_quote = choice(quotes).encode(\"ascii\", \"ignore\")\n\n\ncurrent_date = dt.datetime.now()\nif current_date.weekday() == 1:\n print(\"Sending email.........\")\n email_msg = f\"Subject: Mighty Quotes\\n\\n{special_quote}\"\n send_from_gmail_ymail(email_msg)\n print(\"Email sent !!!\")\n\n","repo_name":"JoeMenMighty/Python-Projects","sub_path":"Day 32/day-32-start/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39147861613","text":"import pickle\r\nimport numpy as np\r\nimport json\r\nimport zipfile\r\nfrom scipy.sparse import csc_matrix, save_npz, load_npz\r\nfrom statistics import mean\r\nimport copy\r\nimport random\r\n\r\nrandom.seed(0)\r\nimport os\r\nfrom itertools import combinations\r\n\r\n# number without the rest note\r\npitch_number = 655\r\noctave_number = 11\r\nvelocity_number = 10\r\n\r\n\r\ndef get_file_path(root_path, file_list, dir_list):\r\n # get all file names and dir names in this folder\r\n dir_or_files = os.listdir(root_path)\r\n for dir_file in dir_or_files:\r\n # get file or dir name\r\n dir_file_path = os.path.join(root_path, dir_file)\r\n # is a file or a dir\r\n if os.path.isdir(dir_file_path):\r\n dir_list.append(dir_file_path)\r\n # get all paths\r\n get_file_path(dir_file_path, file_list, dir_list)\r\n else:\r\n file_list.append(dir_file_path)\r\n\r\n\r\n# get all file names\r\ndef write_filenames(file_path, names, name_path, use_names):\r\n if use_names:\r\n for name in names:\r\n print(name)\r\n # root path\r\n root_path = file_path + '{}'.format(name)\r\n file_list = []\r\n dir_list = []\r\n file_name = open(name_path + '{}'.format(name), \"wb\")\r\n get_file_path(root_path, file_list, dir_list)\r\n pickle.dump(file_list, file_name)\r\n file_name.close()\r\n else:\r\n file_list = []\r\n dir_list = []\r\n file_name = open(name_path, \"wb\")\r\n get_file_path(file_path, file_list, dir_list)\r\n pickle.dump(file_list, file_name)\r\n file_name.close()\r\n\r\ndef get_end_time(instrument_info):\r\n end_time = [note[3] for instrument in instrument_info for note in instrument[1]]\r\n if end_time == []:\r\n pass\r\n else:\r\n return int(max(end_time))\r\n\r\n\r\ndef get_matrix(instrument, end_time):\r\n note_matrix = np.zeros((128, end_time), dtype=int)\r\n for note in instrument:\r\n start = int(note[2]) - 1\r\n end = int(note[3]) - 1\r\n velocity = int(note[1])\r\n pitch = int(note[0]) - 1\r\n if pitch > 127:\r\n break\r\n # start=velocity+10; end=-velocity-10; if start==end, set as velocity+20\r\n if end != start:\r\n # onset=11, velocity num is from 1 to 10\r\n note_matrix[pitch, start] = velocity + 10\r\n # offset=-11\r\n note_matrix[pitch, end] = -(velocity + 10)\r\n note_matrix[pitch, start + 1:end] = velocity\r\n else:\r\n note_matrix[pitch, start] = velocity + 20\r\n return note_matrix\r\n\r\n\r\ndef get_empty(matrix):\r\n # remain track with more than 50% valid note events\r\n index = np.nonzero(matrix)\r\n total_length = matrix.shape[1]\r\n time_info = len(list(index[1]))\r\n if time_info / total_length > 0.5:\r\n return True\r\n else:\r\n return False\r\n\r\n\r\ndef get_pitch(matrix):\r\n # compute the average pitch of the track\r\n index = np.nonzero(matrix)\r\n pitch_info = list(index[0])\r\n pitch_mean = np.mean(pitch_info)\r\n return pitch_mean\r\n\r\n\r\ndef add_note_to_melody(matrix, note, step):\r\n velocity = matrix[note][step]\r\n # start=3,hold=2,end=1\r\n if velocity < 0:\r\n state = 1\r\n else:\r\n if velocity <= 10:\r\n state = 2\r\n else:\r\n state = 3\r\n # pitch, octave, velocity, state\r\n velocity = (abs(velocity) - 1) % 10 + 1\r\n # distinct chroma 0 (rest note) and octave 0 with element 0 by add 1\r\n return int(note % 12 + 1), int(note // 12 + 1), int(velocity), int(state)\r\n\r\n\r\ndef update_sparse(target_dict, sparse_matrix, name):\r\n \"\"\"Turn `sparse_matrix` into a scipy.sparse.csc_matrix and update\r\n its component arrays to the `target_dict` with key as `name`\r\n suffixed with its component type string.\"\"\"\r\n csc = csc_matrix(sparse_matrix)\r\n target_dict[name + '_csc_data'] = csc.data\r\n target_dict[name + '_csc_indices'] = csc.indices\r\n target_dict[name + '_csc_indptr'] = csc.indptr\r\n target_dict[name + '_csc_shape'] = csc.shape\r\n\r\n\r\ndef get_chord(matrix):\r\n from collections import defaultdict\r\n def list_duplicates(seq):\r\n tally = defaultdict(list)\r\n for i, item in enumerate(seq):\r\n tally[item].append(i)\r\n return ((key, locs) for key, locs in tally.items()\r\n if len(locs) > 1)\r\n\r\n index = np.nonzero(matrix)\r\n pitch_info = list(index[0])\r\n time_info = list(index[1])\r\n ticks = []\r\n chords = []\r\n for item in sorted(list_duplicates(time_info)):\r\n tick = int(item[0])\r\n index = item[1]\r\n chord = []\r\n for i in index:\r\n note = int(pitch_info[i])\r\n # not noteoff\r\n if matrix[note][tick] > 0:\r\n chord.append(note)\r\n if len(chord) >= 2:\r\n ticks.append(tick)\r\n chords.append(chord)\r\n return ticks, chords\r\n\r\n\r\ndef split_matrix(info_dict, meta_dict, matrix, new_idx, program):\r\n # split the track by octave ==> chord is limited in a octave\r\n for i in range(11):\r\n temp_matrix = matrix[0 + 12 * i:12 + 12 * i]\r\n if np.nonzero(temp_matrix)[0] != []:\r\n new_matrix = np.zeros((128, len(matrix[0])), dtype=int)\r\n new_matrix[0 + 12 * i:12 + 12 * i] = temp_matrix\r\n ticks, chords = get_chord(new_matrix)\r\n meta_dict[str(new_idx)] = program\r\n meta_dict['track_ticks_{}'.format(new_idx)] = ticks\r\n meta_dict['track_chords_{}'.format(new_idx)] = chords\r\n update_sparse(info_dict, new_matrix, 'track_{}'.format(new_idx))\r\n new_idx += 1\r\n i = i + 1\r\n temp_matrix = matrix[0 + 12 * i:]\r\n if np.nonzero(temp_matrix)[0] != []:\r\n new_matrix = np.zeros((128, len(matrix[0])), dtype=int)\r\n new_matrix[0 + 12 * i:] = temp_matrix\r\n ticks, chords = get_chord(new_matrix)\r\n meta_dict[str(new_idx)] = program\r\n meta_dict['track_ticks_{}'.format(new_idx)] = ticks\r\n meta_dict['track_chords_{}'.format(new_idx)] = chords\r\n\r\n update_sparse(info_dict, new_matrix, 'track_{}'.format(new_idx))\r\n new_idx += 1\r\n return new_idx\r\n\r\n\r\ndef get_time_signature_changes(meta_data):\r\n time_signature_changes = meta_data[0]\r\n time_info = []\r\n for time in time_signature_changes:\r\n numerator = time.numerator * (32 / time.denominator)\r\n time = time.time\r\n time_info.append([int(numerator), int(time)])\r\n return time_info\r\n\r\n# transform midi file to matrix\r\ndef midi_to_matrix(name):\r\n # pickle file that contains all file names in lakh_normalized dir, generated by write_filenames function\r\n file_list = pickle.load(open('filenames/lakh_normalized/{}'.format(name), 'rb'))\r\n root_path = 'dataset/matrix/{}/'.format(name)\r\n file_id = 0\r\n for file in file_list:\r\n print(file_id)\r\n file_id += 1\r\n data = np.load(file, allow_pickle=True)\r\n meta_dict = {'time_signature_changes': get_time_signature_changes(data['meta_info'])}\r\n instrument_info = data['instrument_info']\r\n info_dict = {}\r\n melody_id = 10000\r\n pitch_candidate = 0\r\n temp_instrument_info = []\r\n end_time = get_end_time(instrument_info)\r\n track_num = 0\r\n for idx, insturment in enumerate(instrument_info):\r\n program = int(insturment[0])\r\n note_matrix = get_matrix(insturment[1], end_time=end_time)\r\n if get_empty(note_matrix):\r\n # melody track is the one with the highest average pitch\r\n pitch = get_pitch(note_matrix)\r\n if pitch_candidate < pitch:\r\n pitch_candidate = pitch\r\n melody_id = track_num\r\n temp_instrument_info.append([program, note_matrix])\r\n track_num += 1\r\n else:\r\n continue\r\n if melody_id == 10000:\r\n # a song have and only have one melody track\r\n continue\r\n else:\r\n new_idx = 0\r\n for idx, instrument in enumerate(temp_instrument_info):\r\n program = int(instrument[0])\r\n matrix = instrument[1]\r\n # generate melody info\r\n # if there are multiple notes at the same time\r\n # reserve the note with \"on\" state and the highest pitch\r\n # otherwise, reserve the highest pitch\r\n if idx == melody_id:\r\n melody_info = np.zeros((4, len(matrix[0])), dtype=int)\r\n time_len = matrix.shape[1]\r\n for step in range(time_len):\r\n note_info = list(np.nonzero(matrix[:, step])[0])\r\n if note_info != []:\r\n note_candidate = []\r\n for note in note_info:\r\n if matrix[note][step] > 10:\r\n note_candidate.append(note)\r\n if note_candidate != []:\r\n melody_note = max(note_candidate)\r\n else:\r\n melody_note = max(note_info)\r\n # add melody_note into the final melody track\r\n melody_info[0][step], melody_info[1][step], melody_info[2][step], melody_info[3][\r\n step] = add_note_to_melody(matrix, melody_note, step)\r\n # remove the melody_note from the original track\r\n matrix[melody_note][step] = 0\r\n update_sparse(info_dict, melody_info, 'melody_info')\r\n # reconstruct the remaining notes as a new accompaniment track\r\n new_idx = split_matrix(info_dict, meta_dict, matrix, new_idx, program)\r\n else:\r\n new_idx = split_matrix(info_dict, meta_dict, matrix, new_idx, program)\r\n filename = root_path + file.split('/')[-1]\r\n\r\n np.savez_compressed(filename, **info_dict)\r\n compression = zipfile.ZIP_DEFLATED\r\n with zipfile.ZipFile(filename, 'a') as zip_file:\r\n zip_file.writestr('meta.json', json.dumps(meta_dict), compression)\r\n pass\r\n\r\n\r\n\r\n","repo_name":"mengshor/PiRhDy","sub_path":"2-midi2matrix/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":10291,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"48"} +{"seq_id":"26364400727","text":"import tensorflow as tf\nimport numpy as np\n\n\nclass SentiFunction:\n def __init__(self, nn_config):\n self.nn_config = nn_config\n\n # sentiment expression: for sentiment towards specific attribute\n # the sentiment is choosen by attribute\n def sentiment_matrix(self, graph):\n W = tf.get_variable(name='senti_mat', initializer=tf.random_uniform(shape=(\n self.nn_config['normal_senti_prototype_num'] * 3 + self.nn_config['attribute_senti_prototype_num'] *\n self.nn_config['attributes_num'],\n self.nn_config['sentiment_dim']), dtype='float32'))\n graph.add_to_collection('senti_reg', tf.contrib.layers.l2_regularizer(self.nn_config['reg_rate'])(W))\n graph.add_to_collection('W', W)\n return W\n\n def sentiment_attention(self, H, W, m, graph):\n \"\"\"\n :param h: shape = (batch size, number of words, lstm cell size)\n :param W: shape = (3*attribute numbers + 3,number of sentiment prototypes, lstm cell size). 3*attribute numbers is\n 3 sentiment for each attributes; 3 is sentiment for non-attribute entity, it only has normal sentiment, not attribute\n specific sentiment.\n :param m: mask to eliminate influence of 0; (3*attributes number+3, number of sentiment expression prototypes)\n :return: shape = (batch size,number of words, 3+3*attributes number, number of sentiment prototypes).\n \"\"\"\n # H.shape = (batch size, words num, 3+3*attributes number, word dim)\n H = tf.tile(tf.expand_dims(H, axis=2), multiples=[1, 1, 3 * self.nn_config['attributes_num'] + 3, 1])\n # H.shape = (batch size, words num, 3+3*attributes number, sentiment prototypes, word dim)\n H = tf.tile(tf.expand_dims(H, axis=3), multiples=[1, 1, 1, self.nn_config['normal_senti_prototype_num'] * 3 +\n self.nn_config['attribute_senti_prototype_num'] *\n self.nn_config['attributes_num'],\n 1])\n # temp.shape = (batch size, words num, 3+3*attributes number, sentiment prototypes num)\n temp = tf.multiply(m, tf.exp(tf.reduce_sum(tf.multiply(H, W), axis=4)))\n\n # denominator.shape = (batch size, words num, 3+3*attributes number, 1)\n denominator = tf.reduce_sum(temp, axis=3, keepdims=True)\n\n denominator = tf.tile(denominator, multiples=[1, 1, 1,\n self.nn_config['normal_senti_prototype_num'] * 3 +\n self.nn_config['attribute_senti_prototype_num'] * self.nn_config[\n 'attributes_num']])\n attention = tf.truediv(temp, denominator)\n graph.add_to_collection('senti_attention', attention)\n return attention\n\n def attended_sentiment(self, W, attention, graph):\n \"\"\"\n :param W: all (yi,ai); shape = (3*number of attribute +3, sentiment prototypes, sentiment dim)\n :param attention: shape = (batch size,number of words, 3+3*attributes number, number of sentiment prototypes)\n :param graph: \n :return: (batch size,number of words, 3+3*attributes number, sentiment dim)\n \"\"\"\n # attention.shape = (batch size, number of words, 3+3*attributes number, number of sentiment prototypes, sentiment dim)\n attention = tf.tile(tf.expand_dims(attention, axis=4), multiples=[1, 1, 1, 1, self.nn_config['sentiment_dim']])\n attended_W = tf.reduce_sum(tf.multiply(attention, W), axis=3)\n graph.add_to_collection('attended_W', attended_W)\n return attended_W\n\n def item1(self, W, H, graph):\n \"\"\"\n\n :param W: shape = (batch size,number of words, 3+3*attributes number, sentiment dim)\n :param H: shape = (batch size, number of words, word dim)\n :return: shape = (batch size,number of words, 3+3*attributes number)\n \"\"\"\n # H.shape = (batch size,number of words, 3+3*attributes number, sentiment dim)\n H = tf.tile(tf.expand_dims(H, axis=2), multiples=[1, 1, 3 * self.nn_config['attributes_num'] + 3, 1])\n item1_score = tf.reduce_sum(tf.multiply(W, H), axis=3)\n graph.add_to_collection('item1_score', item1_score)\n return item1_score\n\n # association between attribute and sentiment: towards specific attribute\n def attribute_distribution(self, A, H, graph):\n \"\"\"\n distribution of all attributes in this sentence\n :param A: A.shape = (attributes number +1 , attributes dim(=lstm cell size)) or \n A.shape = (batch size, number of words, number of attributes + 1, attribute dim(=lstm cell dim))\n :param H: batch size, words num, word dim\n :param graph: \n :return: shape = (batch size, number of attributes+1, wrods number)\n \"\"\"\n if not self.nn_config['is_mat']:\n H = tf.reshape(H, shape=(-1, self.nn_config['lstm_cell_size']))\n # A.shape=(number of attributes+1, attribute dim(=lstm cell size))\n # A_dist = (batch size,number of attributes+1,number of words)\n A_dist = tf.nn.softmax(tf.transpose(tf.reshape(tf.matmul(A, H, transpose_b=True),\n shape=(self.nn_config['attributes_num'] + 1, -1,\n self.nn_config['words_num'])), [1, 0, 2]))\n else:\n # A.shape = (batch size, number of words, number of attributes+1, attribute dim(=lstm cell dim))\n # H.shape = (batch size, number of words, number of attributes+1, word dim)\n\n H = tf.tile(tf.expand_dims(H, axis=2), multiples=[1, 1, self.nn_config['attributes_num'] + 1, 1])\n # A_dist.shape = (batch size, attributes number, words number)\n A_dist = tf.nn.softmax(tf.transpose(tf.reduce_sum(tf.multiply(A, H), axis=3), [0, 2, 1]))\n\n graph.add_to_collection('attribute_distribution', A_dist)\n return A_dist\n\n def relative_pos_matrix(self, graph):\n V = tf.get_variable(name='relative_pos',\n initializer=tf.random_uniform(shape=(self.nn_config['rps_num'], self.nn_config['rp_dim']),\n dtype='float32'))\n graph.add_to_collection('senti_reg', tf.contrib.layers.l2_regularizer(self.nn_config['reg_rate'])(V))\n graph.add_to_collection('V', V)\n return V\n\n def relative_pos_ids(self, graph):\n \"\"\"\n :param graph: \n :return: shape = (number of words, number of words)\n \"\"\"\n id4sentence = []\n for i in range(self.nn_config['words_num']):\n id4word_i = []\n for j in range(self.nn_config['words_num']):\n if abs(i - j) < self.nn_config['rps_num']:\n id4word_i.append(abs(i - j))\n else:\n id4word_i.append(self.nn_config['rps_num'] - 1)\n id4sentence.append(id4word_i)\n rp_ids = tf.constant(id4sentence, dtype='int32')\n graph.add_to_collection('relative_pos_ids', rp_ids)\n return rp_ids\n\n def rd_Vi(self, A_dist, V, rp_ids, graph):\n \"\"\"\n :param A_dist: shape = (batch size, number of attributes+1, number of words)\n :param V: shape = (number of relative position, relative position dim)\n :param rp_ids: shape = (number of words, number of words)\n :param graph:\n :return: realtive position vector of each attribute at each position.\n shape = (batch size, number of attributes+1, number of words, relative position dim)\n \"\"\"\n # rp_mat.shape = (number of words, number of words, rp_dim)\n rp_mat=tf.nn.embedding_lookup(V,rp_ids)\n # A_dist.shape = (batch size, number of attributes+1, number of words,relative position dim)\n A_dist = tf.tile(tf.expand_dims(A_dist,axis=3),multiples=[1,1,1,self.nn_config['rp_dim']])\n # A_dist.shape = (batch size, number of attributes+1, number of words, number of words,relative position dim)\n A_dist = tf.tile(tf.expand_dims(A_dist,axis=2),multiples=[1,1,self.nn_config['words_num'],1,1])\n # A_Vi.shape = (batch size, number of attributes+1, number of words, relative position dim)\n A_Vi = tf.reduce_sum(tf.multiply(A_dist,rp_mat),axis=3)\n graph.add_to_collection('A_Vi', A_Vi)\n return A_Vi\n\n def dp_Vi(self, A_dist, PD, graph):\n \"\"\"\n\n :param A_dist: (batch size, number of attributes+1, wrods number)\n :param PD: (batch size, words num, words num, lstm cell size)\n :return: \n \"\"\"\n # PD.shape = (batch size, attributes num +1, words num, words num, lstm cell size)\n PD = tf.tile(tf.expand_dims(PD, axis=1), multiples=[1, self.nn_config['attributes_num'] + 1, 1, 1, 1])\n\n # A_dist.shape = (batch size, attributes num+1, words num, words num)\n A_dist = tf.tile(tf.expand_dims(A_dist, axis=2), multiples=[1, 1, self.nn_config['words_num'], 1])\n # A_dist.shape = (batch size, attributes num+1, words num, words num, lstm cell size)\n A_dist = tf.tile(tf.expand_dims(A_dist, axis=4), multiples=[1, 1, 1, 1, self.nn_config['lstm_cell_size']])\n # A_Vi.shape = (batch size, attributes num+1, words num, lstm cell size)\n A_Vi = tf.reduce_sum(tf.multiply(PD, A_dist), axis=3)\n graph.add_to_collection('A_Vi', A_Vi)\n return A_Vi\n\n def beta(self, graph):\n \"\"\"\n\n :param graph: \n :return: beta weight, shape=(rp_dim)\n \"\"\"\n b = tf.get_variable(name='beta',\n initializer=tf.random_uniform(shape=(self.nn_config['rp_dim'],), dtype='float32'))\n graph.add_to_collection('senti_reg', tf.contrib.layers.l2_regularizer(self.nn_config['reg_rate'])(b))\n graph.add_to_collection('beta', b)\n return b\n\n # sentiment score\n def score(self, item1, item2, mask, graph):\n \"\"\"\n :param item1: shape = (batch size,number of words, 3+3*attributes number)\n :param item2: shape=(batch size, number of attributes+1, number of words)\n :param graph: \n :return: (batch size, 3+3*attributes number, number of words) this is all combinations of yi and ai\n \"\"\"\n # item1.shape = (batch size, 3+3*attributes number, number of words)\n item1 = tf.transpose(item1, [0, 2, 1])\n # item2.shape = (batch size, 3+3*attributes number, number of words)\n item2 = tf.reshape(tf.tile(tf.expand_dims(item2, axis=2), [1, 1, 3, 1]),\n shape=(-1, 3 * self.nn_config['attributes_num'] + 3, self.nn_config['words_num']))\n # score.shape = (batch size, 3+3*attributes number, number of words)\n score = tf.add(item1, item2)\n # mask.shape = (batch size, attributes number, words num)\n mask = tf.tile(tf.expand_dims(mask, axis=1), multiples=[1, 3 + 3 * self.nn_config['attributes_num'], 1])\n # eliminate influence of #PAD#\n score = tf.add(score, mask)\n\n return score\n\n def max_false_senti_score(self, Y_senti, score, graph):\n \"\"\"\n\n :param Y_senti: shape=(batch size, attributes numbers+1, 3)\n :param score: shape=(batch size, 3*attributes numbers+3)\n :param graph: \n :return: shape = (batch size, number of attributes+1,3)\n \"\"\"\n # score.shape = (batch size, attributes numbers+1, 3)\n score = tf.reshape(score, shape=(-1, self.nn_config['attributes_num'] + 1, 3))\n # if value is 1 then it is true, otherwise flase\n condition = tf.equal(tf.ones_like(Y_senti, dtype='float32'), Y_senti)\n # mask.shape = (batch size, attributes numbers+1, 3)\n mask = tf.where(condition,\n tf.ones_like(score, dtype='float32') * tf.constant(-np.inf, dtype='float32'),\n tf.zeros_like(score, dtype='float32'))\n # shape = (batch size, number of attributes+1,1)\n max_fscore = tf.reduce_max(tf.add(score, mask), axis=2, keepdims=True)\n\n # consider when attribute contains all sentiment in a sentence.\n max_fscore = tf.where(tf.is_inf(max_fscore), tf.zeros_like(max_fscore, dtype='float32'), max_fscore)\n # max_fscore.shape = (batch size, number of attributes+1, 3)\n max_fscore = tf.tile(max_fscore, multiples=[1, 1, 3])\n graph.add_to_collection('max_false_senti_score', max_fscore)\n return max_fscore\n\n def loss(self, Y_senti, score, max_false_score, graph):\n \"\"\"\n :param Y_senti: shape=(batch size,attributes numbers+1, 3) the second part is one-hot to represent which sentiment it is.\n :param score: shape=(batch size, 3*number of attributes+3)\n :param max_false_score: shape = (batch size, number of attributes +1, 3)\n :param graph:\n :return: loss for a sentence for all true attributes and mask all false attributes.\n \"\"\"\n # score.shape = (batch size, attribute number +1, 3)\n score = tf.reshape(score, shape=(-1, self.nn_config['attributes_num'] + 1, 3))\n theta = tf.constant(self.nn_config['sentiment_loss_theta'], dtype='float32')\n # senti_loss.shape = (batch size, attribute number +1, 3)\n senti_loss = tf.add(tf.subtract(theta, score), max_false_score)\n # masked_loss.shape = (batch size, attribute number +1, 3)\n masked_loss = tf.multiply(Y_senti, senti_loss)\n #\n zeros_loss = tf.zeros_like(masked_loss, dtype='float32')\n # masked_loss.shape = (batch size, attribute number +1, 3,1)\n zeros_loss = tf.expand_dims(zeros_loss, axis=3)\n masked_loss = tf.expand_dims(masked_loss, axis=3)\n loss = tf.reduce_max(tf.concat([zeros_loss, masked_loss], axis=3), axis=3)\n # TODO: eliminate the influence of batch size.\n batch_loss = tf.reduce_mean(tf.reduce_sum(tf.reduce_sum(loss, axis=2), axis=1)) + tf.multiply(\n 1 / self.nn_config['batch_size'], tf.reduce_sum(graph.get_collection('senti_reg')))\n graph.add_to_collection('senti_loss', batch_loss)\n return batch_loss\n\n def prediction(self, score, Y_atr, graph):\n \"\"\"\n :param score: shape = (batch size, attributes numbers+1,3)\n :param Y_atr: shape = (batch size, attributes numbers+1)\n :param graph: \n :return: \n \"\"\"\n # score.shape = (batch size, attributes numbers+1,3)\n score = tf.nn.softmax(logits=score,axis=-1)\n # pred.shape =(batch size, attributes number +1 , 3)\n pred = tf.where(tf.equal(tf.reduce_max(score,axis=2,keep_dims=True),score),tf.ones_like(score),tf.zeros_like(score))\n # use Y_atr to mask non-activated attributes' sentiment\n Y_atr = tf.tile(tf.expand_dims(Y_atr,axis=2),multiples=[1,1,3])\n pred = tf.multiply(Y_atr, pred)\n\n graph.add_to_collection('prediction', pred)\n return pred\n\n def softmax_loss(self,labels, logits,graph):\n \"\"\"\n \n :param labels: (batch size, number of attributes+1,3)\n :param logits: (batch_size, number of attributes + 1, 3)\n :return: \n \"\"\"\n\n loss = tf.reduce_mean(tf.add(tf.reduce_sum(tf.nn.softmax_cross_entropy_with_logits_v2(labels=labels,logits=logits,dim=-1),axis=1),\n tf.reduce_sum(graph.get_collection('senti_reg'))))\n graph.add_to_collection('senti_loss', loss)\n return loss\n\n def accuracy(self, Y_senti, pred, graph):\n \"\"\"\n\n :param Y_senti: shape = (batch size, attributes number +1,3)\n :param pred: shape = ()\n :param graph: \n :return: \n \"\"\"\n condition = tf.equal(Y_senti, pred)\n cmp = tf.reduce_sum(\n tf.where(condition, tf.zeros_like(Y_senti, dtype='float32'), tf.ones_like(Y_senti, dtype='float32')),\n axis=2)\n condition = tf.equal(cmp, tf.zeros_like(cmp))\n accuracy = tf.reduce_mean(\n tf.where(condition, tf.ones_like(cmp, dtype='float32'), tf.zeros_like(cmp, dtype='float32')))\n graph.add_to_collection('accuracy', accuracy)\n return accuracy\n\n # ===============================================\n # ============= attribute function ==============\n # ===============================================\n def attribute_vec(self, graph):\n \"\"\"\n\n :param graph: \n :return: shape = (number of attributes+1, attributes dim)\n \"\"\"\n # A is matrix of attribute vector\n A = tf.get_variable(name='A_vec', initializer=tf.random_uniform(\n shape=(self.nn_config['attributes_num'], self.nn_config['attribute_dim']),\n dtype='float32'))\n graph.add_to_collection('senti_reg', tf.contrib.layers.l2_regularizer(self.nn_config['reg_rate'])(A))\n graph.add_to_collection('A_vec', A)\n o = tf.get_variable(name='other_vec', initializer=tf.random_uniform(shape=(self.nn_config['attribute_dim'],),\n dtype='float32'))\n graph.add_to_collection('senti_reg', tf.contrib.layers.l2_regularizer(self.nn_config['reg_rate'])(o))\n graph.add_to_collection('o_vec', o)\n A = tf.concat([A, tf.expand_dims(o, axis=0)], axis=0)\n return A\n\n def attribute_mat(self, graph):\n \"\"\"\n\n :param graph: \n :return: shape = (attributes number+1, attribute mat size, attribute dim)\n \"\"\"\n A_mat = tf.get_variable(name='A_mat', initializer=tf.random_uniform(shape=(self.nn_config['attributes_num'],\n self.nn_config['attribute_mat_size'],\n self.nn_config['attribute_dim']),\n dtype='float32'))\n graph.add_to_collection('senti_reg', tf.contrib.layers.l2_regularizer(self.nn_config['reg_rate'])(A_mat))\n graph.add_to_collection('A_mat', A_mat)\n o_mat = tf.get_variable(name='other_vec',\n initializer=tf.random_uniform(shape=(self.nn_config['attribute_mat_size'],\n self.nn_config['attribute_dim']),\n dtype='float32'))\n graph.add_to_collection('senti_reg', tf.contrib.layers.l2_regularizer(self.nn_config['reg_rate'])(o_mat))\n graph.add_to_collection('o_mat', o_mat)\n\n A_mat = tf.concat([A_mat, tf.expand_dims(o_mat, axis=0)], axis=0)\n\n return A_mat\n\n def words_attribute_mat2vec(self, H, A_mat, graph):\n \"\"\"\n convert attribtes matrix to attributes vector for each words in a sentence. A_mat include non-attribute mention matrix.\n :param H: shape = (batch size, number of words, word dim)\n :param A_mat: (number of atr, atr mat size, atr dim)\n :param graph: \n :return: shape = (batch size, number of words, number of attributes + 1, attribute dim(=lstm cell dim))\n \"\"\"\n # H.shape = (batch size, words number, attribute number+1, word dim)\n H = tf.tile(tf.expand_dims(H, axis=2), multiples=[1, 1, self.nn_config['attributes_num'] + 1, 1])\n # H.shape = (batch size, words number, attribute number+1, attribute mat size, word dim)\n H = tf.tile(tf.expand_dims(H, axis=3), multiples=[1, 1, 1, self.nn_config['attribute_mat_size'], 1])\n # attention.shape = (batch size, words number, attribute number, attribute mat size)\n attention = tf.nn.softmax(tf.reduce_sum(tf.multiply(H, A_mat), axis=4))\n # attention.shape = (batch size, words number, attribute number, attribute mat size, attribute dim)\n attention = tf.tile(tf.expand_dims(attention, axis=4), multiples=[1, 1, 1, 1, self.nn_config['attribute_dim']])\n words_A = tf.reduce_sum(tf.multiply(attention, A_mat), axis=3)\n graph.add_to_collection('words_attributes', words_A)\n return words_A\n\n def sentences_input(self, graph):\n X = tf.placeholder(\n shape=(None, self.nn_config['words_num']),\n dtype='int32')\n graph.add_to_collection('X', X)\n return X\n\n def attribute_labels_input(self, graph):\n \"\"\"\n\n :param graph: \n :return: shape = (batch size, attributes number+1)\n \"\"\"\n Y_att = tf.placeholder(shape=(None, self.nn_config['attributes_num']),\n dtype='float32')\n graph.add_to_collection('Y_att', Y_att)\n # TODO: add non-attribute\n batch_size = tf.shape(Y_att)[0]\n non_attr = tf.zeros((batch_size,1),dtype='float32')\n condition = tf.equal(tf.reduce_sum(Y_att,axis=1,keepdims=True),non_attr)\n non_attr = tf.where(condition,tf.ones_like(non_attr),non_attr)\n Y_att = tf.concat([Y_att,non_attr],axis=1)\n return Y_att\n\n def sentiment_labels_input(self, graph):\n \"\"\"\n :param graph: \n :return: shape=[batch_size, number of attributes+1, 3], thus ys=[...,sentence[...,attj_senti[0,1,0],...],...]\n \"\"\"\n Y_senti = tf.placeholder(shape=(None, self.nn_config['attributes_num']+1, 3),\n dtype='float32')\n # TODO: add non-attribute\n graph.add_to_collection('Y_senti', Y_senti)\n return Y_senti\n\n def sequence_length(self, X, graph):\n \"\"\"\n\n :param X: (batch size, max words num)\n :param graph: \n :return: (batch size,)\n \"\"\"\n paddings = tf.ones_like(X, dtype='int32') * self.nn_config['padding_word_index']\n condition = tf.equal(paddings, X)\n seq_len = tf.reduce_sum(tf.where(condition, tf.zeros_like(X, dtype='int32'), tf.ones_like(X, dtype='int32')),\n axis=1, name='seq_len')\n return seq_len\n\n def mask_for_pad_in_score(self, X, graph):\n \"\"\"\n This mask is used in score, to eliminate the influence of pad words when reduce_max. This this mask need to add to the score.\n Since 0*inf = nan\n :param X: the value is word id. shape=(batch size, max words num)\n :param graph: \n :return: \n \"\"\"\n paddings = tf.ones_like(X, dtype='int32') * self.nn_config['padding_word_index']\n condition = tf.equal(paddings, X)\n mask = tf.where(condition, tf.ones_like(X, dtype='float32') * tf.convert_to_tensor(-np.inf),\n tf.zeros_like(X, dtype='float32'))\n return mask\n\n def sentence_lstm(self, X, seq_len, graph):\n \"\"\"\n return a lstm of a sentence\n :param X: shape = (batch size, words number, word dim)\n :param seq_len: shape = (batch size,) show the number of words in a batch\n :param graph: \n :return: \n \"\"\"\n cell = tf.nn.rnn_cell.BasicLSTMCell(self.nn_config['lstm_cell_size'])\n # outputs.shape = (batch size, max_time, cell size)\n outputs, _ = tf.nn.dynamic_rnn(cell=cell, inputs=X, time_major=False, sequence_length=seq_len, dtype='float32')\n graph.add_to_collection('sentence_lstm_outputs', outputs)\n graph.add_to_collection('senti_reg',\n tf.contrib.layers.l2_regularizer(self.nn_config['reg_rate'])(\n graph.get_tensor_by_name('sentence_lstm/rnn/basic_lstm_cell/kernel:0')))\n return outputs\n\n def sentence_bilstm(self, X, seq_len, graph):\n \"\"\"\n return a lstm of a sentence\n :param X: shape = (batch size, words number, word dim)\n :param seq_len: shape = (batch size,) show the number of words in a batch\n :param graph: \n :return: \n \"\"\"\n keep_prob = tf.placeholder(tf.float32)\n tf.add_to_collection('keep_prob_lstm',keep_prob)\n fw_cell = tf.contrib.rnn.DropoutWrapper(tf.nn.rnn_cell.BasicLSTMCell(int(self.nn_config['lstm_cell_size']/2)),input_keep_prob=keep_prob , output_keep_prob=keep_prob,state_keep_prob=keep_prob)\n bw_cell = tf.contrib.rnn.DropoutWrapper(tf.nn.rnn_cell.BasicLSTMCell(int(self.nn_config['lstm_cell_size']/2)),input_keep_prob=keep_prob , output_keep_prob=keep_prob,state_keep_prob=keep_prob)\n # outputs.shape = [(batch size, max time step, lstm cell size/2),(batch size, max time step, lstm cell size/2)]\n outputs, _ = tf.nn.bidirectional_dynamic_rnn(cell_fw=fw_cell,cell_bw=bw_cell,inputs=X,sequence_length=seq_len,dtype='float32')\n # outputs.shape = (batch size, max time step, lstm cell size)\n outputs = tf.concat(outputs, axis=2, name='bilstm_outputs')\n graph.add_to_collection('senti_sentence_bilstm_outputs', outputs)\n graph.add_to_collection('senti_reg',\n tf.contrib.layers.l2_regularizer(self.nn_config['reg_rate'])(\n graph.get_tensor_by_name('senti_sentence_bilstm/bidirectional_rnn/fw/basic_lstm_cell/kernel:0')))\n graph.add_to_collection('senti_reg',\n tf.contrib.layers.l2_regularizer(self.nn_config['reg_rate'])(\n graph.get_tensor_by_name('senti_sentence_bilstm/bidirectional_rnn/bw/basic_lstm_cell/kernel:0')))\n return outputs\n\n def path_dependency_table_input(self, graph):\n \"\"\"\n :param graph: \n :return: \n \"\"\"\n PD = tf.placeholder(shape=(None,\n self.nn_config['words_num'],\n self.nn_config['words_num'],\n self.nn_config['max_path_length']),\n dtype='int32')\n graph.add_to_collection('path_dependency', PD)\n return PD\n\n def path_sequence_length(self, PD):\n \"\"\"\n The PD is words id\n :param PD: matrix of path dependency (batch size, words num, words num, max path length): (sentences number, \n words num, \n tables number for each word, \n length of path)\n :return: (batch size, words num, words num)\n \"\"\"\n PD = tf.reshape(PD, shape=(-1, self.nn_config['max_path_length']))\n paddings = tf.ones_like(PD, dtype='int32') * self.nn_config['padding_word_index']\n condition = tf.equal(paddings, PD)\n seq_len = tf.reduce_sum(tf.where(condition, tf.zeros_like(PD, dtype='int32'), tf.ones_like(PD, dtype='int32')),\n axis=1, name='path_seq_len')\n return seq_len\n\n def path_dependency_bilstm(self, PD, seq_len, graph):\n \"\"\"\n\n :param PD: matrix of path dependency (batch size, words num, words num, max path length, word dim): (sentences number, \n words num, \n tables number for each word, \n words num for each row in a table,\n word dim)\n :param seq_len: (batch size*words num*words num, )\n :param graph: \n :return: \n \"\"\"\n current_batch_size = tf.shape(PD)[0]\n PD = tf.reshape(PD, shape=(-1, self.nn_config['max_path_length'], self.nn_config['word_dim']))\n fw_cell = tf.nn.rnn_cell.BasicLSTMCell(int(self.nn_config['lstm_cell_size']/2))\n bw_cell = tf.nn.rnn_cell.BasicLSTMCell(int(self.nn_config['lstm_cell_size']/2))\n # outputs.shape = [(-1,max words num, lstm cell size/2),(-1,max words num, lstm cell size/2)]\n outputs, _ = tf.nn.bidirectional_dynamic_rnn(cell_fw=fw_cell,\n cell_bw=bw_cell,\n inputs=PD,\n sequence_length=seq_len,\n time_major=False,dtype='float32')\n # outputs.shape = (batch size*words num*words num, max path length, word dim)\n outputs = tf.concat(outputs, axis=2, name='bilstm_outputs')\n # instance_index stands for the index of dependency path\n instance_index = tf.cast(tf.expand_dims(tf.range(start=0, limit=current_batch_size * self.nn_config[\n 'words_num'] * self.nn_config['words_num']),\n axis=1), dtype='int32')\n # instance_length_index stands for the length of the instance\n # for padded sentence, the seq length is 0; then the index will be -1 and still the [0,...,0] will be chosen.\n instance_length_index = tf.cast(tf.expand_dims(seq_len - 1, axis=1), dtype='int32')\n slice_index = tf.concat([instance_index, instance_length_index], axis=1)\n outputs = tf.gather_nd(outputs, slice_index)\n print(outputs)\n outputs = tf.reshape(outputs, shape=(-1,\n self.nn_config['words_num'],\n self.nn_config['words_num'],\n self.nn_config['lstm_cell_size']))\n graph.add_to_collection('senti_reg',\n tf.contrib.layers.l2_regularizer(self.nn_config['reg_rate'])(\n graph.get_tensor_by_name(\n 'dependency_path_bilstm/bidirectional_rnn/fw/basic_lstm_cell/kernel:0')))\n graph.add_to_collection('senti_reg',\n tf.contrib.layers.l2_regularizer(self.nn_config['reg_rate'])(\n graph.get_tensor_by_name(\n 'dependency_path_bilstm/bidirectional_rnn/bw/basic_lstm_cell/kernel:0')))\n return outputs\n\n def lstm_mask(self, X):\n # need to pad the #PAD# words to zeros, otherwise, they will be junks.\n X = tf.cast(X, dtype='float32')\n ones = tf.ones_like(X, dtype='float32') * self.nn_config['padding_word_index']\n is_one = tf.equal(X, ones)\n mask = tf.where(is_one, tf.zeros_like(X, dtype='float32'), tf.ones_like(X, dtype='float32'))\n mask = tf.tile(tf.expand_dims(mask, axis=2), multiples=[1, 1, self.nn_config['lstm_cell_size']])\n return mask\n\n def senti_extors_mat(self, graph):\n \"\"\"\n input a matrix to extract sentiment expression for attributes in sentences. The last one extract sentiment expression for non-attribute.\n The non-attribute only has one sentiment: NEU\n shape of the extractors matrix: [3*attribute numbers+1, \n normal sentiment prototype numbers*3 + attributes sentiment prototypes number*attribute number,\n sentiment epression dim(sentiment dim)]\n :param graph: \n :return: \n \"\"\"\n extors = self.sentiment_extract_mat()\n extors = tf.constant(extors, dtype='float32')\n graph.add_to_collection('senti_extractor', extors)\n return extors\n\n # @ normal_function\n def extor_expandNtile(self, extor, proto_num):\n \"\"\"\n\n :param exter: it is extractor \n :return: \n \"\"\"\n extor = np.expand_dims(extor, axis=1)\n extor = np.tile(extor, reps=[1, self.nn_config[proto_num]])\n extor = np.expand_dims(extor, axis=2)\n extor = np.tile(extor, reps=[1, 1, self.nn_config['sentiment_dim']])\n extor = np.reshape(extor, (-1, self.nn_config['sentiment_dim']))\n return extor\n\n # @ normal_function\n def sentiment_extract_mat(self):\n \"\"\"\n This function return a matrix to extract expression prototype for all (yi,ai) combinations.\n :return: [ sentiment extractor for one sentence[...,[1,...],...,[0,...],...] ,...] \n \"\"\"\n # label = np.ones(shape=(self.nn_config['attributes_num'],), dtype='float32')\n extors = []\n for i in range(self.nn_config['attributes_num']):\n # attribute sentiment prototypes\n att_senti_ext = np.zeros(shape=(self.nn_config['attributes_num'],), dtype='float32')\n att_senti_ext[i] = 1\n att_senti_ext = self.extor_expandNtile(att_senti_ext, proto_num='attribute_senti_prototype_num')\n for j in range(3):\n # normal sentiment prototypes\n normal_senti_ext = np.zeros(shape=(3,), dtype='float32')\n normal_senti_ext[j] = 1\n normal_senti_ext = self.extor_expandNtile(normal_senti_ext, proto_num='normal_senti_prototype_num')\n extors.append(np.concatenate([normal_senti_ext, att_senti_ext], axis=0))\n for i in range(3):\n # non-attribute sentiment prototypes\n o_att_senti_ext = np.zeros(shape=(self.nn_config['attributes_num']), dtype='float32')\n o_att_senti_ext = self.extor_expandNtile(o_att_senti_ext, 'attribute_senti_prototype_num')\n # non-attribute normal sentiment prototypes\n o_normal_senti_ext = np.zeros(shape=(3,), dtype='float32')\n o_normal_senti_ext[i] = 1\n o_normal_senti_ext = self.extor_expandNtile(o_normal_senti_ext, proto_num='normal_senti_prototype_num')\n extors.append(np.concatenate([o_normal_senti_ext, o_att_senti_ext], axis=0))\n return np.array(extors)\n\n def extors_mask(self, extors, graph):\n \"\"\"\n when calculate p(w|h), need to eliminate the the influence of false sentiment.\n :param extor: shape = (3*attribute numbers +3, \n self.nn_config['normal_senti_prototype_num'] * 3 +\n self.nn_config['attribute_senti_prototype_num'] * self.nn_config['attributes_num'],\n sentiment dim)\n :param graph: \n :return: (3*attributes number+3, number of sentiment expression prototypes)\n \"\"\"\n extors = tf.reduce_sum(extors, axis=2)\n condition = tf.equal(extors, np.zeros_like(extors, dtype='float32'))\n mask = tf.where(condition, tf.zeros_like(extors, dtype='float32'), tf.ones_like(extors, dtype='float32'))\n graph.add_to_collection('extors_mask', mask)\n return mask\n\n def optimizer(self, loss, graph):\n # opt = tf.train.AdamOptimizer(self.nn_config['lr']).minimize(loss)\n opt = tf.train.AdamOptimizer(self.nn_config['senti_lr'])\n gradients, variables = zip(*opt.compute_gradients(loss))\n gradients, _ = tf.clip_by_global_norm(gradients, 5.0)\n opt = opt.apply_gradients(zip(gradients, variables))\n graph.add_to_collection('senti_opt', opt)\n return opt\n\n def wordEbmedding_table_input(self,graph):\n table = tf.placeholder(shape=(self.nn_config['lookup_table_words_num'], self.nn_config['word_dim']),\n dtype='float32')\n graph.add_to_collection('table', table)\n rel_word_embeddings = tf.random_uniform(shape=(self.nn_config['rel_words_num'], self.nn_config['rel_word_dim']),\n dtype='float32')\n table = tf.concat([table, rel_word_embeddings], axis=0)\n table = tf.Variable(table, name='table')\n return table\n\n def lookup_table(self, X, mask, table, graph):\n \"\"\"\n :param X: shape = (batch_size, words numbers)\n :param mask: used to prevent update of #PAD#\n :return: shape = (batch_size, words numbers, word dim)\n \"\"\"\n embeddings = tf.nn.embedding_lookup(table, X, partition_strategy='mod', name='lookup_table')\n embeddings = tf.multiply(embeddings, mask)\n graph.add_to_collection('lookup_table', embeddings)\n return embeddings\n\n def is_word_padding_input(self, ids, graph):\n \"\"\"\n To make the sentence have the same length, we need to pad each sentence with '#PAD#'. To avoid updating of the vector,\n we need a mask to multiply the result of lookup table.\n :param graph: \n :return: \n \"\"\"\n ids = tf.cast(ids, dtype='float32')\n ones = tf.ones_like(ids, dtype='float32') * self.nn_config['padding_word_index']\n is_pad = tf.equal(ids, ones)\n mask = tf.where(is_pad, tf.zeros_like(ids, dtype='float32'), tf.ones_like(ids, dtype='float32'))\n mask = tf.tile(tf.expand_dims(mask, axis=2), multiples=[1, 1, self.nn_config['word_dim']])\n return mask\n\n def is_dpword_padding_input(self,ids,graph):\n \"\"\"\n \n :param ids: (batch size, words number, words number, max dp length)\n :param graph: \n :return: \n \"\"\"\n ids = tf.cast(ids, dtype='float32')\n ones = tf.ones_like(ids, dtype='float32') * self.nn_config['padding_word_index']\n is_pad = tf.equal(ids, ones)\n mask = tf.where(is_pad, tf.zeros_like(ids, dtype='float32'), tf.ones_like(ids, dtype='float32'))\n mask = tf.tile(tf.expand_dims(mask,axis=4),multiples=[1,1,1,1,self.nn_config['rel_word_dim']])\n return mask","repo_name":"zapplea/sentiment_coarse_model","sub_path":"sentiment/functions/sentiment_function/sentiment_function.py","file_name":"sentiment_function.py","file_ext":"py","file_size_in_byte":37504,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"36929529052","text":"import sys\nimport os.path\nfrom optparse import OptionParser\n\n\nfrom twython import Twython\nfrom twython import TwythonError\n\n\nimport dt\nimport config\nimport system\nfrom system import REL_PATH\n\n\n# TODO \n# * build 1/2 decent way to extract all data\n# from twitter query, not hard\n# - needs regular testing to see if api changes\n# * check twitter restrictions\n# on search\n# * implement a twitter search count/min\n# * create extraction object for better extraction\n# * internet connected\n# * not get secrets data into github\n# * testing\n# * work out how to:\n# - report errors, halt/return code?\n# - save to filesystem/api?\n#\n\n\n\n#---\n# authenticate_rw: pass in keys, object & return authenticated\n# for full API access to twitter Twython object or F\n#---\ndef authenticate_rw(consumer_key, consumer_secret, \n access_key, access_secret):\n \"\"\"\n authenticate Twython object with keys & secrets, return obj or F\n \"\"\"\n status = False\n try:\n status = Twython(consumer_key, consumer_secret, \n access_key, access_secret)\n except TwythonError as e:\n status = False\n return status\n\n\n\n#---\n# name: Twy_rw\n# date: 2016JUN07\n# 2013SEP22\n# prog: pr\n# desc: simple wrapper for Twython object\n# RW access to twitter API\n# have to pass in valid Twython obj\n# so remember to initialise\n#---\nclass Twy_rw:\n def __init__(self, twitter_obj):\n \"\"\"init Twy object\"\"\"\n self.max_msg_length = 140\n self.twitter = twitter_obj\n self.message = \"\"\n self.message_id = 0\n #\n # TODO check Twython obj valid\n #\n def valid(self):\n \"\"\"is object valid?\"\"\"\n # TODO this really doesn't do the job\n # seems to return obj even without\n # consumer & access keys\n if self.twitter: return True\n else: return False\n def message_len(self):\n \"\"\"return length of message\"\"\"\n # expect F, use zero\n return len(self.message) if self.message else 0 \n def valid_message_length(self):\n \"\"\"check message length is correct\"\"\"\n if self.message_len() > 0:\n if self.message_len() <= self.max_msg_length:\n return True\n return False\n #---\n # build_data: extract data from twitter api call, decode & build\n # dictionary to save. Failed? try url below:\n # \n #\n # original data structure:\n # line = \"\"\"{\"message\": \"%s\",\"status\": \"%s\",\"date\": %s}\\n\"\"\" % \n # (message, update.id, time.mktime(t.timetuple())) \n #\n #---\n def build_data(self, tid, tmsg, tent):\n \"\"\"build dict of data to save to file\"\"\"\n if tid: # have twitter id?\n if tmsg: # have a twitter message?\n if tent: # have a twitter entitiy? (complicated)\n\n # gracefully fail if we screw up\n try:\n dtags = tent['hashtags']\n durls = tent['urls']\n\n # will this survive json if not str?\n dt_str = \"%s\" % dt.db_datetime_utc()\n\n #---\n # data structure for storage\n py_data = dict(id_str=tid, # tweet id\n message=tmsg, # msg sent\n hashtag=tent['hashtags'],# list of #tags \n urls=tent['urls'], # list of urls\n date_str=dt_str) # epoch in utc\n #---\n except:\n return False\n return py_data\n return False\n def save(self, tid, tmsg, tent, fp_rel=REL_PATH):\n \"\"\"save message to somewhere\"\"\"\n # TODO\n # work out if saved previously and give better response\n \n\n # save to file system/rest api? where?\n # save to filesystem\n # TODO what day is this? localtime?\n fn = dt.fn_current_day(ext='json')\n\n # TODO fix: warning on hard coded file paths\n fp = os.path.join(fp_rel) \n #print(\"fn={}\\nfp={}\".format(fn, fp))\n\n # print(\"twitter.save() fp=<%s>\" % fp)\n if os.path.isdir(fp):\n fpn = os.path.join(fp, fn)\n with open(fpn, 'a') as f:\n # TODO: kill if fails\n #print(\"tid={}\\ntmsg={}\\ttent={}\".format(tid, tmsg, tent))\n line_py = self.build_data(tid, tmsg, tent)\n line_json = system.py2json(line_py)\n\n #print(\"line_py={}\".format(line_py))\n #print(\"line_json={}\".format(line_json))\n\n f.write(line_json)\n f.write('\\n') # stops braces butting up\n return True \n\n return False\n def send(self, message):\n \"\"\"send a message\"\"\"\n self.message = message\n status = False\n # only send if valid length\n if self.valid_message_length():\n # catch Twython errors\n try:\n # twitter api call, (trim_user) only ret what we need\n s = self.twitter.update_status(status=self.message,\n trim_user=True)\n\n t_id = s['id_str'] # twitter id as string\n t_msg = s['text'] # twitter message\n t_ent = s['entities'] # twitter urls, tags & misc\n\n if self.save(t_id, t_msg, t_ent):\n return t_id\n else:\n return False\n except TwythonError as e:\n return False\n return status\n def close(self):\n \"\"\"de-allocate Twython object\"\"\"\n self.twitter = None\n return True\n\n\n#---\n# main cli entry point\n#---\ndef main():\n \"\"\"main cli entry point\"\"\"\n usage = \"usage: %prog [v] -t -d\"\n parser = OptionParser(usage)\n\n # --- options ---\n parser.add_option(\"-m\", \"--message\", dest=\"message\", \\\n help=\"send a message\")\n parser.add_option(\"-q\", \"--search\", dest=\"search\", \\\n help=\"search twitter by query\")\n parser.add_option(\"-v\", \"--version\", dest=\"version\",\n action=\"store_true\",\n help=\"current version\") \n options, args = parser.parse_args()\n\n # --- process ---\n if options.version:\n print(\"%s v%s %s %s\" % ('twed', bigbox.__version__, \n '2016JUN07', '(C) 2013-2016'))\n sys.exit(0)\n elif options.message:\n twitter = authenticate_rw(config.CONSUMER_KEY,\n config.CONSUMER_SECRET,\n config.ACCESS_KEY,\n config.ACCESS_SECRET)\n if twitter:\n t = Twy_rw(twitter)\n print(\"send\")\n status = t.send(options.message)\n print(\"status={}\".format(status))\n if status:\n print(\"message saved & sent (%s)\" % t.message_len())\n print(\"ack\")\n else:\n print(\"cant send message (%s)\" % t.message_len())\n print(\"fail\")\n else:\n print(\"bad Twython object, check\")\n\n t.close()\n elif options.search:\n print(\"query = <%s>\" % options.search)\n twitter = authenticate_r(config.CONSUMER_KEY,\n config.CONSUMER_SECRET,\"\")\n if twitter:\n t = Twy_r(twitter)\n if t: \n result = t.search(options.search, count=5)\n t.save(result)\n print(\"ack\") \n else:\n print(\"fail\")\n else:\n print(\"bad Twython object, check\")\n else:\n parser.print_help()\n # --- end process ---\n\n\n# main cli entry point\nif __name__ == \"__main__\":\n main()\n\n\n# vim: ff=unix:ts=4:sw=4:tw=78:noai:expandtab\n","repo_name":"peterrenshaw/twed","sub_path":"backend/twitter/twitter.py","file_name":"twitter.py","file_ext":"py","file_size_in_byte":8129,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15150985002","text":"#\n#\n#\n# Company -> c4media\n# Link ----> https://c4media.com/career\n#\nfrom A_OO_get_post_soup_update_dec import DEFAULT_HEADERS, update_peviitor_api\nfrom L_00_logo import update_logo\n#\nimport requests\nfrom bs4 import BeautifulSoup\n#\nimport uuid\n\n\ndef collect_data_from_c4media():\n '''\n ... collect data from c4media, with one requests.\n '''\n\n response = requests.get(url='https://c4media.com/career',\n headers=DEFAULT_HEADERS)\n soup = BeautifulSoup(response.text, 'lxml')\n\n soup_data = soup.find_all('div', class_='items-center pb-4 m-auto mt-10 mb-4 border-b border-gray-300 md:flex')\n\n lst_with_data = []\n for sd in soup_data:\n title = sd.find('a').text\n\n if 'Romania' in title:\n link = 'https://c4media.com' + sd.find('a')['href']\n\n lst_with_data.append({\n \"id\": str(uuid.uuid4()),\n \"job_title\": title,\n \"job_link\": link,\n \"company\": \"C4Media\",\n \"country\": \"Romania\",\n \"city\": \"Remote\"\n })\n\n return lst_with_data\n\n\n# update data on peviitor!\n@update_peviitor_api\ndef scrape_and_update_peviitor(company_name, data_list):\n \"\"\"\n Update data on peviitor API!\n \"\"\"\n\n return data_list\n\n\ncompany_name = 'C4Media'\ndata_list = collect_data_from_c4media()\nscrape_and_update_peviitor(company_name, data_list)\n\n# update Logo\nprint(update_logo('C4Media',\n 'https://c4media.com/_nuxt/img/c4media-logo.b690907.svg'))\n","repo_name":"peviitor-ro/Scrapers_start_with_digi","sub_path":"sites/c4media_scraper.py","file_name":"c4media_scraper.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"48"} +{"seq_id":"70500977106","text":"import os\nimport shutil\nimport pandas as pd\nfrom os.path import join as opj\n\n\n# copy data to new directory selectively\ndef copy_mri_data(sub_id,mri_modes=('fmap','dwi')):\n original_dir = r'/mnt/workdir/DCM/BIDS/derivatives/fmriprep_volume_fmapless/fmriprep/'\n output_dir = '/media/dell/6363-802B/T1_preprocessed'\n\n sourMriDir = opj(original_dir, sub_id)\n targMriDir = opj(output_dir, sub_id.replace('-', '-'))\n\n if not os.path.exists(targMriDir):\n os.makedirs(targMriDir)\n\n for mode in mri_modes:\n if mode in ['dwi', 'fmap']:\n source_file_path = opj(sourMriDir, mode)\n target_file_path = opj(targMriDir, mode)\n try:\n shutil.move(source_file_path, target_file_path)\n except:\n print(\"The \", sub_id, \"didn't have\", mode)\n continue\n elif mode == 'anat':\n source_file_path = opj(sourMriDir, mode)\n target_file_path = opj(targMriDir, mode)\n try:\n shutil.copytree(source_file_path, target_file_path)\n except:\n print(\"The \", sub_id, \"didn't have\", mode, \"or the file already copyed.\")\n continue\n elif mode == 'func':\n file_list = os.listdir(opj(sourMriDir, 'func'))\n target_files = []\n for f in file_list:\n if 'rest' in f:\n target_files.append(f)\n # print(f)\n else:\n continue\n for target_file in target_files:\n source_file_path = opj(sourMriDir, mode, target_file)\n target_file_path = opj(targMriDir, mode, target_file)\n if not os.path.exists(opj(targMriDir, mode)):\n os.makedirs(opj(targMriDir, mode))\n shutil.copy(source_file_path, target_file_path)\n\n\nif __name__ == \"__main__\":\n participants_tsv = r'/mnt/workdir/DCM/BIDS/participants.tsv'\n participants_data = pd.read_csv(participants_tsv, sep='\\t')\n\n # copy meg data\n #data = participants_data.query('game1_fmri>=0.5')\n #subject_list = data['Participant_ID'].to_list()\n sub_info = pd.read_csv(r\"/mnt/data/DCM/sub_info.csv\")\n subject_list = sub_info['sub_id'].to_list()\n subject_list = [s.replace('_','-') for s in subject_list]\n\n #subject_list = ['sub-'+str(s).zfill(3) for s in subject_list]\n for sub in subject_list:\n copy_mri_data(sub,mri_modes=['anat'])","repo_name":"YukunQu/DCM","sub_path":"misc/select_copy_data.py","file_name":"select_copy_data.py","file_ext":"py","file_size_in_byte":2475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18303635345","text":"import wiredtiger, wttest\nimport os, shutil\nfrom helper import compare_files\nfrom suite_subprocess import suite_subprocess\nfrom wtdataset import simple_key\nfrom wtscenario import make_scenarios\n\n# test_backup17.py\n# Test cursor backup with a block-based incremental cursor and consolidate.\nclass test_backup17(wttest.WiredTigerTestCase, suite_subprocess):\n dir='backup.dir' # Backup directory name\n gran=\"100K\"\n granval=100*1024\n logmax=\"100K\"\n uri=\"table:test\"\n uri2=\"table:test2\"\n nops=1000\n mult=0\n\n conn_config='cache_size=1G,log=(enabled,file_max=%s)' % logmax\n\n pfx = 'test_backup'\n # Set the key and value big enough that we modify a few blocks.\n bigkey = 'Key' * 100\n bigval = 'Value' * 100\n\n def add_data(self, uri):\n c = self.session.open_cursor(uri)\n for i in range(0, self.nops):\n num = i + (self.mult * self.nops)\n key = self.bigkey + str(num)\n val = self.bigval + str(num)\n c[key] = val\n self.session.checkpoint()\n c.close()\n\n def take_incr_backup(self, id, consolidate):\n # Open the backup data source for incremental backup.\n buf = 'incremental=(src_id=\"ID' + str(id - 1) + '\",this_id=\"ID' + str(id) + '\"'\n if consolidate:\n buf += ',consolidate=true'\n buf += ')'\n bkup_c = self.session.open_cursor('backup:', None, buf)\n lens = []\n saw_multiple = False\n while True:\n ret = bkup_c.next()\n if ret != 0:\n break\n newfile = bkup_c.get_key()\n config = 'incremental=(file=' + newfile + ')'\n self.pr('Open incremental cursor with ' + config)\n dup_cnt = 0\n dupc = self.session.open_cursor(None, bkup_c, config)\n while True:\n ret = dupc.next()\n if ret != 0:\n break\n incrlist = dupc.get_keys()\n offset = incrlist[0]\n size = incrlist[1]\n curtype = incrlist[2]\n # 1 is WT_BACKUP_FILE\n # 2 is WT_BACKUP_RANGE\n self.assertTrue(curtype == 1 or curtype == 2)\n if curtype == 1:\n self.pr('Copy from: ' + newfile + ' (' + str(size) + ') to ' + self.dir)\n shutil.copy(newfile, self.dir)\n else:\n self.pr('Range copy file ' + newfile + ' offset ' + str(offset) + ' len ' + str(size))\n lens.append(size)\n rfp = open(newfile, \"r+b\")\n wfp = open(self.dir + '/' + newfile, \"w+b\")\n rfp.seek(offset, 0)\n wfp.seek(offset, 0)\n if size > self.granval:\n saw_multiple = True\n buf = rfp.read(size)\n wfp.write(buf)\n rfp.close()\n wfp.close()\n dup_cnt += 1\n dupc.close()\n self.assertEqual(ret, wiredtiger.WT_NOTFOUND)\n bkup_c.close()\n if consolidate:\n self.assertTrue(saw_multiple)\n else:\n self.assertFalse(saw_multiple)\n return lens\n\n def test_backup17(self):\n\n self.session.create(self.uri, \"key_format=S,value_format=S\")\n self.session.create(self.uri2, \"key_format=S,value_format=S\")\n self.add_data(self.uri)\n self.add_data(self.uri2)\n self.mult += 1\n\n # Open up the backup cursor. This causes a new log file to be created.\n # That log file is not part of the list returned. This is a full backup\n # primary cursor with incremental configured.\n os.mkdir(self.dir)\n config = 'incremental=(enabled,granularity=%s,this_id=\"ID1\")' % self.gran\n bkup_c = self.session.open_cursor('backup:', None, config)\n\n # Now copy the files returned by the backup cursor.\n all_files = []\n while True:\n ret = bkup_c.next()\n if ret != 0:\n break\n newfile = bkup_c.get_key()\n sz = os.path.getsize(newfile)\n self.pr('Copy from: ' + newfile + ' (' + str(sz) + ') to ' + self.dir)\n shutil.copy(newfile, self.dir)\n all_files.append(newfile)\n self.assertEqual(ret, wiredtiger.WT_NOTFOUND)\n bkup_c.close()\n\n # This is the main part of the test for consolidate. Add data to the first table.\n # Then perform the incremental backup with consolidate off (the default). Then add the\n # same data to the second table. Perform an incremental backup with consolidate on and\n # verify we get fewer, consolidated values.\n self.add_data(self.uri)\n uri1_lens = self.take_incr_backup(2, False)\n\n self.add_data(self.uri2)\n uri2_lens = self.take_incr_backup(3, True)\n\n # Assert that we recorded fewer lengths on the consolidated backup.\n self.assertLess(len(uri2_lens), len(uri1_lens))\n # Assert that we recorded the same total data length for both.\n self.assertEqual(sum(uri2_lens), sum(uri1_lens))\n\nif __name__ == '__main__':\n wttest.run()\n","repo_name":"Shuimo03/mongo","sub_path":"src/third_party/wiredtiger/test/suite/test_backup17.py","file_name":"test_backup17.py","file_ext":"py","file_size_in_byte":5217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"75149107664","text":"#!/usr/bin/env python3\n\nimport json\nimport logging\nimport argparse\nfrom pathlib import Path\nfrom scenecut_extractor.__main__ import get_scenecuts\n\n\ndef get_sorted_scenescores(input, output=None, threshold=0, log_level=None):\n scenescores = get_scenescores(input, output, threshold, log_level)\n scenescores = sorted(scenescores, key=lambda ss: ss[\"score\"])\n return scenescores\n\n\ndef get_scenescores(input, output=None, threshold=0, log_level=None):\n \n logging.basicConfig(level = getattr(logging, log_level.upper(), 'INFO'))\n \n if output and Path(output).exists():\n logging.info(f\"Reading scenescores from file {output}\")\n with open(output, 'r') as fd:\n scenescores = json.loads(fd.read())\n else:\n logging.info(f\"Computing scenescores for video {input}...\")\n scenescores = get_scenecuts(input, threshold=0)\n \n if output:\n logging.info(f\"Writing scenescores to file {output}\")\n with open(output, 'w') as fd:\n fd.write(json.dumps(scenescores, indent=4))\n\n return scenescores\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('input', help=\"Video file to analyze\")\n parser.add_argument('output', nargs='?', help=\"Output file where the results are written\")\n parser.add_argument('--threshold', '-t', type=int, default=0, help=\"Minimum scenescore to retain\")\n parser.add_argument('--log-level', default='info')\n args = parser.parse_args()\n scenescores = get_scenecuts(args.input, args.output, args.threshold)\n \n if not args.output:\n print(scenescores)\n","repo_name":"murrutia/study-ffmpeg-and-vmaf","sub_path":"utils/ffmpeg_scenescores.py","file_name":"ffmpeg_scenescores.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28179655620","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nA dialogflow integration for ROS\n\nThe node has support for events, intents, contexts, parameters and even dialogflow actions\n\n\nLicense: BSD\n https://raw.githubusercontent.com/samiamlabs/dyno/master/LICENCE\n\"\"\"\nimport uuid\nimport queue\nimport rospy\nimport random\nimport wave\nimport time\nfrom collections import deque\nfrom google.cloud import dialogflow\nfrom google.protobuf import struct_pb2\nfrom google.type import latlng_pb2\nfrom google.api_core import exceptions\n\nfrom std_msgs.msg import String, Bool, UInt16\nfrom std_msgs.msg import Empty as EmptyMsg\nfrom audio_common_msgs.msg import AudioData\nfrom dialogflow_ros.msg import Response, Event, Context, Parameter\nfrom qt_robot_interface.srv import audio_play, speech_config\nfrom std_srvs.srv import Empty, EmptyResponse\n\nclass DialogflowNode:\n \"\"\" The dialogflow node \"\"\"\n def __init__(self):\n rospy.init_node('dialogflow_node')\n\n self.project_id = \"folke-jkih\"\n self.session_id = str(uuid.uuid4())\n self.language = rospy.get_param('~default_language', 'sv')\n self.disable_audio = rospy.get_param('~disable_audio', False)\n \n time_before_start = rospy.get_param('~time_before_start', 0.8)\n self.save_audio_requests = rospy.get_param('~save_audio_requests', True)\n\n self.session_client = dialogflow.SessionsClient()\n \n self.query_params = dialogflow.QueryParameters(geo_location = latlng_pb2.LatLng(latitude=58.4106611, longitude=15.6198244),\n contexts = [dialogflow.Context(lifespan_count=100,\n name=\"projects/\"+self.project_id+\"/agent/sessions/\"+self.session_id+\"/contexts/linkoping\"\n )]\n )\n \n\n\n self.audio_chunk_queue = deque(maxlen=int(time_before_start * 31.25))# 16000/512 = 31.25, # Times 7.8 since the data is sent in 7.8Hz (16000 / 2048)\n\n # Note: hard coding audio_encoding and sample_rate_hertz for simplicity.\n audio_encoding = dialogflow.AudioEncoding.AUDIO_ENCODING_LINEAR_16\n sample_rate_hertz = 16000\n self.audio_config = dialogflow.InputAudioConfig(\n audio_encoding=audio_encoding,\n language_code=self.language,\n sample_rate_hertz=sample_rate_hertz,\n single_utterance=True)\n\n self.query_result_pub = rospy.Publisher('response', Response, queue_size=2)\n self.query_text_pub = rospy.Publisher('query_text', String, queue_size=2)\n self.transcript_pub = rospy.Publisher('transcript', String, queue_size=2)\n self.fulfillment_pub = rospy.Publisher('fulfillment_text', String, queue_size=10)\n self.is_listening_pub = rospy.Publisher('is_listening', Bool, queue_size=2, latch=True)\n self.is_waiting_for_hot_word = rospy.Publisher('waiting_for_hot_word', Bool, queue_size=2, latch=True)\n self.volume = 0\n self.is_talking = False\n self.is_in_dialog = False\n self.detected_wake_word = False\n self.head_visible = False\n self.waiting_for_wake_word = False\n self.end_of_dialog = False\n self.cancel_stream_intent = False\n self.skip_audio = False\n rospy.wait_for_service('/qt_robot/audio/play')\n self.audio_play_srv = rospy.ServiceProxy('/qt_robot/audio/play', audio_play)\n rospy.wait_for_service('/qt_robot/speech/config')\n self.speech_config_srv = rospy.ServiceProxy('/qt_robot/speech/config', speech_config)\n\n rospy.Subscriber('text', String, self.text_callback)\n rospy.Subscriber('is_talking', Bool, self.is_talking_callback)\n rospy.Subscriber('event', Event, self.event_callback)\n rospy.Subscriber('head_visible', Bool, self.head_visible_callback)\n rospy.Subscriber('detected_wake_word', String, self.detected_wake_word_callback)\n rospy.Subscriber('end_of_conversation', EmptyMsg, self.end_of_conversation_callback)\n\n if not self.disable_audio:\n rospy.Subscriber('sound', AudioData, self.audio_callback)\n rospy.Subscriber('volume', UInt16, self.volume_callback)\n\n self.list_intents_sevice = rospy.Service(\n 'list_intents',\n Empty,\n self.handle_list_intents)\n\n self.list_context_sevice = rospy.Service(\n 'list_context',\n Empty,\n self.handle_list_context)\n\n self.list_context_sevice = rospy.Service(\n 'clear_context',\n Empty,\n self.handle_clear_context)\n\n def handle_list_intents(self, _):\n \"\"\" Prints all intents \"\"\"\n intents_client = dialogflow.IntentsClient()\n parent = intents_client.project_agent_path(self.project_id)\n intents = intents_client.list_intents(parent)\n\n for intent in intents:\n rospy.loginfo('=' * 20)\n rospy.loginfo('Intent name: {}'.format(intent.name))\n rospy.loginfo('Intent display_name: {}'.format(intent.display_name))\n rospy.loginfo('Action: {}\\n'.format(intent.action))\n rospy.loginfo('Root followup intent: {}'.format(\n intent.root_followup_intent_name))\n rospy.loginfo('Parent followup intent: {}\\n'.format(\n intent.parent_followup_intent_name))\n\n rospy.loginfo('Input contexts:')\n for input_context_name in intent.input_context_names:\n rospy.loginfo('\\tName: {}'.format(input_context_name))\n\n rospy.loginfo('Output contexts:')\n for output_context in intent.output_contexts:\n rospy.loginfo('\\tName: {}'.format(output_context.name))\n return EmptyResponse()\n\n def handle_list_context(self, _):\n \"\"\" Prints the current contexts \"\"\"\n contexts_client = dialogflow.ContextsClient()\n contexts = contexts_client.list_contexts(self.session)\n\n rospy.loginfo('Contexts for session {}:\\n'.format(self.session))\n for context in contexts:\n rospy.loginfo('Context name: {}'.format(context.name))\n rospy.loginfo('Lifespan count: {}'.format(context.lifespan_count))\n rospy.loginfo('Fields:')\n for field, value in context.parameters.fields.items():\n if value.string_value:\n rospy.loginfo('\\t{}: {}'.format(field, value))\n return EmptyResponse()\n\n def handle_clear_context(self, _):\n \"\"\" Clear all current contexts \"\"\"\n contexts_client = dialogflow.ContextsClient()\n contexts_client.delete_all_contexts(parent=self.session)\n return EmptyResponse()\n\n def is_talking_callback(self, msg):\n \"\"\" Callback for text input \"\"\"\n self.is_talking = msg.data\n\n def detected_wake_word_callback(self, msg):\n \"\"\" Callback for text input \"\"\"\n if self.waiting_for_wake_word:\n if msg.data == \"swedish\":\n self.language = 'sv'\n self.speech_config_srv(\"sv_SV\", 500, 100)\n elif msg.data == \"english\":\n self.language = 'en'\n self.speech_config_srv(\"en_US\", 150, 80)\n elif msg.data == \"german\":\n self.language = 'de'\n self.speech_config_srv(\"de_DE\", 150, 100)\n elif msg.data == \"chinese\":\n self.language = 'zh-CN'\n self.speech_config_srv(\"zh_MA\", 50, 100)\n else:\n rospy.logerr(\"Not valid language: \" + msg.data)\n self.language = 'sv'\n self.speech_config_srv(\"sv_SV\", 150, 100)\n self.audio_config.language_code = self.language\n \n\n self.detected_wake_word = True\n rospy.Timer(rospy.Duration(0.3), self.set_wake_word_false, oneshot=True)\n\n def end_of_conversation_callback(self, msg):\n self.end_of_dialog = True\n self.handle_clear_context(None)\n\n def set_wake_word_false(self, event):\n self.detected_wake_word = False\n\n def head_visible_callback(self, msg):\n \"\"\" Callback for text input \"\"\"\n self.head_visible = msg.data\n #if not self.head_visible:\n # self.cancel_stream_intent = True\n #else:\n # self.cancel_stream_intent = False\n\n def text_callback(self, text_msg):\n \"\"\" Callback for text input \"\"\"\n self.query_text_pub.publish(text_msg)\n self.end_of_dialog = False\n query_result = self.detect_intent_text(text_msg.data)\n if query_result.intent.end_interaction:\n self.end_of_dialog = True\n self.publish_response(query_result)\n\n def event_callback(self, event_msg):\n \"\"\" Callback for event input \"\"\"\n rospy.loginfo(\"Publishing event %s\", event_msg.name)\n self.end_of_dialog = False\n query_result = self.detect_intent_event(event_msg)\n if query_result.intent.end_interaction:\n self.end_of_dialog = True\n self.publish_response(query_result)\n\n def publish_response(self, query_result):\n \"\"\" Converts the dialogflow query result to the corresponding ros message \"\"\"\n query_result_msg = Response()\n query_result_msg.project_id = self.project_id\n query_result_msg.session_id = self.session_id\n query_result_msg.query_text = query_result.query_text\n query_result_msg.intent_detection_confidence = query_result.intent_detection_confidence\n query_result_msg.language_code = query_result.language_code\n query_result_msg.intent.display_name = query_result.intent.display_name\n query_result_msg.intent.name = query_result.intent.name\n query_result_msg.intent.end_interaction = query_result.intent.end_interaction\n query_result_msg.intent.is_fallback = query_result.intent.is_fallback\n query_result_msg.action = query_result.action\n\n if not query_result.fulfillment_text:\n fulfillment_messages = query_result.fulfillment_messages\n if len(fulfillment_messages) > 0:\n query_result_msg.fulfillment_text = fulfillment_messages[0].text.text[0]\n else:\n rospy.logwarn(\"No fulfillment_text can be parsed\")\n else:\n query_result_msg.fulfillment_text = query_result.fulfillment_text\n\n query_result_msg.parameters.extend(self.create_parameters(query_result.parameters))\n\n for ctx in query_result.output_contexts:\n name = ctx.name.split(\"/\")[-1]\n if not name.endswith(\"__\"):\n c_msg = Context()\n c_msg.name = name\n if ctx.parameters:\n c_msg.parameters.extend(self.create_parameters(ctx.parameters))\n query_result_msg.output_contexts.append(c_msg)\n\n self.query_result_pub.publish(query_result_msg)\n self.fulfillment_pub.publish(query_result_msg.fulfillment_text)\n\n def create_parameters(self, params):\n \"\"\" Helper function for converting dialogflow messages to ROS counterparts \"\"\"\n msg = []\n if not params:\n return msg\n for key in params:\n p_msg = Parameter()\n p_msg.key = key\n value = params.get(key)\n if isinstance(value, str):\n p_msg.value = [value]\n elif isinstance(value, float):\n p_msg.value = [str(value)]\n else:\n p_msg.value = value\n msg.append(p_msg)\n return msg\n\n def audio_callback(self, audio_chunk_msg):\n \"\"\" Callback for audio data \"\"\"\n if self.skip_audio:\n return\n self.audio_chunk_queue.append(audio_chunk_msg.data)\n\n def volume_callback(self, msg):\n \"\"\" Callback for volume \"\"\"\n self.volume = msg.data\n\n def detect_intent_text(self, text):\n \"\"\" Send text to dialogflow and publish response \"\"\"\n self.cancel_stream_intent = True\n text_input = dialogflow.TextInput(text=text, language_code=self.language)\n query_input = dialogflow.QueryInput(text=text_input)\n response = self.session_client.detect_intent(session=self.session, query_input=query_input)\n\n rospy.loginfo('-' * 10 + \" %s \" + '-' * 10, self.project_id)\n rospy.loginfo('Query text: {}'.format(response.query_result.query_text))\n rospy.loginfo('Detected intent: {} (confidence: {})\\n'.format(\n response.query_result.intent.display_name,\n response.query_result.intent_detection_confidence))\n rospy.loginfo('Fulfillment text: {}\\n'.format(\n response.query_result.fulfillment_text))\n self.cancel_stream_intent = False\n return response.query_result\n\n def detect_intent_event(self, event_msg):\n \"\"\" Send event to dialogflow and publish response \"\"\"\n self.cancel_stream_intent = True\n event_input = dialogflow.EventInput(language_code=self.language, name=event_msg.name)\n params = struct_pb2.Struct()\n for param in event_msg.parameters:\n params[param.key] = param.value\n event_input.parameters = params\n query_input = dialogflow.QueryInput(event=event_input)\n response = self.session_client.detect_intent(session=self.session, query_input=query_input)\n\n rospy.loginfo('-' * 10 + \" %s \" + '-' * 10, self.project_id)\n rospy.loginfo('Query text: {}'.format(response.query_result.query_text))\n rospy.loginfo('Detected intent: {} (confidence: {})\\n'.format(\n response.query_result.intent.display_name,\n response.query_result.intent_detection_confidence))\n rospy.loginfo('Fulfillment text: {}\\n'.format(\n response.query_result.fulfillment_text))\n self.cancel_stream_intent = False\n return response.query_result\n\n def detect_intent_stream(self):\n \"\"\" Send streaming audio to dialogflow and publish response \"\"\"\n if self.disable_audio:\n return\n self.end_of_dialog = False\n requests = self.audio_stream_request_generator()\n responses = self.session_client.streaming_detect_intent(requests=requests)\n rospy.loginfo('=' * 10 + \" %s \" + '=' * 10, self.project_id)\n try:\n for response in responses:\n rospy.loginfo('Intermediate transcript: \"{}\".'.format(\n response.recognition_result.transcript))\n response.recognition_result.transcript = response.recognition_result.transcript.replace(\"Lidköping\", \"Linköping\")\n self.transcript_pub.publish(response.recognition_result.transcript)\n except exceptions.OutOfRange as exc:\n rospy.logerr(\"Dialogflow exception. Out of audio quota? \"\n \"No internet connection (%s)\", exc)\n return\n\n\n if self.cancel_stream_intent:\n return\n \n # pylint: disable=undefined-loop-variable\n query_result = response.query_result\n query_result.query_text = query_result.query_text.replace(\"Lidköping\", \"Linköping\")\n if query_result.intent.end_interaction:\n self.end_of_dialog = True\n\n self.query_text_pub.publish(String(data=query_result.query_text))\n\n rospy.loginfo('-' * 10 + \" %s \" + '-' * 10, self.project_id)\n rospy.loginfo('Query text: {}'.format(query_result.query_text))\n rospy.loginfo('Detected intent: {} (confidence: {})\\n'.format(\n query_result.intent.display_name,\n query_result.intent_detection_confidence))\n rospy.loginfo('Fulfillment text: {}\\n'.format(\n query_result.fulfillment_text))\n\n \n if query_result.intent.display_name == \"developer.linkopingMode\":\n self.query_params = dialogflow.QueryParameters(geo_location = latlng_pb2.LatLng(latitude=58.4106611, longitude=15.6198244),\n contexts = [dialogflow.Context(lifespan_count=100,\n name=\"projects/\"+self.project_id+\"/agent/sessions/\"+self.session_id+\"/contexts/linkoping\"\n )]\n )\n elif query_result.intent.display_name == \"developer.bergMode\":\n self.query_params = dialogflow.QueryParameters(geo_location = latlng_pb2.LatLng(latitude=58.48548532662494, longitude=15.530466246782007),\n contexts = [dialogflow.Context(lifespan_count=100,\n name=\"projects/\"+self.project_id+\"/agent/sessions/\"+self.session_id+\"/contexts/berg\"\n )]\n )\n \n self.publish_response(query_result)\n\n def audio_stream_request_generator(self):\n \"\"\" Reads the sound from the ros-topic in an generator \"\"\"\n query_input = dialogflow.QueryInput(audio_config=self.audio_config)\n # The first request contains the configuration.\n yield dialogflow.StreamingDetectIntentRequest(\n session=self.session,\n query_params=self.query_params,\n query_input=query_input)\n\n # Save data to audio file\n if self.save_audio_requests:\n filename = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.gmtime())+\".wav\"\n wf=wave.open(filename,\"w\")\n wf.setnchannels(1)\n wf.setsampwidth(2)\n wf.setframerate(16000)\n # Here we are reading small chunks of audio from a queue\n while not rospy.is_shutdown() and not self.cancel_stream_intent:\n try:\n chunk = self.audio_chunk_queue.popleft()\n except IndexError as e:\n # Wait for new sound data, should come within 0.1s since it is sent in 10Hz\n rospy.sleep(0.1)\n continue\n if self.save_audio_requests:\n wf.writeframes(chunk)\n\n # The later requests contains audio data.\n yield dialogflow.StreamingDetectIntentRequest(input_audio=chunk)\n rospy.loginfo(\"AVBRÖT STREAMING INTENT!!\")\n if self.save_audio_requests:\n wf.close()\n\n def playStartSound(self, hi=False):\n self.skip_audio = True\n if hi:\n if self.language == \"sv\":\n self.audio_play_srv(random.choice([\"hejsan.wav\",\"halla.wav\",\"tja.wav\"]),\"\")\n elif self.language == \"en\":\n self.audio_play_srv(random.choice([\"hello.wav\"]),\"\")\n elif self.language == \"de\":\n self.audio_play_srv(random.choice([\"hallo.wav\"]),\"\")\n elif self.language == 'zh-CN':\n self.audio_play_srv(random.choice([\"nihao.wav\"]),\"\")\n else:\n self.audio_play_srv(\"confirm_listen.wav\",\"\")\n time.sleep(0.1)\n self.skip_audio = False\n\n def playStopSound(self):\n self.skip_audio = True\n self.audio_play_srv(\"confirm_heard.wav\",\"\")\n self.skip_audio = False\n\n\n def run_until_sleep(self):\n isFirst = True\n while not rospy.is_shutdown():\n self.session_id = str(uuid.uuid4())\n self.session = self.session_client.session_path(self.project_id, self.session_id)\n rospy.loginfo('Session path: {}\\n'.format(self.session))\n\n rospy.logwarn(\"VÄNTAR PÅ HOT WORD ELLER FACE!\")\n start_waiting = time.time()\n while (not self.detected_wake_word and not self.head_visible) and not rospy.is_shutdown():\n rospy.sleep(0.1)\n if time.time() > start_waiting + 7:\n rospy.logwarn(\"TIMEOUT, BACK TO SLEEP\")\n return\n if self.end_of_dialog:\n rospy.logwarn(\"Got end of dialog, return 1\")\n return\n\n self.playStartSound(isFirst)\n isFirst = False\n self.is_listening_pub.publish(True)\n rospy.logwarn(\"SKICKAR LJUD TILL DIALOGFLOW\")\n self.detect_intent_stream()\n self.is_listening_pub.publish(False)\n self.playStopSound()\n rospy.logwarn(\"VÄNTAR PÅ ATT ROBOTEN SKA PRATA KLART!\")\n time.sleep(2) # Time to fetch website etc. So we don't skip this loop because we don't have gotten the is_talking flag imediately\n while self.is_talking and not rospy.is_shutdown():\n rospy.sleep(0.1)\n if self.end_of_dialog:\n rospy.logwarn(\"Got end of dialog, return 2\")\n return\n rospy.sleep(0.7)\n\n \n def run(self):\n \"\"\" Update straming intents if we are using audio data \"\"\"\n\n while not rospy.is_shutdown():\n # Create new session\n self.session_id = str(uuid.uuid4())\n self.session = self.session_client.session_path(self.project_id, self.session_id)\n rospy.loginfo('Session path: {}\\n'.format(self.session))\n \n rospy.logwarn(\"VÄNTAR PÅ HOT WORD!\")\n self.is_waiting_for_hot_word.publish(True)\n self.waiting_for_wake_word = True\n while not self.detected_wake_word and not rospy.is_shutdown():\n rospy.sleep(0.1)\n self.waiting_for_wake_word = False\n self.is_waiting_for_hot_word.publish(False)\n self.run_until_sleep()\n rospy.sleep(0.5)\n\nif __name__ == '__main__':\n node = DialogflowNode()\n node.run()\n","repo_name":"DynoRobotics/dialogflow_ros","sub_path":"nodes/dialogflow_node.py","file_name":"dialogflow_node.py","file_ext":"py","file_size_in_byte":21655,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"13752564293","text":"# @Time : 2020/7/8\n# @Author : Lart Pang\n# @Email : lartpang@163.com\n# @File : create_loader_imgs.py\n# @Project : HDFNet\n# @GitHub : https://github.com/lartpang\nfrom prefetch_generator import BackgroundGenerator\nfrom torch.utils.data import DataLoader\n\nfrom config import arg_config\n\n\nclass DataLoaderX(DataLoader):\n def __iter__(self):\n return BackgroundGenerator(super(DataLoaderX, self).__iter__())\n\n\ndef _make_loader(dataset, shuffle=True, drop_last=False):\n return DataLoaderX(\n dataset=dataset,\n batch_size=arg_config[\"batch_size\"],\n num_workers=arg_config[\"num_workers\"],\n shuffle=shuffle,\n drop_last=drop_last,\n pin_memory=True,\n )\n\n\ndef create_loader(data_path, mode, get_length=False, data_mode=\"RGBD\", prefix=(\".jpg\", \".png\")):\n if data_mode == \"RGB\":\n from utils.data.create_rgb_datasets_imgs import TestImageFolder, TrainImageFolder\n elif data_mode == \"RGBD\":\n from utils.data.create_rgbd_datasets_imgs import TestImageFolder, TrainImageFolder\n else:\n raise NotImplementedError\n\n if mode == \"train\":\n print(f\" ==>> 使用训练集{data_path}训练 <<== \")\n train_set = TrainImageFolder(data_path, in_size=arg_config[\"input_size\"], prefix=prefix)\n loader = _make_loader(train_set, shuffle=True, drop_last=True)\n length_of_dataset = len(train_set)\n elif mode == \"test\":\n print(f\" ==>> 使用测试集{data_path}测试 <<== \")\n test_set = TestImageFolder(data_path, in_size=arg_config[\"input_size\"], prefix=prefix)\n loader = _make_loader(test_set, shuffle=False, drop_last=False)\n length_of_dataset = len(test_set)\n else:\n raise NotImplementedError\n\n if get_length:\n return loader, length_of_dataset\n else:\n return loader\n","repo_name":"lartpang/HDFNet","sub_path":"utils/data/create_loader_imgs.py","file_name":"create_loader_imgs.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"en","doc_type":"code","stars":80,"dataset":"github-code","pt":"48"} +{"seq_id":"21415397906","text":"\"\"\"Test\n\nRevision ID: c3e343b9ccc0\nRevises: f53b751d238b\nCreate Date: 2022-06-02 12:08:06.488579\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'c3e343b9ccc0'\ndown_revision = 'f53b751d238b'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('rooms', sa.Column('description', sa.String(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('rooms', 'description')\n # ### end Alembic commands ###\n","repo_name":"pvenv/swimmy","sub_path":"docker/fastapi/migrations/versions/c3e343b9ccc0_test.py","file_name":"c3e343b9ccc0_test.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70874575825","text":"\"\"\"rio-faux.\"\"\"\n\nimport os\nimport warnings\n\nimport click\nimport numpy\nimport rasterio\nfrom rasterio.enums import ColorInterp, MaskFlags\nfrom rasterio.enums import Resampling as ResamplingEnums\nfrom rasterio.io import MemoryFile\nfrom rasterio.rio import options\nfrom rasterio.shutil import copy\n\n\ndef has_mask_band(src_dst):\n \"\"\"Check for mask band in source.\"\"\"\n if any(\n [\n (MaskFlags.per_dataset in flags and MaskFlags.alpha not in flags)\n for flags in src_dst.mask_flag_enums\n ]\n ):\n return True\n return False\n\n\n@click.command()\n@options.file_in_arg\n@options.file_out_arg\n@click.option(\n \"--value\",\n default=None,\n type=float,\n help=\"Set a custom value in the data.\",\n)\n@click.option(\n \"--forward-band-tags\",\n default=False,\n is_flag=True,\n help=\"Forward band tags to output bands.\",\n)\n@click.option(\n \"--forward-dataset-tags\",\n default=False,\n is_flag=True,\n help=\"Forward dataset tags to output image.\",\n)\n@options.creation_options\n@click.option(\n \"--config\",\n \"config\",\n metavar=\"NAME=VALUE\",\n multiple=True,\n callback=options._cb_key_val,\n help=\"GDAL configuration options.\",\n)\ndef faux(\n input,\n output,\n value,\n forward_band_tags,\n forward_dataset_tags,\n creation_options,\n config,\n):\n \"\"\"Create empty copy.\"\"\"\n # Check if the dataset has overviews\n with rasterio.open(input) as src_dst:\n ovr = src_dst.overviews(1)\n\n # Get Overview Blocksize\n overview_blocksize = 512\n if ovr:\n with rasterio.open(input, OVERVIEW_LEVEL=0) as src_dst:\n overview_blocksize = src_dst.profile.get(\"blockxsize\", overview_blocksize)\n\n config.update(\n {\n \"GDAL_NUM_THREADS\": \"ALL_CPUS\",\n \"GDAL_TIFF_INTERNAL_MASK\": os.environ.get(\"GDAL_TIFF_INTERNAL_MASK\", True),\n \"GDAL_TIFF_OVR_BLOCKSIZE\": str(overview_blocksize),\n }\n )\n\n with rasterio.Env(**config):\n with rasterio.open(input) as src_dst:\n meta = src_dst.meta\n with MemoryFile() as m:\n with m.open(**meta) as tmp_dst:\n tmp_dst.colorinterp = src_dst.colorinterp\n\n if tmp_dst.colorinterp[0] is ColorInterp.palette:\n try:\n tmp_dst.write_colormap(1, src_dst.colormap(1))\n except ValueError:\n warnings.warn(\n \"Dataset has `Palette` color interpretation\"\n \" but is missing colormap information\"\n )\n\n if has_mask_band(src_dst):\n tmp_dst.write_mask(src_dst.dataset_mask())\n\n if value:\n tmp_dst.write(\n numpy.full(\n (tmp_dst.count, tmp_dst.height, tmp_dst.width),\n value,\n dtype=tmp_dst.dtypes[0],\n ),\n )\n\n if ColorInterp.alpha in tmp_dst.colorinterp:\n alpha_bidx = src_dst.colorinterp.index(ColorInterp.alpha) + 1\n tmp_dst.write(\n src_dst.read(indexes=alpha_bidx),\n indexes=alpha_bidx,\n )\n\n tags = src_dst.tags()\n\n overview_resampling = tags.get(\n \"OVR_RESAMPLING_ALG\", \"nearest\"\n ).lower()\n if ovr:\n tmp_dst.build_overviews(\n ovr, ResamplingEnums[overview_resampling]\n )\n\n indexes = src_dst.indexes\n\n if forward_band_tags:\n for i, b in enumerate(indexes):\n tmp_dst.set_band_description(\n i + 1, src_dst.descriptions[b - 1]\n )\n tmp_dst.update_tags(i + 1, **src_dst.tags(b))\n\n if forward_dataset_tags:\n tmp_dst.update_tags(**tags)\n\n tmp_dst._set_all_scales([src_dst.scales[b - 1] for b in indexes])\n tmp_dst._set_all_offsets([src_dst.offsets[b - 1] for b in indexes])\n\n output_profile = src_dst.profile\n output_profile.update(\n {\"BIGTIFF\": os.environ.get(\"BIGTIFF\", \"IF_SAFER\")}\n )\n if creation_options:\n output_profile.update(creation_options)\n\n keys = [\n \"dtype\",\n \"nodata\",\n \"width\",\n \"height\",\n \"count\",\n \"crs\",\n \"transform\",\n ]\n for key in keys:\n output_profile.pop(key, None)\n\n copy(tmp_dst, output, copy_src_overviews=True, **output_profile)\n","repo_name":"cogeotiff/rio-faux","sub_path":"rio_faux/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":5183,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"48"} +{"seq_id":"42292374781","text":"#!/usr/bin/python3\n'''\nlistt all the States objects who contain letter a\n'''\n\n\nfrom sys import argv\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom model_state import State\n\n\nif __name__ == '__main__':\n engine = create_engine(\n 'mysql+mysqldb://{}:{}@localhost/{}'.format(argv[1], argv[2], argv[3]))\n insSession = sessionmaker(bind=engine)\n session = insSession()\n\n states = session.query(State).filter(\n State.name.contains('a')).order_by(State.id).all()\n for state in states:\n print('{}: {}'.format(state.id, state.name))\n session.close()\n","repo_name":"sabrallah/alx-higher_level_programming","sub_path":"0x0F-python-object_relational_mapping/9-model_state_filter_a.py","file_name":"9-model_state_filter_a.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"25347446221","text":"import logging\n\nlog = logging.getLogger(__name__)\n_type_map = {}\n\n\nclass TypeMeta(type):\n def __new__(mcs, name, bases, attrs):\n cls = type.__new__(mcs, name, bases, attrs)\n if '__metaclass__' not in attrs:\n _type_map[name.lower()] = cls\n from TelegramBotAPI.types.field import Field\n cls._valid_fields = {}\n for n in dir(cls):\n a = getattr(cls, n)\n if isinstance(a, Field):\n cls._valid_fields[n.lower()] = a\n delattr(cls, n)\n return cls\n\n\nclass Type(object, metaclass=TypeMeta):\n __type_map = _type_map\n __from_raw_dropped = None\n __from_raw_found = None\n _fields = None\n _d = None\n\n def __init__(self, *args):\n for field in self._valid_fields.values():\n field.setup_types()\n if len(args) > 1:\n raise TypeError('%s can take up to 1 argument (%d given)' % (self.__class__.__name__,\n len(args)))\n if args:\n self._from_raw(args[0])\n\n def _from_raw(self, raw):\n self._d = {}\n self.__from_raw_dropped = {}\n self.__from_raw_found = 0\n\n for key in raw:\n if key not in self._valid_fields:\n self.__from_raw_dropped[key] = raw[key]\n continue\n\n if self._valid_fields[key].ignore:\n self.__from_raw_found += 1\n continue\n\n if self._valid_fields[key].list:\n ld = ListDelegate(self._d, key, self._valid_fields[key])\n ld.extend(raw[key])\n else:\n ad = AssignDelegate(self._d, key, self._valid_fields[key])\n ad._from_raw(raw[key])\n self.__from_raw_found += 1\n\n for key, field in self._valid_fields.items():\n if field.optional is False and key not in self._d:\n raise TypeError('\"%s\" is an expected field in %s' % (key, self.__class__.__name__))\n\n if self.__from_raw_found == 0:\n raise TypeError('No fields were found for % in %s' % (self.__class__.__name__, raw))\n\n def _to_raw(self, strict=True):\n if self._leaf:\n return self._d\n raw = {}\n for key in self._valid_fields:\n if self._d is not None and key in self._d:\n raw[key] = self._d[key]._to_raw(strict)\n elif strict and self._valid_fields[key].optional is False:\n raise KeyError('\"%s\" is an expected field in %s' % (key, self.__class__.__name__))\n return raw\n\n def _from_raw_dropped(self):\n if self._leaf:\n return None\n dropped = self.__from_raw_dropped\n for key in self._valid_fields:\n if self._d is not None and key in self._d:\n d = self._d[key]._from_raw_dropped()\n if d:\n dropped[key] = d\n return dropped\n\n def _from_raw_found(self):\n if self._leaf:\n return 1\n return self.__from_raw_found\n\n @classmethod\n def _new(cls, value, type_name=None):\n if type_name is None:\n type_name = set(value.keys()).intersection(list(cls.__type_map.keys()))\n assert len(type_name) == 1\n type_name = type_name.pop()\n value = value[type_name]\n\n instance = cls.__type_map[type_name.lower()]()\n instance._from_raw(value)\n\n return instance\n\n @classmethod\n def _type(cls, name):\n return cls.__type_map[name.lower()]\n\n @property\n def _name(self):\n return self.__class__.__name__\n\n @property\n def _leaf(self):\n return len(self._valid_fields) == 0\n\n def __setattr__(self, key, value):\n self.__set(key, value)\n\n def __setitem__(self, key, value):\n self.__set(key, value)\n\n def __set(self, key, value):\n if key.startswith('_'):\n super(Type, self).__setattr__(key, value)\n return\n\n name = key.lower()\n if name in self._valid_fields:\n if self._d is None:\n self._d = {}\n ad = AssignDelegate(self._d, name, self._valid_fields[name])\n ad._from_raw(value)\n return\n raise TypeError('\"%s\" does not have a \"%s\" field' % (self.__class__.__name__, key))\n\n def __getattr__(self, key):\n return self.__get(key)\n\n def __getitem__(self, key):\n return self.__get(key)\n\n def __get(self, key):\n if not isinstance(key, str):\n raise AttributeError(\"'%s' has no field '%s'\" % (self._name, key))\n\n name = key.lower()\n if self._d and name in self._d:\n if self._d[name]._leaf:\n return self._d[name]._d\n return self._d[name]\n\n if name in self._valid_fields:\n if self._valid_fields[name].leaf and not self._valid_fields[name].list:\n raise AttributeError(\"Optional field '%s' not found in '%s'\" % (key, self._name))\n if self._d is None:\n self._d = {}\n if self._valid_fields[name].list:\n return ListDelegate(self._d, name, self._valid_fields[name])\n return AssignDelegate(self._d, name, self._valid_fields[name])\n\n self.__field_error(key)\n\n def __delattr__(self, key):\n self.__del(key)\n\n def __delitem__(self, key):\n self.__del(key)\n\n def __del(self, key):\n name = key.lower()\n del self._d[name]\n\n def __iter__(self):\n for name in self._d:\n yield name\n\n def __repr__(self):\n return \"<%s %s>\" % (self.__class__.__name__, str(self._to_raw(strict=False)))\n\n def __eq__(self, other):\n if self._leaf:\n return self._d == other\n return repr(self._to_raw(strict=False)) == repr(other._to_raw(strict=False))\n\n def __field_error(self, key):\n raise KeyError('\"%s\" does not have a \"%s\" field' % (self.__class__.__name__, key))\n\n\nclass Delegate(object):\n def __init__(self, d, key, field):\n self._d = d\n self._key = key\n self._field = field\n\n\nclass AssignDelegate(Delegate):\n def _from_raw(self, raw):\n if any([True for t in self._field.types if isinstance(raw, t)]):\n self._d[self._key] = raw\n else:\n self._d[self._key] = self.__from_raw(raw)\n\n def __setattr__(self, key, value):\n return self.__set(key, value)\n\n def __set(self, key, value):\n if key.startswith('_'):\n return super(AssignDelegate, self).__setattr__(key, value)\n if self._key not in self._d:\n self._d[self._key] = None\n self._d[self._key] = self.__from_field(key, value)\n\n def __getattr__(self, key):\n return self.__get(key)\n\n def __get(self, key):\n if key.startswith('_'):\n return super(AssignDelegate, self).__getattribute__(key)\n if not isinstance(key, str):\n raise AttributeError(\"'%s' has no field '%s'\" % (self._name, key))\n\n name = key.lower()\n\n for _type in self._field.types:\n\n if name in _type._valid_fields:\n if _type._valid_fields[name].leaf and not _type._valid_fields[name].list:\n raise AttributeError(\"Optional field '%s' not found in '%s'\" % (key,\n self._key))\n\n self._d[self._key] = _type()\n self._d[self._key]._d = {}\n\n if _type._valid_fields[name].list:\n return ListDelegate(self._d[self._key]._d, name, _type._valid_fields[name])\n return AssignDelegate(self._d[self._key]._d, name, _type._valid_fields[name])\n\n self.__field_error(key)\n\n def __from_raw(self, raw):\n assert not self._field.list\n\n def upcast(cls, raw):\n try:\n value = cls()\n value._from_raw(raw)\n return value._from_raw_found(), value\n except TypeError as e:\n return -1, e\n\n candidates = [upcast(cls, raw) for cls in self._field.types]\n\n best = None\n rank = -1\n for r, v in candidates:\n if r > rank:\n best = v\n rank = r\n\n if best is None:\n raise TypeError('None of %s accepted: %s : %s' % (self._field.types, raw, candidates))\n\n return best\n\n def __from_field(self, key, value):\n last_exception = None\n for cls in self._field.types:\n try:\n v = cls()\n setattr(v, key, value)\n return v\n except TypeError as e:\n last_exception = e\n raise last_exception # pylint: disable=raising-bad-type\n\n def __field_error(self, key):\n raise KeyError('\"%s\" does not have a \"%s\" field' % (self.__class__.__name__, key))\n\n\nclass ListDelegate(Delegate):\n def __init__(self, d, key, field):\n super(ListDelegate, self).__init__(d, key, field)\n self._l = []\n if self._key not in self._d:\n self._d[self._key] = self\n\n def append(self, value):\n t = self._field.types[0]()\n t._from_raw(value)\n self._l.append(t)\n\n def extend(self, values):\n for value in values:\n self.append(value)\n\n @property\n def _leaf(self):\n return False\n # return self._field.leaf\n\n def _to_raw(self, strict=True):\n ret = []\n\n for i in range(len(self._l)):\n v = self._l[i]\n if v:\n ret.append(v._to_raw(strict))\n elif strict:\n raise IndexError('Index [%d] of list \"%s\" not set' % (i, self._key))\n return ret\n\n def _from_raw_dropped(self):\n ret = []\n\n for i in range(len(self._l)):\n v = self._l[i]\n if v:\n d = v._from_raw_dropped()\n if d:\n ret.append(d)\n return ret\n\n def __setitem__(self, index, value):\n t = self._field.types[0]()\n t._from_raw(value)\n self._l[index] = t\n\n def __getitem__(self, index):\n try:\n v = self._l[index]\n if v is None:\n v = self._field.types[0]()\n self._l[index] = v\n return v\n except IndexError:\n pass\n from itertools import count\n for i in count(len(self._l)):\n if i == index:\n v = self._field.types[0]()\n self._l.append(v)\n return v\n else:\n self._l.append(None)\n\n def __iter__(self):\n for value in self._l:\n yield value\n\n def __len__(self):\n return len(self._l)\n\n\n__all__ = ['Type']\n","repo_name":"sourcesimian/pyTelegramBotAPI","sub_path":"TelegramBotAPI/types/type.py","file_name":"type.py","file_ext":"py","file_size_in_byte":10815,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"48"} +{"seq_id":"28732122504","text":"import datetime\nfrom odoo import api, fields, models, _\nfrom odoo.exceptions import UserError\nfrom odoo.tools.misc import clean_context\n\n\nclass IncrementWages(models.TransientModel):\n _name = 'increment.wages'\n\n def do_increments(self):\n contracts = self.env['hr.contract'].search([('increments', '>', 0)])\n for contract in contracts:\n if contract.increments > 0:\n contract.wage = contract.increments + contract.wage\n contract.gosi_salary = contract.increments + contract.gosi_salary\n contract.increments = 0\n return {\n 'name': _('Increments'),\n 'type': 'ir.actions.act_window',\n 'view_mode': 'tree,form',\n 'res_model': 'hr.contract',\n 'views': [\n (self.env.ref('pabs_hr.hr_contract_view_new_tree').id, 'tree'),\n (self.env.ref('hr_contract.hr_contract_view_form').id, 'form'),\n ], # 'res_id': planning_slot.id,\n # 'context': context,\n }","repo_name":"Mx1014/odoolivetest","sub_path":"pabs_hr/wizard/increment_wages.py","file_name":"increment_wages.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19478234756","text":"import requests\nfrom bs4 import BeautifulSoup\nimport csv\n\nlink=requests.get('https://pokemondb.net/pokedex/national')\nsoup=BeautifulSoup(link.text,'html.parser')\n\nalldata=\"\"\nfor a in soup.findAll(class_='infocard'):\n for b in a.findAll('span',class_='infocard-lg-data text-muted'):\n dataperitem=\"\"\n for c in b.findAll(class_='ent-name'):\n for d in b.find('small'):\n dataperitem=dataperitem+str(d)+','+c.text\n alldata=alldata+dataperitem+'\\n'\nprint(alldata)\n\n#saving output to csv file\n\ndatapokemon=open('./file excel/pokemon.csv','w',newline='',encoding='utf8')\n#input header\nheader=csv.DictWriter(datapokemon,fieldnames=[\"id_pokemon\", \"nama_pokemon\"])\nheader.writeheader()\n#input data\ndatapokemon.write(alldata)","repo_name":"anastasyaviviana/Web_Scraping-01-_Import_Into_CSV_File","sub_path":"poke.py","file_name":"poke.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18774880371","text":"import json\n\nclass Router:\n def __init__(self):\n self.methods = {\n \"get\": {},\n \"post\": {},\n }\n \n def parse(self, request, response):\n data = json.loads(request)\n method = data['method']\n endpoint = data['endpoint']\n body = data['body']\n\n if method not in self.methods:\n return lambda: response('Method not allowed', 405)\n\n if endpoint not in self.methods[method]:\n return lambda: response('Not found', 404)\n\n if not body:\n return lambda: self.methods[method][endpoint]()\n\n return lambda: self.methods[method][endpoint](body)\n\n def get(self, endpoint, callback):\n self.methods['get'][endpoint] = callback\n\n def post(self, endpoint, callback):\n self.methods['post'][endpoint] = callback\n","repo_name":"yodono/crypto-python","sub_path":"server/src/router.py","file_name":"router.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34341843122","text":"\ndef is_prime(c):\n if c < 2:\n return False\n if c == 2 or c == 3:\n return True\n for x in range(c-3):\n if c % (x + 2) == 0:\n return False\n else:\n return True\n'''\nn = int(input(\"Enter a number: \"))\n\nif is_prime(n):\n print(n,\"is prime!\")\nelse:\n print(n, \"is not prime.\")\n\nif n < 2:\n print(n,\"prime!\")\nelse:\n count = 2\n prime = True\n while count < n:\n if n % count == 0:\n prime = False\n count += 1\n'''\n","repo_name":"michael940716/accelerated_cs","sub_path":"summer_2019/cs199/fun_with_functions/prime_number.py","file_name":"prime_number.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30611232760","text":"\nimport json\nfrom xossynchronizer.event_steps.eventstep import EventStep\nfrom helpers import DtHelpers\n\n\nclass ONUEventStep(EventStep):\n topics = [\"onu.events\"]\n technology = \"kafka\"\n\n max_onu_retry = 50\n\n def __init__(self, *args, **kwargs):\n super(ONUEventStep, self).__init__(*args, **kwargs)\n\n def process_event(self, event):\n value = json.loads(event.value)\n self.log.info(\"onu.events: received event\", value=value)\n # This is needed to be compatible with both Voltha 1.7 and Voltha 2.x\n # It supposes to have only 1 subscriber per ONU and the subscriber is connected to the first port\n if \"-\" in value[\"serialNumber\"] and not value[\"serialNumber\"].endswith(\"-1\"):\n self.log.info(\"Skip event, only consider [serialNumber]-1 events\")\n return\n\n dt_si = DtHelpers.find_or_create_dt_si(self.model_accessor, self.log, value)\n if value[\"status\"] == \"activated\":\n self.log.info(\"onu.events: activated onu\", value=value)\n dt_si.no_sync = False\n dt_si.uni_port_id = long(value[\"portNumber\"])\n dt_si.of_dpid = value[\"deviceId\"]\n dt_si.oper_onu_status = \"ENABLED\"\n dt_si.save_changed_fields(always_update_timestamp=True)\n elif value[\"status\"] == \"disabled\":\n self.log.info(\"onu.events: disabled onu, resetting the subscriber\", value=value)\n dt_si.oper_onu_status = \"DISABLED\"\n dt_si.save_changed_fields(always_update_timestamp=True)\n return\n else:\n self.log.warn(\"onu.events: Unknown status value: %s\" % value[\"status\"], value=value)\n return\n","repo_name":"opencord/dt-workflow-driver","sub_path":"xos/synchronizer/event_steps/onu_event.py","file_name":"onu_event.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25654388532","text":"# -*- coding: utf-8 -*-\n# ***********************************************************************\n# ****************** CANADIAN ASTRONOMY DATA CENTRE *******************\n# ************* CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES **************\n#\n# (c) 2022. (c) 2022.\n# Government of Canada Gouvernement du Canada\n# National Research Council Conseil national de recherches\n# Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6\n# All rights reserved Tous droits réservés\n#\n# NRC disclaims any warranties, Le CNRC dénie toute garantie\n# expressed, implied, or énoncée, implicite ou légale,\n# statutory, of any kind with de quelque nature que ce\n# respect to the software, soit, concernant le logiciel,\n# including without limitation y compris sans restriction\n# any warranty of merchantability toute garantie de valeur\n# or fitness for a particular marchande ou de pertinence\n# purpose. NRC shall not be pour un usage particulier.\n# liable in any event for any Le CNRC ne pourra en aucun cas\n# damages, whether direct or être tenu responsable de tout\n# indirect, special or general, dommage, direct ou indirect,\n# consequential or incidental, particulier ou général,\n# arising from the use of the accessoire ou fortuit, résultant\n# software. Neither the name de l'utilisation du logiciel. Ni\n# of the National Research le nom du Conseil National de\n# Council of Canada nor the Recherches du Canada ni les noms\n# names of its contributors may de ses participants ne peuvent\n# be used to endorse or promote être utilisés pour approuver ou\n# products derived from this promouvoir les produits dérivés\n# software without specific prior de ce logiciel sans autorisation\n# written permission. préalable et particulière\n# par écrit.\n#\n# This file is part of the Ce fichier fait partie du projet\n# OpenCADC project. OpenCADC.\n#\n# OpenCADC is free software: OpenCADC est un logiciel libre ;\n# you can redistribute it and/or vous pouvez le redistribuer ou le\n# modify it under the terms of modifier suivant les termes de\n# the GNU Affero General Public la “GNU Affero General Public\n# License as published by the License” telle que publiée\n# Free Software Foundation, par la Free Software Foundation\n# either version 3 of the : soit la version 3 de cette\n# License, or (at your option) licence, soit (à votre gré)\n# any later version. toute version ultérieure.\n#\n# OpenCADC is distributed in the OpenCADC est distribué\n# hope that it will be useful, dans l’espoir qu’il vous\n# but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE\n# without even the implied GARANTIE : sans même la garantie\n# warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ\n# or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF\n# PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence\n# General Public License for Générale Publique GNU Affero\n# more details. pour plus de détails.\n#\n# You should have received Vous devriez avoir reçu une\n# a copy of the GNU Affero copie de la Licence Générale\n# General Public License along Publique GNU Affero avec\n# with OpenCADC. If not, see OpenCADC ; si ce n’est\n# . pas le cas, consultez :\n# .\n#\n# : 4 $\n#\n# ***********************************************************************\n#\n\nimport os\n\nfrom caom2pipe.validator_composable import VALIDATE_OUTPUT, Validator\nfrom unittest.mock import Mock, patch\n\n\nclass TValidator(Validator):\n def __init__(self, source_name, preview_suffix):\n super().__init__(source_name, preview_suffix=preview_suffix)\n\n def read_from_source(self):\n import pandas as pd\n return pd.DataFrame({'f_name': [], 'timestamp': []})\n\n def _find_unaligned_dates(self, source, data):\n import pandas as pd\n return pd.DataFrame({'f_name': []})\n\n\n@patch('cadcutils.net.BaseWsClient.post')\n@patch('cadcutils.net.BaseWsClient.get')\n@patch('cadcutils.net.ws.WsCapabilities.get_access_url')\ndef test_validator(caps_mock, ad_mock, tap_mock, test_config, tmpdir):\n caps_mock.return_value = 'https://sc2.canfar.net/sc2repo'\n tap_response = Mock()\n tap_response.status_code = 200\n tap_response.iter_content.return_value = [\n b'uri\\tcontentLastModified\\n'\n b'cadc:NEOSSAT/NEOS_SCI_2019213215700_cord.fits\\t2017-12-12 00:00:00.000\\n'\n b'cadc:NEOSSAT/NEOS_SCI_2019213215700_cor.fits\\t2017-12-12 00:00:00.001\\n'\n b'cadc:NEOSSAT/NEOS_SCI_2019213215700.fits\\t2017-12-12 00:00:00.002\\n'\n ]\n\n tap_mock.return_value.__enter__.return_value = tap_response\n storage_response = Mock()\n storage_response.status_code = 200\n storage_response.text = [b'uri\\tcontentLastModified\\n']\n ad_mock.return_value = storage_response\n orig_cwd = os.getcwd()\n try:\n os.chdir(tmpdir)\n test_config.change_working_directory(tmpdir)\n test_config.proxy_file_name = 'proxy.pem'\n test_config.write_to_file(test_config)\n with open(test_config.proxy_fqn, 'w') as f:\n f.write('test content')\n\n test_subject = TValidator('TEST_SOURCE_NAME', 'png')\n test_source_missing, test_data_missing, test_data_older = test_subject.validate()\n assert test_source_missing is not None, 'expected source result'\n assert test_data_missing is not None, 'expected data dest result'\n assert test_data_older is not None, 'expected data older result'\n assert len(test_source_missing) == 0, 'wrong number of source results'\n assert len(test_data_missing) == 3, 'wrong # of data dest results'\n assert len(test_data_older) == 0, 'wrong # of data older results'\n for n in ['not_at_cadc.txt', 'not_at_TEST_SOURCE_NAME.txt', 'newer_at_TEST_SOURCE_NAME.txt']:\n test_listing_fqn = f'{tmpdir}/{n}'\n assert os.path.exists(test_listing_fqn), f'should create file record {n}'\n finally:\n os.chdir(orig_cwd)\n\n\n@patch('cadcutils.net.BaseWsClient.post')\n@patch('cadcutils.net.ws.WsCapabilities.get_access_url')\ndef test_validator2(caps_mock, storage_mock, test_config, tmpdir):\n caps_mock.return_value = 'https://sc2.canfar.net/sc2repo'\n response = Mock()\n response.status_code = 200\n response.iter_content.return_value = [\n b'uri\\tcontentLastModified\\n'\n b'cadc:NEOSSAT/NEOS_SCI_2015347000000_clean.fits\\t2019-10-23T16:27:19.000\\n'\n b'cadc:NEOSSAT/NEOS_SCI_2015347000000.fits\\t2019-10-23T16:27:27.000\\n'\n b'cadc:NEOSSAT/NEOS_SCI_2015347002200_clean.fits\\t2019-10-23T16:27:33.000\\n'\n b'cadc:NEOSSAT/NEOS_SCI_2015347002200.fits\\t2019-10-23T16:27:40.000\\n'\n b'cadc:NEOSSAT/NEOS_SCI_2015347002500_clean.fits\\t2019-10-23T16:27:47.000\\n'\n ]\n storage_mock.return_value.__enter__.return_value = response\n orig_cwd = os.getcwd()\n try:\n os.chdir(tmpdir)\n test_config.change_working_directory(tmpdir)\n test_config.proxy_file_name = 'proxy.pem'\n test_config.write_to_file(test_config)\n with open(test_config.proxy_fqn, 'w') as f:\n f.write('test content')\n\n test_subject = TValidator('TEST_SOURCE_NAME', 'png')\n test_destination_data = (\n test_subject._read_list_from_destination_data()\n )\n assert test_destination_data is not None, 'expected data result'\n assert len(test_destination_data) == 5, 'wrong number of data results'\n test_result = test_destination_data.loc[1, :]\n assert (\n test_result.f_name == 'NEOS_SCI_2015347000000.fits'\n ), f'wrong value format, should be just a file name, {test_result.f_name}'\n assert (\n test_result.contentLastModified == '2019-10-23T16:27:27.000'\n ), f'should be a datetime value, {test_result.contentLastModified}'\n finally:\n os.chdir(orig_cwd)\n\n\n","repo_name":"opencadc/caom2pipe","sub_path":"caom2pipe/tests/test_validator_composable.py","file_name":"test_validator_composable.py","file_ext":"py","file_size_in_byte":8476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38397938038","text":"# coding: utf-8\n# created by deng on 2018/10/16\n\nfrom time import time\nfrom sklearn.model_selection import cross_validate\nfrom xgboost.sklearn import XGBClassifier\nfrom sklearn.svm import SVC, LinearSVC\nfrom sklearn.model_selection import train_test_split, GridSearchCV, StratifiedKFold\nfrom sklearn.externals import joblib\nfrom sklearn.metrics import f1_score, accuracy_score, precision_score, recall_score, classification_report\nfrom sklearn.preprocessing import MultiLabelBinarizer, LabelBinarizer\nfrom sklearn.multiclass import OneVsRestClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom time import time\nimport numpy as np\nimport pandas as pd\n\nfrom preprocessing.prepare_data import generate_vectors, id2sub\nfrom utils.path_util import from_project_root\nfrom utils.proba_util import predict_proba\nfrom utils.evaluate import evaluate\nfrom bow_model.classes import LinearSVCP\n\nN_JOBS = 6\nN_CLASSES = 10\nRANDOM_STATE = 10\n\n\ndef validate_clf(clf, X, y, cv=5, scoring='f1_micro'):\n \"\"\" do cross validation on clf\n\n Args:\n clf: clf to be tuned\n X: X for fit\n y: y for fit\n cv: cv for cross validate\n scoring: scoring for cross validate\n\n \"\"\"\n s_time = time()\n cv_result = cross_validate(clf, X, y, cv=cv, scoring=scoring, n_jobs=N_JOBS, return_train_score=True)\n train_scores = cv_result['train_score']\n test_scores = cv_result['test_score']\n e_time = time()\n # print cv results\n print(\"validation is done in %.3f seconds\" % (e_time - s_time))\n print(\"metrics of each cv: \")\n for i in range(cv):\n print(\" train_f1 %f, val_f1 %f\" % (train_scores[i], test_scores[i]))\n print('averaged %s on val set: %f\\n' % (scoring, test_scores.mean()))\n\n\ndef calc_metrics(y_true, y_pred, y_probas=None):\n \"\"\" validating clf according metrics described in info page\n\n Args:\n y_true: real labels, shape = (n_samples, n_labels)\n y_pred: predicted labels, shape = (n_samples, ), (n_samples, n_labels)\n y_probas: predicted probabilities of each label, shape = (n_samples, )\n\n \"\"\"\n if len(y_pred.shape) == 1:\n mlb = MultiLabelBinarizer().fit([range(10)])\n y_pred = mlb.transform(y_pred.reshape(-1, 1))\n\n if len(y_pred.shape) == 3:\n y_pred = y_pred[:, :, 1].T\n\n names = ['价格', '配置', '操控', '舒适', '油耗', '动力', '内饰', '安全', '空间', '外观']\n print(\"\\ndetails before fill non result samples:\\n\")\n print(classification_report(y_true, y_pred, target_names=names, digits=6))\n\n # if y_probas gave, make sure each sample has at least 1 label\n if y_probas is not None:\n for i, row in enumerate(y_pred):\n if sum(row) < 1:\n row[y_probas[i].argmax()] = 1\n\n print(\"details after fill non result with argmax:\\n\")\n print(classification_report(y_true, y_pred, target_names=names, digits=6))\n\n # pred[pred < threshold] = 2\n # pred[pred < 2] = 0\n # tp, fp, fn = 0, 0, 0\n # for i in range(pred.shape[0]):\n # no_result = 1\n # for j in range(pred.shape[1]):\n # if true[i][j] > 1 and pred[i][j] > 1: # both == 2\n # continue\n # if true[i][j] == pred[i][j]: # true == pred, correctly predicted\n # tp += 1\n # if pred[i][j] < 2:\n # no_result = 0\n # fp += 1\n # if true[i][j] < 2:\n # fn += 1\n # fp += no_result\n #\n # fn -= tp\n # fp -= tp\n #\n # print(tp, fp, fn, tp + fn)\n # recall = tp / (tp + fn)\n # precision = tp / (tp + fp)\n # micro_f1 = 2 * recall * precision / (recall + precision)\n # print(\"metrics on validation set: \\n recall = %f, precision = %f, micro_f1 = %f\\n\"\n # % (recall, precision, micro_f1))\n\n\ndef init_clfs():\n \"\"\" init classifiers to train\n\n Returns:\n dict, clfs\n\n \"\"\"\n clfs = dict()\n # clfs['xgb'] = XGBClassifier(n_jobs=-1)\n clfs['lsvc'] = LinearSVC()\n return clfs\n\n\ndef validate(pkl_url=None, cv=5, evaluating=False):\n \"\"\" do validating\n\n Args:\n pkl_url: load data from pickle file, set to None to generate data instantly\n cv: do cross validation or not\n evaluating: whether to do evaluating on test_gold\n\n \"\"\"\n clfs = init_clfs()\n val_url = from_project_root(\"data/preliminary/test_gold_ex.csv\")\n if pkl_url is not None:\n # load from pickle\n print(\"loading data from\", pkl_url)\n X, y, X_val = joblib.load(pkl_url)\n else:\n train_url = from_project_root(\"data/preliminary/train_ex.csv\")\n # generate from original csv\n X, y, X_val = generate_vectors(train_url, val_url, column='article', max_n=3, min_df=3, max_df=0.8,\n max_features=20000, trans_type='dc', sublinear_tf=True, balanced=True,\n multilabel_out=False, label_col='subjects', only_single=True, shuffle=True)\n\n print(\"data shapes:\\n\", X.shape, y.shape, X_val.shape)\n for name, clf in clfs.items():\n if len(y.shape) > 1:\n clf = OneVsRestClassifier(clf)\n print(\"cross validation on %s is running\" % name)\n validate_clf(clf, X, y, cv=5, scoring='f1_micro')\n if evaluating:\n print(\"metrics of %s classifier:\" % name)\n clf.fit(X, y)\n y_true = pd.read_csv(val_url, usecols=list(map(str, range(10)))).values < 2\n y_pred = clf.predict(X_val)\n y_probas = predict_proba(clf, X_val)\n calc_metrics(y_true, y_pred, y_probas)\n\n\ndef gen_10bi_result(train_url, test_url, validating=False, evaluating=False):\n \"\"\"\n\n Args:\n train_url: url of csv train data\n test_url: url of csv test data\n validating: whether to do validating\n evaluating: whether to do evaluating on test_gold\n\n Returns:\n stacked probabilities of belonging to each subjects\n\n \"\"\"\n tdf = pd.read_csv(test_url)['content_id']\n n_samples = len(tdf)\n y_probas = np.empty(shape=(n_samples, 0))\n y_pred = np.empty(shape=(n_samples, 0), dtype=int)\n for col in range(10):\n # X, y, X_test = generate_vectors(train_url, test_url, column='article', max_n=3, min_df=3, max_df=0.8,\n # max_features=30000, trans_type='dc', sublinear_tf=True, balanced=True,\n # multilabel_out=False, label_col='subjects', only_single=False, shuffle=True,\n # apply_fun=lambda label: str(col) in label)\n X, y, X_test = joblib.load(from_project_root(\"data/vector/stacked_all_XyX_val_32_%d.pk\" % col))\n clf = LinearSVC()\n print(\"running on subject %s\" % id2sub(col))\n if validating:\n validate_clf(clf, X, y, scoring='f1')\n clf.fit(X, y)\n proba = predict_proba(clf, X_test)[:, 1:2]\n y_probas = np.hstack((y_probas, proba))\n y_pred = np.hstack((y_pred, clf.predict(X_test).reshape(-1, 1)))\n\n if evaluating:\n y_true = pd.read_csv(test_url, usecols=list(map(str, range(10)))).values < 2\n calc_metrics(y_true, y_pred, y_probas)\n return y_pred, y_probas\n\n\ndef gen_multi_result(X, y, X_test):\n \"\"\" generate multilabel result use ovr classifier\n\n Args:\n X: (n_samples, n_features)\n y: (n_samples,) or (n_samples, n_labels)\n X_test: (n_samples, n_features)\n\n Returns:\n y_pred: (n_samples, n_labels)\n y_probas: (n_samples, n_labels)\n\n \"\"\"\n clf = OneVsRestClassifier(LogisticRegression(solver='liblinear'))\n # clf = OneVsRestClassifier(LinearSVCP())\n # clf = OneVsRestClassifier(XGBClassifier())\n if len(y.shape) == 1:\n y = MultiLabelBinarizer().fit([range(10)]).transform(y.reshape(-1, 1))\n clf.fit(X, y)\n y_pred = clf.predict(X_test)\n y_probas = clf.predict_proba(X_test)\n return y_pred, y_probas\n\n\ndef generate_result(evaluating=False, use_n_subjects='pred', senti_url=None):\n \"\"\" generate result\n\n Args:\n evaluating: evaluating use preliminary data\n use_n_subjects: use n_subjects info, 'gold', 'pred' or 'one'\n url to sentiment result\n\n \"\"\"\n train_url = from_project_root(\"data/train_2_ex.csv\")\n test_url = from_project_root(\"data/test_public_2v3_ex.csv\")\n senti = None\n if evaluating:\n train_url = from_project_root(\"data/preliminary/train_ex.csv\")\n test_url = from_project_root(\"data/preliminary/test_gold_ex.csv\")\n senti = joblib.load(senti_url) if senti_url else None\n\n X, y, X_test = generate_vectors(train_url, test_url, column='article', max_n=3, min_df=3, max_df=0.8,\n max_features=20000, trans_type='hashing', sublinear_tf=True, balanced=True,\n multilabel_out=False, label_col='subjects', only_single=True, shuffle=True)\n X, y, X_test = joblib.load(from_project_root('data/vector/stacked_one_XyX_val_32_subjects.pk'))\n\n clf = LinearSVC()\n clf.fit(X, y)\n # pred, probas = clf.predict(X_test), predict_proba(clf, X_test)\n pred, probas = gen_10bi_result(train_url, test_url, validating=True, evaluating=True)\n # pred, probas = gen_multi_result(X, y, X_test)\n result_df = pd.DataFrame(columns=[\"content_id\", \"subject\", \"sentiment_value\", \"sentiment_word\"])\n cids = pd.read_csv(test_url, usecols=['content_id']).values.ravel()\n for i, cid in enumerate(cids):\n k = 1\n if use_n_subjects == 'gold':\n cid_list = pd.read_csv(from_project_root('data/submit_example_2.csv'))['content_id'].tolist()\n k = cid_list.count(cid)\n elif use_n_subjects == 'pred':\n k = max(1, pred[i].sum())\n for j in probas[i].argsort()[-k:]:\n senti_val = 0 if senti is None else senti[i]\n result_df = result_df.append({'content_id': cid, 'subject': id2sub(j), 'sentiment_value': senti_val},\n ignore_index=True)\n\n save_url = from_project_root('data/result/tmp.csv')\n result_df.to_csv(save_url, index=False)\n if evaluating:\n y_true = pd.read_csv(test_url, usecols=list(map(str, range(10)))).values < 2\n calc_metrics(y_true, pred, probas)\n print(\"metrics on %s subjects: \" % use_n_subjects)\n evaluate(save_url, use_senti=False)\n evaluate(save_url, use_senti=True)\n\n\ndef gen_senti_result(pkl_url):\n X, y, X_test = joblib.load(pkl_url)\n clf = XGBClassifier()\n clf.fit(X, y)\n senti = clf.predict(X_test)\n joblib.dump(senti, pkl_url.replace('.pk', '.xgb.result.pk'))\n\n\ndef main():\n # pkl_url = from_project_root(\"data/vector/stacked_one_XyX_val_32_sentiment.pk\")\n # validate(pkl_url=None)\n generate_result(evaluating=True, use_n_subjects='pred')\n # gen_senti_result(pkl_url)\n pass\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"csJd/bdci_sentiment_2018","sub_path":"bow_model/classifiers.py","file_name":"classifiers.py","file_ext":"py","file_size_in_byte":10880,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"40061329192","text":"import matplotlib.pyplot as plt\nimport os\nfrom typing import List, Dict, Any\nimport numpy as np\nimport bbox_visualizer as bbv\nimport seaborn as sns\nfrom pathlib import Path\n\ndef visualize_distribution(y: list, mapping: dict, save_dir: str, filename: str, ylabel: str):\n\n x = []\n for i in mapping.keys():\n x.append(mapping[i])\n\n fig = plt.figure(figsize=(25,5))\n ax = fig.add_subplot(1,1,1)\n\n r_y = [np.round(item, decimals=2) for item in y]\n\n sns.barplot(x=x, y=y, palette=\"Blues_d\", ax=ax)\n ax.bar_label(ax.containers[0], labels=r_y, padding=3)\n Path(save_dir).mkdir(parents=True, exist_ok=True)\n ax.set_ylabel(ylabel)\n ax.set_xlabel('Classes')\n plt.savefig(os.path.join(save_dir, filename))\n\ndef draw_bounding_boxes(img: np.array, boxes: np.array, mapping: Dict=None, labels: List[int]=None, scores: List[float]=None, color: Any = (255, 255, 255)):\n\n vis_boxes = []\n boxes = boxes.astype(int)\n if len(boxes.shape) == 2:\n for i in range(boxes.shape[0]):\n vis_boxes.append(boxes[i, :].tolist())\n \n if len(vis_boxes):\n img = bbv.draw_multiple_rectangles(img, vis_boxes, bbox_color=color)\n\n class_labels = None\n\n if labels is not None and mapping is not None:\n class_labels = [mapping[i] for i in labels]\n\n if scores is not None:\n class_labels = [f'{item}: {np.round(scores[i]*100, decimals=1)}%' for i, item in enumerate(class_labels)]\n\n if class_labels is not None:\n img = bbv.add_multiple_labels(img, class_labels, vis_boxes, top=False, text_bg_color=color)\n\n return img","repo_name":"FraunhoferIKS/smf-object-detection","sub_path":"src/tools/visualization.py","file_name":"visualization.py","file_ext":"py","file_size_in_byte":1619,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"42617248913","text":"import random\nimport turtle\nimport math\nimport matplotlib.pyplot as plt\n\nmyPen = turtle.Turtle()\nmyPen.hideturtle()\nmyPen.speed(0)\nr = 100 # radius of circle (and half side length of square because circle inscribed)\n\n# Square with side length 2*r\nmyPen.up()\nmyPen.setposition(-r,-r)\nmyPen.down()\nmyPen.fd(2*r)\nmyPen.left(90)\nmyPen.fd(2*r)\nmyPen.left(90)\nmyPen.fd(2*r)\nmyPen.left(90)\nmyPen.fd(2*r)\nmyPen.left(90)\n\n# Cirlce with radius, r\nmyPen.up()\nmyPen.setposition(0,-r)\nmyPen.down()\nmyPen.circle(r)\n\ndef monteCarlo(n):\n in_circle = 0\n out_circle = 0\n pi_values,error = [],[]\n for i in range(n):\n # generating random coordinate point inside square\n x = random.randrange(-100,100)\n y = random.randrange(-100,100)\n\n # if less than radius away from center --> is in circle --> plot black point\n if(x**2+y**2>100**2):\n myPen.color(\"black\")\n myPen.up()\n myPen.goto(x,y)\n myPen.down()\n myPen.dot()\n out_circle += 1\n \n # else plot red point\n else:\n myPen.color(\"red\")\n myPen.up()\n myPen.goto(x,y)\n myPen.down()\n myPen.dot()\n in_circle += 1\n\n # deriving value of pi from area estimates\n square_area_estimate = in_circle+out_circle\n circle_area_estimate = in_circle\n pi = 4.0 * circle_area_estimate / square_area_estimate\n pi_values.append(pi)\n\n # calculating difference between estimate and actual value\n error.append(math.pi - pi)\n\n return [pi_values,error]\n\nresults = monteCarlo(1000)\n\n#plotting results\nplt.figure(dpi=200)\nplt.axhline(y=math.pi,color='red',linestyle='dashed')\nplt.plot(results[0])\nplt.xlabel('Iterations')\nplt.ylabel('Pi')\nplt.savefig('pi_estimate.png')\n\n#plotting error\nplt.figure(dpi=200)\nplt.axhline(y=0,color='red',linestyle='dashed')\nplt.plot(results[1])\nplt.xlabel('Iterations')\nplt.ylabel('Error')\nplt.savefig('pi_error.png')","repo_name":"etweisberg/monte-carlo","sub_path":"ethan/turtle_pi.py","file_name":"turtle_pi.py","file_ext":"py","file_size_in_byte":1997,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"806358187","text":"import time\n\nimport requests\nimport os\nfrom dotenv import dotenv_values\n\n\nimport platform\n\nif platform.system() == 'Windows':\n from idm import IDMan\n\n\n# TODO\n# Set connection speed\n# Create a folder for each live ?\n# User can change time.sleep for each process\n\n\n\n# User Part\ndef GetFileSizeByUrl(url):\n response = requests.head(url)\n content_length = response.headers.get('Content-Length')\n if content_length:\n size_in_bytes = int(content_length)\n print(f\"Url file size : {size_in_bytes} bytes\")\n return size_in_bytes\n else:\n print(\"File size could not be determined.\")\n return 0\n\n\ndef GetFileSizeByPath(file_path):\n if os.path.isfile(file_path):\n file_size = os.path.getsize(file_path)\n size_in_bytes = file_size\n return size_in_bytes\n else:\n print(\"Checking for downloaded file...\")\n time.sleep(45)\n return 0\n\n\ndef WaitForDownload(url):\n urlFileSize = GetFileSizeByUrl(url)\n global pathFileSize\n pathFileSize = GetFileSizeByPath(file_path)\n\n if (urlFileSize == 0):\n WaitForDownload()\n\n while True:\n if (urlFileSize != 0 and pathFileSize != 0):\n print(\"Download completed.\")\n time.sleep(5)\n break\n else:\n pathFileSize = GetFileSizeByPath(file_path)\n continue\n\n\ndef Download_With_IDM(url):\n time.sleep(5)\n downloader = IDMan()\n print(f\"Saving in {file_path}\")\n downloader.download(url, rf\"{file_path_to_save}\", f'{filename}', referrer=None, cookie=None,\n postData=None, user=None, password=None, confirm=False, lflag='Test', clip=False)\n if (WaitForDownload(url)):\n print(\"Download finished starting new download ...\")\n time.sleep(10)\n # else:\n # time.sleep(5)\n # WaitForDownload(url)\n\n\ndef Download_With_Request(url):\n chunk_size = 8192 # Adjust the chunk size as per your requirements\n max_retries = 3\n for attempt in range(1, max_retries + 1):\n try:\n response = requests.get(url, stream=True)\n response.raise_for_status()\n\n with open(file_path, 'wb') as file:\n for chunk in response.iter_content(chunk_size=chunk_size):\n file.write(chunk)\n\n print(\"File downloaded successfully!\")\n break # Exit the loop if the download is successful\n except requests.exceptions.RequestException as e:\n print(f\"Error: {e}\")\n if attempt < max_retries:\n print(f\"Retrying download... (Attempt {attempt + 1})\")\n time.sleep(1) # Pause for 1 second before the next attempt\n except IOError as e:\n print(f\"IOError: {e}\")\n break # Exit the loop if there's an IOError\n\n\n# Server Part\ndef RemoveVideo(key):\n url = 'https://dl-api.voorivex.academy/video/remove'\n\n payload = {\n 'key': f'{key}'\n }\n\n response = requests.post(url, headers=headers, json=payload)\n\n if (response.status_code == 201):\n print(\"Removing previous video...\")\n time.sleep(5)\n # print(response.text)\n else:\n print(\"Something went wrong !\")\n\n\ndef CreateVideo(key):\n\n url = 'https://dl-api.voorivex.academy/video/ganerate'\n\n payload = {\n 'key': f'{key}'\n }\n\n response = requests.post(url, headers=headers, json=payload)\n\n if (response.status_code == 201):\n print(f\"Creating {key} video ...\")\n time.sleep(5)\n return True\n # print(response.text)\n elif (response.status_code == 400):\n print(\"You have another video!\")\n return False\n # DownloadVideo(key)\n # CreateVideo()\n\n\ndef GetVideoLink():\n url = 'https://dl-api.voorivex.academy/video/getActiveLink'\n\n response = requests.get(url, headers=headers)\n\n if (response.status_code == 200):\n result = response.json()\n if (result['type'] == 'pending'):\n print(\"Waiting for video link...\")\n time.sleep(10)\n return None, None\n elif (result['type'] == 'active'):\n if (len(result['videos']) != 0):\n videoUrl = result['videos'][0]['url']\n key = result['videos'][0]['key']\n return videoUrl, key\n else:\n print(\"There is no video!\")\n return None, None\n\n\ndef DownloadVideo(key):\n print(\"Start...\")\n videoLink, fileToRemove = GetVideoLink()\n if (videoLink != None):\n RemoveVideo(fileToRemove)\n time.sleep(7)\n result = CreateVideo(key)\n if (result):\n while True:\n download_link, key = GetVideoLink()\n if (download_link != None):\n print('Download link is ', download_link)\n if (download_method == 'idm'):\n Download_With_IDM(download_link)\n elif (download_method == 'default'):\n Download_With_Request(download_link)\n break\n else:\n continue\n # else:\n # DownloadVideo(key)\n\n\n# User input\ndef select_folder():\n folder_path = input(\"Please enter the folder path: \")\n\n # Validate the folder path\n while not os.path.isdir(folder_path):\n print(\"Invalid folder path. Please try again.\")\n folder_path = input(\"Please enter the folder path: \")\n\n # print(\"Selected folder path:\", folder_path)\n return folder_path\n\n\ndef select_bearer():\n config = dotenv_values(\".env\")\n bearer_token = config[\"bearer_token\"]\n if (bearer_token == ''):\n print(\"Please add your bearer token in .env\")\n exit(1)\n return bearer_token\n\n\ndef select_download_method():\n method = input(\n \"Choose the download method:\\n1. Default method\\n2. Use IDM\\nEnter your choice (1 or 2): \")\n if method == \"1\":\n # use constants here\n return 'default'\n elif method == \"2\":\n # use constants here\n return 'idm'\n else:\n print(\"Invalid input. Please choose 1 or 2.\")\n select_download_method()\n\ndef select_key():\n key_path = input(\n \"Which movies you want to download ? (Look at Lives-Keys folder) :\")\n \n # Validate the key path\n while not os.path.exists(key_path):\n print(\"Invalid folder path. Please try again.\")\n key_path = input(\"Which movies you want to download ? (Ta-lives , Yashar-lives , Last-stand-lives) : \")\n\n return key_path\n\n\n\ndef main():\n global file_path\n global filename\n global headers\n global file_path_to_save\n global download_method\n\n file_path_to_save = select_folder()\n bearer_token = select_bearer()\n download_method = select_download_method()\n key_path = select_key()\n \n\n headers = {\n 'Host': 'dl-api.voorivex.academy',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/113.0',\n 'Accept': 'application/json, text/plain, */*',\n 'Content-Type': 'application/json',\n 'Authorization': f'Bearer {bearer_token}'\n }\n\n with open(key_path, '+r') as file:\n lines = file.readlines()\n for key in lines:\n filename = key.strip().split('/')[-1]\n file_path = file_path_to_save + '/' + filename\n if (os.path.exists(file_path)):\n print(\"This file exist \", file_path)\n continue\n else:\n print(\"Downloading new file \", key)\n DownloadVideo(key.strip())\n\n\n# The download process has completed at this point\nif __name__ == \"__main__\":\n main()\n","repo_name":"maverick0o0/Voorivex-Academy-Downloader","sub_path":"voorivex-downloader.py","file_name":"voorivex-downloader.py","file_ext":"py","file_size_in_byte":7585,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"} +{"seq_id":"11931334847","text":"def find_averages_of_subarrays(size: int, arr: list) -> list:\r\n result = list()\r\n window_start: int = 0\r\n window_sum: float = 0.0\r\n for window_end in range(len(arr)):\r\n window_sum += arr[window_end]\r\n if window_end >= size - 1:\r\n result.append(window_sum / size)\r\n window_sum -= arr[window_start]\r\n window_start += 1\r\n return result\r\n\r\n\r\ndef main() -> None:\r\n result: list = find_averages_of_subarrays(5, [1, 3, 2, 6, -1, 4, 1, 8, 2])\r\n print(f'Average of subarrays of given size ({5}) is {result}')\r\n\r\n\r\nmain()\r\n","repo_name":"alekswonder/coding_practice","sub_path":"algorithmic_patterns/sliding_window/1_find_averages_of_subarrays.py","file_name":"1_find_averages_of_subarrays.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25546215704","text":"import unittest\nfrom .parser import parse_lines, parse_program_line, parse_program, \\\n ProgramLine, CommentLine, \\\n parse_blocks, ProgramSyntaxError, \\\n BlockFunction, BlockRoot, \\\n CommandTurn, CommandTimeFromStart, CommandTimeJump, CommandFunctionCall, Function\nfrom ..constants import RuntimeParameters\n\n\nCODE_SAMPLE_INDENTATION_ERROR = \"\"\"\ndef main():\n right(A, to=12, speed=1)\n \n # Another comment\n 0:06 \n left(A, to=6, speed=4)\n left(B, to=6, speed=4)\n \ndef test(X):\n left(X, to=1, time=2)\n\n\"\"\"\n\n\nCODE_SAMPLE_1 = \"\"\"\n# One comment\ndef main():\n right(A, to=12, speed=1)\n \n # Another comment\n 0:06 \n left(A, to=6, speed=4)\n left(B, to=6, speed=4)\n \ndef test(X):\n left(X, to=1, time=2)\n\n0:00\nmain()\ntest(A)\n\n1:00\ntest(B)\n\"\"\"\n\n\nCODE_SAMPLE_2 = \"\"\"\n# One comment\ndef main():\n right(A, to=12, speed=1)\n \n # Another comment\n 0:06 \n left(A, to=6, speed=4)\n left(B, to=6, speed=4)\n \ndef test(X):\n left(X, to=1, speed=2)\n\n0:00\nmain()\ntest(A)\n\n1:00\ntest(B)\n\"\"\"\n\n\nFUNCTION_AT_BOTTOM = \"\"\"\n# Start at second 2\n0:02\nright(A, to=12, speed=1)\n\n# Wait 3 seconds\n+0:03\nleft(A, to=1, speed=3)\n\n# Wait 5 seconds\n+0:05\nsay_no(A)\n\n# This is a function\ndef say_no(X):\n right(X, to=5, speed=3)\n right(X, to=1, speed=3)\n\ndef say_no_again(X):\n right(X, to=5, speed=3)\n right(X, to=1, speed=3)\n\"\"\"\n\n\nFUNCTION_WITHOUT_BODY = \"\"\"\ndef func_a(X):\ndef func_b(X):\n right(X, to=1, speed=3)\n \nfunc_a()\n\"\"\"\n\nFUNCTION_WITH_STOP = \"\"\"\nright(A, speed=1)\nstop(A)\nrestart_program()\n\"\"\"\n\n\nclass ParserTestSuite(unittest.TestCase):\n def setUp(self):\n self.local_variables = ('A', 'B')\n self.runtime_parameters = RuntimeParameters(64, 5)\n\n def test_indentation_error(self):\n errors = []\n list(parse_lines(CODE_SAMPLE_INDENTATION_ERROR, errors))\n self.assertEqual(errors, [\n ProgramSyntaxError(line_num=3, message='Indentation must be multiple of 4 characters'),\n ProgramSyntaxError(line_num=8, message='Indentation must be multiple of 4 characters'),\n ])\n\n def test_parsing_lines(self):\n errors = []\n lines = list(parse_lines(CODE_SAMPLE_1, errors))\n self.assertEqual(errors, [])\n self.assertEqual(lines, [\n CommentLine(text='# One comment', indentation=0, line_num=2),\n ProgramLine(text='def main():', indentation=0, line_num=3),\n ProgramLine(text='right(A, to=12, speed=1)', indentation=1, line_num=4),\n CommentLine(text='# Another comment', indentation=1, line_num=6),\n ProgramLine(text='0:06', indentation=1, line_num=7),\n ProgramLine(text='left(A, to=6, speed=4)', indentation=1, line_num=8),\n ProgramLine(text='left(B, to=6, speed=4)', indentation=1, line_num=9),\n ProgramLine(text='def test(X):', indentation=0, line_num=11),\n ProgramLine(text='left(X, to=1, time=2)', indentation=1, line_num=12),\n ProgramLine(text='0:00', indentation=0, line_num=14),\n ProgramLine(text='main()', indentation=0, line_num=15),\n ProgramLine(text='test(A)', indentation=0, line_num=16),\n ProgramLine(text='1:00', indentation=0, line_num=18),\n ProgramLine(text='test(B)', indentation=0, line_num=19),\n ])\n\n def test_parsing_blocks(self):\n errors = []\n blocks = list(parse_blocks(CODE_SAMPLE_2, errors))\n self.assertEqual(errors, [])\n self.assertEqual(blocks, [\n BlockFunction(name='main', parameter=None, lines=[\n ProgramLine(text='right(A, to=12, speed=1)', indentation=1, line_num=4),\n ProgramLine(text='0:06', indentation=1, line_num=7),\n ProgramLine(text='left(A, to=6, speed=4)', indentation=1, line_num=8),\n ProgramLine(text='left(B, to=6, speed=4)', indentation=1, line_num=9)\n ]),\n BlockFunction(name='test', parameter='X', lines=[\n ProgramLine(text='left(X, to=1, speed=2)', indentation=1, line_num=12)\n ]),\n BlockRoot(lines=[\n ProgramLine(text='0:00', indentation=0, line_num=14),\n ProgramLine(text='main()', indentation=0, line_num=15),\n ProgramLine(text='test(A)', indentation=0, line_num=16),\n ProgramLine(text='1:00', indentation=0, line_num=18),\n ProgramLine(text='test(B)', indentation=0, line_num=19)\n ])\n ])\n\n def test_parsing_command_right(self):\n errors = []\n command = parse_program_line(ProgramLine(text='right(A, to=12, speed=1)', indentation=1, line_num=4), {}, self.local_variables, self.runtime_parameters, errors)\n self.assertEqual(errors, [])\n self.assertEqual(command, CommandTurn(direction='right', target='A', to=12, speed=1))\n\n def test_parsing_command_left(self):\n errors = []\n command = parse_program_line(ProgramLine(text='left(A, to=12, speed=1)', indentation=1, line_num=4), {}, self.local_variables, self.runtime_parameters, errors)\n self.assertEqual(errors, [])\n self.assertEqual(command, CommandTurn(direction='left', target='A', to=12, speed=1))\n\n def test_parsing_command_left_with_local_var(self):\n errors = []\n command = parse_program_line(ProgramLine(text='left(X, to=12, speed=1)', indentation=1, line_num=4), {}, self.local_variables + ('X',), self.runtime_parameters, errors)\n self.assertEqual(errors, [])\n self.assertEqual(command, CommandTurn(direction='left', target='X', to=12, speed=1))\n\n def test_parsing_function_call(self):\n errors = []\n command = parse_program_line(ProgramLine(text='foo(A)', indentation=1, line_num=4), {'foo'}, self.local_variables, self.runtime_parameters, errors)\n self.assertEqual(errors, [])\n self.assertEqual(command, CommandFunctionCall(function_name='foo', params=('A',)))\n\n def test_parsing_command_time_from_start(self):\n errors = []\n command = parse_program_line(ProgramLine(text='0:03', indentation=1, line_num=4), {}, self.local_variables, self.runtime_parameters, errors)\n self.assertEqual(errors, [])\n self.assertEqual(command, CommandTimeFromStart(millis=3000))\n\n def test_parsing_command_time_jump(self):\n errors = []\n command = parse_program_line(ProgramLine(text='+1:03', indentation=1, line_num=4), {}, self.local_variables, self.runtime_parameters, errors)\n self.assertEqual(errors, [])\n self.assertEqual(command, CommandTimeJump(millis=63000))\n\n def test_parsing_program(self):\n errors = []\n commands, functions = parse_program(CODE_SAMPLE_2, self.local_variables, self.runtime_parameters, errors)\n self.assertEqual(errors, [])\n self.assertEqual(commands, [\n CommandTimeFromStart(millis=0),\n CommandFunctionCall(function_name='main', params=()),\n CommandFunctionCall(function_name='test', params=('A',)),\n CommandTimeFromStart(millis=60000),\n CommandFunctionCall(function_name='test', params=('B',))\n ])\n self.assertEqual(functions, {\n 'main': Function(parameter=None, commands=[\n CommandTurn(direction='right', target='A', to=12, speed=1),\n CommandTimeFromStart(millis=6000),\n CommandTurn(direction='left', target='A', to=6, speed=4),\n CommandTurn(direction='left', target='B', to=6, speed=4)\n ]),\n 'test': Function(parameter='X', commands=[\n CommandTurn(direction='left', target='X', to=1, speed=2)\n ])\n })\n\n def test_parse_function_at_bottom(self):\n errors = []\n parse_program(FUNCTION_AT_BOTTOM, self.local_variables, self.runtime_parameters, errors)\n self.assertEqual(errors, [])\n\n def test_function_without_body(self):\n errors = []\n parse_program(FUNCTION_WITHOUT_BODY, self.local_variables, self.runtime_parameters, errors)\n self.assertEqual(errors, [ProgramSyntaxError(line_num=3, message='Function without a body')])\n\n def test_parse_function_with_stop(self):\n errors = []\n parse_program(FUNCTION_WITH_STOP, self.local_variables, self.runtime_parameters, errors)\n self.assertEqual(errors, [])\n\n def test_parse_empty_program(self):\n errors = []\n parse_program('', self.local_variables, self.runtime_parameters, errors)\n self.assertEqual(errors, [])\n","repo_name":"stefanomasini/boost","sub_path":"src/boost/language/parser_tests.py","file_name":"parser_tests.py","file_ext":"py","file_size_in_byte":8529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28321219622","text":"import numpy as np\n \nR = int(input(\"Enter the number of rows:\"))\nC = int(input(\"Enter the number of columns:\"))\nmatrix1 = list(map(int, input().split()))\nmatrix2 = list(map(int, input().split()))\n\nvalue1 = np.array(matrix1).reshape(R, C)\nvalue2 = np.array(matrix2).reshape(R, C)\nprint(value1,value2)\nd=np.dot(value1,value2)\nprint(\"Dot product of matrix is\",d )\n","repo_name":"Meenu-Balagopal/Data-Science-Lab","sub_path":"Program2.1.py","file_name":"Program2.1.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14986427025","text":"\nLANDING_PAGE_ACCEPT_AND_CONTINUE=\"同意して予約する\"\nl_name=\"お名前\"\nl_people=\"人\"\nl_note=\"備考\"\nl_adult=\"大人\"\nl_children=\"子供\"\nl_take=\"上記で予約する\"\nl_update=\"情報の更新\"\nl_data_update=\"情報が更新されました\"\nl_number=\"番号\"\nl_alert_name_null=\"名前をご記入してください\"\nl_alert_adult_zero=\"子供のみの利用はできません\"\nl_seat_assigned=\"Seat is assigned\"\nn_number_prefix=\"あなたの番号は\"\nn_number_suffix=\"番です。\"\nn_do_lineup=\"先に席を確保をお願い致します。\"\nn_wait_seat=\"席が確定するまで少々お待ちください。\"\nn_food_add=\"をカートに追加されました。\"\nc_add=\"カートに入れる\"\nc_name=\"カート\"\nc_place=\"注文\"\no_delete=\"削除\"\no_empty=\"ご注文がありません\"\no_seat=\"席\"\no_hi=\"お客様\"\no_orders=\"注文履歴\"\no_split=\"お会計を割り勘しますか?\"\no_title=\"ご注文\"\no_people=\"人分\"\no_delivered=\"提供済み\"\no_preparing=\"準備中\"\no_subtotal=\"小計:\"\no_service=\"サービス料\"\no_tax=\"消費税\"\no_total=\"合計\"\nt_got=\"戻る\"\nt_tittle=\"Menyのご利用規約について\"\nt_content=\"※引き続きサービスを利用するには、ご利用規約に同意していただく必要があります。\"\nt_button=\"同意して予約する\"\nt_footer=\"利用規約\"\n\ndef hello_japan():\n return 'hello_japan'\n","repo_name":"LynkedKK/QA_test_scripts","sub_path":"tests/lang/jp.py","file_name":"jp.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"ja","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"40327822043","text":"texto = 'entrando...' #para iterar sobre essa string é preciso:\n\ni = 0 #criar um índice\nnovo_texto = ''\n\nwhile i < len(texto):# então criar um laço de repetição onde\\\n #enquanto o índice for menor que 'tamanho_string':\n letra = texto[i] #letra recebe texto e índice\n novo_texto += letra #então é criada uma variável junto com += pra que print na horizontal\n i += 1 #item obrigatório\nprint(novo_texto)#mostrar a string que nesse caso é 'texto' mais a letra\\\n#mais a letra que queres mostrar que nesse caso é o índice\\\n#se print estiver com espaços mostra na vertical\n\n\n\nsenha_salva = '1234'\nsenha_digitada = ''\nrepeticoes = 0\n\nwhile senha_digitada != senha_salva: #enquanto senha_digitada for diferente de senha_salva:\n senha_digitada = input('sua senha({repeticoes}x)')#mostra quantas senhas foram digitadas\n\n if senha_digitada != senha_salva:\n print('senha inválida')\n \n if senha_digitada == senha_salva:\n print('bem_vindo')\n break\n\n repeticoes += 1\n\n print(repeticoes)# pode virar um loop infinito","repo_name":"WadeMcfild/Python","sub_path":"Python_basic/34.iteracao.py","file_name":"34.iteracao.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14549990584","text":"import io\nfrom bs4 import BeautifulSoup\nimport requests\nfrom tqdm import tqdm\n'''\nThis module allows you to download articles from pikabu.ru\n'''\n\nPIKABU_DATE = \"https://pikabu.ru/search?d={}&D={}&page={}\"\nPATH = \"data\"\nFILENAME = \"\\pikabu{}.html\"\n\nheaders = {\n \"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 \"\n \"(KHTML, like Gecko) Chrome/80.0.3987.132 YaBrowser/20.3.1.197 Yowser/2.5 Safari/537.36\"\n}\n\nif __name__ == \"__main__\":\n\n page_range = range(1, 15)\n # date_rage = range(2500, 4482)\n\n date_rage = range(3512, 4200)\n\n for d in tqdm(date_rage):\n for p in page_range:\n r = requests.get(PIKABU_DATE.format(d, d, p), headers=headers)\n soup = BeautifulSoup(r.text, \"lxml\")\n articles = soup.findChildren(\"article\")\n for i, article in enumerate(articles):\n file_name = PATH + FILENAME.format(\"_{}_{}_{}\".format(d, p, i))\n with io.open(file_name, \"w\", encoding=\"utf-8\") as f:\n f.write(str(article))\n f.close()\n","repo_name":"SabinaAlieva/InformationRetrieval","sub_path":"src/data/downloader.py","file_name":"downloader.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31268461715","text":"import snscrape.modules.twitter as sntwitter\nimport pandas as pd\nimport openpyxl\nimport xlsxwriter\n\n\nquery =\"(from:elonmusk) until:2021-07-20 since:2021-01-17\"\ntweets=[]\nlimit =100\n\nfor tweet in sntwitter.TwitterSearchScraper(query).get_items():\n\n # print(vars(tweet))\n # break\n if len(tweets)== limit:\n break\n else:\n tweets.append([tweet.user.username,tweet.content])\n\ndf=pd.DataFrame(tweets, columns=['User','Tweet'])\n\nprint(df)\nprint(\"-------------Converting into xlsx file----------\")\ndf.to_excel(r'C:\\Users\\icom\\Desktop\\newfile.xlsx', index=False)","repo_name":"ihjasdev/research-implementation","sub_path":"tweets.py","file_name":"tweets.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32822071137","text":"# _*_ coding:utf-8 _*_\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n# Import TensorFlow >= 1.10 and enable eager execution\nimport re\nimport os\nimport sys\nimport time\nimport random\nimport numpy as np\nimport tensorflow as tf\nlayers = tf.keras.layers\ntf.enable_eager_execution()\n\nprint(tf.__version__)\n\nabspath = os.path.dirname(os.path.realpath(__file__))\nabspath = os.path.abspath(abspath)\n\nsys.path.append(abspath)\nsys.path.append(os.path.join(abspath, '../utils'))\nfrom Logger import logger\nfrom Encoder import *\nfrom TransferUtils import *\n\n\nclass DecoderLayer(tf.keras.Model):\n def __init__(self, d_model, num_heads, dff, rate=0.1):\n super(DecoderLayer, self).__init__()\n\n self.mha1 = MultiHeadAttention(d_model, num_heads)\n self.mha2 = MultiHeadAttention(d_model, num_heads)\n\n self.ffn = point_wise_feed_forward_network(d_model, dff)\n\n self.layernorm1 = tf.keras.layers.BatchNormalization()\n self.layernorm2 = tf.keras.layers.BatchNormalization()\n self.layernorm3 = tf.keras.layers.BatchNormalization()\n\n #self.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-6)\n #self.layernorm2 = tf.keras.layers.LayerNormalization(epsilon=1e-6)\n #self.layernorm3 = tf.keras.layers.LayerNormalization(epsilon=1e-6)\n\n self.dropout1 = tf.keras.layers.Dropout(rate)\n self.dropout2 = tf.keras.layers.Dropout(rate)\n self.dropout3 = tf.keras.layers.Dropout(rate)\n\n def call(self, x, enc_output, training, look_ahead_mask, padding_mask):\n\n # enc_output.shape == (batch_size, input_seq_len, d_model)\n\n attn1, attn_weights_block1 = self.mha1(x, x, x, look_ahead_mask) # (batch_size, target_seq_len, d_model)\n attn1 = self.dropout1(attn1, training=training)\n out1 = self.layernorm1(attn1 + x)\n\n attn2, attn_weights_block2 = self.mha2(\n enc_output, enc_output, out1, padding_mask) # (batch_size, target_seq_len, d_model)\n attn2 = self.dropout2(attn2, training=training)\n out2 = self.layernorm2(attn2 + out1) # (batch_size, target_seq_len, d_model)\n\n ffn_output = self.ffn(out2) # (batch_size, target_seq_len, d_model)\n ffn_output = self.dropout3(ffn_output, training=training)\n out3 = self.layernorm3(ffn_output + out2) # (batch_size, target_seq_len, d_model)\n\n return out3, attn_weights_block1, attn_weights_block2\n\n\nclass Decoder(tf.keras.Model):\n def __init__(self,\n num_layers,\n vocab_size,\n d_model,\n num_heads,\n dff,\n sos_id=0,\n eos_id=1,\n max_length=250,\n rate=0.1):\n super(Decoder, self).__init__()\n self.sos_id = sos_id\n self.eos_id = eos_id\n self.d_model = d_model\n self.num_layers = num_layers\n\n self.embedding = tf.keras.layers.Embedding(vocab_size, d_model)\n self.pos_encoding = positional_encoding(max_length, self.d_model)\n self.dec_layers = [DecoderLayer(d_model, num_heads, dff, rate) for _ in range(num_layers)]\n self.dropout = tf.keras.layers.Dropout(rate)\n\n def call(self, x, enc_output, training, look_ahead_mask, padding_mask):\n seq_len = tf.shape(x)[1]\n attention_weights = {}\n\n x = self.embedding(x) # (batch_size, target_seq_len, d_model)\n x *= tf.math.sqrt(tf.cast(self.d_model, tf.float32))\n x += self.pos_encoding[:, :seq_len, :]\n\n x = self.dropout(x, training=training)\n\n for i in range(self.num_layers):\n x, block1, block2 = self.dec_layers[i](x, enc_output, training,\n look_ahead_mask, padding_mask)\n\n attention_weights['decoder_layer{}_block1'.format(i + 1)] = block1\n attention_weights['decoder_layer{}_block2'.format(i + 1)] = block2\n\n # x.shape == (batch_size, target_seq_len, d_model)\n return x, attention_weights\n\n\nif __name__ == '__main__':\n\n import numpy as np\n batch_size = 6\n image_width = 32\n image_height = 64\n image_channel = 3\n data = np.random.random((batch_size, image_height, image_width, image_channel))\n widths = [2, 4, 6, 8, 10, 12]\n data = tf.convert_to_tensor(data, dtype=tf.float32)\n\n vocab_size = 8\n num_layers = 2\n sos_id = 0\n eos_id = 1\n d_model = 512\n num_heads = 4\n dff = 1024\n rate = 0.1\n used_rnn = False\n max_width = 1600\n max_length = 256\n\n ecnoder = Encoder(used_rnn=False)\n features, weight_mask = ecnoder(data, widths, True)\n print(\"features shape: {}\".format(features.shape))\n print(\"weight shape: {}\".format(weight_mask.shape))\n\n decoder = Decoder(num_layers,\n vocab_size,\n d_model,\n num_heads,\n dff,\n sos_id,\n eos_id,\n max_length,\n rate=0.1)\n\n padding_len = 10\n target_inputs = []\n target_lengths = []\n for b in range(batch_size):\n target = [sos_id]\n valid_len = random.choice(range(2, padding_len-2))\n target_lengths.append(valid_len+2)\n for i in range(valid_len):\n target.append(random.choice(range(2, vocab_size)))\n for i in range(len(target), padding_len):\n target.append(eos_id)\n target_inputs.append(target)\n\n target_inputs = tf.convert_to_tensor(target_inputs, dtype=tf.int32)\n target_lengths = tf.convert_to_tensor(target_lengths, dtype=tf.int32)\n\n print(\"target_inputs shape: {}\".format(target_inputs.shape))\n print(\"target_lengths shape: {}\".format(target_lengths.shape))\n\n target_mask = tf.sequence_mask(target_lengths, padding_len, dtype=tf.float32)\n print(\"target_mask shape: {}\".format(target_mask.shape))\n\n look_ahead_mask = tf.sequence_mask(tf.range(1, padding_len + 1), padding_len, dtype=tf.float32)\n print(\"look_ahead_mask shape {}\".format(look_ahead_mask.shape))\n\n padding_mask = tf.matmul(tf.expand_dims(target_mask, -1),\n tf.expand_dims(weight_mask, -1), transpose_b=True)\n padding_mask = tf.expand_dims(1.0-padding_mask, axis=1)\n print(\"padding_mask.shape {}\".format(padding_mask.shape))\n look_ahead_mask = 1.0-look_ahead_mask\n x, attentions = decoder(target_inputs, features, True, look_ahead_mask, padding_mask)\n\n print(\"x shape: {}\".format(x.shape))\n print(\"attentions keys: {}\".format(attentions.keys()))\n\n\n '''\n inputs = tf.convert_to_tensor(np.random.random((12, 36, 36, 55)), dtype=tf.float32)\n layer_inst = LayerNormalization(55)\n outputs = layer_inst(inputs)\n print(\"outputs shape: {}\".format(outputs.shape))\n sample_encoder_layer = EncoderLayer(512, 8, 2048)\n sample_encoder_layer_output = sample_encoder_layer(\n tf.random.uniform((64, 43, 512)), False, None)\n\n print(\"sample_encoder_layer_output shape {}\".format(sample_encoder_layer_output.shape))\n sample_decoder_layer = DecoderLayer(512, 8, 2048)\n sample_decoder_layer_output, _, _ = sample_decoder_layer(\n tf.random.uniform((64, 50, 512)), sample_encoder_layer_output,\n False, None, None)\n print(\"sample_decoder_layer_output shape: {}\".format(sample_decoder_layer_output.shape))\n '''\n\n\n\n\n\n","repo_name":"attendfov/att_ctc_tf2","sub_path":"transformer/Decoder.py","file_name":"Decoder.py","file_ext":"py","file_size_in_byte":7398,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"8589448234","text":"from __future__ import annotations\n\nimport json\nimport random\nimport string\nimport time\nimport uuid\nfrom dataclasses import dataclass\nfrom datetime import datetime\nfrom os import PathLike\nfrom sys import maxsize\nfrom typing import TYPE_CHECKING, Iterator, List, Optional, cast\n\nfrom grapl_common.env_helpers import S3ClientFactory, SQSClientFactory\nfrom python_proto.pipeline import Envelope, Metadata\n\nif TYPE_CHECKING:\n from mypy_boto3_s3 import S3Client\n from mypy_boto3_sqs import SQSClient\n\nimport boto3\nimport zstd # type: ignore\n\n\ndef rand_str(l: int) -> str:\n return \"\".join(\n random.choice(string.ascii_uppercase + string.digits) for _ in range(l)\n )\n\n\ndef into_sqs_message(bucket: str, key: str) -> str:\n return json.dumps(\n {\n \"Records\": [\n {\n \"awsRegion\": \"us-east-1\",\n \"eventTime\": datetime.utcnow().isoformat(),\n \"principalId\": {\n \"principalId\": None,\n },\n \"requestParameters\": {\n \"sourceIpAddress\": None,\n },\n \"responseElements\": {},\n \"s3\": {\n \"schemaVersion\": None,\n \"configurationId\": None,\n \"bucket\": {\n \"name\": bucket,\n \"ownerIdentity\": {\n \"principalId\": None,\n },\n },\n \"object\": {\n \"key\": key,\n \"size\": 0,\n \"urlDecodedKey\": None,\n \"versionId\": None,\n \"eTag\": None,\n \"sequencer\": None,\n },\n },\n }\n ]\n }\n )\n\n\n@dataclass\nclass GeneratorOptions:\n bucket: str\n queue_url: str\n key_infix: str\n\n def encode_chunk(self, input: List[bytes]) -> bytes:\n raise NotImplementedError()\n\n\nclass SysmonGeneratorOptions(GeneratorOptions):\n def __init__(self, bucket: str, queue_url: str) -> None:\n super().__init__(\n queue_url=queue_url,\n bucket=bucket,\n key_infix=\"sysmon\",\n )\n\n def encode_chunk(self, input: List[bytes]) -> bytes:\n # zstd encoded line delineated xml\n return cast(bytes, zstd.compress(b\"\\n\".join(input).replace(b\"\\n\\n\", b\"\\n\"), 4))\n\n\nclass OSQueryGeneratorOptions(GeneratorOptions):\n def __init__(self, bucket: str, queue_url: str) -> None:\n super().__init__(\n queue_url=queue_url,\n bucket=bucket,\n key_infix=\"osquery\",\n )\n\n def encode_chunk(self, input: List[bytes]) -> bytes:\n # zstd encoded line delineated xml\n return cast(bytes, zstd.compress(b\"\\n\".join(input).replace(b\"\\n\\n\", b\"\\n\"), 4))\n\n\ndef upload_logs(\n deployment_name: str,\n logfile: PathLike,\n generator_options: GeneratorOptions,\n delay: int = 0,\n batch_size: Optional[int] = 100,\n s3_client: Optional[S3Client] = None,\n sqs_client: Optional[SQSClient] = None,\n) -> None:\n \"\"\"\n set `batch_size` to None to disable batching\n \"\"\"\n print(\n f\"Writing events to {deployment_name} with {delay} seconds between batches of {batch_size}\"\n )\n\n # Ugly hack to cheaply disable batching\n batch_size = batch_size if batch_size is not None else maxsize\n requires_manual_eventing = deployment_name == \"local-grapl\"\n s3 = s3_client or S3ClientFactory(boto3).from_env()\n sqs = sqs_client or SQSClientFactory(boto3).from_env()\n\n with open(logfile, \"rb\") as b:\n body = b.readlines()\n body = [line for line in body]\n\n def chunker(seq: List[bytes], size: int) -> Iterator[List[bytes]]:\n return (seq[pos : pos + size] for pos in range(0, len(seq), size))\n\n bucket = generator_options.bucket\n queue_url = generator_options.queue_url\n\n chunk_count = 0\n for chunk in chunker(body, batch_size):\n chunk_count += 1\n chunk_body = generator_options.encode_chunk(chunk)\n epoch = int(time.time())\n\n key = (\n str(epoch - (epoch % (24 * 60 * 60)))\n + f\"/{generator_options.key_infix}/\"\n + str(epoch)\n + rand_str(6)\n )\n envelope = Envelope(\n metadata=Metadata(\n tenant_id=uuid.uuid4(), # FIXME: be smarter here.\n trace_id=uuid.uuid4(), # FIXME: and here.\n ),\n inner_message=chunk_body,\n inner_type=\"RawEvents\",\n )\n\n s3.put_object(Body=envelope.serialize(), Bucket=bucket, Key=key)\n\n # local-grapl relies on manual eventing\n if requires_manual_eventing:\n sqs.send_message(\n QueueUrl=queue_url,\n MessageBody=into_sqs_message(bucket=bucket, key=key),\n )\n\n time.sleep(delay)\n\n print(f\"Completed uploading {chunk_count} chunks at {time.ctime()}\")\n\n\ndef upload_sysmon_logs(\n deployment_name: str,\n logfile: PathLike,\n log_bucket: str,\n queue_url: str,\n delay: int = 0,\n batch_size: int = 100,\n s3_client: Optional[S3Client] = None,\n sqs_client: Optional[SQSClient] = None,\n) -> None:\n\n upload_logs(\n deployment_name=deployment_name,\n logfile=logfile,\n generator_options=SysmonGeneratorOptions(\n bucket=log_bucket, queue_url=queue_url\n ),\n delay=delay,\n batch_size=batch_size,\n s3_client=s3_client,\n sqs_client=sqs_client,\n )\n\n\ndef upload_osquery_logs(\n deployment_name: str,\n logfile: PathLike,\n log_bucket: str,\n queue_url: str,\n delay: int = 0,\n batch_size: int = 100,\n s3_client: Optional[S3Client] = None,\n sqs_client: Optional[SQSClient] = None,\n) -> None:\n upload_logs(\n deployment_name=deployment_name,\n logfile=logfile,\n generator_options=OSQueryGeneratorOptions(\n bucket=log_bucket, queue_url=queue_url\n ),\n delay=delay,\n batch_size=batch_size,\n s3_client=s3_client,\n sqs_client=sqs_client,\n )\n","repo_name":"macasieb/grapl","sub_path":"src/python/grapl-tests-common/grapl_tests_common/upload_logs.py","file_name":"upload_logs.py","file_ext":"py","file_size_in_byte":6263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"14100938204","text":"import unittest\nfrom io import BytesIO, StringIO, UnsupportedOperation\nfrom tempfile import NamedTemporaryFile, TemporaryFile\n\nfrom pyoxigraph import Literal, NamedNode, Quad, Triple, parse, serialize\n\nEXAMPLE_TRIPLE = Triple(\n NamedNode(\"http://example.com/foo\"),\n NamedNode(\"http://example.com/p\"),\n Literal(\"éù\"),\n)\nEXAMPLE_QUAD = Quad(\n NamedNode(\"http://example.com/foo\"),\n NamedNode(\"http://example.com/p\"),\n Literal(\"1\"),\n NamedNode(\"http://example.com/g\"),\n)\n\n\nclass TestParse(unittest.TestCase):\n def test_parse_file(self) -> None:\n with NamedTemporaryFile() as fp:\n fp.write('

    \"éù\" .'.encode())\n fp.flush()\n self.assertEqual(\n list(parse(fp.name, \"text/turtle\", base_iri=\"http://example.com/\")),\n [EXAMPLE_TRIPLE],\n )\n\n def test_parse_not_existing_file(self) -> None:\n with self.assertRaises(IOError) as _:\n parse(\"/tmp/not-existing-oxigraph-file.ttl\", \"text/turtle\")\n\n def test_parse_str_io(self) -> None:\n self.assertEqual(\n list(\n parse(\n StringIO('

    \"éù\" .'),\n \"text/turtle\",\n base_iri=\"http://example.com/\",\n )\n ),\n [EXAMPLE_TRIPLE],\n )\n\n def test_parse_long_str_io(self) -> None:\n self.assertEqual(\n list(\n parse(\n StringIO('

    \"éù\" .\\n' * 1024),\n \"text/turtle\",\n base_iri=\"http://example.com/\",\n )\n ),\n [EXAMPLE_TRIPLE] * 1024,\n )\n\n def test_parse_bytes_io(self) -> None:\n self.assertEqual(\n list(\n parse(\n BytesIO('

    \"éù\" .'.encode()),\n \"text/turtle\",\n base_iri=\"http://example.com/\",\n )\n ),\n [EXAMPLE_TRIPLE],\n )\n\n def test_parse_io_error(self) -> None:\n with self.assertRaises(UnsupportedOperation) as _, TemporaryFile(\"wb\") as fp:\n list(parse(fp, mime_type=\"application/n-triples\"))\n\n def test_parse_quad(self) -> None:\n self.assertEqual(\n list(\n parse(\n StringIO(' {

    \"1\" }'),\n \"application/trig\",\n base_iri=\"http://example.com/\",\n )\n ),\n [EXAMPLE_QUAD],\n )\n\n\nclass TestSerialize(unittest.TestCase):\n def test_serialize_to_bytes_io(self) -> None:\n output = BytesIO()\n serialize([EXAMPLE_TRIPLE], output, \"text/turtle\")\n self.assertEqual(\n output.getvalue().decode(),\n ' \"éù\" .\\n',\n )\n\n def test_serialize_to_file(self) -> None:\n with NamedTemporaryFile() as fp:\n serialize([EXAMPLE_TRIPLE], fp.name, \"text/turtle\")\n self.assertEqual(\n fp.read().decode(),\n ' \"éù\" .\\n',\n )\n\n def test_serialize_io_error(self) -> None:\n with self.assertRaises(UnsupportedOperation) as _, TemporaryFile(\"rb\") as fp:\n serialize([EXAMPLE_TRIPLE], fp, \"text/turtle\")\n\n def test_serialize_quad(self) -> None:\n output = BytesIO()\n serialize([EXAMPLE_QUAD], output, \"application/trig\")\n self.assertEqual(\n output.getvalue(),\n b' { \"1\" }\\n',\n )\n","repo_name":"oxigraph/oxigraph","sub_path":"python/tests/test_io.py","file_name":"test_io.py","file_ext":"py","file_size_in_byte":3657,"program_lang":"python","lang":"en","doc_type":"code","stars":843,"dataset":"github-code","pt":"48"} +{"seq_id":"37272549699","text":"#!/usr/bin/env python3\n\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimport numpy as np\n\n# This file contain utilities to open images, show them with imshow and resize an array\n\ndef openImage(filename):\n img = Image.open(filename).convert('L')\n return img / np.max(img)\n\ndef show(img):\n if type(img) is Image.Image:\n img = np.array(img)\n plt.imshow(img, cmap='gray')\n\ndef resize(myImg):\n if type(myImg) is np.ndarray:\n myImg = Image.fromarray(myImg)\n return np.array(myImg.resize((int(myImg.width/2), int(myImg.height/2)), Image.ANTIALIAS))\n\nif __name__ == '__main__':\n img = openImage('Lenna.jpg')\n \n plt.plot([1,3])\n\n plt.subplot(1, 3, 1)\n show(img)\n\n plt.subplot(1, 3, 2)\n img = resize(img)\n show(img)\n\n plt.subplot(1, 3, 3)\n img = resize(img)\n show(img.rotate(10))\n\n plt.show()","repo_name":"brunob45/INF8725","sub_path":"projet/imgproc.py","file_name":"imgproc.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42792300516","text":"from fastapi import Depends, FastAPI, HTTPException, Query, Request, Response, status\nfrom fastapi.responses import HTMLResponse, RedirectResponse\nfrom fastapi.security import APIKeyCookie\nfrom fief_client import FiefAsync, FiefUserInfo\nfrom fief_client.integrations.fastapi import FiefAuth\n\n\nclass CustomFiefAuth(FiefAuth): # (1)!\n client: FiefAsync\n\n async def get_unauthorized_response(self, request: Request, response: Response):\n redirect_uri = request.url_for(\"auth_callback\") # (2)!\n auth_url = await self.client.auth_url(redirect_uri, scope=[\"openid\"]) # (3)!\n raise HTTPException(\n status_code=status.HTTP_307_TEMPORARY_REDIRECT, # (4)!\n headers={\"Location\": str(auth_url)},\n )\n\n\nfief = FiefAsync( # (5)!\n \"https://example.fief.dev\",\n \"YOUR_CLIENT_ID\",\n \"YOUR_CLIENT_SECRET\",\n)\n\nSESSION_COOKIE_NAME = \"user_session\"\nscheme = APIKeyCookie(name=SESSION_COOKIE_NAME, auto_error=False) # (6)!\nauth = CustomFiefAuth(fief, scheme) # (7)!\napp = FastAPI()\n\n\n@app.get(\"/auth-callback\", name=\"auth_callback\") # (8)!\nasync def auth_callback(request: Request, response: Response, code: str = Query(...)):\n redirect_uri = request.url_for(\"auth_callback\")\n tokens, _ = await fief.auth_callback(code, redirect_uri) # (9)!\n\n response = RedirectResponse(request.url_for(\"protected\")) # (10)!\n response.set_cookie( # (11)!\n SESSION_COOKIE_NAME,\n tokens[\"access_token\"],\n max_age=tokens[\"expires_in\"],\n httponly=True, # (12)!\n secure=False, # ❌ Set this to `True` in production (13)!\n )\n\n return response\n\n\n@app.get(\"/protected\", name=\"protected\")\nasync def protected(\n user: FiefUserInfo = Depends(auth.current_user()), # (14)!\n):\n return HTMLResponse(\n f\"

    You are authenticated. Your user email is {user['email']}

    \"\n )\n","repo_name":"fief-dev/docs","sub_path":"examples/python/fastapi/web.py","file_name":"web.py","file_ext":"py","file_size_in_byte":1868,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"4589504390","text":"#! /usr/bin/python3\nimport os\nimport csv\nimport numpy as np\nfrom glob import glob\n\nTEST_FILE_PATH = '/Users/cindyshao/Dropbox/ME599/project/rob535-fall-2019-task-1-image-classification/data-2019/test'\nOUTPUT_PATH = os.path.dirname(os.path.abspath(__file__))\n\n\ndef write_dummy_labels(test_file_path, output_path):\n \"\"\"Create dummy label for test samples, just for initial submit.\"\"\"\n files = glob('{}/*/*_cloud.bin'.format(test_file_path))\n files.sort()\n output_file = '{}/test_nolabels.csv'.format(output_path)\n with open(output_file, 'w') as f:\n writer = csv.writer(f, delimiter=',', lineterminator='\\n')\n writer.writerow(['guid/image', 'label'])\n\n for file in files:\n guid = file.split('/')[-2]\n idx = file.split('/')[-1].replace('_cloud.bin', '')\n label = 0\n\n writer.writerow(['{}/{}'.format(guid, idx), label])\n\n print('Wrote report file `{}`'.format(output_file))\n\n\nif __name__ == '__main__':\n for test_file_path in [TEST_FILE_PATH]:\n write_dummy_labels(test_file_path, OUTPUT_PATH)\n","repo_name":"cindyshao/selfdrive","sub_path":"pretrained/process_testdata.py","file_name":"process_testdata.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13805968866","text":"from django.db import transaction\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.utils.dateparse import datetime_re\nfrom rest_framework.serializers import ValidationError\n\nfrom waldur_mastermind.marketplace import processors\nfrom waldur_mastermind.marketplace import models as marketplace_models\n\nfrom .utils import TimePeriod, is_interval_in_schedules\n\n\nclass BookingCreateProcessor(processors.BaseOrderItemProcessor):\n def process_order_item(self, user):\n with transaction.atomic():\n resource = marketplace_models.Resource(\n project=self.order_item.order.project,\n offering=self.order_item.offering,\n plan=self.order_item.plan,\n limits=self.order_item.limits,\n attributes=self.order_item.attributes,\n name=self.order_item.attributes.get('name') or '',\n state=marketplace_models.Resource.States.OK,\n )\n resource.init_cost()\n resource.save()\n resource.init_quotas()\n self.order_item.resource = resource\n self.order_item.save(update_fields=['resource'])\n\n def validate_order_item(self, request):\n schedules = self.order_item.attributes.get('schedules')\n\n # We check that the schedule is set.\n if not schedules:\n raise ValidationError(_('Schedules are required.'))\n\n if not len(schedules):\n raise ValidationError(_('Schedules are required.'))\n\n for period in schedules:\n try:\n start = period['start']\n end = period['end']\n except KeyError:\n raise ValidationError(_('Key \\'start\\' or \\'end\\' does not exist in schedules item.'))\n\n for value in [start, end]:\n match = datetime_re.match(value)\n kw = match.groupdict()\n if list(filter(lambda x: not kw[x], ['hour', 'month', 'second', 'year', 'tzinfo', 'day', 'minute'])):\n raise ValidationError(_('The value %s does not match the format.') % value)\n\n # Check that the schedule is available for the offering.\n offering = self.order_item.offering\n offering_schedules = offering.attributes.get('schedules', [])\n\n for period in schedules:\n if not is_interval_in_schedules(TimePeriod(period['start'], period['end']),\n [TimePeriod(i['start'], i['end']) for i in offering_schedules]):\n raise ValidationError(_('Time period from %s to %s is not available for selected offering.') %\n (period['start'], period['end']))\n\n # Check that there are no other bookings.\n bookings = []\n\n for resource in marketplace_models.Resource.objects.filter(offering=offering,\n state=marketplace_models.Resource.States.OK):\n for period in resource.attributes.get('schedules', []):\n bookings.append(TimePeriod(period['start'], period['end']))\n\n for period in schedules:\n if is_interval_in_schedules(TimePeriod(period['start'], period['end']), bookings):\n raise ValidationError(_('Time period from %s to %s is not available.') %\n (period['start'], period['end']))\n\n\nclass BookingDeleteProcessor(processors.DeleteResourceProcessor):\n pass\n","repo_name":"vasim-rana/waldur-mastermind","sub_path":"src/waldur_mastermind/booking/processors.py","file_name":"processors.py","file_ext":"py","file_size_in_byte":3486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"6830104839","text":"import os\n\nimport src.rsgis.vector.create_crosssection_line as gm\n\nfrom src.logger import logging, project_dir\n\n\ndef main():\n infc = os.path.join(project_dir, \"artifacts\", \"data\",\n \"sample_drainage_lines.shp\")\n # generate perpendicular line at specific interval\n outfc = os.path.join(project_dir, \"test\", \"result\",\n \"out_cross_section.shp\")\n gm.construct_perpendicular_line(\n infc, outfc=outfc, interval=1000, offset=250, coordsys='GCS')\n gm.create_xscl_uniqueid(xscl_available=True, infc=infc, outfc=outfc,\n uidfield=\"UID\", interval=1000, offset=250, coordsys='GCS')\n","repo_name":"dghorai83/rsgis-scripts","sub_path":"test/generate_xscl.py","file_name":"generate_xscl.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"30084304885","text":"#%%\nfrom agent_model import agent_journal\nimport matplotlib.pyplot as plt\n\nmodel = agent_journal.UnivModel(100, 5, 100, class_periods=3, class_size=10, majors=True)\nfor _ in range(model.class_periods):\n model.step()\n\nplt.imshow(model.contactjournal)\n#sns.set_context(\"talk\")\nplt.xlabel(\"Agent ID\")\nplt.ylabel(\"Agent ID\")\nplt.title(\"Agent Contact Counts\")\nplt.colorbar()\nplt.savefig(\"figures/figure2\")\n\n# %%\n","repo_name":"clairevalva/mcrn_multi_DA","sub_path":"multiscale_1.0/eli_plotting.py","file_name":"eli_plotting.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5006139522","text":"import random\n\n# A closely wounded solenoid of n turns and area of cross-section carries a current of i A. What is its associated magnetic moment. \n\nqns = open('./questions.txt', 'w')\nans = open('./answers.txt','w')\n\nno_of_samples = 500000\n\ndef cal1(n, i, A) :\n return n*i*A\n\ndef type1() :\n n = random.randint(1,50)\n n = n*20\n i = random.randint(1,100)\n A = random.randint(1,200)\n A = round(A*0.0001,4)\n q = \"A closely wounded solenoid of \" + str(n) + \" turns and area of cross-section \" + str(A) + \" m2 carries current of \" + str(i) + \" A. What is its associated magnetic moment.\\n\"\n a = \"{:.2e}\".format(cal1(n, i, A)) + \" joule/tesla\\n\"\n return q,a\n\nfor i in range(no_of_samples):\n ques, answer = type1()\n qns.write(ques)\n ans.write(answer)\n\nqns.close()\nans.close()\n","repo_name":"misterpawan/scimat2","sub_path":"science/MagnetismAndMatter/MagneticMomentSolenoid/MagneticMomentSolenoid.py","file_name":"MagneticMomentSolenoid.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"37252156747","text":"from flask import Blueprint, render_template, redirect, Response, make_response, jsonify\nfrom flask_login import login_required\nfrom flask_api import status\nfrom app.models import Project, Topic, db\nfrom app.forms import TopicForm\nfrom app.schemas import topics_schema\nimport json\n\n# Define the blueprint: 'topic', set its url prefix: app.url /topics\nbp = Blueprint('topic', __name__, url_prefix='/topics')\n\n\n@bp.route('/json/', methods=['GET'])\n@login_required\ndef topics_json(project_id):\n project = Project.query.get_or_404(project_id)\n topics = topics_schema.dump(project.topics)\n for topic in topics:\n m_topic = Topic.query.get_or_404(topic['id'])\n topic['text'] = str(m_topic)\n return make_response(jsonify({\"topics\": topics}))\n\n\n@bp.route('/new/', methods=['GET', 'POST'])\n@login_required\ndef create_topic(project_id):\n \"\"\"\n Allows user to creates a new topic.\n \"\"\"\n project = Project.query.get_or_404(project_id)\n form = TopicForm()\n if form.validate_on_submit():\n topic = Topic(name=form.name.data, project=project)\n\n if form.parent.data:\n parent = Topic.query.get_or_404(form.parent.data)\n topic.parent = parent\n\n db.session.add(topic)\n db.session.commit()\n return redirect('/projects/{}/topics'.format(project.name))\n \n if form.errors:\n return render_template('topics/new_topic.html', project=project, form=form), status.HTTP_303_SEE_OTHER\n\n return render_template('topics/new_topic.html', project=project, form=form)\n\n\n@bp.route('/subtopics/', methods=['GET'])\n@login_required\ndef get_subtopics(id):\n topic = Topic.query.get_or_404(id)\n subtopics = Topic.query.filter_by(parent=topic)\n subtopics = topics_schema.dump(subtopics)\n return make_response(jsonify({\"subtopics\": subtopics}))\n\n\n@bp.route('/', methods=['DELETE'])\n@login_required\ndef delete_topics(id):\n \"\"\"\n Allows user to delete an existing subscription.\n \"\"\"\n topic = Topic.query.get_or_404(id)\n if topic.parent is None:\n return Response(\"No se puede eliminar.\", status=status.HTTP_303_SEE_OTHER)\n\n subtopics = Topic.query.filter_by(parent=topic)\n for subtopic in subtopics:\n db.session.delete(subtopic)\n\n db.session.delete(topic)\n db.session.commit()\n return Response(status=status.HTTP_200_OK)\n","repo_name":"GRGarcia066/flask_monitor","sub_path":"app/routes/topics.py","file_name":"topics.py","file_ext":"py","file_size_in_byte":2394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16037345384","text":"from gensim import corpora\nimport jieba\nimport pickle\nimport os\n\n# 首先将文本处理生成dictionary和corpus。\n# dictionary是词典,包含词以及词在词典中对应的位置。\n# corpus将文本存贮成(词在词典中位置,词频)这种形式,每个文本为一行。\n\n\ndef gen_dict_corpus(raw_documents):\n\n # 分词处理\n corpora_documents = [list(jieba.cut(item_text)) for item_text in raw_documents]\n\n # 词典,以(词,词频)方式存储\n dictionary = corpora.Dictionary(corpora_documents)\n\n # 词库,以(id,词频)方式存储\n corpus = [dictionary.doc2bow(text) for text in corpora_documents]\n\n return dictionary, corpus\n\n\ndef dump_data(raw_docs, dictionary_path, corpus_path):\n\n if raw_docs:\n\n dictionary, corpus = gen_dict_corpus(raw_docs)\n\n with open(dictionary_path, 'wb') as f1:\n pickle.dump(dictionary, f1)\n\n with open(corpus_path, 'wb') as f2:\n pickle.dump(corpus, f2)\n\n\ndef read_file(file_path):\n with open(file_path, 'r', encoding='utf-8') as f:\n data = f.readlines()\n return data\n\n\ndef write_file(content, file_path):\n with open(file_path, 'w', encoding='utf-8') as f:\n f.writelines(content)\n\n","repo_name":"JunfengDuan/text-similarity","sub_path":"algorithm_library/gen_dict.py","file_name":"gen_dict.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"48"} +{"seq_id":"27142265192","text":"def find_crossroads(input):\n rowsDict = {}\n columnsDict = {}\n cross_roads = []\n\n \n for point in input:\n row = point[0]\n column = point[1]\n \n #count and increment recurring longitude and latitude values\n rowsDict[row] = rowsDict[row] + 1 if(row in rowsDict.keys()) else 1\n columnsDict[column] = columnsDict[column] + 1 if(column in columnsDict.keys()) else 1\n \n #find and return intersections \n for _row in rowsDict:\n if(rowsDict[_row] > 1):\n for _column in columnsDict:\n if(columnsDict[_column] > 1):\n cross_roads.append(tuple((_row,_column)))\n else:\n continue\n else: \n continue\n\n return cross_roads\n\n","repo_name":"codeconnector/CodingDojo","sub_path":"challenges/2022-08-09-critter-crossing/solutions/python/Moses-Alero/critterCrossing.py","file_name":"critterCrossing.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","stars":68,"dataset":"github-code","pt":"48"} +{"seq_id":"15207262571","text":"__author__ = 'Anand Patil, anand.prabhakar.patil@gmail.com'\n\nfrom pymc import *\n\ndef find_generations(stochastics):\n \"\"\"\n A generation is the set of stochastic variables that only has parents in\n previous generations.\n \"\"\"\n\n generations = []\n\n # Find root generation\n generations.append(set())\n all_children = set()\n\n for s in stochastics:\n all_children.update(s.extended_children & stochastics)\n generations[0] = stochastics - all_children\n\n # Find subsequent _generations\n children_remaining = True\n gen_num = 0\n while children_remaining:\n gen_num += 1\n\n\n # Find children of last generation\n generations.append(set())\n for s in generations[gen_num-1]:\n generations[gen_num].update(s.extended_children & stochastics)\n\n\n # Take away stochastics that have parents in the current generation.\n thisgen_children = set()\n for s in generations[gen_num]:\n thisgen_children.update(s.extended_children & stochastics)\n generations[gen_num] -= thisgen_children\n\n\n # Stop when no subsequent _generations remain\n if len(thisgen_children) == 0:\n children_remaining = False\n return generations\n\n\ndef ravel_submodel(stochastic_list):\n \"\"\"\n Takes a list of stochastics and returns:\n - Indices corresponding to each,\n - Length of each,\n - Slices corresponding to each,\n - Total length,\n\n \"\"\"\n\n N_stochastics = len(stochastic_list)\n stochastic_indices = []\n stochastic_len = np.zeros(N_stochastics, dtype=int)\n slices = np.zeros(N_stochastics, dtype=object)\n\n _len = 0\n for i in xrange(len(stochastic_list)):\n\n stochastic = stochastic_list[i]\n\n # Inspect shapes of all stochastics and create stochastic slices.\n if isinstance(stochastic.value, np.ndarray):\n stochastic_len[i] = len(np.ravel(stochastic.value))\n else:\n stochastic_len[i] = 1\n slices[i] = slice(_len, _len + stochastic_len[i])\n _len += stochastic_len[i]\n\n # Record indices that correspond to each stochastic.\n for j in xrange(len(np.ravel(stochastic.value))):\n stochastic_indices.append((stochastic, j))\n\n return stochastic_indices, stochastic_len, slices, _len\n\ndef set_ravelled_stochastic_values(vec, stochastics, slices):\n for stochastic in stochastics:\n stochastic.value = vec[slices[stochastic]].reshape(np.shape(stochastic.value))\n\ndef find_children_and_parents(stochastic_list):\n children = []\n parents = []\n for s in stochastic_list:\n if len(s.extended_children) > 0:\n if all([not child in stochastic_list for child in s.extended_children]):\n children.append(s)\n if all([not parent in stochastic_list for parent in s.extended_parents]):\n parents.append(s)\n\n return set(children), set(parents)\n\ndef order_stochastic_list(stochastics):\n\n generations = find_generations(stochastics)\n out = []\n for generation in generations[::-1]:\n out += list(generation)\n return out\n","repo_name":"matthew-brett/pymc","sub_path":"pymc/sandbox/graphical_utils.py","file_name":"graphical_utils.py","file_ext":"py","file_size_in_byte":3112,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"48"} +{"seq_id":"10432189625","text":"print(\"Program pobierze kolejne liczby i poda ich wartosc srednia i mediane, aby zakonczyc napisz 'end'\")\n\nnumbers = []\n\nwhile(True):\n\n item = input(\"Wprowadz liczbe: \")\n\n if item == \"end\":\n break\n\n try:\n number = int(item)\n numbers.append(number)\n except ValueError:\n print(\"Blad!\")\n\nn = len(numbers)\n\nif n == 0:\n exit()\n\nnumbers.sort(key=int)\n\nnumbersSum = 0\n\nfor number in numbers:\n numbersSum += number\n\nprint(\"\\nSrednia: \" + str(numbersSum/len(numbers)))\n\nif n % 2 == 0:\n a = n//2\n b = a+1\n median = (numbers[a-1]+numbers[b-1])/2\n\nelse:\n median = numbers[n//2 - 1]\n\nprint(\"Mediana: \" + str(median))","repo_name":"irekkosek/jezyki-skryptowe","sub_path":"python/zadania/pyth-67-100/zad81.py","file_name":"zad81.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74997802066","text":"##\n## Programación con Pandas\n## ===========================================================================\n##\n## Imprima el promedio de la _c2 por cada letra de la _c1 \n## del archivo `tbl0.tsv`.\n## \n## Rta/\n## _c1\n## A 4.625000\n## B 5.142857\n## C 5.400000\n## D 3.833333\n## E 4.785714\n## Name: _c2, dtype: float64\n##\n## >>> Escriba su codigo a partir de este punto <<<\n##\nimport csv\nimport pandas as pd\nimport os\nimport numpy as np\nos.chdir('/home/ces/courses/evaluacion-del-curso-it-trj/04-pandas=1/q02=1')\ndf = open('tbl0.tsv')\nread = csv.reader(df, delimiter='\\t')\ndfl=[]\nfor row in read:\n dfl.append(row)\ndata = pd.DataFrame(dfl ,columns=dfl[0] )\ndata =data.drop([0])\ndata['_c2']= data['_c2'].astype(float)\nh=data.groupby('_c1')\nh=h['_c2'].agg(['mean'])\nind = h.index\nserie = pd.Series(h['mean'])\nserie.name = '_c2'\nprint(serie)\n","repo_name":"it-ces/pythonbasiico-pandas","sub_path":"04-pandas=1/q02=1/question.py","file_name":"question.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13978588790","text":"def solution(nums, target):\n\n sort_nums = sorted(nums)\n\n answer = []\n\n x1 = 0\n x2 = 1\n\n while x1 < len(nums) and x2 < len(nums):\n print(x1, x2)\n\n if nums[x1] + nums[x2] == target:\n answer.append(x1)\n answer.append(x2)\n elif nums[x1] + nums[x2] > target:\n x1 += 1\n x2 = x1\n \n x2 += 1\n\n if x2 == len(nums):\n x1 += 1\n x2 = x1 + 1\n \n return answer\n\n\nprint( solution([2, 7, 11, 15], 26) )\n","repo_name":"minsung8/algorithmProblem_Exercise","sub_path":"two_sum.py","file_name":"two_sum.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22536584520","text":"\"\"\"\nTestYourResourceModel API Service Test Suite\n\nTest cases can be run with the following:\n nosetests -v --with-spec --spec-color\n coverage report -m\n\"\"\"\nfrom cgitb import scanvars\nimport os\nimport logging\nfrom random import randint, sample\nfrom unittest import TestCase\nfrom unittest.mock import MagicMock, patch\nfrom tests.factories import ShopcartFactory, ItemFactory\nfrom service.routes import app\nfrom service.models import Shopcart, db\nfrom service.common import status # HTTP Status Codes\n\nDATABASE_URI = os.getenv(\n \"DATABASE_URI\", \"postgresql://postgres:postgres@localhost:5432/postgres\"\n)\n\nBASE_URL = \"/api/shopcarts\"\n\n######################################################################\n# T E S T C A S E S\n######################################################################\n\n\nclass TestShopcartServer(TestCase):\n \"\"\" REST API Server Tests \"\"\"\n\n @classmethod\n def setUpClass(cls):\n \"\"\" This runs once before the entire test suite \"\"\"\n app.config[\"TESTING\"] = True\n app.config[\"DEBUG\"] = False\n app.config[\"SQLALCHEMY_DATABASE_URI\"] = DATABASE_URI\n app.logger.setLevel(logging.CRITICAL)\n Shopcart.init_db(app)\n\n @classmethod\n def tearDownClass(cls):\n \"\"\" This runs once after the entire test suite \"\"\"\n\n def setUp(self):\n \"\"\" This runs before each test \"\"\"\n db.drop_all()\n db.create_all()\n self.client = app.test_client()\n\n def tearDown(self):\n \"\"\" This runs after each test \"\"\"\n db.session.remove()\n\n ######################################################################\n # H E L P E R M E T H O D S\n ######################################################################\n\n def _create_shopcarts(self, count):\n \"\"\" Factory method to create shopcarts in bulk \"\"\"\n shopcarts = []\n for _ in range(count):\n shopcart = ShopcartFactory()\n resp = self.client.post(BASE_URL, json=shopcart.serialize())\n self.assertEqual(\n resp.status_code, status.HTTP_201_CREATED, \"Could not create test Shopcart\"\n )\n new_shopcart = resp.get_json()\n shopcart.id = new_shopcart[\"id\"]\n shopcarts.append(shopcart)\n return shopcarts\n\n def _create_items(self, count):\n \"\"\"Factory method to create items in bulk\"\"\"\n items = []\n for _ in range(count):\n item = ItemFactory()\n items.append(item)\n\n return items\n\n def _create_items(self, count):\n \"\"\" Factory method to create items in bulk \"\"\"\n items = []\n for _ in range(count):\n item = ItemFactory()\n items.append(item)\n return items\n\n ######################################################################\n # P L A C E T E S T C A S E S H E R E\n ######################################################################\n\n def test_index(self):\n \"\"\" It should call the home page \"\"\"\n resp = self.client.get(\"/\")\n self.assertEqual(resp.status_code, status.HTTP_200_OK)\n\n def test_create_shopcart(self):\n \"\"\"It should Create a new Shopcart\"\"\"\n shopcart = ShopcartFactory()\n resp = self.client.post(\n BASE_URL, json=shopcart.serialize(), content_type=\"application/json\"\n )\n self.assertEqual(resp.status_code, status.HTTP_201_CREATED)\n\n # Make sure location header is set\n location = resp.headers.get(\"Location\", None)\n self.assertIsNotNone(location)\n\n # Check the data is correct\n new_shopcart = resp.get_json()\n self.assertEqual(\n new_shopcart[\"customer_id\"], shopcart.customer_id, \"customer_id does not match\")\n\n # Check that the location header was correct by getting it\n resp = self.client.get(location, content_type=\"application/json\")\n self.assertEqual(resp.status_code, status.HTTP_200_OK)\n new_shopcart = resp.get_json()\n self.assertEqual(\n new_shopcart[\"customer_id\"], shopcart.customer_id, \"customer_id does not match\")\n\n resp = self.client.post(BASE_URL, json=shopcart.serialize(), content_type=\"test/html\"\n )\n self.assertEqual(resp.status_code, status.HTTP_415_UNSUPPORTED_MEDIA_TYPE)\n\n resp = self.client.post(BASE_URL, json={\"name\": \"not enough data\"}, content_type=\"application/json\")\n self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)\n\n def test_get_account(self):\n \"\"\"It should Read a single Shopcart\"\"\"\n # get the id of a Shopcart\n shopcart = self._create_shopcarts(1)[0]\n resp = self.client.get(\n f\"{BASE_URL}/{shopcart.id}\", content_type=\"application/json\"\n )\n self.assertEqual(resp.status_code, status.HTTP_200_OK)\n data = resp.get_json()\n self.assertEqual(data[\"id\"], shopcart.id)\n resp = self.client.get(f\"{BASE_URL}/123456\",\n content_type=\"application/json\")\n self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND)\n\n def test_delete_an_item_from_shopcart(self):\n \"\"\"It should delete an item from a shopcart\"\"\"\n shopcart = self._create_shopcarts(1)[0]\n item = self._create_items(1)[0]\n self.client.post(\n f\"{BASE_URL}/{shopcart.id}/items\", json=item.serialize(), content_type=\"application/json\"\n )\n resp = self.client.delete(f\"{BASE_URL}/{shopcart.id}/items/{item.id}\")\n self.assertEqual(resp.status_code, status.HTTP_204_NO_CONTENT)\n resp = self.client.delete(f\"{BASE_URL}/{shopcart.id}/items/{item.id}\")\n self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND)\n\n def test_list_item(self):\n \"\"\"It should list all items in a Shopcart\"\"\"\n # get the id of a Shopcart\n shopcart = self._create_shopcarts(1)[0]\n items = self._create_items(5)\n for item in items:\n shopcart.items.append(item)\n shopcart.create()\n resp = self.client.get(\n f\"{BASE_URL}/{shopcart.id}/items\"\n )\n self.assertEqual(resp.status_code, status.HTTP_200_OK)\n\n data = resp.get_json()\n for (expect_item, retriveved_item) in zip(shopcart.items, data[\"items\"]):\n self.assertEqual(expect_item.serialize(), retriveved_item)\n\n def test_delete_shopcart(self):\n \"\"\"It should Delete a shopcart with a specific ID\"\"\"\n shopcart = self._create_shopcarts(1)[0]\n resp = self.client.delete(\n f\"{BASE_URL}/{shopcart.id}\"\n )\n\n # delete a non-existing shopcart\n self.assertEqual(resp.status_code, status.HTTP_204_NO_CONTENT)\n resp = self.client.delete(\n f\"{BASE_URL}/{shopcart.id}\"\n )\n self.assertEqual(resp.status_code, status.HTTP_204_NO_CONTENT)\n\n def test_list_all_shopcarts(self):\n \"\"\"It should List all existing shopcarts.\"\"\"\n shopcarts = [sc.serialize() for sc in self._create_shopcarts(5)]\n resp = self.client.get(\n f\"{BASE_URL}\"\n )\n resp_dict = resp.get_json()\n\n self.assertEqual(resp_dict, shopcarts)\n\n def test_reset_shopcart(self):\n \"\"\"It should reset a shopcart (clear all items).\"\"\"\n shopcart = self._create_shopcarts(1)[0]\n shopcart.items = self._create_items(randint(0, 10))\n resp = self.client.put(\n f\"{BASE_URL}/{shopcart.id}/reset\"\n )\n resp_dict = resp.get_json()\n\n # check if the list of items is cleared\n self.assertEqual(len(resp_dict[\"items\"]), 0)\n\n # check if the rest of the shopcart info remains the same\n cleared_shopcart = shopcart\n cleared_shopcart.items.clear()\n self.assertEqual(resp_dict, cleared_shopcart.serialize())\n\n # check if the function behaves given that the shopcart does not exist\n shopcart_id = shopcart.id\n resp = self.client.delete(\n f\"{BASE_URL}/{shopcart.id}\"\n )\n resp = self.client.put(\n f\"{BASE_URL}/{shopcart_id}/reset\"\n )\n self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND)\n\n def test_update_shopcart(self):\n \"\"\"It should update a shopcart with JSON content\"\"\"\n\n # Create a fictional shopcart and POST it\n shopcart = self._create_shopcarts(1)[0]\n resp = self.client.post(\n BASE_URL, json=shopcart.serialize(), content_type=\"application/json\"\n )\n\n # Create items and assign them to shopcart.items\n items = self._create_items(randint(1, 5))\n for item in items:\n item.shopcart_id = shopcart.id\n shopcart.items = items\n\n # Update the Shopcart with JSON from shopcart\n resp = self.client.put(\n f\"{BASE_URL}/{shopcart.id}\",\n json=shopcart.serialize(),\n content_type=\"application/json\"\n )\n # Check if successful\n self.assertEqual(resp.status_code, status.HTTP_200_OK)\n self.assertDictEqual(resp.get_json(), shopcart.serialize())\n\n # Update a shopcart with shopcart_id in JSON unmatched\n resp = self.client.put(\n f\"{BASE_URL}/{shopcart.id + randint(2,10)}\",\n json=shopcart.serialize(),\n content_type=\"application/json\"\n )\n self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)\n\n # Update a non-existing shopcart\n shopcart.id += randint(5, 10)\n resp = self.client.put(\n f\"{BASE_URL}/{shopcart.id}\",\n json=shopcart.serialize(),\n content_type=\"application/json\"\n )\n self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND)\n\n def test_add_an_item_to_shopcart(self):\n \"\"\"It should add an item to a shopcart\"\"\"\n shopcart = self._create_shopcarts(1)[0]\n item = self._create_items(1)[0]\n resp = self.client.post(\n f\"{BASE_URL}/{shopcart.id}/items\", json=item.serialize(), content_type=\"application/json\"\n )\n self.assertEqual(resp.status_code, status.HTTP_201_CREATED)\n\n def test_read_item(self):\n \"\"\" It should return a JSON of the specified item.\"\"\"\n # Create a fictional shopcart and POST it\n shopcart = self._create_shopcarts(1)[0]\n\n # Create items and assign them to shopcart.items\n items = self._create_items(randint(1, 5))\n\n # Use api to add items\n # shopcart.items = items\n\n shopcart_id = shopcart.id\n for item in items:\n item.shopcart_id = shopcart_id\n\n # Add item to the shopcart\n for item in items:\n resp = self.client.post(\n f\"{BASE_URL}/{shopcart_id}/items\", json=item.serialize(), content_type=\"application/json\"\n )\n\n resp = self.client.get(f\"{BASE_URL}/{shopcart_id}\")\n \n # No need to create shopcart again\n # resp = self.client.post(\n # BASE_URL, json=shopcart.serialize(), content_type=\"application/json\"\n # )\n # self.assertEqual(resp.status_code, status.HTTP_201_CREATED)\n\n # TODO(allenpthunag): we might need to fix this behaviour\n # `id` in shopcart JSON is ignored, a new id is created\n # current hack is to use the shopcart_id from server response\n\n # try to read an item that we created above\n # logging.debug(resp.get_json())\n\n item_to_read = items[randint(0, len(items) - 1)]\n resp = self.client.get(\n f\"{BASE_URL}/{shopcart_id}/items/{item_to_read.id}\"\n )\n \n self.assertEqual(resp.status_code, status.HTTP_200_OK)\n self.assertEqual(resp.get_json(), item_to_read.serialize())\n\n # try to read from a non-existing shopcart\n resp = self.client.get(\n f\"{BASE_URL}/{shopcart_id + randint(5, 10)}/items/{item_to_read.id}\"\n )\n self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND)\n\n # try to read a non-existing item\n # change non_existing_item_id 0 to 1, because if the length of items is 1,\n # then this test will fail\n non_existing_item_id = 1\n for item in items:\n non_existing_item_id += item.id + randint(50, 100)\n resp = self.client.get(\n f\"{BASE_URL}/{shopcart_id}/items/{non_existing_item_id}\"\n )\n self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND)\n\n def test_update_item(self):\n \"\"\" It should update specified item.\"\"\"\n shopcart = self._create_shopcarts(1)[0]\n item = self._create_items(1)[0]\n item.shopcart_id = shopcart.id\n\n # first create a shopcart\n self.client.post(\n f\"{BASE_URL}/{shopcart.id}/items\",\n json=item.serialize(), content_type=\"application/json\"\n )\n\n # check if valid change in quantity and price of an item is updated\n req = item.serialize()\n req[\"quantity\"] = 12\n req[\"price\"] = 23\n resp = self.client.put(f\"{BASE_URL}/{shopcart.id}/items/{item.id}\",\n json=req, content_type=\"application/json\"\n )\n item.deserialize(req)\n shopcart.items.append(item)\n self.assertEqual(resp.status_code, status.HTTP_200_OK)\n self.assertEqual(resp.get_json(), shopcart.serialize())\n\n # try to update a negative quantity value\n req[\"quantity\"] = -12\n resp = self.client.put(f\"{BASE_URL}/{shopcart.id}/items/{item.id}\",\n json=req, content_type=\"application/json\"\n )\n self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)\n\n # try to update a negative price value\n req[\"quantity\"] = 12\n req[\"price\"] = -23\n resp = self.client.put(f\"{BASE_URL}/{shopcart.id}/items/{item.id}\",\n json=req, content_type=\"application/json\"\n )\n self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)\n\n # try to update a non existing shopcart\n req[\"price\"] = 23\n resp = self.client.put(f\"{BASE_URL}/{shopcart.id + randint(2,10)}/items/{item.id}\",\n json=req, content_type=\"application/json\"\n )\n self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND)\n\n # try to update a non existing item\n resp = self.client.put(f\"{BASE_URL}/{shopcart.id}/items/{item.id + randint(2,10)}\",\n json=req, content_type=\"application/json\"\n )\n self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND)\n\n # try to update with request json containing neither price nor quantity keys\n req.pop(\"price\")\n req.pop(\"quantity\")\n req.pop(\"color\")\n resp = self.client.put(f\"{BASE_URL}/{shopcart.id}/items/{item.id}\",\n json=req, content_type=\"application/json\"\n )\n self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)\n \n def test_query_shopcarts_by_shopcart_id_and_customer_id(self):\n \"\"\"It should List all shopcarts with query shopcart_id_and_customer_id\"\"\"\n shopcarts = self._create_shopcarts(5)\n test_shopcart_id = shopcarts[0].id\n test_customer_id = shopcarts[0].customer_id\n shopcarts = [sc.serialize() for sc in shopcarts if sc.id == test_shopcart_id and sc.customer_id == test_customer_id]\n\n resp = self.client.get(\n f\"{BASE_URL}\",\n query_string=f\"id={str(test_shopcart_id)}&customer_id={str(test_customer_id)}\"\n )\n\n self.assertEqual(resp.status_code, status.HTTP_200_OK)\n\n def test_query_shopcarts_by_shopcart_id(self):\n \"\"\"It should List all shopcarts with query shopcart_id\"\"\"\n shopcarts = self._create_shopcarts(5)\n test_shopcart_id = shopcarts[0].id\n shopcarts = [sc.serialize() for sc in shopcarts if sc.id == test_shopcart_id]\n\n resp = self.client.get(\n f\"{BASE_URL}\",\n query_string=f\"id={str(test_shopcart_id)}\"\n )\n\n self.assertEqual(resp.status_code, status.HTTP_200_OK)\n \n def test_query_shopcarts_by_customer_id(self):\n \"\"\"It should List all shopcarts with query customer_id\"\"\"\n shopcarts = self._create_shopcarts(5)\n test_customer_id = shopcarts[0].customer_id\n shopcarts = [sc.serialize() for sc in shopcarts if sc.customer_id == test_customer_id]\n\n resp = self.client.get(\n f\"{BASE_URL}\",\n query_string=f\"customer_id={str(test_customer_id)}\"\n )\n\n self.assertEqual(resp.status_code, status.HTTP_200_OK)\n\n def test_checkout_items(self):\n \"\"\" It should return a list of items for checkout, and remove them from the shopcart\"\"\"\n # Create a fictional shopcart and POST it\n shopcart = self._create_shopcarts(1)[0]\n\n # Create items and POST them to the shopcart\n items = self._create_items(randint(5, 10))\n for item in items:\n resp = self.client.post(\n f\"{BASE_URL}/{shopcart.id}/items\",\n json=item.serialize(),\n content_type=\"application/json\"\n )\n\n # sample some of the items to be checked out\n items_to_checkout = sample(items, randint(1, 5))\n\n # prepare a dict to POST\n checkout_dict = {\"items\": []}\n for item in items_to_checkout:\n checkout_dict[\"items\"].append(item.serialize())\n\n # try POSTing to a non-existing shopcart\n resp = self.client.post(\n f\"{BASE_URL}/{shopcart.id + randint(42, 56)}/checkout\",\n json=checkout_dict,\n content_type=\"application/json\"\n )\n self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND)\n\n # try POSTing to a shopcart that does not have these items\n other_shopcart = self._create_shopcarts(1)[0]\n resp = self.client.post(\n f\"{BASE_URL}/{other_shopcart.id}/checkout\",\n json=checkout_dict,\n content_type=\"application/json\"\n )\n self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)\n\n # happy path\n resp = self.client.post(\n f\"{BASE_URL}/{shopcart.id}/checkout\",\n json=checkout_dict,\n content_type=\"application/json\"\n )\n self.assertEqual(resp.status_code, status.HTTP_200_OK)\n self.assertEqual(resp.get_json(), checkout_dict)\n\n # try to checkout the same set of items again\n resp = self.client.post(\n f\"{BASE_URL}/{shopcart.id}/checkout\",\n json=checkout_dict,\n content_type=\"application/json\"\n )\n self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND)\n","repo_name":"CSCI-GA-2820-FA22-001/shopcarts","sub_path":"tests/test_routes.py","file_name":"test_routes.py","file_ext":"py","file_size_in_byte":18607,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26261212240","text":"#!/usr/bin/env python3\n# Apache License, Version 2.0\n# \n\nimport os\nimport re\n\n# This script extracts the '--help' message from Blender's source code,\n# using primitive regex parsing.\n#\n# e.g:\n# python tools_maintenance/blender_help_extract.py \\\n# ../blender/source/creator/creator_args.c \\\n# manual/advanced/command_line/arguments.rst\n\n\ndef text_remove_comments(text):\n def replacer(match):\n s = match.group(0)\n if s.startswith('/'):\n return \" \"\n else:\n return s\n pattern = re.compile(\n r'//.*?$|/\\*.*?\\*/|\\'(?:\\\\.|[^\\\\\\'])*\\'|\"(?:\\\\.|[^\\\\\"])*\"',\n re.DOTALL | re.MULTILINE\n )\n return re.sub(pattern, replacer, text)\n\n\ndef text_join_lines(text):\n lines = text.split(\"\\n\")\n lines_out = [[]]\n for l in lines:\n lines_out[-1].append(l)\n if l.endswith((\";\", \"{\", \")\", \"}\")) or l.lstrip().startswith(\"#\"):\n lines_out.append([])\n text = \"\\n\".join(\n [\n \" \".join(l.lstrip() if i != 0 else l for i, l in enumerate(l_group))\n for l_group in lines_out\n ]\n )\n return text\n\n\ndef text_expand_macros(text):\n # CB() macro\n def replacer_CB(match):\n return match.group(2) + \"_doc, \" + match.group(2)\n\n pattern_CB = re.compile(\n r'\\b(CB)\\s*\\(([^\\,]+)\\)',\n re.DOTALL | re.MULTILINE\n )\n\n # CB_EX() macro\n def replacer_CB_EX(match):\n return match.group(2) + \"_doc_\" + match.group(3) + \", \" + match.group(2)\n\n pattern_CB_EX = re.compile(\n r'\\b(CB_EX)\\s*\\(([^\\,]+),\\s*([^\\)]+)\\)',\n re.DOTALL | re.MULTILINE\n )\n\n # STRINGIFY_ARG() macro\n def replacer_STRINGIFY_ARG(match):\n return \"\\\"``\" + match.group(2) + \"``\\\"\"\n\n pattern_STRINGIFY_ARG = re.compile(\n r'\\b(STRINGIFY_ARG)\\s*\\(([^\\)]+)\\)',\n re.DOTALL | re.MULTILINE\n )\n\n text = re.sub(pattern_CB, replacer_CB, text)\n text = re.sub(pattern_CB_EX, replacer_CB_EX, text)\n text = re.sub(pattern_STRINGIFY_ARG, replacer_STRINGIFY_ARG, text)\n\n return text\n\n\ndef text_extract_args(text):\n\n args = {}\n # use replace to scan (misuse!)\n\n def replacer(match):\n fn = match.group(1)\n s = match.group(2)\n\n # remove first 2 args\n s = s.split(',', 1)[-1]\n # remove last 2 args\n s = s.rsplit(',', 2)[0]\n\n if fn == \"BLI_args_add\":\n # get first 2 args\n arg_short, arg_long, s = [w.strip() for w in s.split(\",\", 2)]\n elif fn == \"BLI_args_add_case\":\n # get first 2 args\n arg_short, _, arg_long, _, s = [w.strip() for w in s.split(\",\", 4)]\n del _\n else:\n # should never happen\n raise Exception(\"Bad function call %r\" % fn)\n\n if arg_short == \"NULL\":\n arg_short = None\n else:\n arg_short = eval(arg_short, {})\n if arg_long == \"NULL\":\n arg_long = None\n else:\n arg_long = eval(arg_long, {})\n args[arg_short, arg_long] = s\n\n # print(arg_short, arg_long, s)\n\n pattern = re.compile(\n r'\\b(BLI_args_add[_case]*)\\s*\\(((?:(?!\\)\\s*;).)*?)\\)\\s*;',\n re.DOTALL | re.MULTILINE\n )\n\n re.sub(pattern, replacer, text)\n return args\n\n\ndef text_extract_strings(text):\n strings = {}\n # use replace to scan (misuse!)\n\n text = (\n text\n ).replace(\n \"PY_ENABLE_AUTO\", \" \\\" (default)\\\"\"\n ).replace(\n \"PY_DISABLE_AUTO\", \" \\\"\\\"\"\n ).replace(\n \"STRINGIFY(BLENDER_STARTUP_FILE)\", \"\\\"startup.blend\\\"\"\n ).replace(\n \"STRINGIFY(BLENDER_MAX_THREADS)\", \"\\\"64\\\"\"\n )\n\n def replacer(match):\n var = match.group(1).strip()\n s = match.group(2)\n s = \" \".join([w.strip() for w in s.split(\"\\n\")])\n s = eval(s, {})\n strings[var] = s\n\n pattern = re.compile(\n r'\\bstatic\\s+const\\s+char\\s+([A-Za-z0-9_]+)\\[\\]\\s*=\\s*((?:(?!\"\\s*;).)*?\")\\s*;',\n re.DOTALL | re.MULTILINE\n )\n\n re.sub(pattern, replacer, text)\n return strings\n\n\ndef text_extract_help(text, args, static_strings):\n func_id = 'static int arg_handle_print_help(int UNUSED(argc), const char **UNUSED(argv), void *data)\\n'\n index_start = text.find(func_id)\n assert(index_start != -1)\n index_end = text.find(\"exit(0);\", index_start)\n # print(index_start, index_end)\n body = text[index_start + len(func_id):index_end]\n body = [l for l in body.split(\"\\n\") if not l.strip().startswith(\"#\")]\n body = [l.strip() for l in body]\n body = [l for l in body if l]\n\n # args dicts\n args_short = {}\n args_long = {}\n args_used = set()\n\n for (arg_short, arg_long), value in args.items():\n if arg_short is not None:\n args_short[arg_short] = (arg_short, arg_long), value\n if arg_long is not None:\n args_long[arg_long] = (arg_short, arg_long), value\n # there is some overlap in short/long args, second pass to fix\n # by assigning long-only\n for (arg_short, arg_long), value in args.items():\n if arg_short is not None:\n if arg_long is None:\n args_short[arg_short] = (arg_short, arg_long), value\n\n def args_get(arg):\n value = args_long.get(arg)\n if value is None:\n value = args_short.get(arg)\n if value is None:\n raise Exception(\"Can't find %r\" % arg)\n return value\n\n text_rst = []\n\n # execute the code!\n other_vars = {\n \"BKE_blender_version_string\": lambda: \"|BLENDER_VERSION|\",\n }\n\n def write_arg(arg):\n (arg_short, arg_long), arg_text = args_get(arg)\n args_used.add((arg_short, arg_long))\n\n # replacement table\n arg_text = re.sub(r\"\\\"\\s*STRINGIFY_ARG\\s*\\(([a-zA-Z0-9_]+)\\)\\\"\", r\"``\\1``\", arg_text)\n arg_text = arg_text.replace('\" STRINGIFY(BLENDER_MAX_THREADS) \"', \"64\")\n arg_text = arg_text.replace('\" STRINGIFY(BLENDER_STARTUP_FILE) \"', \"startup.blend\")\n arg_text = arg_text.replace('\" PY_ENABLE_AUTO', '\\\"')\n arg_text = arg_text.replace('\" PY_DISABLE_AUTO', ', (default).\\\"')\n\n # print(arg_text)\n arg_text = eval(arg_text, static_strings)\n arg_text = arg_text.replace(\"\\t\", \" \")\n\n text_rst.append(\"``\" + \"``, ``\".join([w for w in (arg_short, arg_long) if w is not None]) + \"`` \")\n text_rst.append(arg_text + \"\\n\")\n\n ind_re = None\n for l in body:\n if l.startswith(\"printf\"):\n l = eval(l.replace(\"printf(\", \"\").replace(\");\", \"\"), other_vars)\n if type(l) is tuple:\n # Run the C-style string format.\n l = l[0] % l[1:]\n if l.lstrip() == l and l.strip(\"\\n\").endswith(\":\"):\n # Create RST heading & unique reference target.\n l = l.strip(\":\\n\")\n l = (\n \"\\n\"\n \"\\n\"\n \".. _command-line-args-%s:\\n\"\n \"\\n\"\n \"%s\\n\"\n \"%s\\n\"\n \"\\n\"\n ) % (\n # Create reference so each heading can be linked to.\n \"\".join([(c if c.isalpha() else \"-\") for c in l.lower()]),\n # The heading.\n l,\n # Heading underline.\n len(l) * \"=\",\n )\n ind_re = None\n else:\n # unindent to the previous min indent\n for _ in range(2):\n if ind_re is None:\n ind_re = r\"\\A\\t{0,}\"\n ind_m = re.match(ind_re, l)\n if ind_m:\n ind_re = r\"\\A\\t{\" + str(ind_m.end(0)) + r\"}\"\n l = re.sub(ind_re, '', l)\n break\n else:\n # indent is less than before\n ind_re = None\n\n l = l.replace(\"\\t\", \" \")\n\n text_rst.append(l)\n elif l.startswith(\"BLI_args_print_arg_doc(\"):\n arg = l.split(\",\")[-1].strip(\");\\n\")\n arg = eval(arg, {})\n write_arg(arg)\n elif l.startswith(\"BLI_args_print_other_doc(\"):\n items = list(args.items())\n # sort as strings since we can't order (None <> str)\n items.sort(key=lambda i: str(i[0]))\n for key, value in items:\n if key not in args_used:\n write_arg(key[0] or key[1])\n\n text_rst = \"\".join(text_rst)\n\n # not essential, but nice to have as ````\n text_rst = re.sub(r\"([\\+\\-]*<[a-zA-Z0-9\\(\\)_\\-]+>)\", r\"``\\1``\", text_rst)\n\n # ------\n # Post process (formatting)\n # text_rst = re.split(r\"\\\\n|[()]\", text_rst)\n text_rst = text_rst.splitlines()\n\n for i, l in enumerate(text_rst):\n # detect env var list\n l_strip = l.lstrip()\n if l_strip.startswith(\"$\"):\n l_strip, l_tail = l_strip.lstrip(\"$\").split(\" \", 1)\n if l_strip.isupper():\n l = \":%s: %s\" % (l_strip, l_tail)\n del l_tail\n elif l_strip.startswith(\"#\"):\n indent = l[:len(l) - len(l_strip)]\n l = \"\\n\" + indent + \".. code-block:: sh\\n\\n\" + indent + \" \" + l.lstrip(\"# \") + \"\\n\"\n else:\n # use \"'\" as \"``\", except when used as plural, e.g. \"Python's\"\n l = re.sub(\"(?`` ... --> ``-a`` ````\n # and...\n # -a --> ``-a``\n for i, l in enumerate(text_rst):\n if l.lstrip().startswith(\"-\"):\n l = re.sub(r\"(\\s+)(\\-[a-z])(\\s+``)\", r\"\\1``\\2``\\3\", l)\n l = re.sub(r\"^(\\s+)(\\-[a-z])$\", r\"\\1``\\2``\", l)\n text_rst[i] = l\n\n text_rst = [\n \".. DO NOT EDIT THIS FILE, GENERATED BY %r\\n\" % os.path.basename(__file__),\n \"\\n\"\n \" CHANGES TO THIS FILE MUST BE MADE IN BLENDER'S SOURCE CODE, SEE:\\n\"\n \" https://developer.blender.org/diffusion/B/browse/master/source/creator/creator_args.c\\n\"\n \"\\n\"\n \".. _command_line-args:\\n\"\n \"\\n\"\n \"**********************\\n\"\n \"Command Line Arguments\\n\"\n \"**********************\\n\"\n \"\\n\"\n ] + text_rst\n\n text_rst = \"\\n\".join(text_rst)\n text_rst = text_rst + \"\\n\"\n text_rst = text_rst.replace(\"\\n\\n\\n\\n\", \"\\n\\n\\n\")\n\n return text_rst\n\n\ndef main():\n import sys\n source_file = sys.argv[-2]\n output_file = sys.argv[-1]\n\n if not source_file.endswith(\"creator_args.c\"):\n print(\"Expected 'creator_args.c' to be passed as the second last argument\")\n return\n if not output_file.endswith(\".rst\"):\n print(\"Expected an '.rst' file to be passed as the last argument\")\n return\n\n with open(source_file, 'r') as f:\n text = f.read()\n\n text = text_remove_comments(text)\n # join ',\\n' - function args split across lines.\n text = text_join_lines(text)\n # expand CB macros\n text = text_expand_macros(text)\n # first pass, extract 'BLI_args_add'\n\n args = text_extract_args(text)\n\n static_strings = text_extract_strings(text)\n\n text_rst = text_extract_help(text, args, static_strings)\n\n with open(output_file, 'w') as f:\n f.write(text_rst)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"dfelinto/blender-manual","sub_path":"tools_maintenance/blender_help_extract.py","file_name":"blender_help_extract.py","file_ext":"py","file_size_in_byte":11428,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"13373513699","text":"import networkx as nx\nfrom networkx.utils import not_implemented_for\n\n\ndef pagerank(\n G,\n alpha=0.85,\n personalization=None,\n max_iter=100,\n tol=1.0e-6,\n nstart=None,\n weight=\"weight\",\n dangling=None,\n):\n \"\"\"Returns the PageRank of the nodes in the graph.\n\n PageRank computes a ranking of the nodes in the graph G based on\n the structure of the incoming links. It was originally designed as\n an algorithm to rank web pages.\n\n Parameters\n ----------\n G : graph\n A NetworkX graph. Undirected graphs will be converted to a directed\n graph with two directed edges for each undirected edge.\n\n alpha : float, optional\n Damping parameter for PageRank, default=0.85.\n\n personalization: dict, optional\n The \"personalization vector\" consisting of a dictionary with a\n key some subset of graph nodes and personalization value each of those.\n At least one personalization value must be non-zero.\n If not specfiied, a nodes personalization value will be zero.\n By default, a uniform distribution is used.\n\n max_iter : integer, optional\n Maximum number of iterations in power method eigenvalue solver.\n\n tol : float, optional\n Error tolerance used to check convergence in power method solver.\n\n nstart : dictionary, optional\n Starting value of PageRank iteration for each node.\n\n weight : key, optional\n Edge data key to use as weight. If None weights are set to 1.\n\n dangling: dict, optional\n The outedges to be assigned to any \"dangling\" nodes, i.e., nodes without\n any outedges. The dict key is the node the outedge points to and the dict\n value is the weight of that outedge. By default, dangling nodes are given\n outedges according to the personalization vector (uniform if not\n specified). This must be selected to result in an irreducible transition\n matrix (see notes under google_matrix). It may be common to have the\n dangling dict to be the same as the personalization dict.\n\n Returns\n -------\n pagerank : dictionary\n Dictionary of nodes with PageRank as value\n\n Examples\n --------\n >>> G = nx.DiGraph(nx.path_graph(4))\n >>> pr = nx.pagerank(G, alpha=0.9)\n\n Notes\n -----\n The eigenvector calculation is done by the power iteration method\n and has no guarantee of convergence. The iteration will stop after\n an error tolerance of ``len(G) * tol`` has been reached. If the\n number of iterations exceed `max_iter`, a\n :exc:`networkx.exception.PowerIterationFailedConvergence` exception\n is raised.\n\n The PageRank algorithm was designed for directed graphs but this\n algorithm does not check if the input graph is directed and will\n execute on undirected graphs by converting each edge in the\n directed graph to two edges.\n\n See Also\n --------\n pagerank_numpy, pagerank_scipy, google_matrix\n\n Raises\n ------\n PowerIterationFailedConvergence\n If the algorithm fails to converge to the specified tolerance\n within the specified number of iterations of the power iteration\n method.\n\n References\n ----------\n .. [1] A. Langville and C. Meyer,\n \"A survey of eigenvector methods of web information retrieval.\"\n http://citeseer.ist.psu.edu/713792.html\n .. [2] Page, Lawrence; Brin, Sergey; Motwani, Rajeev and Winograd, Terry,\n The PageRank citation ranking: Bringing order to the Web. 1999\n http://dbpubs.stanford.edu:8090/pub/showDoc.Fulltext?lang=en&doc=1999-66&format=pdf\n\n \"\"\"\n if len(G) == 0:\n return {}\n\n W = G\n\n # Create a copy in (right) stochastic form\n W = nx.stochastic_graph(W, weight=weight,copy=False)\n N = W.number_of_nodes()\n\n # Choose fixed starting vector if not given\n if nstart is None:\n x = dict.fromkeys(W, 1.0 / N)\n else:\n # Normalized nstart vector\n s = float(sum(nstart.values()))\n x = {k: v / s for k, v in nstart.items()}\n\n if personalization is None:\n # Assign uniform personalization vector if not given\n p = dict.fromkeys(W, 1.0 / N)\n else:\n s = float(sum(personalization.values()))\n p = {k: v / s for k, v in personalization.items()}\n\n if dangling is None:\n # Use personalization vector if dangling vector not specified\n dangling_weights = p\n else:\n s = float(sum(dangling.values()))\n dangling_weights = {k: v / s for k, v in dangling.items()}\n dangling_nodes = [n for n in W if W.out_degree(n, weight=weight) == 0.0]\n\n # power iteration: make up to max_iter iterations\n logged_error = []\n for i in range(max_iter):\n print(f\"Completed Iteration {i}\")\n xlast = x\n x = dict.fromkeys(xlast.keys(), 0)\n danglesum = alpha * sum(xlast[n] for n in dangling_nodes)\n for n in x:\n # this matrix multiply looks odd because it is\n # doing a left multiply x^T=xlast^T*W\n for nbr in W[n]:\n x[nbr] += alpha * xlast[n] * W[n][nbr][weight]\n x[n] += danglesum * dangling_weights.get(n, 0) + (1.0 - alpha) * p.get(n, 0)\n # check convergence, l1 norm\n err = sum([abs(x[n] - xlast[n]) for n in x])\n logged_error.append(err)\n if err < N * tol:\n return (x,logged_error)\n raise nx.PowerIterationFailedConvergence(max_iter)\n","repo_name":"valayDave/semantic-scholar-data-pipeline","sub_path":"page_rank.py","file_name":"page_rank.py","file_ext":"py","file_size_in_byte":5397,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"70892913105","text":"'''\n System V UFS filesystems\n'''\n\nfrom . import unix_fs as ufs\n\nclass SysVInode(ufs.Inode):\n ''' System V inode '''\n\n def fix_di_addr(self):\n ''' convert .di_addr[] to .di_db[] and di.ib[] '''\n raw = self.di_addr\n tmp = []\n if self.ufs.ENDIAN == \"<\":\n for i in range(0, len(raw) - 3, 3):\n tmp.append((raw[i + 2] << 16) | (raw[i + 1] << 8) | raw[i + 0])\n else:\n for i in range(0, len(raw) - 3, 3):\n tmp.append((raw[i + 0] << 16) | (raw[i + 1] << 8) | raw[i + 2])\n\n self.di_db = tmp[:-3]\n self.di_ib = tmp[-3:]\n\nclass SysVFileSystem(ufs.UnixFileSystem):\n ''' System V Filesystem '''\n\n FS_TYPE = \"SysV Filesystem\"\n NICFREE = 50\n NICINOD = 100\n CHARSET = \"ISO-8859-1\"\n INODE_SIZE = 0x40\n\n SBLOCK_LAYOUT = (\n (\"s_isize\", \"1H\"),\n (\"s_fsize\", \"1L\"),\n (\"s_nfree\", \"1H\"),\n (\"s_nfree\", \"%dL\" % NICFREE),\n (\"s_ninode\", \"1H\"),\n (\"s_inode\", \"%dH\" % NICINOD),\n (\"s_flock\", \"1B\"),\n (\"s_ilock\", \"1B\"),\n (\"s_fmod\", \"1B\"),\n (\"s_ronly\", \"1B\"),\n (\"s_time\", \"1L\"),\n (\"s_dinfo\", \"4H\"),\n (\"s_tfree\", \"1L\"),\n (\"s_tinode\", \"1H\"),\n (\"s_fname\", \"6B\"),\n (\"s_fpack\", \"6B\"),\n (\"s_start\", \"1H\"),\n (\"s_lowfree\", \"1H\"),\n (\"s_ctime\", \"1L\"),\n (\"s_fill\", \"12L\"),\n (\"s_state\", \"1L\"),\n (\"s_magic\", \"1L\"),\n (\"s_type\", \"1L\"),\n )\n\n INODE_LAYOUT = (\n (\"di_mode\", \"1H\"),\n (\"di_nlink\", \"1H\"),\n (\"di_uid\", \"1H\"),\n (\"di_gid\", \"1H\"),\n (\"di_size\", \"1L\"),\n (\"di_addr\", \"40B\"),\n (\"di_atime\", \"1L\"),\n (\"di_mtime\", \"1L\"),\n (\"di_ctime\", \"1L\"),\n )\n\n MAGIC = {\n bytes.fromhex(\"fd187e20\"): \">\",\n bytes.fromhex(\"207e18fd\"): \"<\",\n }\n\n def get_superblock(self):\n ''' Read the superblock '''\n i = self.this[0x3f8:0x3fc].tobytes()\n self.ENDIAN = self.MAGIC.get(i)\n if not self.ENDIAN:\n return\n print(\"?SysVFIleSystem\", self.this, i.hex())\n\n sblock = self.this.record(\n self.SBLOCK_LAYOUT,\n endian=self.ENDIAN,\n offset=0x200,\n name=\"sblock\",\n )\n if sblock.s_type == 3:\n self.SECTOR_SIZE = 2048\n self.FS_TYPE = \"UNIX UFS 2K Filesystem\"\n elif sblock.s_type == 2:\n self.SECTOR_SIZE = 1024\n self.FS_TYPE = \"UNIX UFS 1K Filesystem\"\n elif sblock.s_type == 1:\n self.SECTOR_SIZE = 512\n self.FS_TYPE = \"UNIX UFS 512B Filesystem\"\n\n sblock.fs_nindir = self.SECTOR_SIZE // 4\n sblock.fs_imax = (sblock.s_isize - 2) * self.SECTOR_SIZE\n sblock.fs_imax //= self.INODE_SIZE\n self.sblock = sblock\n\n def get_inode(self, inum):\n ''' Return an Inode '''\n inoa = 2 * self.SECTOR_SIZE\n inoa += (inum - 1) * self.INODE_SIZE\n return self.this.record(\n self.INODE_LAYOUT,\n offset=inoa,\n endian=self.ENDIAN,\n use_type=SysVInode,\n ufs=self,\n name=\"sysv\",\n di_inum=inum,\n )\n\n def get_block(self, blockno):\n ''' Return a block '''\n offset = blockno * self.SECTOR_SIZE\n return self.this[offset:offset + self.SECTOR_SIZE]\n","repo_name":"Datamuseum-DK/AutoArchaeologist","sub_path":"autoarchaeologist/unix/sysv_filesystem.py","file_name":"sysv_filesystem.py","file_ext":"py","file_size_in_byte":3374,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"48"} +{"seq_id":"15567262500","text":"import os\nimport csv\n\nosdirectory = os.getcwd()\nbudget_data_csv = os.path.join(osdirectory,\"PyBank\",\"Resources\",\"budget_data.csv\")\n\n# INITIAL VARIABLE CONFIG\ntotal_mo = 0\nnet_total = 0\nprev_profit = 0\nchange_list = []\ngrt_increase = {\"date\": \"\", \"amount\": 0}\ngrt_decrease = {\"date\": \"\", \"amount\": 0}\n\n# Reading into csv\nwith open(budget_data_csv, 'r') as csvfile:\n csvreader = csv.reader(csvfile,\n delimiter=',')\n next(csvreader)\n\n # establishing loop, counting the number of months and the net total\n for row in csvreader:\n total_mo += 1\n net_total += int(row[1])\n\n #calc the change in profit or loss since the previous row\n if prev_profit != 0:\n change = int(row[1]) - prev_profit\n change_list.append(change)\n\n #calc check to see if its the greatest increase/decrease over the period\n if change > grt_increase[\"amount\"]:\n grt_increase[\"date\"] = row[0]\n grt_increase[\"amount\"] = change\n elif change < grt_decrease[\"amount\"]:\n grt_decrease[\"date\"] = row[0]\n grt_decrease[\"amount\"] = change\n\n #storing the active profit/loss for the next loop\n prev_profit = int(row[1])\n \n #calculating the average of all Profit/Losses\n avg_change = round(sum(change_list) / len(change_list),2)\n\n# setting up variables to print \nsummary_title = \"Financial Analysis\"\nsummary_mo = \"Total Months: \" + str(total_mo)\nsummary_tot = \"Total: \" + str(\"${:,}\".format(net_total))\nsummary_avg = \"Average Change: \" + str(\"${:,}\".format(avg_change))\nsummary_grti = \"Greatest Increase in Profits: \" + str(grt_increase[\"date\"]) + \" \" + str(\"${:,}\".format(grt_increase[\"amount\"]))\nsummary_grtd = \"Greatest Decrease in Profits: \" + str(grt_decrease[\"date\"]) + \" \" + str(\"${:,}\".format(grt_decrease[\"amount\"]))\n\n# writting financial analysis to terminal \nprint(summary_title)\nprint(\"-----------------------------\")\nprint(summary_mo)\nprint(summary_tot)\nprint(summary_avg)\nprint(summary_grti)\nprint(summary_grtd)\n\n# saving file to txt\nprintPyBank = os.path.join(osdirectory,\"PyBank\", \"analysis\", \"Financial_Analysis.txt\")\n\nwith open(printPyBank, 'w') as outfile:\n outfile.write(summary_title + \"\\n\")\n outfile.write(\"-----------------------------\\n\")\n outfile.write(summary_mo + \"\\n\")\n outfile.write(summary_tot + \"\\n\")\n outfile.write(summary_avg + \"\\n\")\n outfile.write(summary_grti + \"\\n\")\n outfile.write(summary_grtd + \"\\n\")\n","repo_name":"kuromasadev/python-challenge","sub_path":"PyBank/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2653,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"12446757674","text":"import unittest\nimport sys\nsys.path.insert(0, \"..\") # noqa\nfrom dkit.etl import source\nfrom dkit.etl.extensions.ext_parquet import ParquetSink, ParquetSource\n# from dkit.etl.extensions.ext_arrow import OSFileWriter\n\nPARQUET_FILE = \"output/test.parquet\"\n\n\nclass TestAParquetSink(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n with source.load(\"output/speed.jsonl\") as input_data:\n cls.data = list(input_data)\n\n def test_write_all_fields(self):\n sink = ParquetSink(PARQUET_FILE, chunk_size=1000)\n sink.process(self.data)\n\n\nclass TestBParquetSource(unittest.TestCase):\n\n def test_read_all_fields(self):\n rows = list(ParquetSource(PARQUET_FILE))\n print(len(rows))\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"cobusn/dkit","sub_path":"test/_test_extension_parquet.py","file_name":"_test_extension_parquet.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22661666837","text":"from collections import Counter\nimport string\n\nlines = [x.strip() for x in open('input.txt', 'r')]\n\ntemplate = lines[0]\n\nrules = {x.split(' -> ')[0]:x.split(' -> ')[1] for x in lines[2:]}\n\n# def run_insertation(template, rules):\n# result = template[0]\n# for i, c in enumerate(template[1:]):\n# result = result + rules[template[i] + c] + c\n# return result\n\n# for _ in range(10):\n# template = run_insertation(template, rules)\n\n# freq = [template.count(c) for c in string.ascii_uppercase if c in template]\n# mi = min(freq)\n# ma = max(freq)\n# print(mi, ma, ma-mi)\n\n# PART 2\n\nglobal_count = {c:0 for c in string.ascii_uppercase}\nleafs = {(k[0], k[1]):((k[0], v), (v, k[1])) for (k, v) in rules.items()}\n\ndef count(template, iter=10):\n cnt = Counter()\n for i in range(len(template) - 1):\n cnt[tuple(template[i:i+2])] += 1\n \n for _ in range(iter):\n items = list(cnt.items())\n cnt = Counter()\n for (pair, num) in items:\n l1, l2 = leafs[pair]\n cnt[l1] += num\n cnt[l2] += num \n \n cnt2 = Counter()\n for (k, v) in cnt.items():\n cnt2[k[0]] += v\n cnt2[k[1]] += v\n cnt2[template[0]] += 1\n cnt2[template[-1]] += 1\n print((max(cnt2.values()) - min(cnt2.values()))/2)\n\ncount(template, 10)\ncount(template, 40)","repo_name":"whymatter/AdventOfCode2021","sub_path":"puzzle_14/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12191777950","text":"from random import random\nfrom personajes.enemigos import *\nfrom items.items import *\nfrom items.mochila import *\nfrom compartido.utils import *\nfrom .batalla import *\n\n\n# Cada lugar está representado por una función, como una narración.\n# Podemos tener variables globales como en_paz que pueden ser cambiadas\n# desde dentro de alguna de estas funciones y afectar también lo que\n# sucede en otros lugares, dependiendo de decisiones anteriores que hayamos tomado\n\nen_paz = False\ntiene_llave = False\ntiene_album = False\n\ndef hogar(jugador):\n if en_paz:\n progresivo(\"Estás en tu hogar.\")\n progresivo(\"Aquí empezó todo.\")\n progresivo(\"Ahora comprendés.\")\n print()\n progresivo(\"The end\")\n exit()\n else:\n progresivo(\"Te encontrás en tu casa.\")\n progresivo(\"Las frías paredes te oprimen.\")\n progresivo(\"Una congoja existencial te agravia.\")\n progresivo(\"Debés salir a la aventura.\")\n opcion = menu_sencillo([\"Salir al mundo\", \"Revisar la casa\"])\n print(opcion)\n if opcion == '2':\n progresivo(\"Encontrás tu vieja mochila de viaje\")\n jugador.dar(Mochila(10))\n progresivo(\"Encontrás unas pociones en un viejo armario\")\n jugador.dar(PocionHP(24))\n jugador.dar(PocionMP(24))\n progresivo(\"\")\n if not tiene_llave:\n progresivo(\"...\")\n progresivo(\"Un viejo cajón cerrado.\")\n progresivo(\"Con llave.\")\n progresivo(\"Qué tenía?...\")\n progresivo(\"Lo olvidaste...\")\n else:\n progresivo(\"Con la llave abrís el viejo cajón cerrado.\")\n progresivo(\"Un álbum de fotos.\")\n progresivo(\"Reconocés en algunas a tu madre.\")\n progresivo(\"Hay otras personas que no reconocés.\")\n progresivo(\"[Obtenido: Antiguo álbum de fotos]\")\n tiene_album = True\n\n\n\ndef bosque(jugador):\n progresivo(\"La tupida arboleda te proteje.\")\n progresivo(\"Pero las criaturas acechan por la noche...\")\n progresivo(\"Pasarás aquí la noche? [s/n]\")\n\n if menu_sn():\n if random() < 0.5:\n progresivo(\"Un lobo salvage aparece!\")\n try:\n Arena().con_jugadores([jugador]).con_enemigos([Lobo()]).batallar()\n except JugadorPierde:\n progresivo('The end')\n exit()\n jugador.dar(PocionHP(30))\n else:\n progresivo(\"La noche pasa sin mayores problemas...\")\n progresivo(\"Lo que no te mata te fortalece.\")\n progresivo(\"Empezás con +0.3 Dfs en el próximo combate!\")\n jugador.dfs += 0.3\n\ndef aldea(jugador):\n progresivo(\"El cálido ronroneo del ajetreo cotidiano.\")\n progresivo(\"Deseas comprar algo?...\")\n progresivo(\"...\")\n progresivo(\"Hm, parece que el desarrollador todavía no implementó la compra de items\")\n progresivo(\"Aquí hay uno gratis...\")\n jugador.dar(PocionHP(30))\n\n\ndef rio(jugador):\n progresivo(\"El suave arruyo de las venas de la tierra restaura toda tu vitalidad.\")\n jugador.hp = jugador.hp_max\n jugador.mp = jugador.mp_max\n progresivo(\"HP y MP recuperado!\")\n\ndef montaña(jugador):\n global en_paz\n progresivo(\"No tan rápido.\")\n progresivo(\"La montaña es sagrada.\")\n progresivo(\"El guardián Fermín corta tu paso.\")\n progresivo(\"Prueba tu valía o muere.\")\n getch()\n\n enemigo = None\n # Si el jugador es guerrero el boss va a ser un mago...\n if isinstance(jugador, Guerrero):\n enemigo = PNJMago('Fermín', 200, 150, [BolaDeFuego, PicosDeHielo])\n\n # Si el jugador es mago el boss va a ser un guerrero...\n if isinstance(jugador, Mago):\n enemigo = PNJGuerrero('Fermín', 200, '3d6', Espada(5))\n\n try:\n Arena()\\\n .con_jugadores([jugador])\\\n .con_enemigos([enemigo])\\\n .no_manejar_huida()\\\n .batallar()\n progresivo(\"Más allá de los valles y ríos, fría y hostil, la cima del mundo.\")\n progresivo(\"Contemplás el atardecer en silencio.\")\n progresivo(\"Alcanzás la sabiduría.\")\n progresivo(\"Podés volver en paz.\")\n en_paz = True\n except JugadorPierde:\n progresivo(\"Fermín te destrozó.\")\n progresivo(\"No hay sensatez en quien no sabe retirarse a tiempo.\")\n print()\n progresivo(\"Game over\")\n exit()\n except Huida:\n progresivo(\"Tu dignidad no está en riesgo\")\n progresivo(\"Tendrás otra chance\")\n\n\n\n# Este diccionario representa el mapa. Para cada lugar, le decimos qué función ejecutar y a qué otros lugares se puede llegar desde allí. Esto último es lo que a fin de cuentas lo convierte en un mapa.\n\nmapa = {\n 'Hogar' : {\n 'caminos' : ['Bosque', 'Río'],\n 'acciones' : hogar\n },\n 'Bosque' : {\n 'caminos' : ['Hogar', 'Aldea'],\n 'acciones' : bosque\n },\n 'Aldea' : {\n 'caminos' : ['Montaña', 'Bosque', 'Río'],\n 'acciones' : aldea\n },\n 'Río' : {\n 'caminos' : ['Hogar', 'Aldea'],\n 'acciones' : rio\n },\n 'Montaña' : {\n 'caminos' : ['Aldea'],\n 'acciones' : montaña\n }\n}\n\n\n# Esta función -recursiva- se encarga de ir recorriendo los lugares y ejecutando las funciones. Cuando se la llama ejecuta las acciones de ese lugar y a continuación nos ofrece los destinos posibles. Una vez elegido un destino, se ejecuta a sí misma con ese destino nuevo.\n# El mapa está construído como un *grafo*\n\ndef aventura(lugar, jugador):\n print()\n accion = mapa[lugar]['acciones']\n accion(jugador)\n print()\n print('Elegí el próximo paso:')\n proximo = menu_textual(mapa[lugar]['caminos'])\n aventura(proximo, jugador)\n","repo_name":"VladimirCharkot/pyrpg","sub_path":"mundo/mapa.py","file_name":"mapa.py","file_ext":"py","file_size_in_byte":5874,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72622447187","text":"# Задание 8 лабораторная 5\n# Вариант 1\n# Збаразский С.С\n\nimport numpy as np\n\nfruits = np.array(\n ['Абрикос', 'Айва', 'Виноград', 'Вишня', 'Груша', 'Земляника', 'Крыжовник', 'Малина', 'Персик', 'Слива',\n 'Черная смородина', 'Черешня', 'Шиповник', 'Яблоко'])\nvitamin_amounts = np.array([\n [1.6, 0.03, 0.06, 0.07, 6, 570],\n [0.2, 0.03, 0.03, 0.02, 115, 415],\n [0.01, 0.01, 0.01, 0.06, 4, 300],\n [0.7, 0.03, 0.03, 0.04, 15, 370],\n [0.01, 0.02, 0.03, 0.01, 5, 120],\n [0.03, 0.03, 0.05, 0.03, 60, 200],\n [0.2, 0.01, 0.02, 0.25, 32, 250],\n [0.02, 0.02, 0.05, 0.06, 25, 180],\n [0.05, 0.04, 0.01, 0.07, 15, 350],\n [0.07, 0.06, 0.04, 0.06, 5, 312],\n [0.1, 0.02, 0.02, 0.03, 200, 500],\n [0.15, 0.01, 0.01, 0.04, 15, 95],\n [0.25, 0.03, 0.06, 0.05, 300, 600],\n [0.03, 0.01, 0.03, 0.03, 5, 250]\n])\nvitamins = np.array(['А', 'В1', 'В2', 'РР', 'С', 'Р'])\n\nindexed_vitamins = np.rec.fromarrays((vitamins, range(1, len(vitamins) + 1)))\nprint(indexed_vitamins)\n\nvitamin_indx = int(input((\"Выберите витамин (цифра): \"))) - 1\nmax_vitamins_indx = np.argmax(vitamin_amounts, axis=0)\nprint(\"Содержание выбранного витамина максимально в:\", fruits[max_vitamins_indx[vitamin_indx]])\n\nvitamin_indx = int(input((\"Выберите витамин (цифра): \"))) - 1\namount = float(input((\"Задайте желаемое количество: \")))\nfor index, el in np.ndenumerate(vitamin_amounts):\n (r, c) = index\n if c == vitamin_indx:\n count = amount / el\n print(fruits[r], \" - Масса: %.2f\" % count)\n\nprint(\"Задайте набор фруктов\")\nvitamins_sum = np.zeros((len(vitamins),))\nfor i in range(len(fruits)):\n count = 0\n try:\n count = float(input(\"%s \" % fruits[i]))\n except ValueError as identifier:\n pass\n\n vitamins_sum = vitamins_sum + vitamin_amounts[i] * count\n\nrecords = np.rec.fromarrays((vitamins, vitamins_sum), names=('vitamins', 'amount'))\nnp.set_printoptions(suppress=True)\nprint('Содержание витаминов в наборе', records)\n","repo_name":"Zbara/ZbaraLabs","sub_path":"Z_lab_5/Z_5_8.py","file_name":"Z_5_8.py","file_ext":"py","file_size_in_byte":2253,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73746028304","text":"import plotly.graph_objects as go\nimport plotly.io as pio\n\n\n\n\nmy_charcoal = \"#3f4142\"\nmy_lightgray = \"#ebf0f2\"\nhighlight = \"#8D3B34\"\n\n# From https://github.com/empet/scientific-colorscales/blob/master/scicolorscales.py\nlapaz= [[0.0, 'rgb(26, 12, 101)'],\n [0.1, 'rgb(33, 46, 124)'],\n [0.2, 'rgb(39, 77, 145)'],\n [0.3, 'rgb(49, 105, 159)'],\n [0.4, 'rgb(68, 131, 167)'],\n [0.5, 'rgb(102, 153, 164)'],\n [0.6, 'rgb(141, 163, 152)'],\n [0.7, 'rgb(179, 167, 139)'],\n [0.8, 'rgb(223, 183, 148)'],\n [0.9, 'rgb(253, 217, 197)'],\n [1.0, 'rgb(255, 243, 243)']]\n\ndavos= [[0.0, 'rgb(44, 26, 76)'],\n [0.1, 'rgb(40, 59, 110)'],\n [0.2, 'rgb(42, 94, 151)'],\n [0.3, 'rgb(68, 117, 193)'],\n [0.4, 'rgb(96, 137, 190)'],\n [0.5, 'rgb(125, 156, 181)'],\n [0.6, 'rgb(155, 175, 172)'],\n [0.7, 'rgb(186, 196, 163)'],\n [0.8, 'rgb(215, 217, 161)'],\n [0.9, 'rgb(237, 236, 206)'],\n [1.0, 'rgb(255, 255, 255)']]\n\ndavos_colors = [color[1] for color in davos]\nlapaz_colors = [color[1] for color in lapaz]\n\n\n\n\ndev_temp = go.layout.Template()\ndev_temp.data.scatter = [go.Scatter(marker=dict(symbol=\"circle\"))]\ndev_temp.layout.font=dict(family=\"Avenir\", color=my_charcoal)\ndev_temp.layout.paper_bgcolor = \"#fff\"\ndev_temp.layout.plot_bgcolor = \"#fff\"\ndev_temp.layout.colorscale = dict(sequential=davos_colors)\ndev_temp.layout.colorway = davos_colors\ndev_temp.layout.xaxis = dict(color=my_charcoal, linewidth = 1, gridcolor = my_lightgray, gridwidth = 0.5)\ndev_temp.layout.yaxis = dict(color=my_charcoal, linewidth = 1, gridcolor = my_lightgray, gridwidth = 0.5)\ndev_temp.layout.violingap = 0.4\n \npio.templates[\"aptviz\"] = dev_temp \n","repo_name":"asizemore/aptviz","sub_path":"aptviz/aptviz_themes.py","file_name":"aptviz_themes.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"23277370032","text":"import os\nimport shutil\nimport ftplib\n# import getpass\nfrom ftplib import FTP_TLS\nfrom config import FTP_HOST, FTP_USER, FTP_PASS\n\n# save connection to ftp-server\ntry:\n print(\"Connecting to minimusiker ftp server!\") \n ftp = FTP_TLS(FTP_HOST, timeout=30)\n # passwd = getpass(\"Enter your password: \")\n ftp.login(FTP_USER, FTP_PASS)\n ftp.prot_p() \n ftp.encoding = \"utf-8\"\n ftp.cwd(\"htdocs/hoerthin/mp3\")\n print(\"Connection success! Directory: \", ftp.pwd())\nexcept ftplib.all_errors as e:\n print('FTP error:', e)\n\ndef uploadThis(uploadFolder):\n files = os.listdir(uploadFolder)\n os.chdir(uploadFolder)\n for f in files:\n print(\"Uploading...\", f)\n if os.path.isfile(uploadFolder + r'/{}'.format(f)):\n fh = open(f, 'rb')\n ftp.storbinary('STOR %s' % f, fh)\n fh.close()\n elif os.path.isdir(uploadFolder + r'/{}'.format(f)):\n ftp.mkd(f)\n ftp.cwd(f)\n uploadThis(uploadFolder + r'/{}'.format(f))\n ftp.cwd('..')\n os.chdir('..')\n\ndesktop = os.path.join(os.path.join(os.path.expanduser('~')), 'Desktop')\n\nfor folderName in os.listdir(desktop):\n if folderName.startswith(\"MM\"):\n base = desktop + \"/\" + folderName\n splitFolderName = folderName.split()\n schoolID = splitFolderName[0][2:]\n print(\"\\n-------------------------------------------------------------\")\n print(\"folder created on sftp-server: \", schoolID)\n print(\"-------------------------------------------------------------\\n\")\n\nmp3Folder = base + \"/mp3\"\nuploadFolder = base + \"/\" + str(schoolID)\nos.rename(os.path.join(base, mp3Folder), os.path.join(base, schoolID).replace('mp3', schoolID))\n\n# upload mp3Folder to ftp server\nprint(\"Creating mp3 folder on ftp server!\")\nftp.mkd(schoolID)\nftp.cwd(schoolID)\nuploadThis(uploadFolder)\n\nftp.quit()\n\n# delete cache Folder \ntry:\n shutil.rmtree(base)\n print(\"cache folder deleted!\")\nexcept OSError as e:\n print(\"Error: %s - %s.\" % (e.filename, e.strerror))\n\nprint(\"Job done!\")\nexit(0)","repo_name":"hms-challenger/dave","sub_path":"ftp_upload.py","file_name":"ftp_upload.py","file_ext":"py","file_size_in_byte":2053,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11314380508","text":"import socket\r\nimport threading\r\nimport Mek_master\r\n\r\n\r\n# 创建一个socket连接\r\nclass Server:\r\n def __init__(self):\r\n self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n # 绑定端口和IP\r\n self.s.bind(('127.0.0.1', 9090))\r\n # 把socket变成一个被动监听的socket 128位最大请求数\r\n # x=s.accept()#接收客户端的请求\r\n self.s.listen(128)\r\n # 结果是元组 拆分信息\r\n # 用第一个信息的recv方法获得数据\r\n while True:\r\n client_socket, client_addr = self.s.accept()\r\n # tcp里使用recv获取数据,1024指获取的字节\r\n data = client_socket.recv(5120)\r\n print('接收到了{}客户端{}端口号发送的数据,内容是:{}'.format(\r\n client_addr[0], client_addr[1], data.decode('utf8')))\r\n #print(len(data.decode('utf8')))\r\n\r\n\r\nclass Client:\r\n def __init__(self):\r\n self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n\r\n # 设置连接的IP地址和端口号\r\n self.s.connect(('127.0.0.1', 9090))\r\n # 发送数据\r\n\r\n self.s.send(Mek_master.get_random_letters(16).encode('utf8'))\r\n self.s.close()\r\n\r\n\r\ndef s():\r\n Server()\r\n\r\n\r\ndef c():\r\n for i in range(10):\r\n Client()\r\n\r\n\r\nif __name__ == '__main__':\r\n # 创建服务线程\r\n st = threading.Thread(target=s)\r\n ct = threading.Thread(target=c)\r\n # 启动线程\r\n st.start()\r\n ct.start()\r\n","repo_name":"mekwenby/Master","sub_path":"demo/网络编程/socket通信.py","file_name":"socket通信.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28899615284","text":"from os import remove\nfrom threading import Thread\nfrom time import sleep\n\nfrom arrow import utcnow\nfrom gspread.exceptions import *\nfrom toolz import merge\n\nfrom flusher import gc, daiquiri\nfrom flusher.export import to_csv\nfrom flusher.load.bigquery import load as bqload\nfrom flusher.refresh_interval import is_scheduled\nfrom flusher.utils import instrumented\n\n\n# TODO: create own control sheet if it does not exists (and share with who?)\n# TODO: better instructions on sheet\n# TODO: s3 destinations with boto and s3fs\n# TODO: discover jobs manager worksheet structure rather than hard-coding it\n# TODO: better errors, more information on runs (?better log messages?)\n# TODO (ideally): redshift destination with facility for table creation ...\n# TODO: parallelism with multiprocessing\n# TODO: inline documentation\n# TODO: Job class\n\nMANAGER_DOCUMENT = 'Flush Control'\nMANAGER_JOBS_WORKSHEET = 'Jobs Manager'\nMANAGER_LOGS_WORKSHEET = 'Log'\n\nlog = daiquiri.getLogger(__name__)\n\n\n@instrumented(log.debug)\ndef read_control_sheet():\n return [merge(spec, {'row': rnumber+2}) # zero-based + 1 row of header\n for rnumber,spec in enumerate(jobs_sheet.get_all_records())\n if spec['Document']]\n\n\n@instrumented(log.info)\ndef run_export(document, sheet, cellrange):\n try:\n return (to_csv(document, sheet, cellrange), None)\n except Exception as e:\n return (None, e)\n\n\n\n@instrumented(log.info)\ndef run_load(source_file, job_spec):\n try:\n target_system = job_spec['Target System'].lower().replace(' ','')\n destination = job_spec['Destination'].lower().replace(' ','')\n incremental = job_spec.get('Incremental')\n if target_system == 'bigquery':\n return (bqload(source_file, destination, incremental), None)\n else:\n raise NotImplementedError('Not Implemented: ' + target_system)\n\n except Exception as e:\n return (None, e)\n\n\n@instrumented(log.debug)\ndef available_sheets(document):\n return [s.title for s in gc.open(document).worksheets()]\n\n\ndef translate_error(e, args):\n if type(e) == SpreadsheetNotFound:\n return \"\"\"Unable to find document: {doc}.\nYou might need to share it with: {email}.\nOtherwise check for typos.\"\"\".format(doc=args['document'], email=gc.auth.service_account_email)\n if type(e) == WorksheetNotFound:\n candidates = ', '.join(available_sheets(args['document']))\n return \"\"\"Unable to find worksheet: {sheet}.\nCheck for typos.\nWorksheets found: {candidates}.\"\"\".format(sheet=args['sheet'], candidates=candidates)\n else:\n return e\n\n\n@instrumented(log.debug)\ndef update_running(job_spec):\n row = job_spec['row']\n\n refresh_now = jobs_sheet.cell(row, 7)\n refresh_now.value = ''\n state = jobs_sheet.cell(row, 10)\n state.value = 'Running'\n\n jobs_sheet.update_cells([refresh_now, state])\n\n return utcnow().isoformat()\n\n\n@instrumented(log.debug)\ndef update_success(job_spec, result):\n row = job_spec['row']\n\n refresh_now = jobs_sheet.cell(row, 7)\n refresh_now.value = ''\n last_success = jobs_sheet.cell(row, 9)\n last_success.value = utcnow().isoformat()\n state = jobs_sheet.cell(row, 10)\n state.value = 'Success'\n last_result = jobs_sheet.cell(row, 11)\n last_result.value = result\n\n jobs_sheet.update_cells([refresh_now, last_success, state, last_result])\n\n return utcnow().isoformat()\n\n\n@instrumented(log.debug)\ndef update_failure(job_spec, message):\n row = job_spec['row']\n\n refresh_now = jobs_sheet.cell(row, 7)\n refresh_now.value = ''\n refresh_interval = jobs_sheet.cell(row, 8)\n refresh_interval.value = ''\n state = jobs_sheet.cell(row, 10)\n state.value = 'Failure'\n last_result = jobs_sheet.cell(row, 11)\n last_result.value = message\n\n jobs_sheet.update_cells([refresh_now, refresh_interval, state, last_result])\n\n return utcnow().isoformat()\n\n\n@instrumented(log.debug)\ndef update_invalid_schedule(job_spec, message):\n row = job_spec['row']\n\n refresh_interval = jobs_sheet.cell(row, 8)\n refresh_interval.value = ''\n state = jobs_sheet.cell(row, 10)\n state.value = 'Failure'\n last_result = jobs_sheet.cell(row, 11)\n last_result.value = message\n\n jobs_sheet.update_cells([refresh_interval, state, last_result])\n\n\ndef add_log_line(job_args, result, error, start, end):\n logs_sheet = control_doc.worksheet(MANAGER_LOGS_WORKSHEET)\n\n @instrumented(log.debug)\n def addlog(*args):\n return logs_sheet.append_row(*args)\n\n Thread( target=addlog,\n args=([\n start,\n end,\n job_args['document'],\n job_args['sheet'],\n job_args['cellrange'],\n 'Failure' if error else 'Success',\n error if error else result\n ],)\n ).start()\n\n\ndef filter_fixing_invalid_schedules(jobs):\n for job in jobs:\n if job['Refresh Interval']:\n try:\n is_scheduled(job)\n except Exception as e:\n update_invalid_schedule(job, e)\n continue\n yield job\n\n\ndef should_run(job):\n return (not job['State'] == 'Running') \\\n and (job['Refresh Now'] or is_scheduled(job))\n\n\ndef run_job(job):\n start = update_running(job)\n\n args = {\n 'document': job['Document'],\n 'sheet': job['Sheet'],\n 'cellrange': job['Range']\n }\n result, error = run_export(**args)\n\n if not error and job['Target System']:\n temp_file = result\n result, error = run_load(temp_file, job)\n remove(temp_file)\n\n if error:\n end = update_failure(job, translate_error(error, args))\n else:\n end = update_success(job, result)\n\n return args, result, error, start, end\n\n\n@instrumented(log.info)\ndef run():\n while(True):\n sleep(1)\n all_jobs = read_control_sheet()\n for job in filter_fixing_invalid_schedules(all_jobs):\n if should_run(job):\n run_report = run_job(job)\n add_log_line(*run_report)\n\n\ncontrol_doc = gc.open(MANAGER_DOCUMENT)\njobs_sheet = control_doc.worksheet(MANAGER_JOBS_WORKSHEET) if MANAGER_JOBS_WORKSHEET else control_doc.sheet1\n\n","repo_name":"danielerapati/flusher","sub_path":"flusher/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":6239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32822348202","text":"import pandas as pd\nimport numpy as np\n\ndef load_Nair(fn_cat, verbose=False, field_list=['ID','TT', 'area']):\n \"\"\"\n The catalog seems to have written low level languages in mind. \n It's strictly formatted (using white spaces for missing values), making CSV utilities useless.\n\n NOTE\n ----\n 'label' is originally 'Tt' field in the paper. But I will just overwrite this field later.\n \"\"\"\n headings =['ID', 'RA', 'dec', 'zred', 'zred_q', \n 'mg', 'mr', 'Mag_r', 'logLg', 'Rpetro', \n 'Rp50', 'Rp90', 'spID', 'logM', 'Age', \n 'g_r', 'sfrt', 'sfrm', 'mu_g', 'mu_M',\n 'MvoerL','area', 'bovera', 'Seeing', 'ng',\n 'nr', 'chi2g', 'chi2r', 'R50n', 'R90n', \n 'sigma', 'e_sigma', 'VoverVmax', 'TT', 'Bar', \n 'Ring', 'f_Ring', 'Lens', 'TTq', 'Pair', \n 'f_Pair', 'Int', 'nt', 'RC3', 'Tt']\n\n colspecs = [(l[0]-1, l[1]-1) for l in [(1,21), (22,28), (32,38), (42,46), (50,54), \n (56,61), (63,68), (70,76), (78,83), (85,90), \n (93,99), (101,106), (108, 121), (123,128), (130,135), \n (138,143), (147,153), (157,163), (165,170), (172,178), \n (180,185), (189,195), (197,201), (205,208), (224, 228),\n (231,235), (237,245), (247,255), (257,262), (265,270),\n (272,278), (280,286), (288,292), (376,379), (380,382),\n (383,386), (387,389), (390,392), (393,394), (395,397),\n (398,401), (402,406), (407,409), (410,417), (418,421)] ]\n\n dat = pd.read_fwf(fn_cat, colspecs=colspecs, \n names=headings, header=None)\n\n if verbose:\n with pd.option_context('display.max_rows', 10, 'display.max_columns', None):\n print(dat)\n\n # follow result_arr's convention\n dat['ID'] = dat['ID'].apply(lambda x: x.replace('-','m'))\n dat['ID'] = dat['ID'].apply(lambda x: x.replace('+','p'))\n dat = dat.sort_values(\"ID\")\n\n return dat[field_list].copy(deep=True)\n\n\n# Array manipulation - all replaced by sklearn preprocessing module :(\n\ndef view_fields(arr, fields):\n return arr.getfield(np.dtype({name:arr.dtype.fields[name] for name in fields}))\n\ndef select_columns(arr, fields):\n dtype = np.dtype([(name, arr.dtype.fields[name][0]) for name in fields])\n newarr = np.zeros(arr.shape, dtype=dtype)\n for name in dtype.names:\n newarr[name] = arr[name]\n return newarr\n\ndef struct_to_ndarray(strarr):\n \"\"\"\n Takes 'contiguous' structured array. Doesn't work with discontinuous views!\n \n \"\"\"\n return strarr.view(np.float64).reshape(strarr.shape + (-1,))","repo_name":"Hoseung/astroBF","sub_path":"astrobf/utils/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":2622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"3124955264","text":"LECTURE = 'le'\nPRACTICAL_LESSON = 'pl'\nLABORATORY_LESSON = 'lw'\nTEST = 'te'\nHOME_WORK = 'hw'\nCOURSE_WORK = 'cw'\n\n# TYPE_OF_MARK_CHOICES = [\n# ('Лекция', LECTURE),\n# ('Лабораторна', LABORATORY_LESSON),\n# ('Практическое занятие', PRACTICAL_LESSON),\n# ('Тест', TEST),\n# ('Домашнее занятие', HOME_WORK),\n# ('Курсовая работа', COURSE_WORK),\n# ]\n\nTYPE_OF_MARK_CHOICES = [\n (LECTURE, 'Лекция'),\n (LABORATORY_LESSON, 'Лабораторная работа'),\n (PRACTICAL_LESSON, 'Практическое занятие'),\n (TEST, 'Тест'),\n (HOME_WORK, 'Домашнее занятие'),\n (COURSE_WORK, 'Курсовая работа'),\n]\n\n\nmatching_numbers_and_names = dict()\nfor key, value in (\n ('number_of_lectures', LECTURE), ('number_of_practical_lessons', PRACTICAL_LESSON),\n ('number_of_laboratory_lessons', LABORATORY_LESSON), ('number_of_tests', TEST),\n ('number_of_home_works', HOME_WORK), ('course_work', COURSE_WORK)):\n matching_numbers_and_names[key] = value\n# NUMBER_OF_LESSONS_CHOICES = {\n# 'number_of_lectures':,\n# 'number_of_lectures': ,\n# 'number_of_lectures': ,\n# 'number_of_lectures': ,\n# 'number_of_lectures': ,\n# 'number_of_lectures': ,\n# }\n","repo_name":"anton000v/NURE_marks","sub_path":"NURE_marks/choices.py","file_name":"choices.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17844546498","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Sep 19 07:52:12 2020\n\n@author: Savvas\n\"\"\"\nfrom PIL import Image\nimport os \n\nfrom PIL import Image\n\ninfile = 'E:/Segmentation Images/Vanhingen/img/top_mosaic_09cm_area1.tif'\nchopsize = 250\n\nimg = Image.open(infile)\nwidth, height = img.size\n\n# Save Chops of original image\nfor x0 in range(0, width, chopsize):\n for y0 in range(0, height, chopsize):\n box = (x0, y0,\n x0+chopsize if x0+chopsize < width else width - 1,\n y0+chopsize if y0+chopsize < height else height - 1)\n print('%s %s' % (infile, box))\n img.crop(box).save(f'E:/Segmentation Images/izee/zcho{x0},{y0}.tif')\n \n \n","repo_name":"savvas17/Entropy-Unet","sub_path":"Entropy-Unet/slicer.py","file_name":"slicer.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7441450380","text":"from networks.damas_fista_net import DAMAS_FISTANet\nfrom utils.utils import pyContourf_two, Logger\nfrom datasets.dataset import SoundDataset\nimport numpy as np\nimport torch\nimport argparse\nimport os\nimport sys\nimport h5py\nfrom utils.config import Config\nimport math\nimport time\nfrom utils.utils import get_search_freq, neighbor_2_zero, find_match_source\n\ndef parse_option():\n parser = argparse.ArgumentParser('argument for testing')\n\n parser.add_argument('--test_dir', \n help='The directory used to evaluate the models',\n default='./data/One_test.txt', type=str)\n parser.add_argument('--results_dir', \n help='The directory used to save the save image',\n default='./img_results/', type=str)\n parser.add_argument('--output_dir', \n help='The directory used to save the save image',\n default='./output_results/', type=str)\n parser.add_argument('--label_dir', \n help='The directory used to evaluate the models',\n default='D:/Ftp_Server/zgx/data/Acoustic-NewData/DAMAS_FISTA_Net_Label/', type=str)\n parser.add_argument('--ckpt', type=str, default='',\n help='path to pre-trained model')\n \n parser.add_argument('--LayNo', \n default=5, \n type=int,\n help='iteration nums')\n parser.add_argument('--show_DAS_result',\n action='store_true',\n help='whether show DAS result')\n\n parser.add_argument('--micro_array_path', default='./data/56_spiral_array.mat', type=str, help='micro array path')\n parser.add_argument('--wk_reshape_path', default='./data/wk_reshape.npy', type=str, help='wk_reshape path')\n parser.add_argument('--A_path', default='./data/A.npy', type=str, help='A path')\n parser.add_argument('--ATA_path', default='./data/ATA.npy', type=str, help='ATA path')\n parser.add_argument('--L_path', default='./data/ATA_eigenvalues.npy', type=str, help='L path')\n parser.add_argument('--more_source', action='store_true', help='whether use more source')\n parser.add_argument('--source_num', default=1, type=int, help='source_num')\n parser.add_argument('--config', default='./utils/config.yml', type=str, help='config file path')\n parser.add_argument('--add_noise', action='store_true', help='whether add gaussian noise to test')\n parser.add_argument('--dB_value', default=0, type=float, help='gaussian noise value')\n \n\n args = parser.parse_args()\n\n args.results_dir += args.ckpt.split('/')[-2] + '/' + args.ckpt.split('/')[-1].split('.')[0] + '/'\n if not os.path.exists(args.results_dir):\n os.makedirs(args.results_dir)\n\n args.output_dir += args.ckpt.split('/')[-2] + '/' + args.ckpt.split('/')[-1].split('.')[0] + '/'\n if not os.path.exists(args.output_dir):\n os.makedirs(args.output_dir)\n\n return args\n\n# 加载声源数据\ndef set_loader(args, config):\n test_dataloader = torch.utils.data.DataLoader(\n \n SoundDataset(args.test_dir, args.label_dir, config['z_dist'], args.micro_array_path, args.wk_reshape_path, args.A_path, args.ATA_path, args.L_path, None, args.config, add_noise=args.add_noise, dB_value=args.dB_value, more_source=args.more_source),\n batch_size=1, shuffle=True,\n num_workers=0, pin_memory=True)\n\n return test_dataloader\n\n\ndef set_model(args):\n\n if not args.show_DAS_result:\n ckpt = torch.load(args.ckpt, map_location='cpu')\n state_dict = ckpt['model']\n if torch.cuda.is_available():\n new_state_dict = {}\n for k, v in state_dict.items():\n k = k.replace(\"module.\", \"\")\n new_state_dict[k] = v\n state_dict = new_state_dict\n\n model = DAMAS_FISTANet(args.LayNo)\n model = model.cuda()\n model.load_state_dict(state_dict)\n\n else:\n model = DAMAS_FISTANet(args.LayNo, args.show_DAS_result)\n model = model.cuda()\n\n return model\n\n\n# def test(test_dataloader, model, args, config):\n \n# model.eval()\n# location_bias_list = list()\n# Power_bias_list = list()\n# time_list = list()\n# scanning_area_X = np.arange(config['scan_x'][0], config['scan_x'][1] + config['scan_resolution'], config['scan_resolution'])\n# scanning_area_Y = np.arange(config['scan_y'][0], config['scan_y'][1] + config['scan_resolution'], config['scan_resolution'])\n\n \n\n\n# with torch.no_grad():\n# for idx, (CSM, wk_reshape, A, ATA, L, label, sample_name) in enumerate(test_dataloader):\n# sample_name = sample_name[0]\n# CSM = CSM.cuda(non_blocking=True)\n# wk_reshape = wk_reshape.cuda(non_blocking=True)\n# A = A.cuda(non_blocking=True)\n# ATA = ATA.cuda(non_blocking=True)\n# L = L.cuda(non_blocking=True)\n\n# output = None\n# torch.cuda.synchronize()\n# start_time = time.time()\n\n# # forward\n# for K in range(len(args.frequencies)):\n# CSM_K = CSM[:, :, :, K]\n# wk_reshape_K = wk_reshape[:, :, :, K]\n# A_K = A[:, :, :, K]\n# ATA_K = ATA[:, :, :, K]\n# L_K = L[:, K]\n# L_K = torch.unsqueeze(L_K, 1).to(torch.float64)\n# L_K = torch.unsqueeze(L_K, 2).to(torch.float64)\n# # forward\n# if output is None:\n# output = model(CSM_K, wk_reshape_K, A_K, ATA_K, L_K)\n# else:\n# output += model(CSM_K, wk_reshape_K, A_K, ATA_K, L_K)\n\n# # 同步GPU时间\n# torch.cuda.synchronize()\n# end_time = time.time()\n# now_time = end_time - start_time\n \n\n# np_gt = label.cpu().numpy()\n# np_output = output.cpu().numpy()\n\n# np_label = np_gt.reshape(41, 41, order='F')\n# np_out = np_output.reshape(41, 41, order='F')\n# f = h5py.File(args.output_dir + sample_name + '.h5','w')\n# f['damas_fista_net_output'] = np_out\n# f.close()\n# pyContourf_two(np_out, np_label, args.results_dir, sample_name)\n\n# np_gt = np.squeeze(np_gt, 0)\n# max_gt = max(np_gt)[0]\n# np_gt = np.where(np_gt == max(np_gt))\n# gt_x_pos = math.ceil((np_gt[0][0] + 1) / len(scanning_area_X))\n# gt_y_pos = np.mod((np_gt[0][0] + 1), len(scanning_area_Y))\n# gt_x = scanning_area_X[gt_x_pos - 1]\n# gt_y = scanning_area_Y[gt_y_pos - 1]\n\n\n# np_output = np.squeeze(np_output, 0)\n# max_output = max(np_output)[0]\n# np_output = np.where(np_output == max(np_output))\n# output_x_pos = math.ceil((np_output[0][0] + 1) / len(scanning_area_X))\n# output_y_pos = np.mod((np_output[0][0] + 1), len(scanning_area_Y))\n# output_x = scanning_area_X[output_x_pos - 1]\n# output_y = scanning_area_Y[output_y_pos - 1]\n\n# Power_output = max_output\n# Power_label = max_gt \n# Power_bias = np.abs(Power_output - Power_label)\n \n# location_bias = np.sqrt(((output_x - gt_x)**2 + (output_y - gt_y)**2))\n# location_bias_list.append(location_bias)\n# Power_bias_list.append(Power_bias)\n\n# time_list.append(now_time)\n \n\n# print(str(idx + 1) + \"___label_x={}\\t label_y={}\\t Power_label={}\".format(\n# gt_x, gt_y, Power_label))\n\n# print(str(idx + 1) + \"___output_x={}\\t output_y={}\\t Power_output={}\\t time={}\".format(\n# output_x, output_y, Power_output, now_time))\n\n# print(str(idx + 1) + \"___location_bias={}\\t Power_bias={}\".format(\n# location_bias, Power_bias))\n \n# print(\"mean_location_bias_in_val={}\\t mean_Power_bias_in_val={}\\t time_for_mean={}\".format(np.mean(location_bias_list), np.mean(Power_bias_list), np.mean(time_list)))\n\n\ndef test_more_source(test_dataloader, model, args, config):\n \"\"\"test\"\"\"\n\n model.eval()\n location_bias_list = list()\n Power_bias_list = list()\n time_list = list()\n scanning_area_X = np.arange(config['scan_x'][0], config['scan_x'][1] + config['scan_resolution'], config['scan_resolution'])\n scanning_area_Y = np.arange(config['scan_y'][0], config['scan_y'][1] + config['scan_resolution'], config['scan_resolution'])\n\n # 预热\n cnt=1\n with torch.no_grad():\n for idx, (CSM, wk_reshape, A, ATA, L, _, _) in enumerate(test_dataloader):\n if cnt==100:\n break\n cnt+=1\n \n CSM = CSM.cuda(non_blocking=True)\n wk_reshape = wk_reshape.cuda(non_blocking=True)\n A = A.cuda(non_blocking=True)\n ATA = ATA.cuda(non_blocking=True)\n L = L.cuda(non_blocking=True)\n\n output = None\n # forward\n for K in range(len(args.frequencies)):\n CSM_K = CSM[:, :, :, K]\n wk_reshape_K = wk_reshape[:, :, :, K]\n A_K = A[:, :, :, K]\n ATA_K = ATA[:, :, :, K]\n L_K = L[:, K]\n L_K = torch.unsqueeze(L_K, 1).to(torch.float64)\n L_K = torch.unsqueeze(L_K, 2).to(torch.float64)\n # forward\n if output is None:\n output = model(CSM_K, wk_reshape_K, A_K, ATA_K, L_K)\n else:\n output += model(CSM_K, wk_reshape_K, A_K, ATA_K, L_K)\n\n\n\n \n with torch.no_grad():\n for idx, (CSM, wk_reshape, A, ATA, L, label, sample_name) in enumerate(test_dataloader):\n \n sample_name = sample_name[0]\n CSM = CSM.cuda(non_blocking=True)\n wk_reshape = wk_reshape.cuda(non_blocking=True)\n A = A.cuda(non_blocking=True)\n ATA = ATA.cuda(non_blocking=True)\n L = L.cuda(non_blocking=True)\n\n # forward\n output = None\n torch.cuda.synchronize()\n start_time = time.time()\n for K in range(len(args.frequencies)):\n CSM_K = CSM[:, :, :, K]\n wk_reshape_K = wk_reshape[:, :, :, K]\n A_K = A[:, :, :, K]\n ATA_K = ATA[:, :, :, K]\n L_K = L[:, K]\n L_K = torch.unsqueeze(L_K, 1).to(torch.float64)\n L_K = torch.unsqueeze(L_K, 2).to(torch.float64)\n # forward\n if output is None:\n output = model(CSM_K, wk_reshape_K, A_K, ATA_K, L_K)\n else:\n output += model(CSM_K, wk_reshape_K, A_K, ATA_K, L_K)\n\n torch.cuda.synchronize()\n end_time = time.time()\n now_time = end_time - start_time\n time_list.append(now_time)\n\n np_gt = label.cpu().numpy()\n np_output = output.cpu().numpy() \n\n np_label = np_gt.reshape(41, 41, order='F')\n np_out = np_output.reshape(41, 41, order='F')\n f = h5py.File(args.output_dir + sample_name + '.h5','w')\n f['damas_fista_net_output'] = np_out\n f.close()\n pyContourf_two(np_out, np_label, args.results_dir, sample_name)\n\n\n np_gt = np.squeeze(np.squeeze(np_gt, 0), 1)\n np_output = np.squeeze(np.squeeze(np_output, 0), 1)\n print(\"source num is->\", args.source_num)\n\n # use the output_mat and gt_mat to calculate the location error\n output_mat = np.zeros((args.source_num, 3))\n gt_mat = np.zeros((args.source_num, 3))\n\n for i in range(args.source_num):\n max_gt = max(np_gt)\n print(\"max_gt->\", max_gt)\n np_gt_index = np.where(np_gt == max_gt)[0][0]\n print(\"np_gt_index->\", np_gt_index)\n\n gt_y_pos = math.ceil((np_gt_index + 1) / len(scanning_area_X))\n gt_x_pos = (np_gt_index + 1) - (gt_y_pos - 1) * len(scanning_area_X)\n gt_x = scanning_area_X[gt_x_pos - 1]\n gt_y = scanning_area_Y[gt_y_pos - 1]\n\n max_output = max(np_output)\n print(\"max_output->\", max_output)\n np_output_index = np.where(np_output == max_output)[0][0]\n print(\"np_output_index->\", np_output_index)\n \n output_y_pos = math.ceil((np_output_index + 1) / len(scanning_area_X))\n output_x_pos = (np_output_index + 1) - (output_y_pos - 1) * len(scanning_area_X)\n output_x = scanning_area_X[output_x_pos - 1]\n output_y = scanning_area_Y[output_y_pos - 1]\n\n output_mat[i][0] = output_x\n output_mat[i][1] = output_y\n output_mat[i][2] = max_output\n\n gt_mat[i][0] = gt_x\n gt_mat[i][1] = gt_y\n gt_mat[i][2] = max_gt\n \n # 置零操作\n gt_matrix = np_gt.reshape(41, 41, order='F')\n out_matrix = np_output.reshape(41, 41, order='F')\n\n gt_matrix = neighbor_2_zero(gt_matrix, gt_x_pos-1, gt_y_pos-1)\n out_matrix = neighbor_2_zero(out_matrix, output_x_pos-1, output_y_pos-1)\n\n np_gt = gt_matrix.reshape(gt_matrix.size, order='F')\n np_output = out_matrix.reshape(out_matrix.size, order='F')\n\n\n \n temp_gt_mat = gt_mat\n for i in range(args.source_num):\n gt_mat = temp_gt_mat\n min_index, location_bias, Power_bias, temp_gt_mat = find_match_source(output_mat[i], temp_gt_mat)\n location_bias_list.append(location_bias)\n Power_bias_list.append(Power_bias)\n\n print(sample_name + \"__\" + str(idx + 1) + \"___source_num_\" + str(i) + \"___label_x={}\\t label_y={}\\t Power_label={}\".format(\n gt_mat[min_index][0], gt_mat[min_index][1], gt_mat[min_index][2]))\n\n print(sample_name + \"__\" + str(idx + 1) + \"___source_num_\" + str(i) + \"___output_x={}\\t output_y={}\\t Power_output={}\\t time={}\".format(\n output_mat[i][0], output_mat[i][1], output_mat[i][2], now_time))\n\n print(sample_name + \"__\" + str(idx + 1) + \"___source_num_\" + str(i) + \"___location_bias={}\\t Power_bias={}\".format(\n location_bias, Power_bias))\n\n print(\"mean_location_bias_in_val={}\\t mean_Power_bias_in_val={}\\t time_for_mean={}\".format(np.mean(location_bias_list), np.mean(Power_bias_list), np.mean(time_list)))\n\n\n \n\ndef main():\n args = parse_option()\n sys.stdout = Logger(args.results_dir + \"log.txt\")\n con = Config(args.config).getConfig()['base']\n _, _, _, _, args.frequencies = get_search_freq(con['N_total_samples'], con['scan_low_freq'], con['scan_high_freq'], con['fs'])\n\n model = set_model(args)\n print(model)\n # build data loader\n test_dataloader = set_loader(args, con)\n # test(test_dataloader, model, args, con)\n test_more_source(test_dataloader, model, args, con)\n\nif __name__ == '__main__':\n \n main()","repo_name":"JoaquinChou/DAMAS_FISTA_Net","sub_path":"vis.py","file_name":"vis.py","file_ext":"py","file_size_in_byte":15570,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"29733975282","text":"from configparser import ConfigParser\n\nimport numpy as np\nimport torch\nfrom utils.data_utils import load_img, load_msk, load_2_5d_img\n\nconfig_parser = ConfigParser()\nconfig_parser.read('/home/chenk/model_train/kaggle/GI_Tract_Image_Segmentation/mysql.cfg')\ncfg = config_parser['default']\n\nclass My_Dataset(torch.utils.data.Dataset):\n def __init__(self, df, label=True, transform=None):\n self.df = df\n self.label = label\n self.transform = transform\n self.image_path = df['image_path'].tolist()\n self.mask_path = df['mask_path'].tolist()\n\n def __len__(self):\n return len(self.df)\n\n def __getitem__(self, item):\n image_path = self.image_path[item]\n if cfg['input'] == '2.5D':\n img = load_2_5d_img(image_path)\n else:\n img = load_img(image_path)\n if self.label:\n mask_path = self.mask_path[item]\n # 这里返回的是一个三通道的归一化mask\n # 这里是一个多标签的问题, 每个通道代表一个类别的label值,三个通道就相当于集合了三个类别的label值\n # 且label值为0,1,这就相当于转化成了三个二分类的问题\n mask = load_msk(mask_path)\n if self.transform:\n data = self.transform(image=img, mask=mask)\n img = data['image']\n mask = data['mask']\n img = np.transpose(img, (2, 0, 1))\n mask = np.transpose(mask, (2, 0, 1))\n return torch.tensor(img, dtype=torch.float), torch.tensor(mask, dtype=torch.float)\n else:\n if self.transform:\n data = self.transform(image=img)\n img = data['image']\n img = np.transpose(img, (2, 0, 1))\n return torch.tensor(img, dtype=torch.float)\n","repo_name":"iKnowCkll/GI_Tract_Image_Segmentation","sub_path":"my_dataset.py","file_name":"my_dataset.py","file_ext":"py","file_size_in_byte":1831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22870190255","text":"# SPDX-License-Identifier: Apache-2.0\n\nimport atexit\nimport logging\nimport multiprocessing as mp\nimport random\n\nimport mxnet as mx\nimport numpy as np\n\ntry:\n import Queue\nexcept ImportError:\n import queue\n\nimport utils\n\n\nclass CityLoader(mx.io.DataIter):\n \"\"\"\n Data Loader class for Cityscapes Dataset.\n Performs loading and preparing of images from the dataset for train/val/test.\n Used in duc-validation.ipynb\n \"\"\"\n def __init__(self, data_list, input_args):\n super(CityLoader, self).__init__()\n self.input_args = input_args\n self.data_list = data_list\n self.data = CityLoader.read_data(self.data_list)\n self.data_path = input_args.get('data_path', '')\n self.data_shape = input_args.get('data_shape')\n self.label_shape = input_args.get('label_shape')\n self.multi_thread = input_args.get('multi_thread', False)\n self.n_thread = input_args.get('n_thread', 7)\n self.data_name = input_args.get('data_name', ['data'])\n self.label_name = input_args.get('label_name', ['seg_loss_label'])\n self.data_loader = input_args.get('data_loader')\n self.stop_word = input_args.get('stop_word', '==STOP--')\n self.batch_size = input_args.pop('batch_size', 4)\n self.current_batch = None\n self.data_num = None\n self.current = None\n self.worker_proc = None\n\n if self.multi_thread:\n self.stop_flag = mp.Value('b', False)\n self.result_queue = mp.Queue(maxsize=self.batch_size*3)\n self.data_queue = mp.Queue()\n\n @staticmethod\n def read_data(data_list):\n data = []\n with open(data_list, 'r') as f:\n for line in f:\n frags = line.strip().split('\\t')\n item = list()\n item.append(frags[1]) # item[0] is image path\n item.append(frags[2]) # item[1] is label path\n if len(frags) > 3:\n item.append(frags[3:]) # item[2] is parameters for cropping\n data.append(item)\n return data\n\n def _insert_queue(self):\n for item in self.data:\n self.data_queue.put(item)\n [self.data_queue.put(self.stop_word) for pid in range(self.n_thread)]\n\n def _thread_start(self):\n self.stop_flag = False\n self.worker_proc = [mp.Process(target=CityLoader._worker,\n args=[pid,\n self.data_queue,\n self.result_queue,\n self.input_args,\n self.stop_word,\n self.stop_flag])\n for pid in range(self.n_thread)]\n [item.start() for item in self.worker_proc]\n\n def cleanup():\n self.shutdown()\n atexit.register(cleanup)\n\n @staticmethod\n def _worker(worker_id, data_queue, result_queue, input_args, stop_word, stop_flag):\n count = 0\n for item in iter(data_queue.get, stop_word):\n if stop_flag == 1:\n break\n image, label = CityLoader._get_single(item, input_args)\n result_queue.put((image, label))\n count += 1\n\n @property\n def provide_label(self):\n return [(self.label_name[i], self.label_shape[i]) for i in range(len(self.label_name))]\n\n @property\n def provide_data(self):\n return [(self.data_name[i], self.data_shape[i]) for i in range(len(self.data_name))]\n\n def reset(self):\n self.data_num = len(self.data)\n self.current = 0\n self.shuffle()\n if self.multi_thread:\n self.shutdown()\n self._insert_queue()\n self._thread_start()\n\n def get_batch_size(self):\n return self.batch_size\n\n def shutdown(self):\n if self.multi_thread:\n # clean queue\n while True:\n try:\n self.result_queue.get(timeout=1)\n except Queue.Empty:\n break\n while True:\n try:\n self.data_queue.get(timeout=1)\n except Queue.Empty:\n break\n # stop worker\n self.stop_flag = True\n if self.worker_proc:\n for i, worker in enumerate(self.worker_proc):\n worker.join(timeout=1)\n if worker.is_alive():\n logging.error('worker {} is join fail'.format(i))\n worker.terminate()\n\n def shuffle(self):\n random.shuffle(self.data)\n\n def next(self):\n if self._get_next():\n return self.current_batch\n else:\n raise StopIteration\n\n def _get_next(self):\n batch_size = self.batch_size\n if self.current + batch_size > self.data_num:\n return False\n xs = [np.zeros(ds) for ds in self.data_shape]\n ys = [np.zeros(ls) for ls in self.label_shape]\n cnt = 0\n for i in range(self.current, self.current + batch_size):\n if self.multi_thread:\n image, label = self.result_queue.get()\n else:\n image, label = CityLoader._get_single(self.data[i], self.input_args)\n for j in range(len(image)):\n xs[j][cnt, :, :, :] = image[j]\n for j in range(len(label)):\n ys[j][cnt, :] = label[j]\n cnt += 1\n xs = [mx.ndarray.array(x) for x in xs]\n ys = [mx.ndarray.array(y) for y in ys]\n self.current_batch = mx.io.DataBatch(data=xs, label=ys, pad=0, index=None)\n self.current += batch_size\n return True\n\n @staticmethod\n def _get_single(item, input_args):\n return utils.get_single_image_duc(item, input_args)\n","repo_name":"onnx/models","sub_path":"vision/object_detection_segmentation/duc/dependencies/cityscapes_loader.py","file_name":"cityscapes_loader.py","file_ext":"py","file_size_in_byte":5907,"program_lang":"python","lang":"en","doc_type":"code","stars":6586,"dataset":"github-code","pt":"48"} +{"seq_id":"20808345460","text":"#Problem - 1043 (Game Time)\nA, B = list(map(int, input().split()))\n\nif(A None:\n \"\"\"2D Gaussian Filer\n\n Args:\n window_size (int, optional): The window size of the gaussian filter. Defaults to 11.\n in_channels (int, optional): The number of channels of the 4d tensor. Defaults to False.\n sigma (float, optional): The sigma of the gaussian filter. Defaults to 1.5.\n \"\"\"\n super().__init__()\n self.window_size = window_size\n if not (window_size % 2 == 1):\n raise ValueError(\"Window size must be odd.\")\n self.in_channels = in_channels\n self.padding = window_size // 2\n self.sigma = sigma\n self.register_buffer(name=\"gaussian_window2d\", tensor=self._get_gaussian_window2d())\n\n def _get_gaussian_window1d(self):\n sigma2 = self.sigma * self.sigma\n x = torch.arange(-(self.window_size // 2), self.window_size // 2 + 1)\n w = torch.exp(-0.5 * x ** 2 / sigma2)\n w = w / w.sum()\n return w.reshape(1, 1, self.window_size, 1)\n\n def _get_gaussian_window2d(self):\n gaussian_window_1d = self._get_gaussian_window1d()\n w = torch.matmul(gaussian_window_1d, gaussian_window_1d.transpose(dim0=-1, dim1=-2))\n w.reshape(1, 1, self.window_size, self.window_size)\n return w.repeat(self.in_channels, 1, 1, 1)\n\n def forward(self, x):\n x = F.conv2d(input=x, weight=self.gaussian_window2d, padding=self.padding, groups=x.shape[1])\n return x\n\n\nclass SSIM(nn.Module):\n def __init__(\n self, window_size=11, in_channels=1, sigma=1.5, K1=0.01, K2=0.03, L=1, keep_batch_dim=False, return_log=False\n ):\n \"\"\"Calculate the mean SSIM (MSSIM) between two 4D tensors.\n\n Args:\n window_size (int, optional): The window size of the gaussian filter. Defaults to 11.\n in_channels (int, optional): The number of channels of the 4d tensor. Defaults to False.\n sigma (float, optional): The sigma of the gaussian filter. Defaults to 1.5.\n K1 (float, optional): K1 of MSSIM. Defaults to 0.01.\n K2 (float, optional): K2 of MSSIM. Defaults to 0.03.\n L (int, optional): The dynamic range of the pixel values (255 for 8-bit grayscale images). Defaults to 1.\n keep_batch_dim (bool, optional): Whether to keep the batch dim. Defaults to False.\n return_log (bool, optional): Whether to return the logarithmic form. Defaults to False.\n\n ```\n # setting 0: for 4d float tensors with the data range [0, 1] and 1 channel\n ssim_caller = SSIM().cuda()\n # setting 1: for 4d float tensors with the data range [0, 1] and 3 channel\n ssim_caller = SSIM(in_channels=3).cuda()\n # setting 2: for 4d float tensors with the data range [0, 255] and 3 channel\n ssim_caller = SSIM(L=255, in_channels=3).cuda()\n # setting 3: for 4d float tensors with the data range [0, 255] and 3 channel, and return the logarithmic form\n ssim_caller = SSIM(L=255, in_channels=3, return_log=True).cuda()\n # setting 4: for 4d float tensors with the data range [0, 1] and 1 channel,return the logarithmic form, and keep the batch dim\n ssim_caller = SSIM(return_log=True, keep_batch_dim=True).cuda()\n\n # two 4d tensors\n x = torch.randn(3, 1, 100, 100).cuda()\n y = torch.randn(3, 1, 100, 100).cuda()\n ssim_score_0 = ssim_caller(x, y)\n # or in the fp16 mode (we have fixed the computation progress into the float32 mode to avoid the unexpected result)\n with torch.cuda.amp.autocast(enabled=True):\n ssim_score_1 = ssim_caller(x, y)\n assert torch.isclose(ssim_score_0, ssim_score_1)\n ```\n \"\"\"\n super().__init__()\n self.window_size = window_size\n self.C1 = (K1 * L) ** 2 # equ 7 in ref1\n self.C2 = (K2 * L) ** 2 # equ 7 in ref1\n self.keep_batch_dim = keep_batch_dim\n self.return_log = return_log\n\n self.gaussian_filter = GaussianFilter2D(window_size=window_size, in_channels=in_channels, sigma=sigma)\n\n @torch.cuda.amp.autocast(enabled=False)\n def forward(self, x, y):\n \"\"\"Calculate the mean SSIM (MSSIM) between two 4d tensors.\n\n Args:\n x (Tensor): 4d tensor\n y (Tensor): 4d tensor\n\n Returns:\n Tensor: MSSIM\n \"\"\"\n assert x.shape == y.shape, f\"x: {x.shape} and y: {y.shape} must be the same\"\n assert x.ndim == y.ndim == 4, f\"x: {x.ndim} and y: {y.ndim} must be 4\"\n if x.type() != self.gaussian_filter.gaussian_window2d.type():\n x = x.type_as(self.gaussian_filter.gaussian_window2d)\n if y.type() != self.gaussian_filter.gaussian_window2d.type():\n y = y.type_as(self.gaussian_filter.gaussian_window2d)\n\n mu_x = self.gaussian_filter(x) # equ 14\n mu_y = self.gaussian_filter(y) # equ 14\n sigma2_x = self.gaussian_filter(x * x) - mu_x * mu_x # equ 15\n sigma2_y = self.gaussian_filter(y * y) - mu_y * mu_y # equ 15\n sigma_xy = self.gaussian_filter(x * y) - mu_x * mu_y # equ 16\n\n # equ 13 in ref1\n A1 = 2 * mu_x * mu_y + self.C1\n A2 = 2 * sigma_xy + self.C2\n B1 = mu_x * mu_x + mu_y * mu_y + self.C1\n B2 = sigma2_x + sigma2_y + self.C2\n S = (A1 * A2) / (B1 * B2)\n\n if self.return_log:\n S = S - S.min()\n S = S / S.max()\n S = -torch.log(S + 1e-8)\n\n if self.keep_batch_dim:\n return S.mean(dim=(1, 2, 3))\n else:\n return S.mean()\n\n\ndef ssim(\n x, y, *, window_size=11, in_channels=1, sigma=1.5, K1=0.01, K2=0.03, L=1, keep_batch_dim=False, return_log=False\n):\n \"\"\"Calculate the mean SSIM (MSSIM) between two 4D tensors.\n\n Args:\n x (Tensor): 4d tensor\n y (Tensor): 4d tensor\n window_size (int, optional): The window size of the gaussian filter. Defaults to 11.\n in_channels (int, optional): The number of channels of the 4d tensor. Defaults to False.\n sigma (float, optional): The sigma of the gaussian filter. Defaults to 1.5.\n K1 (float, optional): K1 of MSSIM. Defaults to 0.01.\n K2 (float, optional): K2 of MSSIM. Defaults to 0.03.\n L (int, optional): The dynamic range of the pixel values (255 for 8-bit grayscale images). Defaults to 1.\n keep_batch_dim (bool, optional): Whether to keep the batch dim. Defaults to False.\n return_log (bool, optional): Whether to return the logarithmic form. Defaults to False.\n\n\n Returns:\n Tensor: MSSIM\n \"\"\"\n ssim_obj = SSIM(\n window_size=window_size,\n in_channels=in_channels,\n sigma=sigma,\n K1=K1,\n K2=K2,\n L=L,\n keep_batch_dim=keep_batch_dim,\n return_log=return_log,\n ).to(device=x.device)\n return ssim_obj(x, y)\n","repo_name":"lartpang/CAVER","sub_path":"method/mssim.py","file_name":"mssim.py","file_ext":"py","file_size_in_byte":7103,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"48"} +{"seq_id":"27734764733","text":"from sys import stdin\n\n\ndef reactive(a, b):\n return a != b and a.lower() == b.lower()\n\n\ndef main():\n arg = list(stdin.read().strip())\n arg.reverse()\n result = []\n\n while arg:\n if result and reactive(arg[-1], result[-1]):\n arg.pop()\n result.pop()\n else:\n result.append(arg.pop())\n\n print(len(result))\n\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"elemel/advent-of-code","sub_path":"python/2018/day_05/part_1.py","file_name":"part_1.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8669053399","text":"\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport cv2\nimport numpy as np\nimport random\n\n#%% construct the entire CSV file\n\nif False:\n import sys, os\n #sys.path.append(os.path.join(os.path.dirname(sys.path[0]),'../submission/'))\n from utils import list_files, imshow\n \n csv_directory = '../data/Lepus/csv_files'\n \n csv_files = list_files(csv_directory)\n \n print(*csv_files)\n csv_list = []\n for csv_file in csv_files:\n csv_list.append(pd.read_csv(csv_file))\n \n data = pd.concat(csv_list)\n \n data.to_csv(csv_directory + '/DeepLearningExport.csv', header = True, index = False)\n\n#%% read full data\n\ndata = pd.read_csv('../data/Lepus/csv_files/DeepLearningExport.csv')\n\nprint(data.head())\n\nprint('The amount of present species and humans is:', data.taxon_name.count())\n\n#%% empty/human/animal images imbalancing\n\ndf = data.copy()\n\nprint(df.taxon_name.isna().sum())\nprint((df.taxon_name=='[TEAM]').sum())\nprint((df.taxon_name.notna().values & (df.taxon_name!='[TEAM]').values).sum())\n\ndf['category'] = 'animal'\ndf.category[df.taxon_name.isna()] = 'empty'\ndf.category[df.taxon_name=='[TEAM]'] = 'human'\n\ncount_by_category = df.groupby(['category']).count()\n\ncount_by_category_norm = count_by_category / df.count()\n\nf=plt.figure()\ncount_by_category_norm.file_id.plot.bar(ax=f.gca())\nplt.ylabel('images proportion')\nplt.title('Data imbalancing for each category')\nplt.tight_layout()\n#plt.ylim([0, 1])\nplt.show()\n\nprint(*count_by_category_norm.file_id.values)\n\n#%% CUMULATIVE PERCENTAGE OF SPECIES + EXAMPLE OF MOST PRESENT SPECIES\n\nanimals = df[df.category == 'animal']\n\ncount_animal_species = animals.groupby(['taxon_name']).count()\n\ncum_percentage = count_animal_species.file_id.sort_values(ascending=False).cumsum()\ncum_percentage /= count_animal_species.file_id.sum()\n\ncum_percentage.reset_index().plot(marker='o',legend=False,grid=True)\nplt.xlabel('Species')\nplt.ylabel('Percentage of species in animal set')\n\n# show one image for the three most present species\n\ndirectory = '../data/Lepus/'\n\n# Create figure with subplots\nfig, axes = plt.subplots(nrows=1, ncols=5, figsize=(15, 5))\n\nfor i, axis in enumerate(axes.flatten()):\n print(i, animals[animals.taxon_name==cum_percentage.index[i]].file_path.values[0])\n img = cv2.imread(directory + animals[animals.taxon_name==cum_percentage.index[i]].file_path.values[0]).astype(np.float32)/255\n if len(img.shape) > 2:\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n \n axis.set_title('Taxon: {}'.format(cum_percentage.index[i]))\n axis.imshow(img)\n axis.get_xaxis().set_visible(False) # disable x-axis\n axis.get_yaxis().set_visible(False) # disable y-axis\n \nplt.show()\n\n#%% empty images\n\n# drop data with empty images\n#data_clr = data.drop(data.index[data.taxon_name.isna()],0)\ndata_clr = data\n\nprint(data_clr.taxon_name.isna().sum())\n\n#%% Data imbalancing\n\ncount_by_species = data_clr.groupby(['taxon_name']).count()\n\nf=plt.figure()\ncount_by_species.file_id.plot.bar(ax=f.gca())\nplt.ylabel('images counting')\nplt.title('Data imbalancing for each species')\nplt.tight_layout()\nplt.show()\n\n#%% empty/human/animal Additional information as improvment\n\ncount_by_category_period = df.groupby(['category','file_period']).count()\n\ncategory_period_statistics = pd.DataFrame(count_by_category_period.file_id / count_by_category.file_id)\ncategory_period_statistics = category_period_statistics.unstack(fill_value=0)\nprint(category_period_statistics.head())\n\nf=plt.figure()\ncategory_period_statistics.plot.bar(stacked=False, ax=f.gca())\nplt.legend(loc='center left', bbox_to_anchor=(1.0, 0.5))\nplt.ylabel('day/night/twilight proportion')\nplt.title('Proportion of day/night/twilight for each category')\nplt.tight_layout()\nplt.show()\n\n#%% empty/human/animal and solar angle\n\ngroup_by_category = df.groupby(['category'])\n\nf=plt.figure()\ngroup_by_category.sun_angle.plot.hist(alpha=0.5, density=True, ax=f.gca())\nplt.legend(loc='center left', bbox_to_anchor=(1.0, 0.5))\nplt.ylabel('proportion of data for each category')\nplt.xlabel('solar angle')\nplt.tight_layout()\nplt.show()\n\n#%% Additional information as improvment\n\ncount_by_species_period = data_clr.groupby(['taxon_name','file_period']).count()\n\nspecies_period_statistics = pd.DataFrame(count_by_species_period.file_id / count_by_species.file_id)\nspecies_period_statistics = species_period_statistics.unstack(fill_value=0)\nprint(species_period_statistics.head()*100)\n\nf=plt.figure()\nspecies_period_statistics.plot.bar(stacked=False, ax=f.gca())\nplt.legend(loc='center left', bbox_to_anchor=(1.0, 0.5))\nplt.ylabel('proportion in %')\nplt.title('Proportion of day/night/twilight for each species')\nplt.tight_layout()\nplt.show()\n\n#%% Timelaps images\n\ndf = data.set_index('file_id')\n\ndirectory = '../data/DeepLearning/DeepLearning/'\n\nidx = 14\n\ntitle1 = 'Timelaps image ' + str(idx) + ' with label: ' + str(df.taxon_name[idx])\nimg1 = cv2.imread(directory + df.file_path[idx][8:]).astype(np.float32)/255\nimg1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB)\n\nidx = idx+1\n\ntitle2 = 'Timelaps image ' + str(idx) + ' with label: ' + str(df.taxon_name[idx])\nimg2 = cv2.imread(directory + df.file_path[idx][8:]).astype(np.float32)/255\nimg2 = cv2.cvtColor(img2, cv2.COLOR_BGR2RGB)\n\ntitle3 = 'Difference of the two images'\nimg3 = 0.5*(img2 - img1) + 0.5\n\n# Create figure with subplots\nfig, axes = plt.subplots(nrows=1, ncols=3, figsize=(20, 7))\n\naxes[0].set_title(title1)\naxes[0].imshow(img1)\naxes[0].get_xaxis().set_visible(False) # disable x-axis\naxes[0].get_yaxis().set_visible(False) # disable y-axis\n\naxes[1].set_title(title2)\naxes[1].imshow(img2)\naxes[1].get_xaxis().set_visible(False) # disable x-axis\naxes[1].get_yaxis().set_visible(False) # disable y-axis\n\naxes[2].set_title(title3)\naxes[2].imshow(img3)\naxes[2].get_xaxis().set_visible(False) # disable x-axis\naxes[2].get_yaxis().set_visible(False) # disable y-axis\n\nplt.show()\n\n#%% Events number and images number\n\nevents = df.groupby(['event_id']).count()\n\nf=plt.figure()\nplt.subplot(121)\nevents.file_path.hist(ax=f.gca(), bins=50)\nplt.ylabel('Number of events')\nplt.xlabel('Number of images')\nplt.title('Number of images per events')\nplt.tight_layout()\nplt.show()\n\nplt.subplot(122)\nbins = np.arange(0, events.file_path.max() + 0.5) - 0.5\nevents.file_path.hist(ax=f.gca(),bins=bins)\nplt.ylabel('Number of events')\nplt.xlabel('Number of images')\nplt.title('Number of images per events')\nplt.tight_layout()\nplt.xlim([0, 25])\nplt.show()\n\n#%% Examples of images\n\nrandom.seed(4)\nrand_path = random.sample(list(data_clr.file_path),8)\n\n# Create figure with subplots\nfig, axes = plt.subplots(nrows=2, ncols=4, figsize=(15, 5))\n\n# Plot the 16 kernels from the first convolutional layer\nfor i, axis in enumerate(axes.flatten()):\n img = cv2.imread(directory + rand_path[i][8:]).astype(np.float32)/255\n if len(img.shape) > 2:\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n \n axis.set_title('Image: {}'.format(rand_path[i][8:]))\n axis.imshow(img)\n axis.get_xaxis().set_visible(False) # disable x-axis\n axis.get_yaxis().set_visible(False) # disable y-axis\n \nplt.show()\n","repo_name":"JSmets/Lepus","sub_path":"proposal/proposal_figures.py","file_name":"proposal_figures.py","file_ext":"py","file_size_in_byte":7093,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33226746601","text":"from api import Insta_App\n\n\n\nclass send_DM:\n\n def __init__(self):\n super().__init__()\n\n self.api = Insta_App()\n\n \n def send_direct_msg(self):\n ''' 다이렉트 메세지를 보냅니다. '''\n \n # self.api.login('abigailsmithley','abigailsmithley3')\n self.api.send_dm('zerowater_health')\n\n\n\n\n\nif __name__ == '__main__':\n s = send_DM()\n s.send_direct_msg()","repo_name":"zerowater-may/git-practice","sub_path":"adb/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7822792849","text":"import sys\n\ndef quickSort(listData):\n pivot = len(listData) // 2\n if pivot == 0:\n return listData\n frontData = []\n middleData = []\n backData = []\n for data in listData:\n if data < listData[pivot]:\n frontData.append(data)\n elif data > listData[pivot]:\n backData.append(data)\n else:\n middleData.append(data)\n return quickSort(frontData) + middleData + quickSort(backData)\n\n\nn, l = map(int, sys.stdin.readline().split())\npositions = quickSort(list(map(int, sys.stdin.readline().split())))\n\ncount = 0\ncoveredPosition = 0\nfor position in positions:\n if position > coveredPosition:\n count += 1\n coveredPosition = position + l - 1\nprint(count)","repo_name":"easyandones/Algorithm","sub_path":"Baekjoon/Python/1449.py","file_name":"1449.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8295030501","text":"from guizero import App, PushButton\nfrom gpiozero import LED\nimport sys\n\nled = LED(21)\n\ndef exitApp():\n sys.exit()\n \ndef toggleLED():\n led.toggle()\n if led.is_lit :\n ledButton.text =\"LED OFF\" \n else :\n ledButton.text =\"LED ON\" \n \napp = App('First Gui', height = 600, width = 800)\n\nledButton = PushButton(app, toggleLED, text=\"LED ON\", align=\"top\",width = 15, height = 3)\nledButton.text_size = 36\n\nexitButton = PushButton(app, exitApp, text=\"Exit\", align=\"bottom\" , width = 15, height = 3)\nexitButton.text_size = 36\n\napp.display()","repo_name":"educ8s/Raspberry-Pi-Simple-Gui","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"72788468945","text":"import os\nimport sqlite3\nfrom datetime import datetime\n\nimport dotenv\nfrom flask import (Flask, flash, jsonify, redirect, render_template, request,\n session)\nfrom flask_session import Session\nfrom werkzeug.security import check_password_hash, generate_password_hash\nfrom werkzeug.utils import secure_filename\n\nfrom .helpers import (FULL_UPLOAD_FOLDER, UPLOAD_FOLDER, allowed_file,\n erase_picture, find_pic, give_feedback, list_to_html,\n login_required)\n\ndotenv.load_dotenv('../.env')\n\napp = Flask(__name__)\n\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\napp.config['MAX_CONTENT_LENGTH'] = 5 * 1024 * 1024 # limit uploads size to 5MB\napp.config['SECRET_KEY'] = os.getenv('SECRET_KEY')\napp.config[\"TEMPLATES_AUTO_RELOAD\"] = True\n\napp.config[\"SESSION_FILE_DIR\"] = './sessions/'\napp.config[\"SESSION_PERMANENT\"] = False\napp.config[\"SESSION_TYPE\"] = \"filesystem\"\n\nSession(app)\n\n\n@app.route('/')\ndef index():\n try:\n return redirect(f\"/profile/{session['username']}\")\n except KeyError:\n return redirect(\"/login\")\n\n\n@app.route(\"/profile/\", methods=[\"GET\", \"POST\"])\n@login_required\ndef profile(username):\n \"\"\"Display (even other) user's profile page and handle new posts\"\"\"\n\n if request.method == 'GET':\n\n # check if user has changed the default jokes display order\n try:\n order = session['order']\n except KeyError:\n order = 'date_time'\n\n # connect to the data base\n connection = sqlite3.connect('phun.db')\n # set a cursor to simulate the blinking prompt\n cursor = connection.cursor()\n\n # get info regarding the user, their posts and all the jokes they voted for\n user_id = cursor.execute('SELECT id FROM users WHERE username = ?', [username]).fetchone()\n user_jokes = cursor.execute(f'SELECT joke, rating, user_id, id FROM jokes WHERE user_id = (?) ORDER BY {order} DESC',\n [user_id[0]]).fetchall()\n all_user_votes = cursor.execute('SELECT * FROM votes WHERE user_id = ?', [session['user_id']]).fetchall()\n q = 'SELECT * FROM comments WHERE joke_id IN (SELECT id FROM jokes WHERE user_id = ?)'\n comments = cursor.execute(q, [user_id[0]]).fetchall()\n\n # close connection(.quit)\n connection.close()\n\n # look for the user's profile pic\n ppic = find_pic(user_id[0])\n # get commenters profile pictures\n c_pics = {}\n for row in comments:\n c_pics[row[1]] = find_pic(row[1])\n\n return render_template(\"profile.html\",\n ppic=ppic,\n username=username,\n user_jokes=list_to_html(user_jokes),\n all_user_votes=all_user_votes,\n comments=list_to_html(comments),\n c_pics=c_pics,\n user_id=user_id[0])\n else:\n # ensure user inputs a joke\n joke = request.form.get('joke')\n if not joke or joke.strip() == '':\n flash('😜 Was that supposed to be a joke? 😜', 'alert-info')\n return redirect(\"/\")\n\n # get current date and time\n now = datetime.now()\n\n connection = sqlite3.connect('phun.db')\n cursor = connection.cursor()\n\n # register joke in the database, so that we can remember it\n cursor.execute('INSERT INTO jokes (user_id, joke, rating, date_time) VALUES (?, ?, ?, ?)',\n [session['user_id'], joke, 0, now])\n\n # save changes to database\n connection.commit()\n connection.close()\n\n return redirect('/')\n\n\n@app.route('/sort/', methods=['POST'])\n@login_required\ndef sort(order):\n \"\"\"Sort jokes in profile page\"\"\"\n\n # storing value in session seemed better than displaying it in the url\n session['order'] = order\n #return None\n return ('', 204)\n\n\n@app.route('/upload_pic', methods=['POST'])\n@login_required\ndef upload_pic():\n \"\"\"Handle picture uploads\"\"\"\n\n # check if the post request has the file part\n if 'file' not in request.files:\n flash('😕 Something went wrong with the request, please try again 😕', 'alert-info')\n return redirect('/')\n f = request.files['file']\n\n # if user does not select file, browser also submit an empty part without filename\n if f.filename == '':\n flash('😐 No selected file 😐', 'alert-info')\n return redirect('/')\n\n # ensure user inputs an allowed file type\n if allowed_file(f.filename):\n # use secure_filename() to protect against malicious filenames, that could mess everything up\n filename = secure_filename(f.filename)\n # get the file extension\n ext = filename.rsplit('.', 1)[1].lower()\n\n # erase user's former picture, if there is one\n erase_picture(find_pic(session['user_id']))\n # save new picture in the system\n f.save(os.path.join(FULL_UPLOAD_FOLDER, f\"{session['user_id']}.{ext}\"))\n return redirect('/')\n else:\n flash('😬 File type not allowed. Profile pictures must be .png, .jpg, .jpeg or .gif 😬', 'alert-warning')\n return redirect('/')\n\n\n@app.route('/rate/', methods=[\"POST\"])\n@login_required\ndef rate(vote):\n \"\"\"Handle joke voting\"\"\"\n\n connection = sqlite3.connect('phun.db')\n cursor = connection.cursor()\n\n # vote[0] is the joke id and vote[1] is the vote itself, either add or remove\n vote = vote.split(',', 1)\n joke_id = vote[0]\n\n if vote[1] == 'add':\n # ensure users can't vote more than once for a single joke\n if not cursor.execute('SELECT * FROM votes WHERE user_id = (?) AND joke_id = (?)',\n [session['user_id'], joke_id]).fetchone():\n # remember user's vote for this joke\n cursor.execute('INSERT INTO votes (user_id, joke_id) VALUES (?, ?)',\n [session['user_id'], joke_id])\n else:\n # ensure users can only remove their own votes\n if cursor.execute('SELECT * FROM votes WHERE user_id = (?) AND joke_id = (?)',\n [session['user_id'], joke_id]).fetchone():\n # remove user's vote from this joke\n cursor.execute('DELETE FROM votes WHERE user_id = (?) AND joke_id = (?)',\n [session['user_id'], joke_id])\n\n # update votes count\n cursor.execute('UPDATE jokes SET rating = (SELECT COUNT() FROM votes WHERE joke_id = (?)) WHERE id = (?)', [joke_id, joke_id])\n # get that joke's current rating\n rating = cursor.execute('SELECT rating FROM jokes WHERE id = ?', [joke_id]).fetchone()\n\n connection.commit()\n connection.close()\n\n # return rating to js as a json, so that the vote count(rating) can be visually updated\n return jsonify(rating)\n\n\n@app.route('/posts/')\n@login_required\ndef posts(sort_order):\n \"\"\" Display all posts \"\"\"\n\n # change page's title and heading according to the order of display\n if sort_order == 'newest':\n order_by = 'date_time'\n title = 'Newest'\n else:\n order_by = 'rating'\n title = 'Phuniest'\n\n connection = sqlite3.connect('phun.db')\n cursor = connection.cursor()\n\n # get all users info, posts and all the jokes they voted for\n all_users = cursor.execute('SELECT id, username FROM users').fetchall()\n all_jokes = cursor.execute(f'SELECT joke, rating, user_id, id FROM jokes ORDER BY {order_by} DESC').fetchall()\n all_user_votes = cursor.execute('SELECT * FROM votes WHERE user_id = ?', [session['user_id']]).fetchall()\n all_comments = cursor.execute('SELECT * FROM comments').fetchall()\n connection.close()\n\n # get all users profile pictures\n all_pics = {}\n for row in all_users:\n all_pics[row[0]] = find_pic(row[0])\n\n return render_template('posts.html',\n all_jokes=list_to_html(all_jokes),\n all_users=all_users,\n all_user_votes=all_user_votes,\n all_pics=all_pics,\n all_comments=list_to_html(all_comments),\n title=title)\n\n\n@app.route('/comment/', methods=[\"POST\"])\n@login_required\ndef comment(joke_id):\n \"\"\"Add comment to a joke\"\"\"\n\n comment = request.form['comment']\n\n # add comment to database\n connection = sqlite3.connect('phun.db')\n cursor = connection.cursor()\n\n cursor.execute('INSERT INTO comments (comment, user_id, joke_id, c_username) VALUES (?, ?, ?, ?)',\n [comment, session['user_id'], joke_id, session['username']])\n # retrieve the comment_id of the row that have just been inserted\n # if two people are using different cursors, that should be transaction safe\n comment_id = cursor.lastrowid\n\n connection.commit()\n connection.close()\n\n info = {\n 'user_id': session['user_id'],\n 'username': session['username'],\n 'ppic': find_pic(session['user_id']),\n 'comment_id': comment_id\n }\n return jsonify(info)\n\n\n@app.route('/delete/', methods=[\"POST\"])\n@login_required\ndef delete_post(stuff):\n\n connection = sqlite3.connect('phun.db')\n cursor = connection.cursor()\n\n if stuff == 'joke':\n\n joke_id = request.form['joke_id']\n cursor.execute('DELETE FROM jokes WHERE id = ?', [joke_id])\n\n # the joke that user wants to delete may or may not have comments and votes,\n # so the try except clause prevents the server from crashing\n try:\n cursor.execute('DELETE FROM comments WHERE joke_id = ?', [joke_id])\n cursor.execute('DELETE FROM votes WHERE joke_id = ?', [joke_id])\n except:\n pass\n\n if stuff == 'comment':\n\n comment_id = request.form['comment_id']\n cursor.execute('DELETE FROM comments WHERE comment_id = ?', [comment_id])\n\n if stuff == 'account':\n\n # delete user from the users table and anything else that may exist related to him\n cursor.execute('DELETE FROM users WHERE id = ?', [session['user_id']])\n try:\n cursor.execute('DELETE FROM jokes WHERE user_id = ?', [session['user_id']])\n cursor.execute('DELETE FROM comments WHERE user_id = ?', [session['user_id']])\n\n # fetchall() returns a list of tupples\n jokes_ids = cursor.execute(f\"SELECT joke_id FROM votes WHERE user_id = {session['user_id']}\").fetchall()\n # so even when iterating over the results, in order to get a 'clean' data\n # we must index into the first and only element of each tupple inside the list\n for joke_id in jokes_ids:\n cursor.execute(\"UPDATE jokes SET rating = (SELECT COUNT() FROM votes WHERE user_id != (?) AND joke_id = (?)) WHERE id = (?)\",\n [session['user_id'], joke_id[0], joke_id[0]])\n\n cursor.execute('DELETE FROM votes WHERE user_id = ?', [session['user_id']])\n except:\n pass\n\n connection.commit()\n connection.close()\n\n erase_picture(find_pic(session['user_id']))\n session.clear()\n flash(\"😭 Baby please don't go 😭\", 'alert-info')\n return redirect('/login')\n\n connection.commit()\n connection.close()\n\n # that's how we properly return 'None'\n return ('', 204)\n\n\n@app.route(\"/login\", methods=[\"GET\", \"POST\"])\ndef login():\n \"\"\"Log user in\"\"\"\n\n if request.method == 'POST':\n\n if not request.form.get('username/email'):\n flash(\"😑 Missing username or e-mail 😑\", \"alert-danger\")\n return redirect(\"/login\")\n if not request.form.get('password'):\n flash(\"😑 Missing password 😑\", \"alert-danger\")\n return redirect(\"/login\")\n\n connection = sqlite3.connect('phun.db')\n cursor = connection.cursor()\n\n # ensure credentials are correct(fetchone() grabs one result from the query's output and returns a tupple)\n query = cursor.execute('SELECT * FROM users WHERE username = ?',\n [request.form.get('username/email')]).fetchone()\n if not query:\n query = cursor.execute('SELECT * FROM users WHERE email = ?',\n [request.form.get('username/email')]).fetchone()\n if not query or not check_password_hash(query[2], request.form.get('password')):\n flash('😐 Invalid username, e-mail and/or password 😐', 'alert-danger')\n connection.close()\n return redirect('/login')\n\n # remember which user has logged in\n session['user_id'] = query[0]\n session['username'] = query[1]\n session['email'] = query[3]\n connection.close()\n return redirect('/')\n\n else:\n return render_template(\"login.html\")\n\n\n@app.route(\"/register\", methods=[\"GET\", \"POST\"])\ndef register():\n \"\"\"Register user\"\"\"\n\n if request.method == \"POST\":\n\n inputs = request.form\n # cool one line if else statement\n all = True if len(inputs) == 4 else False\n feedback = give_feedback(inputs, inputs.keys(), all)\n\n # that is, if not all inputs are valid\n for key in feedback:\n if feedback[key] != '🤗 Perfect 🤗':\n return jsonify(feedback)\n\n # that is, if user is not submitting the whole form\n if not all:\n return jsonify(feedback)\n\n # never store plaintext password\n password = generate_password_hash(inputs['password'])\n\n connection = sqlite3.connect('phun.db')\n cursor = connection.cursor()\n\n cursor.execute(\"INSERT INTO users (username, hash, email) VALUES (?, ?, ?)\",\n [inputs['username'], password, inputs['email'],])\n\n connection.commit()\n connection.close()\n\n flash(\"😎 Registration succesfull! 😎\", \"alert-success\")\n return jsonify('200 OK')\n\n else:\n return render_template(\"register.html\")\n\n\n@app.route(\"/logout\")\ndef logout():\n \"\"\"Log user out\"\"\"\n\n # forget any information stored in session\n session.clear()\n flash(\"😢 You are logged out 😢\", \"alert-info\")\n return redirect(\"/\")\n","repo_name":"cayo-rodrigues/joking","sub_path":"app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":14417,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"14222910795","text":"class Node:\n \"\"\"This class creates the node \"\"\"\n def __init__(self,value):\n self.value=value\n self.next= None\n\nclass linkedlist:\n \"\"\"this class append and delete a node\"\"\"\n def __init__(self):\n self.head=None\n\n def append(self,node):\n \"\"\"this is responseble to append a node\"\"\"\n if self.head==None:\n self.head=node\n else:\n current=self.head\n while current.next is not None:\n current = current.next\n current.next = node\n\n def find_middle(self):\n \"\"\"This function will return the mid value of the linked list\"\"\"\n counter=0\n current=self.head\n while current is not None:\n prev=current\n current = current.next\n counter+=1\n if counter==1:\n print(\"the mid is \",prev.value)\n return prev.value\n elif counter==0:\n print (\"the list is empty\")\n return \"the list is empty\" \n elif counter % 2 ==1: \n mid=counter/2 + 0.5\n elif counter % 2 ==0:\n mid=counter/2+1 \n \n counter=1\n current=self.head\n while current.next is not None:\n current = current.next\n counter+=1\n if counter==mid:\n print(\"the mid is \",current.value)\n return current.value\n \n def printAll(self):\n \"\"\"this is for printing\"\"\"\n if self.head is None:\n print(\"The linked list is empty\")\n else:\n current = self.head\n while current is not None:\n print(current.value)\n current = current.next\n\n \n def test_fun(self):\n \"\"\"this is for testing\"\"\"\n lst=[]\n if self.head is None:\n return\"The linked list is empty\"\n else:\n current = self.head\n while current is not None:\n lst.append(current.value)\n current = current.next\n return lst\n\n\n\nlinkedList1 = linkedlist()\nnode1 = Node(\"1\")\nlinkedList1.append(node1)\n\nnode2 = Node(\"2\")\nlinkedList1.append(node2)\n\nnode3 = Node(\"3\")\nlinkedList1.append(node3)\n\nnode4 = Node(\"4\")\nlinkedList1.append(node4)\n\nnode5 = Node(\"5\")\nlinkedList1.append(node5)\n\nnode6 = Node(\"6\")\nlinkedList1.append(node6)\nlinkedList1.printAll() \n\nlinkedList1.find_middle()","repo_name":"osamadado123/Code-Challenges-and-Algorithms","sub_path":"python/code_challenges/linkedlist/challenge02/challenge02.py","file_name":"challenge02.py","file_ext":"py","file_size_in_byte":2409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"43294590768","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[2]:\n\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# Load the dataset\niris = pd.read_csv('Iris.csv')\n\n\n# In[3]:\n\n\nprint(iris.head())\n\n\n# In[4]:\n\n\n# Scatter plot of sepal length vs sepal width\nplt.scatter(iris['SepalLengthCm'], iris['SepalWidthCm'])\nplt.xlabel('Sepal Length (cm)')\nplt.ylabel('Sepal Width (cm)')\nplt.show()\n\n\n# In[5]:\n\n\n# Scatter plot of petal length vs petal width, colored by species\ncolors = {'Iris-setosa': 'red', 'Iris-versicolor': 'green', 'Iris-virginica': 'blue'}\nplt.scatter(iris['PetalLengthCm'], iris['PetalWidthCm'], c=iris['Species'].map(colors))\nplt.xlabel('Petal Length (cm)')\nplt.ylabel('Petal Width (cm)')\nplt.show()\n\n\n# In[6]:\n\n\n# Box plot of sepal width by species\nplt.boxplot([iris[iris['Species']=='Iris-setosa']['SepalWidthCm'],\n iris[iris['Species']=='Iris-versicolor']['SepalWidthCm'],\n iris[iris['Species']=='Iris-virginica']['SepalWidthCm']],\n labels=['Iris-setosa', 'Iris-versicolor', 'Iris-virginica'])\nplt.ylabel('Sepal Width (cm)')\nplt.show()\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"Jawadak47/hello","sub_path":"iris dataset.py","file_name":"iris dataset.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42366955028","text":"import math\n\nfrom CONST import *\nfrom draw import *\n\ndef find_closest_point(pos):\n '''\n Finds the closest hexagon based on a position\n '''\n min_distance = float('inf')\n closest_point = None\n\n for point in ALL_POS: # Loop over all points on the screen\n x1, y1 = point\n x2, y2 = pos\n distance = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2) # Find distance between clicked point and target point\n if distance < min_distance:\n min_distance = distance\n closest_point = point\n\n if closest_point in HEXAGON_POS: # Check if closest point is on a hexagon\n return closest_point # Return closest point if it is a hexagon\n else:\n return None # Else return None\n\ndef find_hexagon(pos):\n '''\n Given a certain x,y position, check if there is a hexagon on screen\n '''\n try:\n return POS_TO_TILE[pos] # Returns the index of the hexagon\n except:\n return None # Else returns None\n\ndef selected_hexagons(pos, selected_hexagon, board, turn, surface):\n '''\n Logic regarding what hexagon has to be selected, if this is the first or\n second hexagon which is selected, and when a square has to be deselected\n '''\n first, second = selected_hexagon\n hexagon = find_hexagon(pos)\n y,x = hexagon\n try:\n selected_color = board[x][y].piece.color\n except:\n selected_color = None\n\n if first is None and second is None and selected_color == turn:\n board[x][y].selected = True\n return (hexagon, None)\n elif first is not None and second is None and hexagon is not first and selected_color != turn:\n board[x][y].selected = True\n return (first, hexagon)\n elif first is not None and second is None and hexagon is not first and selected_color == turn:\n return (first, None)\n elif first is not None and second is not None and first != second:\n board[x][y].selected = True\n return (first, second)\n elif first is not None and first == hexagon:\n draw_board(surface, COLOR_BOARD)\n draw_pieces(surface, board)\n return (None, None) \n else:\n return (None, None)\n\ndef deselect_hexagons(surface, board):\n '''\n Deselect a hexagon after a move has been made, or the player clicked the hexagon again.\n '''\n draw_board(surface, COLOR_BOARD)\n draw_pieces(surface, board)\n return (None, None)\n\ndef deselect_piece(surface, board):\n '''\n Deselect a piece after a move has been made, or the piece has been pressed again\n '''\n draw_board(surface, COLOR_BOARD)\n draw_pieces(surface, board)\n return None\n\ndef switch_turns(turn):\n '''\n Switch the turn between players\n '''\n if turn == 'white':\n return 'black'\n return 'white'\n\ndef make_move(board, move, piece):\n '''\n When a move is made, make the actual move on the board\n '''\n board[move.initial[1]][move.initial[0]].piece = None\n piece.position = move.target\n piece.coords = TILE_TO_POS[piece.position]\n board[move.target[1]][move.target[0]].piece = piece\n\ndef on_board(position, board):\n '''\n Check if a given position is on the board\n ''' \n row, col = position\n try:\n if board[col][row] != None:\n return True\n except:\n return False\n\ndef empty_hexagon(position, board):\n '''\n Return if a square is empty\n '''\n row, col = position\n try:\n if board[col][row].piece == None:\n return True\n except:\n return False\n\ndef piece_color_on_position(position, board):\n '''\n Return color of piece on hexagon position\n '''\n row, col = position\n return board[col][row].piece.color\n\ndef find_target_locations(moves):\n '''\n Gatheres all the locations where a piece can go to, such that we can draw this on the screen\n '''\n targets = []\n for move in moves:\n targets.append(move.target)\n return targets\n\ndef has_moved(piece):\n '''\n Sets the variable has_moved true for a pawn if it moves\n '''\n if piece.name == 'pawn':\n piece.has_moved = True","repo_name":"mattijsgietman/Hexagon-Chess","sub_path":"helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":4151,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70846703825","text":"from collections import deque\n\nn = int(input())\nlst = deque(range(1,n+1))\ncnt = 0\ncard = 0\nwhile lst:\n cnt+=1\n card = lst.popleft()\n if cnt % 2 == 0:\n lst.append(card)\nprint(card)","repo_name":"hvvany/TIL","sub_path":"Algorithm/Baekjoon/code_folder/2164.py","file_name":"2164.py","file_ext":"py","file_size_in_byte":185,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"22548893885","text":"import requests\n\n\ndef get_web_page(link, retries=5):\n\tpage = None\n\ti = 1\n\twhile i < retries:\n\t\ttry:\n\t\t\tpage = requests.get(link)\n\t\t\tbreak\n\t\texcept requests.exceptions.RequestException as err:\n\t\t\tprint(err)\n\t\t\ti += 1\n\treturn page\n","repo_name":"matjojo/fanfiction_parser","sub_path":"src/parsers/_parsers_util.py","file_name":"_parsers_util.py","file_ext":"py","file_size_in_byte":229,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20115258884","text":"# 바이낸스, 상승장, 변동성 돌파, 변동성 조절 Coins : [BTC, ETH, XRP, LTC]\n# nohup python3 binance8.py > output.log &\nimport ccxt\nimport time\nimport datetime\nimport math\nimport logging\nimport pandas as pd\nimport bibase as bb\n\nlogging.basicConfig(filename='binance8.log', level=logging.INFO, format='%(asctime)s:%(message)s:%(lineno)d')\n\t\naccess_key = \"a\"\nsecret_key = \"b\"\nbinance = ccxt.binance({'apiKey': access_key, 'secret': secret_key})\n\n# with open(\"/Users/sugang/Desktop/school/\" + \"bibi.txt\")as f:\n# lines = f.readlines()\n# access_key = lines[2].strip()\n# secret_key = lines[3].strip()\n# binance = ccxt.binance({'apiKey': access_key, 'secret': secret_key})\n\ntickers = [\"BTC/USDT\", \"ETH/USDT\", \"XRP/USDT\", \"LTC/USDT\"]\ntarget_v = 0.05\nk = 0.5\n\ndef get_range(ticker):\n df = bb.get_daily_ohlcv_from_base(ticker)\n y_day = df.iloc[-2]\n\n y_high = y_day['high']\n y_low = y_day['low']\n range = y_high - y_low\n return range\n\ndef get_open(ticker):\n df = bb.get_daily_ohlcv_from_base(ticker)\n today = df.iloc[-1]\n open = today['open']\n return open\n\ndef get_y_open(ticker):\n df = bb.get_daily_ohlcv_from_base(ticker)\n today = df.iloc[-2]\n open = today['open']\n return open\n\ndef get_percentage(ticker):\n range = get_range(ticker)\n y_open = get_y_open(ticker)\n range_ratio = range/y_open\n if target_v > range_ratio:\n percentage = 1/4\n else:\n percentage = (1/4)*(target_v/range_ratio)\n return percentage\n\ndef get_target_price(ticker):\n df = bb.get_daily_ohlcv_from_base(ticker)\n today = df.iloc[-1]\n\n t_open = today['open']\n range = get_range(ticker)\n target_price = t_open + range * k\n return target_price\n\ndef get_ma5(ticker):\n df = bb.get_daily_ohlcv_from_base(ticker)\n open = df['open']\n ma = open.rolling(window=5).mean()\n return ma[-1]\n\ndef buyable():\n btc_price = get_target_price(\"BTC/USDT\")\n btc_price = btc_price * 1.002\n btc_price = btc_price * 100\n btc_price = math.floor(btc_price)\n btc_price = btc_price + 1\n btc_price = btc_price / 100\n\n eth_price = get_target_price(\"ETH/USDT\")\n eth_price = eth_price * 1.002\n eth_price = eth_price * 100\n eth_price = math.floor(eth_price)\n eth_price = eth_price + 1\n eth_price = eth_price / 100\n\n xrp_price = get_target_price(\"XRP/USDT\")\n xrp_price = xrp_price * 1.002\n xrp_price = xrp_price * 10000\n xrp_price = math.floor(xrp_price)\n xrp_price = xrp_price + 1\n xrp_price = xrp_price / 10000\n\n ltc_price = get_target_price(\"LTC/USDT\")\n ltc_price = ltc_price * 1.002\n ltc_price = ltc_price * 10\n ltc_price = math.floor(ltc_price)\n ltc_price = ltc_price + 1\n ltc_price = ltc_price / 10\n\n return btc_price, eth_price, xrp_price, ltc_price\n\ndef buy_btc(balance):\n percentage = get_percentage(\"BTC/USDT\")\n balance = balance * percentage\n btc_price = buyable()[0]\n unit = balance/float(btc_price)\n binance.create_limit_buy_order(\"BTC/USDT\", unit, btc_price)\n\ndef buy_eth(balance):\n percentage = get_percentage(\"ETH/USDT\")\n balance = balance * percentage\n eth_price = buyable()[1]\n unit = balance/float(eth_price)\n binance.create_limit_buy_order(\"ETH/USDT\", unit ,eth_price)\n\ndef buy_xrp(balance):\n percentage = get_percentage(\"XRP/USDT\")\n balance = balance * percentage\n xrp_price = buyable()[2]\n unit = balance/float(xrp_price)\n binance.create_limit_buy_order(\"XRP/USDT\", unit, xrp_price)\n\ndef buy_ltc(balance):\n percentage = get_percentage(\"LTC/USDT\")\n balance = balance * percentage\n ltc_price = buyable()[3]\n unit = balance/float(ltc_price)\n binance.create_limit_buy_order(\"LTC/USDT\", unit, ltc_price)\n\ndef sellable():\n btc_price = binance.fetch_ticker(\"BTC/USDT\")\n btc_price = btc_price['close']\n btc_price = btc_price * 0.998\n btc_price = btc_price * 100\n btc_price = math.floor(btc_price)\n btc_price = btc_price - 1\n btc_price = btc_price / 100\n\n eth_price = binance.fetch_ticker(\"ETH/USDT\")\n eth_price = eth_price['close']\n eth_price = eth_price * 0.998\n eth_price = eth_price * 100\n eth_price = math.floor(eth_price)\n eth_price = eth_price - 1\n eth_price = eth_price / 100\n\n xrp_price = binance.fetch_ticker(\"XRP/USDT\")\n xrp_price = xrp_price['close']\n xrp_price = xrp_price * 0.998\n xrp_price = xrp_price * 10000\n xrp_price = math.floor(xrp_price)\n xrp_price = xrp_price - 1\n xrp_price = xrp_price / 10000\n\n ltc_price = binance.fetch_ticker(\"LTC/USDT\")\n ltc_price = ltc_price['close']\n ltc_price = ltc_price * 0.998\n ltc_price = ltc_price * 10\n ltc_price = math.floor(ltc_price)\n ltc_price = ltc_price - 1\n ltc_price = ltc_price / 10\n\n return btc_price, eth_price, xrp_price, ltc_price\n\ndef sell_limit():\n btc_unit = binance.fetch_balance()[\"BTC\"]['free']\n eth_unit = binance.fetch_balance()[\"ETH\"]['free']\n xrp_unit = binance.fetch_balance()[\"XRP\"]['free']\n ltc_unit = binance.fetch_balance()[\"LTC\"]['free']\n try:\n if btc_unit > 0:\n btc_price = sellable()[0]\n binance.create_limit_sell_order(\"BTC/USDT\", btc_unit, btc_price)\n except Exception as e:\n logging.info(\"btc sell error : \" + str(e))\n\n try:\n if eth_unit > 0:\n eth_price = sellable()[1]\n binance.create_limit_sell_order(\"ETH/USDT\", eth_unit, eth_price)\n except Exception as e:\n logging.info(\"eth sell error : \" + str(e))\n\n try:\n if xrp_unit > 0:\n xrp_price = sellable()[2]\n binance.create_limit_sell_order(\"XRP/USDT\", xrp_unit, xrp_price)\n except Exception as e:\n logging.info(\"xrp sell error : \" + str(e))\n\n try: \n if ltc_unit > 0:\n ltc_price = sellable()[3]\n binance.create_limit_sell_order(\"LTC/USDT\", ltc_unit, ltc_price)\n except Exception as e:\n logging.info(\"ltc sell error : \" + str(e))\n\ndef get_current_price(ticker):\n price = binance.fetch_ticker(ticker)\n price = price['close']\n return price\n\nnow = datetime.datetime.now()\nten = datetime.datetime(now.year, now.month, now.day) + datetime.timedelta(hours=10)\nif now > ten:\n ten = ten + datetime.timedelta(1)\n\na = 0\nwhile a == 0:\n try:\n btc_open = get_open(\"BTC/USDT\")\n btc_ma5 = get_ma5(\"BTC/USDT\")\n btc_target = get_target_price(\"BTC/USDT\")\n btc_percent = get_percentage(\"BTC/USDT\")\n btc_status = 0\n\n eth_open = get_open(\"ETH/USDT\")\n eth_ma5 = get_ma5(\"ETH/USDT\")\n eth_target = get_target_price(\"ETH/USDT\")\n eth_percent = get_percentage(\"ETH/USDT\")\n eth_status = 0\n\n xrp_open = get_open(\"XRP/USDT\")\n xrp_ma5 = get_ma5(\"XRP/USDT\")\n xrp_target = get_target_price(\"XRP/USDT\")\n xrp_percent = get_percentage(\"XRP/USDT\")\n xrp_status = 0\n\n ltc_open = get_open(\"LTC/USDT\")\n ltc_ma5 = get_ma5(\"LTC/USDT\")\n ltc_target = get_target_price(\"LTC/USDT\")\n ltc_percent = get_percentage(\"LTC/USDT\")\n ltc_status = 0\n\n balance = binance.fetch_balance()['USDT']['free']\n logging.info(f\"btc_percent = {btc_percent}, btc_open : {btc_open}, btc_ma5 : {btc_ma5}, btc_target : {btc_target}, btc_status : {btc_status}\")\n logging.info(f\"eth_percent = {eth_percent}, eth_open : {eth_open}, eth_ma5 : {eth_ma5}, eth_target : {eth_target}, eth_status : {eth_status}\")\n logging.info(f\"xrp_percent = {xrp_percent}, xrp_open : {xrp_open}, xrp_ma5 : {xrp_ma5}, xrp_target : {xrp_target}, xrp_status : {xrp_status}\")\n logging.info(f\"ltc_percent = {ltc_percent}, ltc_open : {ltc_open}, ltc_ma5 : {ltc_ma5}, ltc_target : {ltc_target}, ltc_status : {ltc_status}\")\n logging.info(\"initial balance(USDT) : \" + str(balance))\n a = 1\n except Exception as e:\n logging.info(\"initiating error : '\" + str(e) + \"' try again in 5 sec\")\n time.sleep(1)\n\nlogging.info('program started')\n\nwhile True:\n try:\n now = datetime.datetime.now()\n if ten < now:\n if btc_status == 1 or eth_status == 1 or xrp_status == 1 or ltc_status == 1:\n btc_status = 0\n eth_status = 0\n xrp_status = 0\n ltc_status = 0\n logging.info(\"sell try\")\n sell_limit()\n logging.info(\"sell success\")\n time.sleep(60)\n btc_target = get_target_price(\"BTC/USDT\")\n eth_target = get_target_price(\"ETH/USDT\")\n xrp_target = get_target_price(\"XRP/USDT\")\n ltc_target = get_target_price(\"LTC/USDT\")\n btc_ma5 = get_ma5(\"BTC/USDT\")\n eth_ma5 = get_ma5(\"ETH/USDT\")\n xrp_ma5 = get_ma5(\"XRP/USDT\")\n ltc_ma5 = get_ma5(\"LTC/USDT\")\n btc_open = get_open(\"BTC/USDT\")\n eth_open = get_open(\"ETH/USDT\")\n xrp_open = get_open(\"XRP/USDT\")\n ltc_open = get_open(\"LTC/USDT\")\n btc_percent = get_percentage(\"BTC/USDT\")\n eth_percent = get_percentage(\"ETH/USDT\")\n xrp_percent = get_percentage(\"XRP/USDT\")\n ltc_percent = get_percentage(\"LTC/USDT\")\n btc_status = 0\n eth_status = 0\n xrp_status = 0\n ltc_status = 0\n balance = binance.fetch_balance()['USDT']['free']\n ten = datetime.datetime(now.year, now.month, now.day) + datetime.timedelta(days=1, hours=10)\n logging.info(f\"btc_percent = {btc_percent}, btc_open : {btc_open}, btc_ma5 : {btc_ma5}, btc_target : {btc_target}, btc_status : {btc_status}\")\n logging.info(f\"eth_percent = {eth_percent}, eth_open : {eth_open}, eth_ma5 : {eth_ma5}, eth_target : {eth_target}, eth_status : {eth_status}\")\n logging.info(f\"xrp_percent = {xrp_percent}, xrp_open : {xrp_open}, xrp_ma5 : {xrp_ma5}, xrp_target : {xrp_target}, xrp_status : {xrp_status}\")\n logging.info(f\"ltc_percent = {ltc_percent}, ltc_open : {ltc_open}, ltc_ma5 : {ltc_ma5}, ltc_target : {ltc_target}, ltc_status : {ltc_status}\")\n logging.info(\"initial balance(USDT) : \" + str(balance))\n\n btc_current_price = get_current_price(\"BTC/USDT\")\n eth_current_price = get_current_price(\"ETH/USDT\")\n xrp_current_price = get_current_price(\"XRP/USDT\")\n ltc_current_price = get_current_price(\"LTC/USDT\")\n\n if btc_current_price > btc_target and btc_status == 0 and btc_open > btc_ma5:\n buy_btc(balance)\n logging.info(\"BTC get\")\n btc_status = 1\n\n if eth_current_price > eth_target and eth_status == 0 and eth_open > eth_ma5:\n buy_eth(balance)\n logging.info(\"ETH get\")\n eth_status = 1\n\n if xrp_current_price > xrp_target and xrp_status == 0 and xrp_open > xrp_ma5:\n buy_xrp(balance)\n logging.info(\"XRP get\")\n xrp_status = 1\n\n if ltc_current_price > ltc_target and ltc_status == 0 and ltc_open > ltc_ma5:\n buy_ltc(balance)\n logging.info(\"LTC get\")\n ltc_status = 1\n\n except Exception as e:\n logging.info(\"programm error : \" + str(e))\n time.sleep(1)","repo_name":"suganglive/coinauto","sub_path":"noneed/binance8.py","file_name":"binance8.py","file_ext":"py","file_size_in_byte":11181,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7823223193","text":"from typing import List, Union\n\ndef get_inductees(names: List[str], dates: List[Union[int, None]], genders: List[Union[str, None]]) -> None:\n\tcur_year = 2021\n\tdef create_humans(names: List[str], dates: List[Union[int, None]], genders: List[Union[str, None]]) -> List[dict]:\n\t\tres = []\n\t\tfor i in range(len(names)):\n\t\t\thuman = {\n\t\t\t\t\"name\": names[i],\n\t\t\t}\n\t\t\tif dates[i] is not None:\n\t\t\t\thuman[\"birth_year\"] = dates[i]\n\t\t\tif genders[i] is not None:\n\t\t\t\thuman[\"gender\"] = genders[i]\n\t\t\tres.append(human)\n\t\treturn res\n\thumans = create_humans(names, dates, genders)\n\n\tdef q(humans: List[dict], cur_year=cur_year):\n\t\t\"\"\"Фильтрация военнообязанных\"\"\"\n\t\treturn [\n\t\t\thuman for human in humans\n\t\t\tif (\n\t\t\t\tcur_year - human.get(\"birth_year\", 2023) >= 18\n\t\t\t\tand\n\t\t\t\thuman.get(\"gender\") == \"Male\")\n\t\t\t]\n\n\tdef q2(humans: List[dict], cur_year=cur_year):\n\t\t\"\"\"Фильтрация военнообязанных под вопросом\"\"\"\n\t\t# Проверка исполнена муторно, но верно\n\t\treturn [\n\t\t\thuman for human in humans\n\t\t\tif (\n\t\t\t\t\t(human.get(\"gender\") is None and human.get(\"birth_year\") is None)\n\t\t\t\t\tor\n\t\t\t\t\t(human.get(\"gender\") is None and cur_year - human.get(\"birth_year\") >= 18)\n\t\t\t\t\tor\n\t\t\t\t\t(human.get(\"gender\") == \"Male\" and human.get(\"birth_year\") is None)\n\t\t\t\t)\n\t\t\t]\n\n\tsearching_man = q(humans)\n\tunsure_man = q2(humans)\n\n\tdef pf(man: List[dict], is_sure=True):\n\t\t\"\"\"Вспомогательная функция печати\"\"\"\n\t\tman_str_form = []\n\t\tsure_str_form = '' if is_sure else '- под вопросом'\n\t\tfor men in man:\n\t\t\tman_str_form.append(f'{men[\"name\"]}, {men.get(\"birth_year\", \"неизвестного\")} года рождения {sure_str_form}')\n\t\tprint(\"\\n\".join(man_str_form))\n\n\tpf(searching_man)\n\tprint(\"=\" * 40)\n\tpf(unsure_man, False)\n","repo_name":"demogi4523/testy_gform_programmers_in_hi","sub_path":"2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1814,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"39444372396","text":"import keras\nimport keras\nimport numpy as np\nimport tensorflow as tf\nfrom keras.utils import np_utils\nfrom sklearn.model_selection import train_test_split\n\nfrom deepcardio_utils import IMAGE_ID, DATASETS_PATH, ImageReader, get_rolled_images\n\n\ndef load_data(classesFromFile=False, imageId=IMAGE_ID, datasetsPath=DATASETS_PATH, gaussianFilter=False, rolledImages=False):\n imageReader = ImageReader(imageId=imageId, datasetsPath=datasetsPath)\n images = imageReader.get_full_padded_images(gaussianFilter=gaussianFilter)\n\n if rolledImages:\n images = get_rolled_images(images)\n\n imageIdxs = list(range(images.shape[0]))\n\n classes = imageReader.get_frame_wise_class_gmm(imageIdxs, classesFromFile=classesFromFile)\n\n # Transform targets to keras compatible format\n num_classes = 2\n Y = np_utils.to_categorical(classes, num_classes)\n\n # preprocess data\n X = images.astype('float32')\n X = X / 255.0\n\n # Split train / test data\n X_train, X_valid, Y_train, Y_valid = train_test_split(X, Y, test_size=0.2, random_state=1)\n print(f\"Prop of sparks in train dataset: {round(Y_train.sum(axis=0)[1]/Y_train.shape[0]*100, 2)}, \"\n f\"and in validation dataset: {round(Y_valid.sum(axis=0)[1]/Y_valid.shape[0]*100, 2)}\")\n\n return X_train, Y_train, X_valid, Y_valid\n\ndef _sigmoid(x):\n return 2/(1+tf.math.exp(-5*x))-1\n\ndef _recall_and_false_spark(ratio=.6):\n def recall_and_false_spark(y_true, y_pred):\n # metrica ponderada 0.2 accuracy + 0.8 recall (classes spark exclusivament), sempre que hi hagi sparks, sino acc\n realSparks = tf.math.argmax(y_true, axis=1) == 1\n predSparks = tf.math.argmax(y_pred, axis=1) == 1\n wellPredSparks = realSparks & predSparks\n wellPredNoSparks = ~realSparks & ~predSparks\n wrongPredSparks = ~realSparks & predSparks\n\n totalElementsCount = tf.cast(tf.shape(y_true)[0], np.float32)\n realSparksCount = tf.math.reduce_sum(tf.cast(realSparks, np.float32))\n wellPredSparksCount = tf.math.reduce_sum(tf.cast(wellPredSparks, np.float32))\n wellPredCount = tf.math.reduce_sum(tf.cast(wellPredNoSparks, np.float32)) + wellPredSparksCount\n wrongPredSparksCount = tf.math.reduce_sum(tf.cast(wrongPredSparks, np.float32))\n realNonSparksCount = tf.math.reduce_sum(tf.cast(~realSparks, np.float32))\n\n recall = wellPredSparksCount / realSparksCount\n accuracy = wellPredCount / totalElementsCount\n wrongSparksMetricAux = wrongPredSparksCount / realNonSparksCount\n wrongSparksMetric = 1 - _sigmoid(wrongSparksMetricAux)\n\n\n # ret = recall * 0.8 + accuracy * 0.2if realSparksCount > 0 else accuracy\n return tf.cond(tf.greater(realSparksCount, 0),\n lambda: recall * ratio + wrongSparksMetric * (1-ratio),\n lambda: wrongSparksMetric)\n return recall_and_false_spark\n\ndef sigmoid_spark_and_non_spark_loss(y_true, y_pred):\n mul = tf.constant([0, 1], shape=[2, 1], dtype=y_true.dtype)\n\n realSparks = tf.squeeze(tf.matmul(y_true, mul) == 1)\n predSparks = tf.squeeze(tf.matmul(y_pred, mul) == 1)\n wrongPredSparks = ~realSparks & predSparks\n wrongPredNonSparks = realSparks & ~predSparks\n\n realSparksCount = tf.math.reduce_sum(tf.cast(realSparks, np.float32), axis=-1)\n realNonSparksCount = tf.math.reduce_sum(tf.cast(~realSparks, np.float32), axis=-1)\n wrongPredSparksCount = tf.math.reduce_sum(tf.cast(wrongPredSparks, np.float32), axis=-1)\n wrongPredNonSparksCount = tf.math.reduce_sum(tf.cast(wrongPredNonSparks, np.float32), axis=-1)\n\n wrongSparksMetricAux = wrongPredSparksCount / realNonSparksCount\n wrongPredNonSparks = wrongPredNonSparksCount / realSparksCount\n aux = _sigmoid(wrongSparksMetricAux)\n comb = 0.5 * aux + 0.5 * wrongPredNonSparks\n return tf.where(tf.math.is_nan(comb), aux, comb)\n\ndef sigmoid_loss(y_true, y_pred):\n return _sigmoid(tf.reduce_mean(tf.square(y_true-y_pred), axis=-1))\n\nif __name__=='__main__':\n a = tf.cast(tf.convert_to_tensor([[[0, 1] if np.random.randint(0,2) else [1, 0] for _ in range(5)] for _ in range(10)]), np.float32)\n b = tf.cast(tf.convert_to_tensor([[[0, 1] if np.random.randint(0, 2) else [1, 0] for _ in range(5)] for _ in range(10)]), np.float32)\n sigmoid_loss(a, b)\n sigmoid_spark_and_non_spark_loss(a, b)\n\n a = tf.convert_to_tensor([[0, 1] if np.random.randint(0, 2) else [1, 0] for _ in range(5)])\n b = tf.convert_to_tensor([[0, 1] if np.random.randint(0, 2) else [1, 0] for _ in range(5)])\n sigmoid_spark_and_non_spark_loss(a, b)\n\n X_train, Y_train, X_valid, Y_valid = load_data(classesFromFile=True)\n\n # Inception V3\n modelv3 = keras.applications.InceptionV3(include_top=True, weights=None, classes=2, input_shape=X_train[0].shape)\n modelv3.summary()\n\n batch_size = 32\n epochs = 25\n\n opt = keras.optimizers.RMSprop(learning_rate=0.0001, decay=1e-6)\n modelv3.compile(loss=sigmoid_loss, optimizer=opt, metrics=[_recall_and_false_spark(0.6)])\n\n modelv3.fit(X_train, Y_train, batch_size=batch_size, epochs=epochs, validation_data=(X_valid, Y_valid), shuffle=True)\n\n modelv3.save('train/inceptionv32.h5')\n pass","repo_name":"raulbenitez/DEEPCARDIO","sub_path":"sparks/train/frameWiseInception.py","file_name":"frameWiseInception.py","file_ext":"py","file_size_in_byte":5183,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"33949030490","text":"# -*- coding: utf-8 -*-\nfrom zope.component.hooks import getSite\nfrom zope.i18nmessageid import Message\nfrom collective.jekyll.symptoms import SymptomBase\n\nfrom collective.checktranslated import checktranslatedMessageFactory as _\n\nSTATUS = {'correct': True, 'warning': 'warning', 'error': False}\n\n\nclass HasTranslated(SymptomBase):\n title = _(u\"Translation\")\n help = _(u\"This object should be translated into all site languages.\")\n\n def _update(self):\n site = getSite()\n languages = site.portal_languages.getAvailableLanguages().keys()\n self.status, self.description = check_translated(self.context,\n languages)\n\n\ndef check_translated(context, languages):\n site_languages = languages\n obj_lang = context.Language()\n status = ''\n description = []\n\n if len(site_languages) == 1 and obj_lang != '':\n status = STATUS['error']\n #status = STATUS['warning']\n msgid = _(u\"There is only one language installed on your site.\")\n desc = context.translate(msgid)\n return status, desc\n if obj_lang == '':\n status = STATUS['error']\n msgid = _(u\"This is a neutral language object.\")\n desc = context.translate(msgid)\n return status, desc\n\n if obj_lang not in site_languages:\n status = STATUS['error']\n msgid = _(u\"Language not installed.\")\n desc = context.translate(msgid)\n return status, desc\n\n for lang in languages:\n if hasattr(context, 'getTranslation'):\n translate_context = context.getTranslation(lang)\n if translate_context is None:\n status = STATUS['error']\n msgid = _(u\"There is no ${language} translation\")\n msg = Message(msgid, mapping=dict(language=lang)) \n description.append(context.translate(msg))\n if len(description) == 0:\n status = STATUS['correct']\n msgid = _(u\"Translated into all languages.\")\n description.append(context.translate(msgid))\n return status, \", \".join(description)\n","repo_name":"collective/collective.checktranslated","sub_path":"collective/checktranslated/symptoms.py","file_name":"symptoms.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5161048548","text":"n = int(input())\r\nfor c in range(n):\r\n x = c + 1\r\n sheldon, raj = input().split()\r\n if sheldon == raj:\r\n print('Caso #{}: De novo!'.format(x))\r\n elif sheldon == 'papel':\r\n if raj == 'tesoura' or raj == 'lagarto':\r\n print('Caso #{}: Raj trapaceou!'.format(x))\r\n elif raj == 'Spock' or raj == 'pedra':\r\n print('Caso #{}: Bazinga!'.format(x))\r\n elif sheldon == 'pedra':\r\n if raj == 'papel' or raj == 'Spock':\r\n print('Caso #{}: Raj trapaceou!'.format(x))\r\n elif raj == 'tesoura' or raj == 'lagarto':\r\n print('Caso #{}: Bazinga!'.format(x))\r\n elif sheldon == 'tesoura':\r\n if raj == 'Spock' or raj == 'pedra':\r\n print('Caso #{}: Raj trapaceou!'.format(x))\r\n elif raj == 'papel' or raj == 'lagarto':\r\n print('Caso #{}: Bazinga!'.format(x))\r\n elif sheldon == 'lagarto':\r\n if raj == 'pedra' or raj == 'tesoura':\r\n print('Caso #{}: Raj trapaceou!'.format(x))\r\n elif raj == 'Spock' or raj == 'papel':\r\n print('Caso #{}: Bazinga!'.format(x))\r\n elif sheldon == 'Spock':\r\n if raj == 'lagarto' or raj == 'papel':\r\n print('Caso #{}: Raj trapaceou!'.format(x))\r\n elif raj == 'tesoura' or raj == 'pedra':\r\n print('Caso #{}: Bazinga!'.format(x))\r\n","repo_name":"Rkluk/uri","sub_path":"1828 Bazinga!.py","file_name":"1828 Bazinga!.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72650005585","text":"def frange(start, stop, step=None, howmany=None):\n if not step and not howmany:\n howmany = 100\n\n range_list = []\n if not step and howmany:\n step = (stop - start) / float(howmany)\n av = start\n\n while av < stop:\n range_list.append(av)\n av += step\n return range_list\n\ndef_Bs = frange(0., 2, howmany=50)\ndef_Hs_for_B = [0., 0.5, 1.]\n\ndef_Bs_for_H = [0.1, 0.7, 1.5]\ndef_Hs = frange(-4, 4, howmany=50)\n\nBs_af = [1., 1.5, 2., 3., 4.]\nHs_af = frange(-6, 6, step=0.1)\n\ndr = frange(-3.0, 3.0, howmany=500)\ndl = [0.3, 0.44068, 3.0]\ndrb = frange(0.00001, 1., howmany=100)\n\n# beta = 5, 3, 2, 1, 0.5, 0.2\n","repo_name":"bevesce/ising","sub_path":"frange.py","file_name":"frange.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5440628467","text":"import tensorflow as tf\r\nfrom tensorflow.examples.tutorials.mnist import input_data\r\n\r\nmax_steps=1000 # 训练最大步数\r\nlearning_rate=0.001 # 设置学习率\r\ndropout=0.9 # 神经元保留比例\r\ndata_dir='./MNIST_data' # 数据存放路径 百度网盘下载 链接: https://pan.baidu.com/s/13M8TYuw77D_cH0tnLU4O4g 密码: xa2w\r\nlog_dir='./' # 日志保存路径\r\n\r\n\r\n# 初始化权重函数\r\n # We can't initialize these variables to 0 - the network will get stuck.\r\ndef weight_variable(shape):\r\n \"\"\"Create a weight variable with appropriate initialization.\"\"\"\r\n initial = tf.truncated_normal(shape, stddev=0.1)\r\n return tf.Variable(initial)\r\n\r\n# 初始化偏置函数\r\ndef bias_variable(shape):\r\n \"\"\"Create a bias variable with appropriate initialization.\"\"\"\r\n initial = tf.constant(0.1, shape=shape)\r\n return tf.Variable(initial)\r\n\r\n# 将某个变量写入tensorboard\r\ndef variable_summaries(var):\r\n \"\"\"Attach a lot of summaries to a Tensor (for TensorBoard visualization).\"\"\"\r\n with tf.name_scope('summaries'):\r\n mean = tf.reduce_mean(var)\r\n tf.summary.scalar('mean', mean) # 写入均值\r\n with tf.name_scope('stddev'):\r\n stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean))) # 写入方差\r\n tf.summary.scalar('stddev', stddev) # 写入方差\r\n tf.summary.scalar('max', tf.reduce_max(var)) # 写入最大值\r\n tf.summary.scalar('min', tf.reduce_min(var)) # 写入最小值\r\n tf.summary.histogram('histogram', var) # 绘制直方图\r\n\r\ndef nn_layer(input_tensor, input_dim, output_dim, layer_name, act=tf.nn.relu):\r\n \"\"\"Reusable code for making a simple neural net layer.\r\n It does a matrix multiply, bias add, and then uses relu to nonlinearize.\r\n It also sets up name scoping so that the resultant graph is easy to read,\r\n and adds a number of summary ops.\r\n \"\"\"\r\n # Adding a name scope ensures logical grouping of the layers in the graph.\r\n with tf.name_scope(layer_name):\r\n # This Variable will hold the state of the weights for the layer\r\n with tf.name_scope('weights'):\r\n weights = weight_variable([input_dim, output_dim])\r\n variable_summaries(weights) # 记录变量\r\n with tf.name_scope('biases'):\r\n biases = bias_variable([output_dim])\r\n variable_summaries(biases) # 记录变量\r\n with tf.name_scope('Wx_plus_b'):\r\n preactivate = tf.matmul(input_tensor, weights) + biases\r\n tf.summary.histogram('pre_activations', preactivate) # 激活前的直方图\r\n activations = act(preactivate, name='activation')\r\n tf.summary.histogram('activations', activations) # 激活后的直方图,观察激活前后的直方图变化\r\n return activations\r\n\r\n\r\n\r\n\r\n # Import data\r\nmnist = input_data.read_data_sets(data_dir,one_hot=True)\r\nsess = tf.InteractiveSession()\r\n\r\n\r\n#-----------------------------------------------------------------------------------------------------------\r\n # Create a multilayer model.\r\n # Input placeholders\r\n # 创建输入\r\nwith tf.name_scope('input'):\r\n x = tf.placeholder(tf.float32, [None, 784], name='x-input')\r\n y_ = tf.placeholder(tf.float32, [None, 10], name='y-input')\r\n\r\n # 对创建的输入进行reshape。\r\nwith tf.name_scope('input_reshape'):\r\n image_shaped_input = tf.reshape(x, [-1, 28, 28, 1])\r\n tf.summary.image('input', image_shaped_input, 10)\r\n# 该部分主要用于在tensorboard中展示图片\r\n\r\nhidden1 = nn_layer(x, 784, 500, 'layer1')\r\nwith tf.name_scope('dropout'):\r\n keep_prob = tf.placeholder(tf.float32) # 此变量需要run时feed进来\r\n tf.summary.scalar('dropout_keep_probability', keep_prob) # 记录keep_prob随着训练步数的变化曲线\r\n dropped = tf.nn.dropout(hidden1, keep_prob) # 将第一层的结果进行dropout\r\n # Do not apply softmax activation yet, see below.\r\n\r\ny = nn_layer(dropped, 500, 10, 'layer2', act=tf.identity)\r\n\r\n# 此部分是整个模型框架,包括输入每一层的搭建需要feed(x-input,y-input,keep-prob)\r\n#-----------------------------------------------------------------------------------------------------------\r\n\r\nwith tf.name_scope('cross_entropy'):\r\n # The raw formulation of cross-entropy,\r\n #\r\n # tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.softmax(y)),\r\n # reduction_indices=[1]))\r\n #\r\n # can be numerically unstable.\r\n #\r\n # So here we use tf.nn.softmax_cross_entropy_with_logits on the\r\n # raw outputs of the nn_layer above, and then average across\r\n # the batch.\r\n diff = tf.nn.softmax_cross_entropy_with_logits(logits=y, labels=y_)\r\n with tf.name_scope('total'):\r\n cross_entropy = tf.reduce_mean(diff) # 求取平均值\r\n\r\ntf.summary.scalar('cross_entropy', cross_entropy)\r\n\r\nwith tf.name_scope('train'): # 执行训练\r\n train_step = tf.train.AdamOptimizer(learning_rate).minimize(cross_entropy)\r\n\r\nwith tf.name_scope('accuracy'): # 执行准确率\r\n with tf.name_scope('correct_prediction'):\r\n correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\r\n with tf.name_scope('accuracy'):\r\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\r\ntf.summary.scalar('accuracy', accuracy)\r\n \r\n # Merge all the summaries and write them out to /tmp/mnist_logs (by default)\r\nmerged = tf.summary.merge_all()\r\ntrain_writer = tf.summary.FileWriter(log_dir + '/train', sess.graph)\r\ntest_writer = tf.summary.FileWriter(log_dir + '/test')\r\ntf.global_variables_initializer().run()\r\n # Train the model, and also write summaries.\r\n # Every 10th step, measure test-set accuracy, and write test summaries\r\n # All other steps, run train_step on training data, & add training summaries\r\n\r\ndef feed_dict(train):\r\n \"\"\"Make a TensorFlow feed_dict: maps data onto Tensor placeholders.\"\"\"\r\n if train:\r\n xs, ys = mnist.train.next_batch(100)\r\n k = dropout\r\n else:\r\n xs, ys = mnist.test.images, mnist.test.labels\r\n k = 1.0\r\n return {x: xs, y_: ys, keep_prob: k}\r\n\r\nsaver = tf.train.Saver() # 用于保存模型文件\r\n\r\nfor i in range(max_steps): # 一共训练的step数目\r\n # 记录测试结果\r\n if i % 10 == 0: # Record summaries and test-set accuracy # 每隔10次测试一次准确率,并写入summary\r\n summary, acc = sess.run([merged, accuracy], feed_dict=feed_dict(False)) # 运行准确率,并且记录summary\r\n test_writer.add_summary(summary, i) # 将所有要记录的变量写入summary\r\n print('Accuracy at step %s: %s' % (i, acc)) # 输出准确率\r\n \r\n # 每隔100个step记录训练结果,保存模型文件\r\n else: # Record train set summaries, and train\r\n if i % 100 == 99: # Record execution stats\r\n run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)\r\n run_metadata = tf.RunMetadata() # 这两行代码是记录运行状态的\r\n summary, _ = sess.run([merged, train_step],\r\n feed_dict=feed_dict(True),\r\n options=run_options,\r\n run_metadata=run_metadata)\r\n train_writer.add_run_metadata(run_metadata, 'step%03d' % i)\r\n train_writer.add_summary(summary, i)\r\n saver.save(sess, log_dir+\"./model/model.ckpt\", i)\r\n print('Adding run metadata for', i)\r\n else: # Record a summary\r\n summary, _ = sess.run([merged, train_step], feed_dict=feed_dict(True))\r\n train_writer.add_summary(summary, i)\r\ntrain_writer.close()\r\ntest_writer.close()\r\n\r\n","repo_name":"cuppersd/Tools","sub_path":"tensorboard/tensorboard完整实例.py","file_name":"tensorboard完整实例.py","file_ext":"py","file_size_in_byte":7343,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"4210728107","text":"import sqlite3\nimport json\nfrom datetime import datetime\nfrom models import Subscriptions\n\ndef get_all_subscriptions():\n \"\"\"this is a docstring\"\"\"\n # Open a connection to the database\n with sqlite3.connect('./db.sqlite3') as conn:\n\n # Just use these. It's a Black Box.\n conn.row_factory = sqlite3.Row\n db_cursor = conn.cursor()\n\n # Write the SQL query to get the information you want\n db_cursor.execute(\"\"\"\n SELECT\n s.id,\n s.author_id,\n s.follower_id,\n s.created_on\n FROM Subscriptions s\n ORDER BY s.created_on DESC\n \"\"\")\n # Initialize an empty list to hold all user representations\n subscriptions = []\n\n # Convert rows of data into a Python list\n dataset = db_cursor.fetchall()\n\n for row in dataset:\n subscription_list = Subscriptions(row['id'], row['author_id'], row['follower_id'], row['created_on'])\n\n # user = Users(row['id'], row['first_name'], row['last_name'], row['email'], row['bio'], row['profile_image_url'], row['created_on'], row['active'], row['password'])\n # # Add the dictionary representation of the users to the posts\n # subscription_list.user = user.__dict__\n\n subscriptions.append(subscription_list.__dict__)\n\n return json.dumps(subscriptions)\n\ndef get_single_subscription(id):\n # Open a connection to the database\n with sqlite3.connect('./db.sqlite3') as conn:\n\n # Just use these. It's a Black Box.\n conn.row_factory = sqlite3.Row\n db_cursor = conn.cursor()\n\n # Write the SQL query to get the information you want\n db_cursor.execute(\"\"\"\n SELECT\n s.id,\n s.author_id,\n s.follower_id,\n s.created_on\n FROM Subscriptions s\n WHERE s.id = ?\n \"\"\", ( id, ))\n\n # Convert rows of data into a Python list\n data = db_cursor.fetchone()\n subscription_list = Subscriptions(data['id'], data['author_id'], data['follower_id'], data['created_on'])\n\n return json.dumps(subscription_list.__dict__)\n\ndef create_subscription(new_subscription):\n \"\"\"docstring\"\"\"\n with sqlite3.connect('./db.sqlite3') as conn:\n conn.row_factory = sqlite3.Row\n db_cursor = conn.cursor()\n\n db_cursor.execute(\"\"\"\n INSERT INTO Subscriptions (author_id, follower_id, created_on) values (?, ?, ?)\n \"\"\", (\n new_subscription['author_id'],\n new_subscription['follower_id'],\n datetime.now()\n ))\n\n id = db_cursor.lastrowid\n new_subscription['id'] = id\n return json.dumps(new_subscription)\n\ndef delete_subscription(id):\n \"\"\"docstring\n \"\"\"\n with sqlite3.connect(\"./db.sqlite3\") as conn:\n db_cursor = conn.cursor()\n\n db_cursor.execute(\"\"\"\n DELETE FROM subscriptions\n WHERE id = ?\n \"\"\", (id, ))\n\ndef update_subscription(id, new_subscription):\n \"\"\"docstring\"\"\"\n # Iterate the subscriptions list, but use enumerate() so that\n # you can access the index value of each item.\n with sqlite3.connect('./db.sqlite3') as conn:\n db_cursor = conn.cursor()\n db_cursor.execute(\"\"\"\n UPDATE Subscriptions\n SET\n author_id = ?,\n follower_id = ?,\n created_on = ?\n WHERE id = ?\n \"\"\", (\n new_subscription['author_id'],\n new_subscription['follower_id'],\n new_subscription['created_on'],\n id,\n ))\n\n rows_affected = db_cursor.rowcount\n\n if rows_affected == 0:\n return False\n else:\n return True\n","repo_name":"nss-evening-cohort-19/rare-python-server-the-crashing-pumpkins","sub_path":"views/subscription_request.py","file_name":"subscription_request.py","file_ext":"py","file_size_in_byte":3671,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"24133801530","text":"actor_name = input()\npoints = float(input())\nnumber_of_judges = int(input())\nis_nominated = False\n\nfor i in range(number_of_judges):\n name_of_judge = input()\n points_of_judge = float(input())\n points = points + (len(name_of_judge) * points_of_judge/ 2)\n if points > 1250.5:\n is_nominated = True\n break\n\nif is_nominated:\n print(f\"Congratulations, {actor_name} got a nominee for leading role with {points:.1f}!\")\nelse:\n print(f\"Sorry, {actor_name} you need {1250.5 - points:.1f} more!\")\n","repo_name":"1van101/SoftUni-Software-Engineering","sub_path":"python_basics/exams/15_and_16_june_2019/oscars.py","file_name":"oscars.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37944226560","text":"\"\"\"For Simple-Model Learning process\"\"\"\n\nfrom tqdm import tqdm\nimport pickle\n\nimport torch\n\nfrom src import set_logger\nfrom src import choice_optimizer\nfrom src import add_datetime_path, fix_seed\nfrom ohta_dataset import OhtaDataset\nfrom ohta_dataloader import OhtaDataloader\nfrom ohta_trainer import OhtaTrainer\nfrom model.ohta.alpha import build_alpha\nfrom model.ohta.alphaS import build_alphaS\nfrom model.ohta.utils import get_args\n\nSEED = 42\nfix_seed(SEED)\n\nargs = get_args()\nlogger = set_logger(\"TRAIN\", args.log)\n\ntorch.backends.cudnn.benchmark = True\nscaler = torch.cuda.amp.GradScaler()\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\ndataset = OhtaDataset(**vars(args))\ndataloader = OhtaDataloader(dataset, **vars(args))\n\nif args.use_model == \"alpha\":\n model = build_alpha(**vars(args)).to(device=device)\nelif args.use_model == \"alphaS\":\n model = build_alphaS(**vars(args)).to(device=device)\nelse:\n raise ValueError(f\"Invalid model {args.use_model}\")\n\noptimizer = choice_optimizer(model.parameters(), **vars(args))\n\ntrainer = OhtaTrainer(\n net=model,\n optimizer=optimizer,\n dataloader=dataloader,\n scaler=scaler,\n logger=logger,\n **vars(args),\n)\nwith open(add_datetime_path(\"./loader/dataloader.dl\"), \"wb\") as p:\n pickle.dump(trainer.train_valid_loader, p)\n\ntrain_length = len(trainer.train_valid_loader[\"train\"])\nvalid_length = len(trainer.train_valid_loader[\"valid\"])\n\ntrain_fpath = add_datetime_path(args.train_result_path)\nvalid_fpath = add_datetime_path(args.valid_result_path)\nt_f = open(train_fpath, mode=\"w\", encoding=\"utf-8\")\nt_f.write(f\"loss, acc, {train_length}\\n\")\nt_f.close()\nv_f = open(valid_fpath, mode=\"w\", encoding=\"utf-8\")\nv_f.write(f\"loss, acc, {valid_length}\\n\")\nv_f.close()\nfpath = {\"train\": train_fpath, \"valid\": valid_fpath}\n\n\ndef process(_mode):\n phase_loss = []\n phase_acc = []\n\n text = \"\"\n\n trainer.set_mode(_mode)\n\n with tqdm(trainer, desc=_mode) as prog:\n for i, (loss, acc) in enumerate(prog):\n\n if i % 100 == 0:\n with open(fpath[_mode], mode=\"a\", encoding=\"utf-8\") as f:\n f.write(text)\n text = \"\"\n else:\n text += f\"{loss},{acc}\\n\"\n\n prog.postfix = f\"L:{round(loss, 2)}, A:{round(acc, 2)}\"\n\n phase_loss.append(loss)\n phase_acc.append(acc)\n\n phase_loss = sum(phase_loss) / len(phase_loss)\n phase_acc = sum(phase_acc) / len(phase_acc)\n\n return phase_loss, phase_acc\n\n\nif not args.skip_first_valid:\n logger.info(\" Init Valid-Mode >>> \")\n _loss, _acc = process(\"valid\")\n logger.info(\" Result |[ Loss : %s, Acc : %s ]|\", round(_loss, 2), round(_acc, 2))\n\nfor current_epoch in range(args.epoch):\n logger.info(\" Epoch >>> %s / %s\", (current_epoch + 1), args.epoch)\n\n for mode in [\"train\", \"valid\"]:\n _loss, _acc = process(mode)\n logger.info(\" Result |[ Loss : %s, Acc : %s ]|\", _loss, _acc)\n\n epo_inf = f\"0{current_epoch}\" if current_epoch < 10 else str(current_epoch)\n path = \".\".join(args.model_save_path.split(\".\")[:-1]) + f\"E{epo_inf}.pth\"\n trainer.save_model(path)\n","repo_name":"MTamon/SLP_LAB","sub_path":"HME/MODEL/ohta.py","file_name":"ohta.py","file_ext":"py","file_size_in_byte":3149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41162620511","text":"import os, inspect, glob\n\nimport numpy as np\nfrom sklearn.utils import shuffle\n\nclass DataSet(object):\n\n def __init__(self):\n\n self.data_path = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))+\"/../dataset\"\n\n self.list_train_lr = self.sorted_list(os.path.join(self.data_path, \"train_lr\", \"*.npy\"))\n self.list_train_hr = self.sorted_list(os.path.join(self.data_path, \"train_hr\", \"*.npy\"))\n\n self.list_validation_lr = self.sorted_list(os.path.join(self.data_path, \"validation_lr\", \"*.npy\"))\n self.list_validation_hr = self.sorted_list(os.path.join(self.data_path, \"validation_hr\", \"*.npy\"))\n\n self.list_test_lr = self.sorted_list(os.path.join(self.data_path, \"test_lr\", \"*.npy\"))\n self.list_test_hr = self.sorted_list(os.path.join(self.data_path, \"test_hr\", \"*.npy\"))\n\n self.list_test_exp = self.sorted_list(os.path.join(self.data_path, \"test_exp\", \"*.npy\"))\n\n self.amount_tr = len(self.list_train_lr)\n self.amount_val = len(self.list_validation_lr)\n self.amount_te = len(self.list_test_lr)\n self.amount_te_exp = len(self.list_test_exp)\n\n self.idx_tr = 0\n self.idx_val = 0\n self.idx_te = 0\n self.idx_te_exp = 0\n\n def sorted_list(self, path):\n tmplist = glob.glob(path)\n tmplist.sort()\n\n return tmplist\n\n # Load the training data\n def next_train(self, batch_size=1):\n\n data = np.zeros((0, 1, 1, 1))\n label = np.zeros((0, 1, 1, 1))\n terminator = False\n\n while(True):\n data_tmp = np.expand_dims(np.load(self.list_train_lr[self.idx_tr]), axis=0)\n label_tmp = np.expand_dims(np.load(self.list_train_hr[self.idx_tr]), axis=0)\n\n if(len(data_tmp.shape) < 4):\n data_tmp = np.expand_dims(data_tmp, axis=3)\n label_tmp = np.expand_dims(label_tmp, axis=3)\n\n if(data.shape[0] == 0):\n data = data_tmp\n label = label_tmp\n else:\n if((data.shape[1] == data_tmp.shape[1]) and (data.shape[2] == data_tmp.shape[2]) and (data.shape[3] == data_tmp.shape[3])):\n data = np.append(data, data_tmp, axis=0)\n label = np.append(label, label_tmp, axis=0)\n\n self.idx_tr += 1\n if(self.idx_tr >= self.amount_tr):\n self.list_train_lr, self.list_train_hr = shuffle(self.list_train_lr, self.list_train_hr)\n self.idx_tr = 0\n terminator = True\n break\n elif(data.shape[0] == batch_size): break\n else: pass\n\n return data, label, terminator\n\n # Load the validation data\n def next_val(self, batch_size_val=1):\n data = np.zeros((0, 1, 1, 1))\n label = np.zeros((0, 1, 1, 1))\n\n for i in range(batch_size_val):\n if self.idx_val >= self.amount_val:\n raise Exception('Need more validation data to match the batch size ratio between training and validation datasets')\n\n data_tmp = np.expand_dims(np.load(self.list_validation_lr[self.idx_val]), axis=0)\n label_tmp = np.expand_dims(np.load(self.list_validation_hr[self.idx_val]), axis=0)\n\n if (len(data_tmp.shape) < 4):\n data_tmp = np.expand_dims(data_tmp, axis=3)\n label_tmp = np.expand_dims(label_tmp, axis=3)\n\n if (data.shape[0] == 0):\n data = data_tmp\n label = label_tmp\n\n else:\n if((data.shape[1] == data_tmp.shape[1]) and (data.shape[2] == data_tmp.shape[2]) and (data.shape[3] == data_tmp.shape[3])):\n data = np.append(data, data_tmp, axis=0)\n label = np.append(label, label_tmp, axis=0)\n\n self.idx_val += 1\n\n return data, label\n\n # Load the testing data\n def next_test(self):\n\n data = np.expand_dims(np.load(self.list_test_lr[self.idx_te]), axis=0)\n label = np.expand_dims(np.load(self.list_test_hr[self.idx_te]), axis=0)\n\n if(len(data.shape) < 4):\n data = np.expand_dims(data, axis=3)\n label = np.expand_dims(label, axis=3)\n\n self.idx_te += 1\n\n if(self.idx_te > self.amount_te):\n self.idx_te = 0\n return None, None\n else: return data, label\n\n # Load ARPES experiment data for testing\n def next_test_exp(self):\n\n data = np.expand_dims(np.load(self.list_test_exp[self.idx_te_exp]), axis=0)\n\n if (len(data.shape) < 4):\n data = np.expand_dims(data, axis=3)\n\n self.idx_te_exp += 1\n\n if (self.idx_te_exp > self.amount_te_exp):\n self.idx_te_exp = 0\n return None\n else: return data\n","repo_name":"avdfo/PHYS_549_package","sub_path":"SR-CNN/source/datamanager.py","file_name":"datamanager.py","file_ext":"py","file_size_in_byte":4761,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"7929139395","text":"import os\nimport time\nimport sys\nfrom collections.abc import Iterable\nimport math\nimport subprocess\nimport shlex\nimport signal\n\nimport pyqtgraph.opengl\nfrom loguru import logger\nimport yaml\n\nimport numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nfrom scipy.spatial.transform import Rotation as SciRotation\n\nfrom PyQt5.QtWidgets import QPushButton, QMainWindow, QApplication, QFileDialog, QWidget, QVBoxLayout, QLabel, \\\n QSizePolicy, QDockWidget, QTextEdit\nfrom PyQt5.QtGui import QIcon, QPixmap, QMouseEvent, QFont, QVector3D, QImage\nfrom PyQt5.QtCore import qDebug, QTimer, QObject, QEvent, Qt, pyqtSignal, QThread, QSize\n\nimport pyqtgraph as pg\nimport pyqtgraph.opengl as gl\nfrom pyqtgraph import Transform3D, ColorMap, mkColor, makeRGBA\n\nimport rospy\nfrom std_msgs.msg import String, Int8\nfrom sensor_msgs.msg import JointState, Imu, Image as Image_msg, PointCloud2\nfrom ros_numpy.image import image_to_numpy, numpy_to_image\nfrom ros_numpy.point_cloud2 import pointcloud2_to_array\nfrom geometry_msgs.msg import Twist, Vector3\nfrom rostopic import _rostopic_list, get_info_text\n\n\ndef cloud_msg2numpy(cloud_msg, fields=('x', 'y', 'z', 'intensity'), max_intensity=float('inf'), remove_nans=True):\n \"\"\"\n 从ros的雷达原始消息中获取相应字段信息\n :param cloud_msg: PointCloud2 ros消息类型\n :param fields: tuple 需要的fields\n :param remove_nans: bool\n :param max_intensity: int 最大强度阈值 ouster的雷达强度从0到3000+且数据分布不均匀, 造成大部分数据的范围相对压缩.\n :return: points: numpy.ndarray `N x len(fields)`\n \"\"\"\n cloud_array = pointcloud2_to_array(cloud_msg)\n if remove_nans:\n mask = np.isfinite(cloud_array['x']) & np.isfinite(cloud_array['y']) & np.isfinite(cloud_array['z'])\n cloud_array = cloud_array[mask]\n # pull out target fields\n points = np.zeros(cloud_array.shape + (len(fields),), dtype=np.float32)\n\n for i, field_name in enumerate(fields):\n points[..., i] = cloud_array[field_name]\n if field_name == 'intensity':\n points[..., i] = np.minimum(max_intensity, points[..., i])\n\n return points\n\n\ndef letterbox_image(image, target_shape):\n \"\"\"\n 缩放图片, 填充短边\n :param image: np.ndarray [H, W, C]\n :param target_shape: tuple (H, W)\n :return:\n \"\"\"\n image_h, image_w = image.shape[:2]\n target_h, target_w = target_shape\n # 获取缩放尺度, resize\n scale = min(float(target_h) / image_h, float(target_w) / image_w)\n new_h = int(image_h * scale)\n new_w = int(image_w * scale)\n image = cv2.resize(image, (new_w, new_h))\n canvas = np.zeros(shape=[target_h, target_w, 3], dtype=np.float32)\n canvas[:, :, :] = (128, 128, 128)\n start_h, start_w = (target_h - new_h) // 2, (target_w - new_w) // 2\n canvas[start_h:start_h + new_h, start_w:start_w + new_w, :] = image[:, :, :]\n canvas = canvas.astype(np.uint8)\n return canvas\n\n\nclass ConsoleTextEdit(QTextEdit):\n _color_stdout = Qt.blue\n _color_stderr = Qt.red\n _color_stdin = Qt.black\n _multi_line_char = '\\\\'\n _multi_line_indent = ' '\n _prompt = ('$ ', ' ') # prompt for single and multi line\n\n class TextEditColoredWriter:\n\n def __init__(self, text_edit, color):\n self._text_edit = text_edit\n self._color = color\n\n def write(self, line):\n old_color = self._text_edit.textColor()\n self._text_edit.setTextColor(self._color)\n self._text_edit.insertPlainText(line)\n self._text_edit.setTextColor(old_color)\n self._text_edit.ensureCursorVisible()\n\n def __init__(self, parent=None):\n super(ConsoleTextEdit, self).__init__(parent)\n self.setFont(QFont('Mono'))\n\n self._multi_line = False\n self._multi_line_level = 0\n self._command = ''\n self._history = []\n self._history_index = -1\n\n # init colored writers\n self._stdout = self.TextEditColoredWriter(self, self._color_stdout)\n self._stderr = self.TextEditColoredWriter(self, self._color_stderr)\n self._comment_writer = self.TextEditColoredWriter(self, self._color_stdin)\n self._add_prompt()\n\n def print_message(self, msg):\n self._clear_current_line(clear_prompt=True)\n self._comment_writer.write(msg + '\\n')\n self._add_prompt()\n\n def _add_prompt(self):\n self._comment_writer.write(\n self._prompt[self._multi_line] + self._multi_line_indent * self._multi_line_level)\n\n def _clear_current_line(self, clear_prompt=False):\n # block being current row\n prompt_length = len(self._prompt[self._multi_line])\n if clear_prompt:\n prompt_length = 0\n length = len(self.document().lastBlock().text()[prompt_length:])\n if length == 0:\n return None\n else:\n # should have a better way of doing this but I can't find it\n for _ in range(length):\n self.textCursor().deletePreviousChar()\n return True\n\n def _move_in_history(self, delta):\n # used when using the arrow keys to scroll through _history\n self._clear_current_line()\n if -1 <= self._history_index + delta < len(self._history):\n self._history_index += delta\n if self._history_index >= 0:\n self.insertPlainText(self._history[self._history_index])\n return True\n\n def _exec_code(self, code):\n try:\n self._pipe = subprocess.Popen([code], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n out, err = self._pipe.communicate(timeout=3) # 防止永远阻塞\n self._stdout.write(out.decode('utf-8'))\n self._stderr.write(err.decode('utf-8'))\n except Exception as e:\n self._stderr.write(str(e) + '\\n')\n\n def keyPressEvent(self, event):\n prompt_length = len(self._prompt[self._multi_line])\n block_length = self.document().lastBlock().length()\n document_length = self.document().characterCount()\n line_start = document_length - block_length\n prompt_position = line_start + prompt_length\n\n # only handle keys if cursor is in the last line\n if self.textCursor().position() >= prompt_position:\n if event.key() == Qt.Key_Down:\n if self._history_index == len(self._history):\n self._history_index -= 1\n self._move_in_history(-1)\n return None\n\n if event.key() == Qt.Key_Up:\n self._move_in_history(1)\n return None\n\n if event.key() in [Qt.Key_Backspace]:\n # don't allow cursor to delete into prompt\n if (self.textCursor().positionInBlock() == prompt_length and\n not self.textCursor().hasSelection()):\n return None\n\n if event.key() in [Qt.Key_Return, Qt.Key_Enter]:\n # set cursor to end of line to avoid line splitting\n cursor = self.textCursor()\n cursor.setPosition(document_length - 1)\n self.setTextCursor(cursor)\n\n self._history_index = -1\n line = str(self.document().lastBlock().text())[\n prompt_length:].rstrip() # remove prompt and trailing spaces\n\n self.insertPlainText('\\n')\n if len(line) > 0:\n if line[-1] == self._multi_line_char:\n self._multi_line = True\n self._multi_line_level += 1\n self._history.insert(0, line)\n\n if self._multi_line: # multi line command\n self._command += line + '\\n'\n\n else: # single line command\n self._exec_code(line)\n self._command = ''\n\n else: # new line was is empty\n\n if self._multi_line: # multi line done\n self._exec_code(self._command)\n self._command = ''\n self._multi_line = False\n self._multi_line_level = 0\n\n self._add_prompt()\n return None\n\n # allow all other key events\n super(ConsoleTextEdit, self).keyPressEvent(event)\n\n # fix cursor position to be after the prompt, if the cursor is in the last line\n if line_start <= self.textCursor().position() < prompt_position:\n cursor = self.textCursor()\n cursor.setPosition(prompt_position)\n self.setTextCursor(cursor)\n\n\nclass RosNode(QThread):\n data_arrive_signal = pyqtSignal()\n image_arrive_signal = pyqtSignal()\n pointcloud_arrive_signal = pyqtSignal()\n\n def __init__(self):\n super(RosNode, self).__init__()\n self.initialize_roscore()\n rospy.init_node('qt_ros_node')\n self.stop_flag = False\n\n self.loop_rate = rospy.Rate(30, reset=True)\n self.turtlesim_publisher = rospy.Publisher('/turtle1/cmd_vel', Twist, queue_size=1)\n self.turtlesim_subscriber = rospy.Subscriber('/turtle1/cmd_vel', Twist, callback=self.f, queue_size=1)\n self.image_subscriber = rospy.Subscriber('/tracking_image', Image_msg, callback=self.image_callback,\n queue_size=1)\n self.pointcloud_subscriber = rospy.Subscriber('/test_pointcloud', PointCloud2,\n callback=self.pointcloud_callback, queue_size=1)\n\n self.msg = None\n self.image = None\n self.points = None\n\n def initialize_roscore(self):\n \"\"\"\n initialize the roscore process.\n :return:\n \"\"\"\n cmd = \"ps -ef | grep 'roscore' | grep -v grep | awk '{print $2}'\"\n old_pid = subprocess.getoutput(cmd)\n if old_pid == '':\n self.roscore_process = subprocess.Popen(shlex.split('roscore'),\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n shell=False)\n logger.info('roscore initialized with pid %d' % self.roscore_process.pid)\n time.sleep(0.5)\n else:\n logger.info('using already existed roscore process with pid %s' % old_pid)\n\n def pointcloud_callback(self, msg):\n self.points = cloud_msg2numpy(msg, fields=('x', 'y', 'z'))\n self.pointcloud_arrive_signal.emit()\n\n def image_callback(self, msg):\n self.image = image_to_numpy(msg)\n self.image_arrive_signal.emit()\n\n def f(self, msg):\n self.msg = msg\n self.data_arrive_signal.emit()\n\n def publish_twist_message(self):\n sender = self.sender()\n message = Twist()\n if sender.text() == 'up':\n message.linear = Vector3(2, 0, 0)\n elif sender.text() == 'down':\n message.linear = Vector3(-2, 0, 0)\n elif sender.text() == 'left':\n message.angular = Vector3(0, 0, 2)\n elif sender.text() == 'right':\n message.angular = Vector3(0, 0, -2)\n self.turtlesim_publisher.publish(message)\n\n def run(self) -> None:\n while not rospy.is_shutdown() and not self.stop_flag:\n self.loop_rate.sleep()\n\n\nclass MainWindow(QMainWindow):\n \"\"\"\n 在pyqt中进行三维数据可视化(以激光雷达点云为例, mayavi, open3d, pyqtgraph, opengl, vtk等方法解析)\n \"\"\"\n\n def __init__(self):\n super(MainWindow, self).__init__()\n self.resize(1600, 900)\n self.widget = QWidget()\n self.setCentralWidget(self.widget)\n self.layout = QVBoxLayout(self.widget)\n\n self.og_widget = gl.GLViewWidget()\n self.layout.addWidget(self.og_widget)\n self.grid_item = gl.GLGridItem()\n self.og_widget.addItem(self.grid_item)\n\n self.x_axis_item = gl.GLLinePlotItem(pos=np.array([[0, 0, 0], [10, 0, 0]], dtype=np.float32),\n color=(1, 0, 0, 1),\n width=2)\n self.og_widget.addItem(self.x_axis_item)\n\n self.y_axis_item = gl.GLLinePlotItem(pos=np.array([[0, 0, 0], [0, 10, 0]], dtype=np.float32),\n color=(0, 1, 0, 1),\n width=2)\n self.og_widget.addItem(self.y_axis_item)\n\n self.z_axis_item = gl.GLLinePlotItem(pos=np.array([[0, 0, 0], [0, 0, 10]], dtype=np.float32),\n color=(0, 0, 1, 1),\n width=2)\n self.og_widget.addItem(self.z_axis_item)\n\n self.up_btn = QPushButton('up', self.widget)\n self.down_btn = QPushButton('down')\n self.left_btn = QPushButton('left')\n self.right_btn = QPushButton('right')\n self.label = QLabel('Data to show')\n self.layout.addWidget(self.up_btn)\n self.layout.addWidget(self.down_btn)\n self.layout.addWidget(self.left_btn)\n self.layout.addWidget(self.right_btn)\n self.layout.addWidget(self.label)\n\n self.add_item_btn = QPushButton('add')\n self.delete_item_btn = QPushButton('delete')\n self.layout.addWidget(self.add_item_btn)\n self.layout.addWidget(self.delete_item_btn)\n self.add_item_btn.clicked.connect(self.add_item)\n self.delete_item_btn.clicked.connect(self.delete_item)\n\n self.ros_topic_list_btn = QPushButton('topic list')\n self.layout.addWidget(self.ros_topic_list_btn)\n self.ros_topic_list_btn.clicked.connect(self.show_topic_list)\n\n self.start_rviz_btn = QPushButton('rviz')\n self.layout.addWidget(self.start_rviz_btn)\n self.start_rviz_btn.clicked.connect(self.start_rviz)\n\n self.start_bag_record_btn = QPushButton('start record')\n self.stop_bag_record_btn = QPushButton('stop record')\n self.layout.addWidget(self.start_bag_record_btn)\n self.layout.addWidget(self.stop_bag_record_btn)\n self.start_bag_record_btn.clicked.connect(self.start_bag_record)\n self.stop_bag_record_btn.clicked.connect(self.stop_bag_record)\n\n self.console_text_edit = ConsoleTextEdit()\n self.layout.addWidget(self.console_text_edit)\n self.layout.setStretch(0, 7)\n\n self.image_label = QLabel('image')\n self.image_label.setMinimumSize(300, 1)\n size_policy = QSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)\n self.image_label.setSizePolicy(size_policy)\n self.image_label.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n\n self.dock_widget = QDockWidget(self)\n self.dock_widget.setWindowTitle('Image')\n self.dock_widget.setWidget(self.image_label)\n self.addDockWidget(Qt.DockWidgetArea(1), self.dock_widget)\n\n self.image_label2 = QLabel('image2')\n self.image_label2.setMinimumSize(300, 1)\n size_policy = QSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)\n self.image_label2.setSizePolicy(size_policy)\n self.image_label2.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n self.dock_widget2 = QDockWidget(self)\n self.dock_widget2.setWindowTitle('Image2')\n self.dock_widget2.setWidget(self.image_label2)\n self.addDockWidget(Qt.DockWidgetArea(1), self.dock_widget2)\n\n self.ros_node = RosNode()\n self.ros_node.start()\n\n self.up_btn.clicked.connect(self.ros_node.publish_twist_message)\n self.down_btn.clicked.connect(self.ros_node.publish_twist_message)\n self.left_btn.clicked.connect(self.ros_node.publish_twist_message)\n self.right_btn.clicked.connect(self.ros_node.publish_twist_message)\n self.ros_node.data_arrive_signal.connect(self.show_msg)\n self.ros_node.pointcloud_arrive_signal.connect(self.show_pointcloud)\n\n self.ros_node.image_arrive_signal.connect(self.show_image)\n\n def start_bag_record(self):\n cmd = 'rosbag record -a'\n self.ros_node.record_process = subprocess.Popen(shlex.split(cmd),\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n shell=False)\n\n def stop_bag_record(self):\n self.ros_node.record_process.send_signal(signal.SIGINT)\n\n def start_rviz(self):\n cmd = 'rviz'\n self.ros_node.rviz_process = subprocess.Popen(shlex.split(cmd),\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n shell=False)\n logger.info('rviz started with pid %d' % self.ros_node.rviz_process.pid)\n\n def show_topic_list(self):\n cmd = 'rostopic list'\n output = subprocess.getoutput(cmd)\n print(output)\n # _rostopic_list(None)\n # text = get_info_text('/rosout')\n # print(text)\n\n def add_item(self):\n self.box_item = gl.GLScatterPlotItem(pos=np.array([10, 10, 10]),\n color=(1, 0, 0, 1),\n size=5,\n pxMode=False)\n self.og_widget.addItem(self.box_item)\n\n def delete_item(self):\n if hasattr(self, 'box_item'):\n self.og_widget.removeItem(self.box_item)\n del self.box_item\n\n def show_pointcloud(self):\n points = self.ros_node.points\n colors = np.ones(shape=(points.shape[0], 4))\n size = np.zeros(shape=points.shape[0]) + 0.03\n if hasattr(self, 'points_item'):\n self.points_item.setData(pos=points,\n color=colors,\n size=size,\n pxMode=False)\n else:\n self.points_item = gl.GLScatterPlotItem(pos=points,\n color=colors,\n size=size,\n pxMode=False)\n self.og_widget.addItem(self.points_item)\n\n def show_image(self):\n image = cv2.cvtColor(self.ros_node.image, cv2.COLOR_BGR2RGB)\n target_shape1 = [self.dock_widget.height(), self.dock_widget.width()]\n image1 = letterbox_image(image, target_shape1)\n show_image1 = QImage(image1, image1.shape[1], image1.shape[0], image1.shape[1] * 3, QImage.Format_RGB888)\n self.image_label.setPixmap(QPixmap(show_image1))\n\n target_shape2 = [self.dock_widget2.height(), self.dock_widget2.width()]\n image2 = letterbox_image(image, target_shape2)\n show_image2 = QImage(image2, image2.shape[1], image2.shape[0], image2.shape[1] * 3, QImage.Format_RGB888)\n self.image_label2.setPixmap(QPixmap(show_image2))\n\n def show_msg(self):\n self.label.setText(str(self.ros_node.msg.linear.x))\n\n def closeEvent(self, a0) -> None:\n self.ros_node.stop_flag = True\n if hasattr(self.ros_node, 'rviz_process'):\n self.ros_node.rviz_process.send_signal(signal.SIGINT)\n self.ros_node.rviz_process.wait()\n logger.info('rviz with pid %d finished.' % self.ros_node.rviz_process.pid)\n if hasattr(self.ros_node, 'roscore_process'):\n self.ros_node.roscore_process.send_signal(signal.SIGINT)\n self.ros_node.roscore_process.wait()\n logger.info('roscore with pid %d finished.' % self.ros_node.roscore_process.pid)\n self.ros_node.quit()\n self.ros_node.wait()\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n w = MainWindow()\n # apply_stylesheet(app, theme='dark_teal.xml')\n w.show()\n sys.exit(app.exec_())\n","repo_name":"ZhengXinyue/bilibili_project","sub_path":"qt_ros/vis_example.py","file_name":"vis_example.py","file_ext":"py","file_size_in_byte":20033,"program_lang":"python","lang":"en","doc_type":"code","stars":82,"dataset":"github-code","pt":"48"} +{"seq_id":"23264557705","text":"picture = [\r\n [0,0,0,1,0,0,0],\r\n [0,0,1,1,1,0,0],\r\n [0,1,1,1,1,1,0],\r\n [1,1,1,1,1,1,1],\r\n [0,0,0,1,0,0,0],\r\n [0,0,0,1,0,0,0]\r\n]\r\n\r\nfor row in picture:\r\n for j in row:\r\n if (j == 1):\r\n print('*',end='')\r\n else:\r\n print(' ' ,end='')\r\n print('')\r\n\r\n\r\n\r\nsome_list = ['a','b','c','b','d','m','n','n']\r\n\r\nduplicates = []\r\nfor value in some_list:\r\n if some_list.count(value) > 1:\r\n if value not in duplicates:\r\n duplicates.append(value)\r\n\r\nprint(duplicates)\r\n\r\nfunctions\r\n\r\ndef say_hello():\r\n print('Hello i am a function')\r\n\r\nfor i in range(2):\r\n say_hello()\r\n\r\n#parameters vs arguments\r\n\r\n#parameters\r\ndef say_hello(name,emoji):\r\n print(f'Hey {name} {emoji}')\r\n\r\n#arguments\r\nsay_hello('Simanta',':)')\r\n\r\n# keywords arguments\r\nsay_hello(emoji = ':)',name = \"Karki\")\r\n\r\n#default parameter\r\ndef call_hello(name = 'Shreya',emoji = '(:'):\r\n print(f'hello {name} {emoji}')\r\ncall_hello()\r\n\r\n# #return\r\ndef sum(num1,num2):\r\n def another_func(n1,n2):\r\n return n1+n2\r\n return another_func(num1,num2)\r\n\r\nprint(sum(2,5))\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"SimantaKarki/Python","sub_path":"class6.py","file_name":"class6.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40523489961","text":"import Crypto\r\nimport binascii\r\nimport base64\r\nfrom Crypto.PublicKey import RSA\r\nfrom Crypto.Cipher import PKCS1_OAEP\r\n\r\n\r\n\r\nrandom_generator = Crypto.Random.new().read # fuente segura de Entropía\r\n\r\n#Generación de llaves\r\n# PRIVADA\r\n# Argumentos (Tamaño de llaves,numero aleatorio)\r\nprivate_key = RSA.generate(1024, random_generator)\r\n\r\n# PUBLICA\r\n# Se genera a partir de la llave privada\r\npublic_key = private_key.publickey()\r\n\r\n#CONVERSIÓN A UTF8\r\n#private_key = private_key.exportKey(format='DER')\r\n#public_key = public_key.exportKey(format='DER')\r\n\r\n#private_key = binascii.hexlify(private_key).decode('utf8')\r\n#public_key = binascii.hexlify(public_key).decode('utf8')\r\n\r\n#PROCESO INVERSO\r\n#private_key = RSA.importKey(binascii.unhexlify(private_key))\r\n#public_key = private_key.publickey()\r\narchivo=input(\"Ingrese el nombre del archivo a cifrar: \")\r\nwith open(archivo, \"rb\") as img_file:\r\n image = base64.b64encode(img_file.read())\r\n\r\n#############################\r\n# CIFRADO #\r\n#############################\r\ncipher = PKCS1_OAEP.new(public_key) #Objeto para cifrar\r\nencrypted_message = cipher.encrypt(image) # MENSAJE CIFRADO\r\nencrypted64 = base64.b64encode(encrypted_message)\r\n\r\nimage = open(\"\"+archivo, \"wb\")\r\nimage.write(base64.b64decode(encrypted64))\r\nimage.close()\r\nprint(\"Guardado como \",\"\"+archivo)\r\n\r\ninput(\"Ingrese alguna tecla para continuar...\")\r\n#print(encrypted_message)\r\n\r\n################################\r\n# DESCIFRADO #\r\n################################\r\n# Para descifrar se hace uso de la llave privada\r\narchivo=input(\"Ingrese el nombre del archivo a cifrar: \")\r\nwith open(archivo, \"rb\") as img_file:\r\n image = base64.b64encode(img_file.read())\r\n\r\nencrypted_message = base64.b64decode(image)\r\n\r\ncipher = PKCS1_OAEP.new(private_key) #Objeto de descifrado\r\nmessage = cipher.decrypt(encrypted_message) #Mensaje en Claro\r\n\r\nimage = open(\"\"+archivo, \"wb\")\r\nimage.write(base64.b64decode(message))\r\nimage.close()\r\nprint(\"Guardado como \",\"\"+archivo)\r\n\r\nprint(base64.b64decode(message))","repo_name":"antoniotorres0605/proyectoDiploSecreInfo","sub_path":"CifradoRSA.py","file_name":"CifradoRSA.py","file_ext":"py","file_size_in_byte":2057,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13060938327","text":"from dataclasses import asdict\r\nimport json\r\nfrom typing import Callable, Awaitable\r\n\r\nfrom src.exceptions import AppError\r\nfrom src.instance_manager.instance.exceptions import (\r\n InstanceAlreadyExists,\r\n InstanceNotFound, EndMessageProcessing\r\n)\r\nfrom src.instance_manager.message import message_dispatcher\r\nfrom src.instance_manager.message.input_message import InputMessage\r\nfrom src.instance_manager.message.response_status import ResponseStatus\r\nimport logging\r\nfrom src.instance_manager.message.output_message import CtlAcknowledgeMessage\r\nfrom instance_manager.message import Action\r\n\r\nlogger = logging.getLogger(__name__)\r\n\r\n\r\nclass MessageHandler:\r\n def __init__(\r\n self,\r\n status_queue_name,\r\n controller_queue_name,\r\n rabbitmq_client,\r\n instance_service\r\n ):\r\n self.status_queue_name = status_queue_name\r\n self.controller_queue_name = controller_queue_name\r\n self.rabbitmq_client = rabbitmq_client\r\n self.instance_service = instance_service\r\n self.instance_ack_exchange_name = \"instance_ack_exchange\"\r\n\r\n async def send(\r\n self,\r\n response_message,\r\n response_status,\r\n device_id: int,\r\n action: Action\r\n ):\r\n \"\"\"\r\n Sends a message to the RabbitMQ queue.\r\n Parameters:\r\n response_message: message to be sent.\r\n response_status: status of the message.\r\n device_id: device id of the message.\r\n action: action that was executed on the instance.\r\n \"\"\"\r\n action_name = action.name if action else None\r\n\r\n ack_message = CtlAcknowledgeMessage(\r\n code=self.__message_code_mapper(response_status),\r\n device_id=device_id,\r\n action=action_name,\r\n message=response_message\r\n )\r\n\r\n await self.rabbitmq_client.send_message(\r\n routing_key=self.status_queue_name,\r\n exchange_name=self.instance_ack_exchange_name,\r\n message=asdict(ack_message)\r\n )\r\n\r\n async def __process_unique_message(\r\n self,\r\n input_message: InputMessage,\r\n ):\r\n \"\"\"\r\n Function use for processing messages that are unique to an instance.\r\n \"\"\"\r\n await message_dispatcher(input_message, self.instance_service)\r\n\r\n async def __process_shared_message(\r\n self,\r\n input_message: InputMessage,\r\n device_id: int,\r\n onACK: Callable[[], Awaitable[None]]\r\n ):\r\n \"\"\"\r\n Function use for processing messages that are shared between other instances.\r\n \"\"\"\r\n if not await self.instance_service.validate_instance(device_id):\r\n # Discard message if the instance does not exist, but send ack anyway, this message is not for us\r\n logger.warning(\"Instance does not exist. Discarding message...\")\r\n await onACK()\r\n raise EndMessageProcessing()\r\n\r\n await message_dispatcher(input_message, self.instance_service)\r\n\r\n async def process_shared_messages(\r\n self,\r\n received_message):\r\n await self._process_message(received_message, True)\r\n\r\n async def process_unique_messages(\r\n self,\r\n received_message):\r\n await self._process_message(received_message, False)\r\n\r\n async def _process_message(\r\n self,\r\n received_message,\r\n is_shared: bool = False\r\n ):\r\n \"\"\"\r\n Callback function for processing received messages from RabbitMQ.\r\n Parameters:\r\n received_message: message received from RabbitMQ.\r\n \"\"\"\r\n logger.info(\"Starting to process message...\")\r\n try:\r\n input_message = self.__build_message_dto(received_message)\r\n device_id = input_message.device_id\r\n action = input_message.action\r\n\r\n if not is_shared:\r\n await self.__process_unique_message(input_message)\r\n else:\r\n try:\r\n await self.__process_shared_message(input_message, device_id, received_message.ack)\r\n except EndMessageProcessing:\r\n return\r\n\r\n await self.send(\r\n response_status=ResponseStatus.Ok,\r\n response_message=\"OK\",\r\n device_id=device_id,\r\n action=action\r\n )\r\n await received_message.ack()\r\n except (KeyError, json.decoder.JSONDecodeError):\r\n # Discard message if it hasn't the required format\r\n logger.warning(\"Invalid message format. Discarding message...\")\r\n await received_message.ack()\r\n except AppError as e:\r\n await self.send(\r\n response_status=self.__app_error_status_mapper(e),\r\n response_message=e.message,\r\n device_id=device_id,\r\n action=action\r\n )\r\n await received_message.ack()\r\n except Exception:\r\n logger.exception(\"Unexpected error.\")\r\n await received_message.reject(requeue=False)\r\n\r\n def __build_message_dto(self, input_message) -> InputMessage:\r\n \"\"\"\r\n Builds a InputMessage object from the received message.\r\n Parameters:\r\n input_message: message received from RabbitMQ.\r\n Returns:\r\n InputMessage object.\r\n \"\"\"\r\n message_body = input_message.body.decode()\r\n message_dict = json.loads(message_body)\r\n\r\n message_dto = InputMessage(\r\n action=Action[message_dict[\"action\"]],\r\n device_id=message_dict[\"device_id\"],\r\n device_stream_url=message_dict.get(\"device_stream_url\")\r\n )\r\n\r\n logger.info(f\"Received message: {message_dto}\")\r\n return message_dto\r\n\r\n def __message_code_mapper(self, status):\r\n mapper = {\r\n ResponseStatus.Ok: 2000,\r\n ResponseStatus.BadRequest: 4000,\r\n ResponseStatus.NotFound: 4004,\r\n ResponseStatus.Conflict: 4009,\r\n ResponseStatus.InternalError: 5000,\r\n ResponseStatus.InconsistentContainerState: 5001\r\n }\r\n return mapper[status]\r\n\r\n def __app_error_status_mapper(self, error):\r\n mapper = {\r\n InstanceNotFound: ResponseStatus.NotFound,\r\n InstanceAlreadyExists: ResponseStatus.Conflict\r\n }\r\n return mapper[error.__class__]\r\n","repo_name":"sensiflow/instance-manager","sub_path":"src/rabbitmq/message_handler.py","file_name":"message_handler.py","file_ext":"py","file_size_in_byte":6590,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"41945335251","text":"import numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\nimport gym\nimport time\nimport retro\nimport random\nfrom collections import deque\n\nenv=gym.make('CartPole-v1')\nenv.reset()\n\nnum_train_episodes=500\n\nclass agent:\n def __init__(self, observation_space_shape, action_space_shape):\n self.action_space_shape=action_space_shape\n self.observation_space_shape=observation_space_shape\n self.replay_memory=deque(maxlen=100_000)\n self.model=self.make_model()\n self.target_model=self.make_model()\n self.epsilon=1\n self.max_epsilon=1\n self.min_epsilon=0.01\n self.decay=0.0001\n\n def make_model(self):\n learning_rate=0.001\n\n model=keras.Sequential()\n model.add(keras.layers.Dense(128,input_shape=self.observation_space_shape,activation=tf.nn.relu))\n model.add(keras.layers.Dense(128,activation=tf.nn.relu))\n model.add(keras.layers.Dense(128,activation=tf.nn.relu))\n #model.add(keras.layers.Dense(32, activation=tf.nn.relu))\n model.add(keras.layers.Dense(self.action_space_shape,activation='linear'))\n model.compile(loss=tf.keras.losses.Huber(), optimizer=tf.keras.optimizers.Adam(learning_rate=learning_rate),metrics=['accuracy'])\n return model\n\n def train(self):\n learning_rate=0.7\n discount_factor=0.99\n\n min_replay_size=1000\n if len(self.replay_memory)=100:\n print(\"updating target model\")\n self.update_target_model()\n steps_to_update_target_model=0\n break\n\n self.epsilon=max(self.min_epsilon,self.epsilon-self.decay)\n\n if episodes%50==0:\n self.target_model.save('trained_model ' + str(episodes))\n if render==True:\n render=False\n if episodes%20==0:\n render=True\n\n def load_model(self, path):\n self.model=keras.models.load_model(path)\n\n def choose_trained_action(self, observations):\n observation = observations.reshape([1, observations.shape[0]])\n predicted_value = self.model.predict(observation).flatten()\n action = np.argmax(predicted_value)\n return action\n\n def play_using_trained_model(self, num_episodes, path):\n self.load_model(path)\n for _ in range(num_episodes):\n observation=env.reset()\n done=False\n total_reward=0\n while not done:\n env.render()\n action=self.choose_trained_action(observation)\n new_observation, reward, done, info = env.step(action)\n observation=new_observation\n total_reward+=reward\n\n print(\"reward = {}; episode = {}\".format(total_reward, _))\n\n\n\ndef main():\n print(env.observation_space)\n print(env.action_space)\n game_agent=agent(env.observation_space.shape, env.action_space.n)\n game_agent.learn(num_train_episodes)\n\n # play using trained model\n # game_agent=agent(env.observation_space.shape, env.action_space.n)\n # game_agent.play_using_trained_model(100, \"CartPole-v1/trained_model 200\")\n\n # random agent\n # env.reset()\n # while(True):\n # action=env.action_space.sample()\n # observation ,reward, done, info = env.step(action)\n # if done:\n # env.reset()\n # env.render()\n\n env.close()\n\n\nif __name__==\"__main__\":\n main()\n","repo_name":"YuviTz1/reinforcement-learning","sub_path":"Deep Q learning/cartpole-v1.py","file_name":"cartpole-v1.py","file_ext":"py","file_size_in_byte":5931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"43021208754","text":"class Solution:\n def groupAnagrams(self, strs: List[str]) -> List[List[str]]:\n from collections import defaultdict, Counter\n alphabets = 'abcdefghijklmnopqrstuvwxyz'\n table = defaultdict(list)\n for s in strs:\n counter = Counter(s)\n key = tuple(counter[c] for c in alphabets)\n table[key].append(s)\n return [v for k, v in table.items()]\n ","repo_name":"IvanaGyro/LeetCode-Answer","sub_path":"0049_20190416_195519.py","file_name":"0049_20190416_195519.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71966782227","text":"import requests,csv\r\nfrom bs4 import BeautifulSoup\r\nimport urllib.request as ulreq\r\n#import urllib\r\n#https://zh.wikipedia.org/wiki/2019%E5%86%A0%E7%8B%80%E7%97%85%E6%AF%92%E7%97%85%E5%85%A8%E7%90%83%E5%90%84%E5%9C%B0%E7%96%AB%E6%83%85\r\nurl_1 ='https://zh.wikipedia.org/wiki/2019%E5%86%A0%E7%8B%80%E7%97%85%E6%AF%92%E7%97%85%E5%85%A8%E7%90%83%E5%90%84%E5%9C%B0%E7%96%AB%E6%83%85'\r\nr_data = requests.get(url_1)\r\n\r\nsoup = BeautifulSoup(r_data.text,'lxml')\r\n\r\n#table class = wikitable mw-collapsible sortable jquery-tablesorter mw-made-collapsible\r\n\r\ncovid_n = soup.find(id ='covid19-container')\r\ncovid_n_rows = covid_n.findAll('tr') #
    \r\nres=[]\r\npath = 'covid19_world.csv'\r\n#\r\nfor row in covid_n_rows:\r\n rowList=[]\r\n for cell in row.findAll(['td','th']):\r\n rowList.append(cell.get_text().replace('\\n',''))\r\n res.append(rowList[:4])\r\n \r\nwith open(path,'w',newline= '',encoding='utf-8-sig') as fp:\r\n writer = csv.writer(fp)\r\n for i in range(len(res)-2):\r\n writer.writerow(res[i])\r\n \r\n#img gallery mw-gallery-nolines\r\ncovid_img = soup.find(class_='gallery')\r\ncovid_img_n = covid_img.findAll('li')\r\nimg_o_url = []\r\nfor i in range(len(covid_img_n)):\r\n img_tag= covid_img_n[i].find('img')\r\n img_src= img_tag.get('src')\r\n req = ulreq.urlopen('https:'+img_src) \r\n img_a = covid_img_n[i].a.get('href')\r\n #img_o_url.append(img_a)\r\n with open('imges\\\\' +str(i).zfill(5)+ '.jpg','wb') as fp:\r\n size = 0\r\n while True:\r\n info = req.read(10000)\r\n if len(info)<1:\r\n break\r\n size += len(info)\r\n fp.write(info) \r\n print(f\"{str(i).zfill(5)}.jpg ,size is {size}\")\r\n \r\n #https://zh.wikipedia.org\r\n r_img_data = requests.get('https://zh.wikipedia.org'+img_a)\r\n \r\n img_soup = BeautifulSoup(r_img_data.text,'lxml')\r\n o_img_c = img_soup.find(class_='fullImageLink')\r\n o_img = o_img_c.find('a').get('href')\r\n img_o_req = ulreq.urlopen('https:'+o_img)\r\n \r\n with open('imges\\\\o_' +str(i).zfill(5)+ '.jpg','wb') as fp:\r\n size = 0\r\n while True:\r\n info = img_o_req.read(10000)\r\n if len(info)<1:\r\n break\r\n size += len(info)\r\n fp.write(info) \r\n print(f\"o_{str(i).zfill(5)}.jpg ,size is {size}\")\r\n \r\n\r\n\r\n\r\n \r\n ","repo_name":"Fangan998/bbg","sub_path":"main_covid19.py","file_name":"main_covid19.py","file_ext":"py","file_size_in_byte":2391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17130531731","text":"import torch\r\nfrom torch import nn\r\n\r\nfrom torch.utils.data import Dataset\r\nfrom torch.utils.data import DataLoader\r\nimport torch.nn.functional as F\r\n\r\n\r\nclass MyNet(nn.Module):\r\n def __init__(self):\r\n super(MyNet, self).__init__()\r\n\r\n self.conv1 = nn.Conv2d(\r\n in_channels=1,\r\n out_channels=12,\r\n kernel_size=5,\r\n stride=1,\r\n padding=1)\r\n self.bn1 = nn.BatchNorm2d(12)\r\n self.pool = nn.MaxPool2d(2, 2)\r\n self.conv4 = nn.Conv2d(\r\n in_channels=12,\r\n out_channels=24,\r\n kernel_size=5,\r\n stride=1,\r\n padding=1)\r\n self.bn4 = nn.BatchNorm2d(24)\r\n self.fc1 = nn.Linear(2904, 10)\r\n\r\n def forward(self, input):\r\n output = F.relu(self.bn1(self.conv1(input)))\r\n output = self.pool(output)\r\n output = F.relu(self.bn4(self.conv4(output)))\r\n output = output.view(-1, 2904)\r\n output = self.fc1(output)\r\n\r\n return output\r\n","repo_name":"zheedong/DL_Rebuilding","sub_path":"models/fashion_mynet.py","file_name":"fashion_mynet.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42667054181","text":"import numpy as np\nimport scipy.sparse as sp\nfrom scipy.sparse import identity, diags\nimport networkx as nx\nfrom time import time\nfrom gensim.models import Word2Vec\n\n\ndef normalize_adjacency(A):\n n = A.shape[0]\n A = A + identity(n)\n degs = A.dot(np.ones(n))\n inv_degs = np.power(degs, -1)\n D_inv = diags(inv_degs)\n A_hat = D_inv.dot(A)\n return A_hat\n\ndef create_and_normalize_adjacency(G):\n adj = nx.adjacency_matrix(G) # Obtains the adjacency matrix of the training graph\n adj = normalize_adjacency(adj)\n #adj = normalize_adj(adj)\n print('Created a normalized adjancency matrix of shape', adj.shape)\n indices = np.array(adj.nonzero()) # Gets the positions of non zeros of adj into indices\n print('Created indices', indices.shape, 'with the positions of non zeros in adj matrix')\n return adj, indices\n\n\ndef random_walk(G, node, walk_length):\n walk = [node]\n \n for i in range(walk_length-1):\n neibor_nodes = list(G.neighbors(walk[-1]))\n if len(neibor_nodes) > 0:\n next_node = choice(neibor_nodes)\n walk.append(next_node)\n walk = [node for node in walk] # in case the nodes are in string format, we don't need to cast into string, but if the nodes are in numeric or integer, we need this line to cast into string\n return walk\n\n\ndef generate_walks(G, num_walks, walk_length):\n # Runs \"num_walks\" random walks from each node, and returns a list of all random walk\n t = time()\n print('Start generating walks....')\n walks = list() \n for i in range(num_walks):\n for node in G.nodes():\n walk = random_walk(G, node, walk_length)\n walks.append(walk)\n #print('walks : ', walks)\n print('Random walks generated in in {}s!'.format(round(time()-t)))\n return walks\n\ndef apply_word2vec_on_features(features, nodes, vector_size=128, window=5, min_count=0, sg=1, workers=8):\n t = time()\n print('Start applying Word2Vec...')\n wv_model = Word2Vec(vector_size=vector_size, window=window, min_count=min_count, sg=sg, workers=workers)\n wv_model.build_vocab(features)\n wv_model.train(features, total_examples=wv_model.corpus_count, epochs=5) \n print('Word2vec model trained on features in {} min!'.format(round((time()-t)/60)))\n features_np = []\n for node in nodes:\n features_np.append(wv_model.wv[node])\n\n features_np = np.array(features_np)\n print(features_np.shape, 'features numpy array created in {} min!'.format(round((time()-t)/60)))\n return features_np\n\n","repo_name":"ghassenabdedayem/Link-prediction","sub_path":"data_processing/data_processing_graph.py","file_name":"data_processing_graph.py","file_ext":"py","file_size_in_byte":2524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"24138032837","text":"# %%\nimport torch\nfrom torch.distributions import Normal\nfrom torch.nn.functional import softplus\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom itertools import product\nfrom tqdm import tqdm\n\n# %%\n\nnum_samples = 1000\nnum_samples_entropy = 10000\n\n\ndef entropy(μ, σ):\n pi_distribution = Normal(μ, σ)\n pi_action = pi_distribution.sample((num_samples_entropy,))\n\n logp_pi = pi_distribution.log_prob(pi_action)\n logp_pi -= 2 * (np.log(2) - pi_action - softplus(-2 * pi_action))\n\n return -logp_pi.mean().item()\n\n\nμs = np.linspace(-2, 2, num_samples)\nσs = np.logspace(0.1, 10, num_samples)\nσs = np.linspace(np.exp(-20), 1, num_samples)\nσs = np.linspace(1e-3, 3, num_samples)\n\n\nX, Y = np.meshgrid(μs, σs)\n\n\n# %%\n\ndata = np.zeros((num_samples, num_samples))\n\nfor idx, idy in tqdm(product(range(num_samples), range(num_samples)), ncols=100):\n μ = X[idx, idy]\n σ = Y[idx, idy]\n result = entropy(μ, σ)\n # print(f\"{μ:.4f}, {σ:.4f}, {result:.4f}\")\n data[idx, idy] = result\n\nZ = data\n\n# %%\nfig, ax = plt.subplots(1, 1)\ncp = ax.contourf(X, Y, Z)\nfig.colorbar(cp) # Add a colorbar to a plot\nax.set_title(\"Entropy\")\nax.set_xlabel(\"μ\")\nax.set_ylabel(\"σ\")\nplt.show()\n\n\n# plt.contour(μs, σs, data)\n# plt.show()\n\n# %%\nfig = plt.figure()\nax = fig.add_subplot(projection=\"3d\")\nax.plot_surface(X, Y, Z)\nax.set_xlabel(\"μ\")\nax.set_ylabel(\"σ\")\nax.set_zlabel(\"Entropy\")\nplt.show()\n\n# %%\nidx, idy = np.unravel_index(np.argmax(data), np.array(data).shape)\nμ = X[idx, idy]\nσ = Y[idx, idy]\nprint(f\"μ: {μ}, σ: {σ}\")\n\n# %%\n\ndata = np.load(\"data.npy\")\n\n# %%\n","repo_name":"johannespitz/entropy","sub_path":"grid.py","file_name":"grid.py","file_ext":"py","file_size_in_byte":1592,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42563763644","text":"# Write a function that copies a file to an other\n# It should take the filenames as parameters\n# It should return a boolean that shows if the copy was successful\n\ndef copier(Path1, Path2):\n try:\n with open(Path1, 'r') as file_from:\n file_content = file_from.readlines()\n with open(Path2, 'w') as file_to:\n file_to.writelines(file_content)\n except IOError:\n return False\n return True\n\nif copier(r'''C:\\Users\\Miki\\greenfox\\DonBattery\\week-03\\day-2\\my-file.txt''',r'''C:\\Users\\Miki\\greenfox\\DonBattery\\week-03\\day-2\\my-file2.txt'''):\n print('Copied successfully')\nelse:\n print('error')","repo_name":"green-fox-academy/DonBattery","sub_path":"week-03/day-2/copy_file.py","file_name":"copy_file.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"647750550","text":"import os\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\nclass Preprocessing():\r\n def __init__(self, set_name, cwd):\r\n self.set_name = set_name\r\n self.cwd = cwd # current working directory\r\n self.df = None\r\n\r\n def change_file_name(self):\r\n # Rename files\r\n os.chdir(cwd + '\\\\set-' + self.set_name)\r\n for i, filename in enumerate(os.listdir(\".\")):\r\n os.rename(filename, str(i) + \".txt\")\r\n\r\n def read_data(self):\r\n # Get all the features\r\n feature_list = ['RecordID', 'Age', 'Gender', 'Height', 'ICUType', 'Weight', 'Albumin', 'ALP', 'ALT',\r\n 'AST', 'Bilirubin', 'BUN', 'Cholesterol', 'Creatinine', 'DiasABP', 'FiO2', 'GCS', 'Glucose',\r\n 'HCO3', 'HCT', 'HR', 'K', 'Lactate', 'Mg', 'MAP', 'MechVent', 'Na', 'NIDiasABP', 'NIMAP',\r\n 'NISysABP', 'PaCO2', 'PaO2', 'pH', 'Platelets', 'RespRate', 'SaO2', 'SysABP', 'Temp', 'TropI',\r\n 'TropT', 'Urine', 'WBC']\r\n new_feature_list = feature_list[:5]\r\n for i in range(5, 42):\r\n f = feature_list[i]\r\n new_feature_list.extend([f + 'Min', f + 'Max', f + 'Mean', f + 'Variance', f + 'Count'])\r\n # Standardised format\r\n self.df = pd.DataFrame(columns=new_feature_list[:])\r\n # Read data from text files\r\n self.change_file_name()\r\n for i in range(4000):\r\n row = dict(zip(feature_list, [[] for k in range(42)]))\r\n new_row = dict(zip(new_feature_list, [[] for k in range(190)]))\r\n text = open(str(i) + '.txt', 'r').read().split('\\n')\r\n count = [0]*42\r\n for line in text[1:]:\r\n line = line.split(',')\r\n if len(line) == 3:\r\n try:\r\n f = line[1]\r\n val = line[2]\r\n row[str(f)].append([float(val)])\r\n except KeyError:\r\n pass\r\n for k in range(5):\r\n new_row[feature_list[k]] = row[feature_list[k]]\r\n for k in range(5, 42):\r\n f = feature_list[k]\r\n if len(row[f]) > 0:\r\n new_row[f + 'Min'] = min(row[f])[0]\r\n new_row[f + 'Max'] = max(row[f])[0]\r\n new_row[f + 'Mean'] = np.mean(row[f])\r\n new_row[f + 'Variance'] = np.var(row[f])\r\n new_row[f + 'Count'] = len(row[f])\r\n else:\r\n new_row[f + 'Min'] = 0\r\n new_row[f + 'Max'] = 0\r\n new_row[f + 'Mean'] = 0\r\n new_row[f + 'Variance'] = 0\r\n new_row[f + 'Count'] = 0\r\n new_row = list(new_row.values())\r\n for i in range(5):\r\n new_row[i] = new_row[i][0][0]\r\n self.df.loc[len(self.df)] = new_row\r\n # Read outcome\r\n os.chdir(\"..\")\r\n mortality = open('Outcomes-' + self.set_name + '.txt', 'r').read().split('\\n')\r\n outcome = []\r\n for line in mortality[1:]:\r\n if line != '':\r\n if line[-1] == '1':\r\n outcome.append(1)\r\n else:\r\n outcome.append(0)\r\n self.df['Outcome'] = pd.Series(outcome)\r\n\r\n def createNew(self, col, type, up=None, down=None):\r\n new_col = []\r\n if type == 'up':\r\n for item in col:\r\n if item > up:\r\n new_col.append(1)\r\n else:\r\n new_col.append(0)\r\n elif type == 'down':\r\n for item in col:\r\n if item < down:\r\n new_col.append(1)\r\n else:\r\n new_col.append(0)\r\n else:\r\n for item in col:\r\n if item < up and item > down:\r\n new_col.append(1)\r\n else:\r\n new_col.append(0)\r\n return new_col\r\n\r\n def replaceCol(self, col_name, type, up=None, down=None):\r\n col = self.df[col_name].tolist()\r\n new_col = self.createNew(col, type, up, down)\r\n self.df[col_name + 'Dis'] = pd.Series(new_col)\r\n self.df.drop(col_name, axis=1, inplace=True)\r\n\r\n def replaceByMean(self, col_name, stan):\r\n col = np.array(self.df[col_name])\r\n colMean = np.mean(col[col > stan])\r\n for i in range(len(col)):\r\n if col[i] <= stan:\r\n col[i] = colMean\r\n self.df[col_name] = col[:]\r\n\r\n def replaceByMode(self, col_name, stan):\r\n col = np.array(self.df[col_name])\r\n unique, count = np.unique(np.array(col[col > stan]), return_counts=True)\r\n colMode = unique[np.argmax(count)]\r\n for i in range(len(col)):\r\n if col[i] <= stan:\r\n col[i] = colMode\r\n self.df[col_name] = col[:]\r\n\r\n def process_data(self):\r\n feature_list = list(self.df.columns.values)\r\n # Remove variance features and those with same values\r\n variance_list = []\r\n for feature in feature_list:\r\n if 'Variance' in feature:\r\n variance_list.append(feature)\r\n self.df.drop(variance_list, axis=1, inplace=True)\r\n\r\n other_drop = ['ALPMax', 'ALTMin', 'ALTMax', 'ALTMean', 'ASTMin', 'ASTMax', 'ASTMean', 'BilirubinMin', 'BilirubinMax',\r\n 'BilirubinMean', 'CholesterolMin', 'CholesterolMax', 'CholesterolMean',\r\n 'CholesterolCount', 'pHMax', 'RespRateMin', 'RespRateMax', 'RespRateMean', 'RespRateCount']\r\n self.df.drop(other_drop, axis=1, inplace=True)\r\n # Features with different distributions for two classes\r\n self.replaceCol('ALPCount', 'up', 2)\r\n self.replaceCol('ALTCount', 'up', 2)\r\n self.replaceCol('ASTCount', 'up', 2)\r\n self.replaceCol('BilirubinCount', 'up', 2)\r\n self.replaceCol('FiO2Min', 'both', 0.8, 0.2)\r\n self.replaceCol('FiO2Mean', 'down', None, 0.3)\r\n self.replaceCol('GCSMax', 'down', None, 10)\r\n self.replaceCol('PaCO2Min', 'both', 60, 10)\r\n self.replaceCol('PaCO2Max', 'both', 80, 20)\r\n self.replaceCol('PaCO2Mean', 'both', 70, 20)\r\n # Remove TropI and TropT\r\n for var in [\"TropI\", \"TropT\"]:\r\n for type in [\"Min\", \"Max\", \"Mean\", \"Count\"]:\r\n self.df.drop(var+type, 1, inplace=True)\r\n # Imputation\r\n mean_replace = ['Height 100', 'WeightMin 20', 'WeightMax 20', 'WeightMean 20', 'AlbuminMin 0', 'AlbuminMax 0',\r\n 'AlbuminMean 0', 'ALPMean 0', 'ALPMean 0', 'BUNMean 0', 'DiasABPMin 0', 'DiasABPMax 0', 'DiasABPMean 0',\r\n 'GCSMin 0', 'GCSMean 0', 'GlucoseMin 0', 'GlucoseMean 0',\r\n 'GlucoseMax 0', 'HCO3Min 0', 'HCO3Max 0', 'HCO3Mean 0', 'HCTMin 0', 'HCTMean 0', 'HCTMax 0', 'HRMin 0',\r\n 'HRMax 0', 'HRMean 0', 'KMean 0', 'KMin 0', 'KMax 0', 'LactateMin 0', 'LactateMean 0', 'LactateMax 0',\r\n 'MgMin 0', 'MgMax 0', 'MgMean 0', 'MAPMin 0', 'MAPMean 0', 'MAPMax 0', 'NaMin 0', 'NaMean 0', 'NaMax 0',\r\n 'NIDiasABPMin 0', 'NIDiasABPMean 0', 'NIDiasABPMax 0', 'NIMAPMin 0', 'NIMAPMean 0', 'NIMAPMax 0',\r\n 'NISysABPMin 0', 'NISysABPMean 0', 'NISysABPMax 0',\r\n 'PaO2Min 0', 'PaO2Mean 0', 'PaO2Max 0', 'pHMin 0', 'pHMean 0', 'PlateletsMin 0', 'PlateletsMean 0',\r\n 'PlateletsMax 0', 'SaO2Min 0', 'SaO2Mean 0', 'SaO2Max 0', 'SysABPMin 0', 'SysABPMean 0', 'SysABPMax 0',\r\n 'TempMin 24', 'TempMax 0', 'TempMean 0', 'UrineMin 0', 'UrineMax 0', 'UrineMean 0', 'WBCMin 0', 'WBCMax 0',\r\n 'WBCMean 0']\r\n for item in mean_replace:\r\n col_name, stan = item.split()\r\n self.replaceByMean(col_name, float(stan))\r\n mode_replace = ['BUNMin 0', 'BUNMax 0']\r\n for item in mode_replace:\r\n col_name, stan = item.split()\r\n self.replaceByMode(col_name, float(stan))\r\n # Normalise\r\n # for i in range(1, len(df.columns)):\r\n # col = df.ix[:,i]\r\n # min_col = min(col)\r\n # max_col = max(col)\r\n # col = (col - min_col)/(max_col-min_col)\r\n # df.ix[:,i] = col[:]\r\n\r\n def write_file(self):\r\n self.read_data()\r\n self.process_data()\r\n # Write files\r\n if self.set_name == 'a':\r\n self.df.to_csv('train.csv')\r\n else:\r\n self.df.to_csv('validation.csv')\r\n\r\ncwd = os.getcwd()\r\n\r\nprep = Preprocessing('a', cwd)\r\nprep.write_file()\r\n\r\nprep = Preprocessing('c', cwd)\r\nprep.write_file()\r\n","repo_name":"giantonia/Predicting-mortality-of-ICU-patients","sub_path":"preproc.py","file_name":"preproc.py","file_ext":"py","file_size_in_byte":8739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"27505442086","text":"import numpy as np\nfrom typing import List, Tuple, Optional, Union, Callable, Any\nimport warnings\n\nwarnings.filterwarnings('ignore')\nnp.set_printoptions(suppress=True)\n\n\nclass ParticleSwarm():\n \"\"\"Implementation of PSO using Numpy\"\"\"\n\n def __init__(self,\n num_particles: int = 1000,\n w: float = 1.0,\n c1: float = 0.5,\n c2: float = 0.5,\n bounds: Optional[Tuple[Optional[float]]] = None,\n patience: int = 50,\n max_iter: Optional[int] = None,\n verbose: Union[bool, int] = 1) -> None:\n\n self.num_particles = num_particles\n self.w = w\n self.c1 = c1\n self.c2 = c2\n self.bounds = bounds or [None, None]\n self.patience = patience\n self.max_iter = max_iter or float('inf')\n self.verbose = verbose\n\n def _initialize_particles(self,\n p0: List[Tuple[float]],\n v0: List[Tuple[float]]\n ) -> Tuple[np.ndarray, np.ndarray]:\n dim = (self.num_particles, len(p0))\n p_pos = np.random.uniform(\n low=[p[0] for p in p0], high=[p[1] for p in p0], size=dim)\n p_vel = np.random.uniform(\n low=[v[0] for v in v0], high=[v[1] for v in v0], size=dim)\n return p_pos, p_vel\n\n def _update_velocity(self,\n p_vel: np.ndarray,\n p_pos: np.ndarray,\n p_best_pos: np.ndarray,\n g_best_pos: np.ndarray\n ) -> np.ndarray:\n r1, r2 = np.random.uniform(0, 1, size=(2))\n cog_acc = self.c1 * r1 * (p_best_pos - p_pos)\n soc_acc = self.c2 * r2 * (g_best_pos - p_pos)\n return (self.w * p_vel) + cog_acc + soc_acc\n\n def _update_position(self,\n p_pos: np.ndarray,\n p_vel: np.ndarray\n ) -> np.ndarray:\n p_pos_updated = p_pos + p_vel\n p_pos_updated = p_pos_updated.reshape(-1)\n p_vel = p_vel.reshape(-1)\n\n if self.bounds[0] is not None:\n # update new position, with upper bounds\n p_pos_updated = np.where(\n p_pos_updated > self.bounds[0],\n p_pos_updated-(2*p_vel),\n p_pos_updated)\n\n if self.bounds[1] is not None:\n # update new position, with lower bounds\n p_pos_updated = np.where(\n p_pos_updated < self.bounds[1],\n p_pos_updated-(2*p_vel),\n p_pos_updated)\n\n p_pos_updated = p_pos_updated.reshape((self.num_particles, -1))\n\n return p_pos_updated\n\n def fit(self,\n obj_fn: Callable,\n p0: List[Tuple[float]],\n v0: List[Tuple[float]],\n args: Union[List[Any], Tuple[Any]] = ()\n ) -> np.ndarray:\n\n self.p_pos, self.p_vel = self._initialize_particles(p0, v0)\n\n self.p_best_pos = np.zeros(self.p_pos.shape)\n self.p_best_obj_val = np.full((self.p_pos.shape[0],), np.inf)\n self.g_best_pos = np.zeros((self.p_pos.shape[1]))\n self.g_best_obj_val = np.inf\n\n k = 1\n iters_with_no_improv = 0\n while (self.patience - iters_with_no_improv) and k <= self.max_iter:\n\n obj_val = obj_fn(self.p_pos, *args)\n obj_val_improved = obj_val < obj_fn(self.p_best_pos, *args)\n\n self.p_best_pos[obj_val_improved] = self.p_pos[obj_val_improved]\n self.p_best_obj_val[obj_val_improved] = obj_val[obj_val_improved]\n\n self.iter_best = self.p_best_obj_val.min()\n if self.iter_best < self.g_best_obj_val:\n best_idx = np.argmin(self.p_best_obj_val)\n self.g_best_pos = self.p_best_pos[best_idx]\n self.g_best_obj_val = self.iter_best\n iters_with_no_improv = 0\n else:\n iters_with_no_improv += 1\n\n if self.verbose:\n template = \"Iter {:05d} : Best particle MAE {:.7f} : \"\n template += \"Params [\" + \"{:.3f} \" * len(self.g_best_pos) + \"]\"\n print(template.format(k, self.g_best_obj_val, *self.g_best_pos),\n end='\\r')\n\n self.p_vel = self._update_velocity(\n self.p_vel, self.p_pos, self.p_best_pos, self.g_best_pos)\n\n self.p_pos = self._update_position(\n self.p_pos, self.p_vel)\n\n if self.max_iter and k >= self.max_iter:\n break\n\n k += 1\n\n return self.g_best_pos\n\n\nif __name__ == '__main__':\n\n POLY_DEGREE = 5\n RANDOM_SEED = 2000\n XLIM = (-2.2, 2.2)\n NOISE_SIGMA = 0.6\n NUM_DATAPOINTS = 1000\n\n def poly_fn(x, coefs):\n y = coefs[0] * np.ones_like(x)\n for i, coef in enumerate(coefs[1:]):\n y += coef * x**(i+1)\n return y\n\n def random_data():\n if RANDOM_SEED: np.random.seed(RANDOM_SEED)\n coefs = np.random.randn(POLY_DEGREE)\n x = np.random.uniform(*XLIM, NUM_DATAPOINTS)\n y = poly_fn(x, coefs) + np.random.randn(x.shape[0]) * NOISE_SIGMA\n return x, y\n\n x, y = random_data()\n\n fitted_coefs = ParticleSwarm().fit(\n obj_fn=lambda p, x, y: np.square(y-poly_fn(x, p.T[..., None])).mean(1),\n p0=[(-1, 1)]*POLY_DEGREE,\n v0=[(0, 0)]*POLY_DEGREE,\n args=(x, y)\n )\n\n try:\n import matplotlib.pyplot as plt\n import matplotlib\n matplotlib.use('TkAgg')\n\n x_linspace = np.linspace(*XLIM, 1_000)\n y_linspace = poly_fn(x_linspace, coefs=fitted_coefs)\n plt.plot(x_linspace, y_linspace, color='C3', label='fitted line')\n plt.scatter(x, y, s=20, alpha=0.5, label='datapoints')\n plt.legend(fontsize=14)\n plt.show(block=True);\n\n except Exception as e:\n print(e)\n\n print()\n","repo_name":"akensert/algorithms-in-Python","sub_path":"optimization/particle_swarm.py","file_name":"particle_swarm.py","file_ext":"py","file_size_in_byte":5925,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12124267025","text":"#!/usr/bin/python3\n# -*- coding: UTF-8 -*-\n\nimport re\nimport copy\nfrom skl_shared.localize import _\nimport skl_shared.shared as sh\n\n\n''' Tag patterns:\n • Dictionary titles:\n define them by the .ifo file, set the tag manually\n • Short dictionary titles:\n define them manually by the file name\n • Terms:\n \n (in phrases)\n • Comments:\n \n • Word forms:\n \n • Transcription:\n \n • Parts of speech:\n # A XDXF tag meaning grammar information about the word\n \n '''\n\n# Full dictionary titles\npdic = ''\n\n# Comments\npcom = ''\n\n# Word Forms\npwf = ''\n\n# Parts of speech\npsp = ''\n\n# Terms\nptm = ''\n\n# Terms in the 'Phrases' section\npph = ''\n\n# Transcription\nptr1 = ''\nptr2 = ''\n\nuseful_tags = [pdic,pcom,ptr1,pwf,ptm,pph,psp]\n\n\n\nclass Block:\n\n def __init__(self):\n self.block = -1\n # Applies to non-blocked cells only\n self.cellno = -1\n self.dic = ''\n self.dicf = ''\n self.dprior = 0\n self.first = -1\n self.i = -1\n self.j = -1\n self.last = -1\n self.no = -1\n self.same = -1\n ''' 'select' is an attribute of a *cell* which is valid\n if the cell has a non-blocked block of types 'term',\n 'phrase' or 'transc'.\n '''\n self.select = -1\n self.speech = ''\n self.sprior = -1\n self.term = ''\n self.text = ''\n self.transc = ''\n ''' 'comment', 'correction', 'dic', 'invalid', 'phrase',\n 'speech', 'term', 'transc', 'wform'\n '''\n self.type_ = 'comment'\n self.url = ''\n self.urla = ''\n self.wform = ''\n\n\n\nclass AnalyzeTag:\n\n def __init__(self,tag):\n self.block = ''\n self.blocks = []\n self.cur = Block()\n self.elems = []\n self.tag = tag\n\n def set_dic(self):\n f = '[MClient] plugins.stardict.tags.AnalyzeTag.set_dic'\n if pdic in self.block:\n self.cur.type_ = 'dic'\n \n def run(self):\n self.split()\n self.blocks = [block for block in self.blocks if block.strip()]\n for self.block in self.blocks:\n if self.block.startswith('<'):\n if self.is_useful():\n self.cur.type_ = ''\n self.set_phrases()\n # Phrases and word forms have conflicting tags\n # We check 'type_' to speed up\n if not self.cur.type_:\n self.set_wform()\n if not self.cur.type_:\n self.set_dic()\n if not self.cur.type_:\n self.set_term()\n if not self.cur.type_:\n self.set_speech()\n if not self.cur.type_:\n self.set_comment()\n if not self.cur.type_:\n self.set_transc()\n else:\n self.cur.type_ = 'invalid'\n else:\n self.run_plain()\n\n def is_useful(self):\n for tag in useful_tags:\n if tag in self.block:\n return True\n\n def run_plain(self):\n self.cur.text = self.block\n ''' #NOTE: The analysis must be reset after '':\n tmp += sym\n self.blocks.append(tmp)\n tmp = ''\n elif sym == '<':\n if tmp:\n self.blocks.append(tmp)\n tmp = sym\n else:\n tmp += sym\n if tmp:\n self.blocks.append(tmp)\n\n def set_comment(self):\n if self.block.startswith(pcom):\n self.cur.type_ = 'comment'\n\n def set_wform(self):\n if pwf in self.block:\n self.cur.type_ = 'wform'\n\n def set_phrases(self):\n if pph in self.block:\n self.cur.type_ = 'phrase'\n\n def set_term(self):\n if ptm in self.block:\n self.cur.type_ = 'term'\n\n # Transcription\n def set_transc(self):\n if ptr1 in self.block:\n type_ = 'transc'\n text = self.block.replace(ptr1,'',1).replace(ptr2,'',1)\n # Will be empty for non-Stardict sources\n if text:\n self.cur.type_, self.cur.text = type_, text\n self.elems.append(copy.copy(self.cur))\n\n def set_speech(self):\n if psp in self.block:\n self.cur.type_ = 'speech'\n\n\n\nclass Tags:\n\n def __init__ (self,text,Debug=False\n ,maxrow=20,maxrows=1000\n ):\n if text:\n self.text = list(text)\n else:\n self.text = ''\n self.abbr = {}\n self.blocks = []\n self.Debug = Debug\n self.maxrow = maxrow\n self.maxrows = maxrows\n self.tags = []\n\n def get_tags(self):\n ''' Split the text by closing tags. To speed up, we remove\n closing tags right away.\n '''\n if not self.tags:\n Ignore = False\n tmp = ''\n for i in range(len(self.text)):\n if self.text[i] == '<':\n if i < len(self.text) - 1 \\\n and self.text[i+1] == '/':\n Ignore = True\n if tmp:\n self.tags.append(tmp)\n tmp = ''\n else:\n tmp += self.text[i]\n elif self.text[i] == '>':\n if Ignore:\n Ignore = False\n else:\n tmp += self.text[i]\n elif not Ignore:\n tmp += self.text[i]\n # Should be needed only for broken tags\n if tmp:\n self.tags.append(tmp)\n return self.tags\n\n def debug_tags(self):\n f = '[MClient] plugins.stardict.tags.Tags.debug_tags'\n message = ''\n for i in range(len(self.tags)):\n message += '%d:%s\\n' % (i,self.tags[i])\n sh.com.run_fast_debug(f,message)\n\n def debug_blocks (self):\n f = '[MClient] plugins.stardict.tags.Tags.debug_blocks'\n headers = ('NO','TYPE','TEXT','URL','SAMECELL')\n rows = []\n for i in range(len(self.blocks)):\n rows.append ([i + 1\n ,self.blocks[i].type_\n ,self.blocks[i].text\n ,self.blocks[i].url\n ,self.blocks[i].same\n ]\n )\n mes = sh.FastTable (headers = headers\n ,iterable = rows\n ,maxrow = self.maxrow\n ,maxrows = self.maxrows\n ,Transpose = True\n ).run()\n mes = _('Non-DB blocks:') + '\\n\\n' + mes\n sh.com.run_fast_debug(f,mes)\n\n def debug(self):\n if self.Debug:\n self.debug_tags()\n self.debug_blocks()\n\n def get_blocks(self):\n if not self.blocks:\n for tag in self.tags:\n analyze = AnalyzeTag(tag)\n analyze.run()\n lst = analyze.elems\n for i in range(len(lst)):\n if i > 0:\n lst[i].same = 1\n else:\n lst[i].same = 0\n self.blocks += lst\n return self.blocks\n\n def run(self):\n self.get_tags()\n self.get_blocks()\n self.debug()\n return self.blocks\n","repo_name":"sklprogs/mclient","sub_path":"src/plugins/stardict/tags.py","file_name":"tags.py","file_ext":"py","file_size_in_byte":8155,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"12111952126","text":"class main():\n def bankSystem():\n def deposit():\n deposit = input('Deposite um valor: ')\n return float(deposit)\n\n def withDrawal():\n withDrawal = input('Escolha um valor para sacar de até 500 reais: ')\n return float(withDrawal)\n \n def choose():\n print('-------------Banco------------')\n user = input('[D]epósito\\n[S]aque\\n[E]xtrato\\nEscolha uma operação: ').strip()\n print('------------------------------')\n return user.upper()\n \n try:\n history = []\n register = 800.00\n limitWD = 3\n\n while True:\n user = choose()\n if user in ['D', 'DEPOSITO', 'DEPÓSITO']:\n print(f'Seu saldo: R$ {register}')\n value = deposit()\n register += value\n history.append(f'+ R${value}')\n\n elif user in ['S', 'SAQUE']:\n if limitWD == 0:\n print('Só é permetido três saques.')\n elif register <= 0:\n print(f'Seu saldo: R$ {register}')\n print('Saldo insuficiente para sacar.')\n else:\n print(f'Seu saldo: R$ {register}')\n value = withDrawal()\n if value <= 500:\n register -= value\n history.append(f'- R${value}')\n limitWD -= 1\n else:\n print('Só é permetido saque abaixo de R$ 500')\n\n elif user in ['E','EXTRATO']:\n if len(history) == 0:\n print(' EXTRATO \\n')\n print(f'Seu saldo: R$ {register}')\n print('Não foram realizadas movimentações.')\n else:\n print(' EXTRATO ')\n for show in history:\n print(show)\n print(f'\\nSeu saldo: R$ {register}')\n\n else:\n print('Encerrando a operação')\n break \n\n except:\n print('Erro em realizar a operação.')\n\nif __name__ == '__main__':\n main.bankSystem()","repo_name":"ttpepeu/Sistema-de-Banco","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2431,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20350235837","text":"from ast import literal_eval\nimport pandas as pd\n\n\ndef company(df_data):\n all_companies = df_data['production_companies']\n uniques = dict()\n for row in all_companies:\n if row != [] and row is not None:\n row = literal_eval(row)\n for company in row:\n id, name = company['id'], company['name']\n uniques[id] = name\n pd.DataFrame(data=uniques.values(), index=uniques.keys()).to_csv(\"unique_companies.csv\")\n\n # set the generated file unique_companies.csv in import folder of the DB\n # load data in neo4j:\n \"\"\"LOAD CSV WITH HEADERS FROM 'file:///unique_companies.csv' AS row\n MERGE (c:Company{company_id: toInteger(row.id)})\n SET c.name = CASE trim(row.name) WHEN \"\" THEN null ELSE row.name END\"\"\"\n\n\ndef keywords(df_data):\n all_keywords = df_data['keywords']\n uniques = dict()\n for row in all_keywords:\n if row != [] and row is not None:\n row = literal_eval(row)\n for keyword in row:\n id, name = keyword['id'], keyword['name']\n uniques[id] = name\n\n pd.DataFrame(data=uniques.values(), index=uniques.keys()).to_csv(\"unique_keywords.csv\")\n\n # load data in neo4j:\n \"\"\"\n LOAD CSV WITH HEADERS FROM 'file:///unique_keywords.csv' AS row\n MERGE (c:Keyword{keyword_id: toInteger(row.id)})\n SET c.uid = apoc.create.uuid()\n SET c.name = CASE trim(row.keyword) WHEN \"\" THEN null ELSE row.keyword END\n \"\"\"\n\n\ndef movies(df_data):\n titles = df_data['title']\n original_titles = df_data['original_title']\n budgets = df_data['budget']\n is_adult = df_data['adult']\n movie_ids = df_data['id']\n imdb_ids = df_data['imdb_id']\n overviews = df_data['overview']\n popularities = df_data['popularity']\n poster_paths = df_data['poster_path']\n release_dates = df_data['release_date']\n revenues = df_data['revenue']\n runtimes = df_data['runtime']\n status = df_data['status']\n taglines = df_data['tagline']\n vote_counts = df_data['vote_count']\n vote_avgs = df_data['vote_average']\n\n check_lens = list(map(lambda n: len(n),\n [titles, original_titles, budgets, is_adult, movie_ids,\n imdb_ids, overviews, popularities,\n poster_paths, release_dates, revenues,\n runtimes, status, taglines, vote_counts, vote_avgs]))\n check_lens = set(check_lens)\n assert len(check_lens) == 1\n\n new_df = pd.DataFrame()\n new_df['titles'] = df_data['title']\n new_df['original_titles'] = df_data['original_title']\n new_df['budgets'] = df_data['budget']\n new_df['is_adult'] = df_data['adult']\n new_df['movie_ids'] = df_data['id']\n new_df['imdb_ids'] = df_data['imdb_id']\n new_df['overviews'] = df_data['overview']\n new_df['popularities'] = df_data['popularity']\n new_df['poster_paths'] = df_data['poster_path']\n new_df['release_dates'] = df_data['release_date']\n new_df['revenues'] = df_data['revenue']\n new_df['runtimes'] = df_data['runtime']\n new_df['status'] = df_data['status']\n new_df['taglines'] = df_data['tagline']\n new_df['vote_counts'] = df_data['vote_count']\n new_df['vote_avgs'] = df_data['vote_average']\n\n new_df.to_csv(\"all_movies.csv\")\n\n # load data in neo4j:\n \"\"\"\n LOAD CSV WITH HEADERS FROM 'file:///all_movies.csv' AS row\n MERGE (c:Movie{movie_id: toInteger(row.movie_ids)})\n WITH row, c, [item in split(row.release_dates, \"/\") |toInteger(item)] AS dateComponents\n SET c.uid = apoc.create.uuid(),\n c.title = row.titles,\n c.original_title = row.original_titles,\n c.budget = toFloat(row.budgets),\n c.adult = toBoolean(row.is_adult),\n c.imdb_id = toInteger(row.imdb_ids),\n c.overview = row.overviews,\n c.popularity = toFloat(row.popularities),\n c.poster_path = row.poster_paths,\n c.release_date = date({day: dateComponents[1], month: dateComponents[0], year: dateComponents[2]}),\n c.revenue = toFloat(row.revenues),\n c.runtime = toInteger(row.runtimes),\n c.status = row.status,\n c.tagline = row.taglines,\n c.vote_count = toInteger(row.vote_counts),\n c.vote_average = toFloat(row.vote_avgs)\n \"\"\"\n\n\ndef movies_collection(df_data):\n collections = df_data['belongs_to_collection']\n movies_ids = df_data['id']\n collections_ids = [literal_eval(col)['id'] if col is not None else '' for col in collections]\n\n # print(collections_ids)\n pd.DataFrame(data=collections_ids, index=movies_ids).to_csv(\"belongs_to_collection_bulk.csv\")\n\n # load data in neo4j:\n # when None value for movie the Match clause is not satisfied so relationship is not generated\n \"\"\"\n LOAD CSV WITH HEADERS FROM 'file:///belongs_to_collection_bulk.csv' AS row\n MATCH (m:Movie{movie_id: toInteger(row.movie_id)})\n MATCH (c:Collection{collection_id: toInteger(row.collection_id)})\n CREATE (m)-[r:BELONGS_TO]->(c)\n \"\"\"\n\n\ndef movies_genres(df_data):\n genres_ids = df_data['genres']\n genres_ids = [\n [dict_genre['id'] for dict_genre in literal_eval(genre_per_movie) if literal_eval(genre_per_movie) is not []]\n for genre_per_movie in genres_ids]\n movies_ids = df_data['id']\n movies_genres_dict = dict(zip(movies_ids, genres_ids))\n\n assert len(movies_ids) == len(genres_ids)\n movies_pairs = [(key, value) for key, values in movies_genres_dict.items() for value in values]\n\n pd.DataFrame(data=movies_pairs, columns=['movie_id', 'genre_id']).to_csv(\"movie_has_genre_bulk.csv\")\n\n # load data in neo4j:\n \"\"\"\n LOAD CSV WITH HEADERS FROM 'file:///movie_has_genre_bulk.csv' AS row\n MATCH (m:Movie{movie_id: toInteger(row.movie_id)})\n MATCH (c:Genre{genre_id: toInteger(row.genre_id)})\n CREATE (m)-[r:HAS_GENRE]->(c)\n \"\"\"\n\n\ndef orig_language(df_data):\n original_languages = df_data['original_language']\n movies_ids = df_data['id']\n\n assert len(movies_ids) == len(original_languages)\n\n pd.DataFrame(data=original_languages, index=movies_ids).to_csv(\"movie_orig_lang_bulk.csv\")\n\n \"\"\"\n LOAD CSV WITH HEADERS FROM 'file:///movie_orig_lang_bulk.csv' AS row\n MATCH (m:Movie{movie_id: toInteger(row.id)})\n MATCH (c:Language{iso_lang_code: row.original_language})\n CREATE (m)-[r:ORIGINAL_LANGUAGE]->(c)\n \"\"\"\n\n\ndef spoken_language(df_data):\n spoken_languages = df_data['spoken_languages']\n spoken_languages = [[dict_genre['iso_639_1'] for dict_genre in literal_eval(langs_per_movie) if\n literal_eval(langs_per_movie) is not []] for langs_per_movie in spoken_languages]\n movies_ids = df_data['id']\n assert len(movies_ids) == len(spoken_languages)\n\n movies_langs_dict = dict(zip(movies_ids, spoken_languages))\n movies_pairs = [(key, value) for key, values in movies_langs_dict.items() for value in values]\n\n pd.DataFrame(data=movies_pairs, columns=['movie_id', 'lang_iso']).to_csv(\"movie_spoken_lang_bulk.csv\")\n \"\"\"\n LOAD CSV WITH HEADERS FROM 'file:///movie_spoken_lang_bulk.csv' AS row\n MATCH (m:Movie{movie_id: toInteger(row.movie_id)})\n MATCH (c:Language{iso_lang_code: row.lang_iso})\n CREATE (m)-[r:SPOKEN_LANGUAGE]->(c)\n \"\"\"\n\n\ndef movie_production_company(df_data):\n production_companies = df_data['production_companies']\n production_companies = [[dict_genre['id'] for dict_genre in literal_eval(company_per_movie) if\n literal_eval(company_per_movie) is not []] for company_per_movie in production_companies]\n movies_ids = df_data['id']\n assert len(movies_ids) == len(production_companies)\n\n movies_company_dict = dict(zip(movies_ids, production_companies))\n movies_pairs = [(key, value) for key, values in movies_company_dict.items() for value in values]\n\n pd.DataFrame(data=movies_pairs, columns=['movie_id', 'company_id']).to_csv(\"movie_prod_company_bulk.csv\")\n \"\"\"\n LOAD CSV WITH HEADERS FROM 'file:///movie_prod_company_bulk.csv' AS row\n MATCH (m:Movie{movie_id: toInteger(row.movie_id)})\n MATCH (c:Company{company_id: row.company_id})\n CREATE (m)-[r:PRODUCTION_BY]->(c)\n \"\"\"\n\n\ndef movie_production_country(df_data):\n production_countries = df_data['production_countries']\n production_countries = [[dict_country['iso_3166_1'] for dict_country in literal_eval(country_per_movie) if\n literal_eval(country_per_movie) is not []] for country_per_movie in production_countries]\n movies_ids = df_data['id']\n assert len(movies_ids) == len(production_countries)\n\n movies_country_dict = dict(zip(movies_ids, production_countries))\n movies_pairs_country = [(key, value) for key, values in movies_country_dict.items() for value in values]\n\n pd.DataFrame(data=movies_pairs_country, columns=['movie_id', 'country_iso']).to_csv(\"movie_prod_country_bulk.csv\")\n\n \"\"\"\n LOAD CSV WITH HEADERS FROM 'file:///movie_prod_country_bulk.csv' AS row\n MATCH (m:Movie{movie_id: toInteger(row.movie_id)})\n MATCH (c:Country{iso_country_code: row.country_iso})\n CREATE (m)-[r:PRODUCTION_IN]->(c)\n \"\"\"\n\n\ndef movie_keywords(df_data):\n keywords = df_data['keywords']\n keywords = [[dict_keyword['id'] for dict_keyword in literal_eval(keywords_per_movie) if\n literal_eval(keywords_per_movie) is not []] for keywords_per_movie in keywords]\n movies_ids = df_data['id']\n assert len(movies_ids) == len(keywords)\n\n movies_keywords_dict = dict(zip(movies_ids, keywords))\n movies_pairs_keywords = [(key, value) for key, values in movies_keywords_dict.items() for value in values]\n\n pd.DataFrame(data=movies_pairs_keywords, columns=['movie_id', 'keyword_id']).to_csv(\"movie_keywords_bulk.csv\")\n\n \"\"\"\n LOAD CSV WITH HEADERS FROM 'file:///movie_keywords_bulk.csv' AS row\n MATCH (m:Movie{movie_id: toInteger(row.movie_id)})\n MATCH (c:Keyword{keyword_id: toInteger(row.keyword_id)})\n CREATE (m)-[r:HAS_KEYWORD]->(c)\n \"\"\"\n\n\ndef users_ratings(df_data):\n # data is already formated for reading in DB in the original file\n \"\"\"\n LOAD CSV WITH HEADERS FROM 'file:///ratings_small.csv' AS row\n MATCH (m:Movie{movie_id: toInteger(row.movieId)})\n MERGE (u:User{user_id: toInteger(row.userId)})\n CREATE (u)-[r:RATED]->(m)\n SET r.rating = toFloat(row.rating),\n r.timestamp = toInteger(row.timestamp)\n \"\"\"\n\n\ndef cast(df_data):\n cast_rows = df_data['cast']\n movies_ids = df_data['id']\n\n cast_rows = [\n [{'personId': dict_cast['id'], 'personName': dict_cast['name'], 'personGender': dict_cast['gender'],\n 'castId': dict_cast['cast_id'], 'characterName': dict_cast['character']} for\n dict_cast in literal_eval(cast_per_movie) if\n literal_eval(cast_per_movie) is not []] for cast_per_movie in cast_rows]\n\n assert len(cast_rows) == len(movies_ids)\n\n cast_dict = dict(zip(movies_ids, cast_rows))\n cast_pairs_movies = [(key, value) for key, values in cast_dict.items() for value in values]\n\n movies_ids, ids, names, genders, castIds, charNames = [], [], [], [], [], []\n for (key, value) in cast_pairs_movies:\n movies_ids.append(key)\n ids.append(value['personId'])\n names.append(value['personName'])\n genders.append(value['personGender'])\n castIds.append(value['castId'])\n charNames.append(value['characterName'])\n\n df = pd.DataFrame()\n df['movieId'] = movies_ids\n df['id'] = ids\n df['name'] = names\n df['gender'] = genders\n df['castId'] = castIds\n df['charName'] = charNames\n df.to_csv(\"cast_bulk.csv\")\n\n \"\"\"\n LOAD CSV WITH HEADERS FROM 'file:///cast_bulk.csv' AS row\n MATCH (m:Movie{movie_id: toInteger(row.movieId)})\n MERGE (p:Person{person_id: toInteger(row.id)})\n CREATE (p)-[r:CAST_IN]->(m)\n SET r.cast_id = toInteger(row.castId),\n r.character_name = row.charName,\n p.name = row.name,\n p.gender = toInteger(row.gender)\n \"\"\"\n\n\ndef crew(df_data):\n crew_rows = df_data['crew']\n movies_ids = df_data['id']\n\n crew_rows = [\n [{'personId': dict_crew['id'], 'personName': dict_crew['name'], 'personGender': dict_crew['gender'],\n 'departmentName': dict_crew['department'], 'jobName': dict_crew['job']} for\n dict_crew in literal_eval(crew_per_movie) if\n literal_eval(crew_per_movie) is not []] for crew_per_movie in crew_rows]\n\n assert len(crew_rows) == len(movies_ids)\n\n crew_dict = dict(zip(movies_ids, crew_rows))\n crew_pairs_movies = [(key, value) for key, values in crew_dict.items() for value in values]\n\n movies_ids, ids, names, genders, departments, jobs = [], [], [], [], [], []\n for (key, value) in crew_pairs_movies:\n movies_ids.append(key)\n ids.append(value['personId'])\n names.append(value['personName'])\n genders.append(value['personGender'])\n departments.append(value['departmentName'])\n jobs.append(value['jobName'])\n\n # data columns\n df = pd.DataFrame()\n df['movieId'] = movies_ids\n df['id'] = ids\n df['name'] = names\n df['gender'] = genders\n df['departmentName'] = departments\n df['jobName'] = jobs\n df.to_csv(\"crew_bulk.csv\")\n\n \"\"\"\n LOAD CSV WITH HEADERS FROM 'file:///crew_bulk.csv' AS row\n MATCH (m:Movie{movie_id: toInteger(row.movieId)})\n MATCH (d:Department{name:row.departmentName})\n MERGE (p:Person{person_id: toInteger(row.id)})\n CREATE (p)-[r:CREW_IN]->(m)\n CREATE (p)-[r2:WORKS_IN]-(d)\n SET r2.job_name = row.jobName,\n p.name = row.name,\n p.gender = toInteger(row.gender)\n \"\"\"\n","repo_name":"Tijana37/UnstructuredDB","sub_path":"bulk_loading.py","file_name":"bulk_loading.py","file_ext":"py","file_size_in_byte":13537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19078425350","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 26 19:38:29 2018\n\n@author: Daniel\n\"\"\"\n\nimport argparse\nimport os\nfrom minder_config import minder_cfg \nfrom minder_database import minder_db\nfrom minder_htmlreport import minder_report\nimport time\nimport hashlib\nimport uuid\n\n\nclass get_lastreview:\n \n def __init__(self, minder_dict, topdir, cfg_exclude, cfg_type):\n \n \n print(topdir)\n print(cfg_exclude)\n print(cfg_type)\n print(minder_dict)\n filecnt = 0\n for root, dirs, files in os.walk(topdir):\n for name in files:\n find = False\n for i in range(0,len(cfg_exclude)):\n\n if os.path.join(root, name).startswith(os.path.dirname(cfg_exclude[i])):\n find = True\n if find is True:\n continue\n for j in range(0,len(cfg_type)): \n if name.lower().endswith(cfg_type[j]):\n try:\n flog = open(os.path.join(root, name), \"rb\")\n flog.close() \n flog = open(os.path.join(root, name), 'r+') \n flog.close() \n filecnt+=1\n except:\n print(\"ERROR: No Access to: \" + os.path.join(root, name))\n raise Exception\n print(filecnt)\n ","repo_name":"hodea/hodea-review-minder","sub_path":"minder_lastreview.py","file_name":"minder_lastreview.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"6287852033","text":"import requests\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import Select\nimport time\nimport json\nfrom selenium.webdriver.common.by import By\nfrom flask import Flask,request\nfrom flask import make_response\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nimport pprint\n\napp = Flask(__name__)\nurl = \"https://www.cars.com/for-sale/searchresults.action\"\n\n#Tek methodda ister parametre göndersin ister göndermesin multi yada filtresiz olarak tüm araçlar listelenebiliyor.\n@app.route('/cars/list', methods=['get'])\ndef getFiftyCars():\n with requests.get(url) as res:\n if res.status_code == 200:\n Cars= []\n global title,brand,color,trans,img,year,price\n browser=webdriver.Firefox()\n browser.get(url)\n trans=request.args.get('trans') # requestte karşılık gelen parametre var ise alıyor\n brand=request.args.get('brand')\n extcolor=request.args.get('extcolor')\n year=request.args.get('year')\n if trans!=None:\n buttonTrans = browser.find_element(By.ID, \"trigger_transmissions\")\n time.sleep(2)\n buttonTrans.click()\n time.sleep(2)\n chcTran=browser.find_element(by=By.ID,value=\"panel_transmissions\")\n chcTran=chcTran.find_elements(by=By.CLASS_NAME,value=\"sds-checkbox\")\n \n for x in range(len(chcTran)):\n value=chcTran[x].find_element(by=By.CLASS_NAME,value=\"sds-input\")\n value=value.get_attribute('value')\n if value==trans.lower():\n label=chcTran[x].find_element(by=By.CLASS_NAME,value=\"sds-label\")\n time.sleep(2)\n label.click()\n time.sleep(2)\n\n if brand!=None:\n drp=browser.find_element(by=By.ID,value=\"make_select\")\n drp=Select(drp)\n drp.select_by_value(brand.lower())\n\n if extcolor!=None:\n buttonColors = browser.find_element(By.ID, \"trigger_exterior_colors\")\n time.sleep(2)\n buttonColors.click()\n chcColor=browser.find_element(by=By.XPATH,value=\"//*[@id=\\\"panel_exterior_colors\\\"]\")\n chcColor=chcColor.find_elements(by=By.CLASS_NAME,value=\"sds-checkbox\")\n for x in range(len(chcColor)):\n value=chcColor[x].find_element(by=By.CLASS_NAME,value=\"sds-input\")\n value=value.get_attribute('value')\n if value==extcolor.lower():\n label=chcColor[x].find_element(by=By.CLASS_NAME,value=\"sds-label\")\n time.sleep(2)\n label.click()\n time.sleep(2)\n\n if year!=None:\n yearSelect=Select(browser.find_element(by=By.ID,value=\"year_year_min_select\"))\n time.sleep(1) \n yearSelect.select_by_value(year.lower())\n time.sleep(2) #time.sleep leri kaldırınca patlıyor kritik bölgeye al yada farklı bir yol bul\n if brand==None and trans==None and extcolor==None and year==None:\n drp=Select(browser.find_element(by=By.ID,value=\"pagination-dropdown\"))\n drp.select_by_value(\"50\") #100 araçseçilince next butonu gelmiyor farklı bir yoldan çöz\n time.sleep(3)\n carCount=50\n else:\n carCount=50\n if int(carCount)>49:\n carCount=\"49\" \n\n for x in range(int(carCount)):\n car = dict()\n if x==0:\n browser.find_element(by=By.CLASS_NAME,value=\"vehicle-card-link\").click()\n tempTitle=browser.find_element(by=By.XPATH,value=\"/html/body/section/div[5]/section/header/div[1]/h1\").text\n title = tempTitle\n\n tempPrice=browser.find_element(by=By.XPATH,value=\"/html/body/section/div[5]/section/header/div[2]/span\").text\n price = tempPrice\n\n titles=tempTitle.split(' ')\n brand = titles[1]\n\n year=titles[0]\n try:\n imgDiv=browser.find_element(by=By.ID,value=\"swipe-index-0\") #çoğu araçta olmasına rağmen 360 derece foto eklenen araçlarda yok bu yüzden try kullanıldı\n img=imgDiv.get_attribute('src')\n except :\n imgDiv=browser.find_element(by=By.CLASS_NAME,value=\"row-pic\")\n img=imgDiv.get_attribute('src')\n carColor=browser.find_element(by=By.XPATH,value=\"/html/body/section/div[5]/div[2]/section[1]/dl/dd[1]\").text\n color=carColor\n carTrans=browser.find_element(by=By.XPATH,value=\"/html/body/section/div[5]/div[2]/section[1]/dl/dd[6]\").text\n trans=carTrans\n #car=Car(title, price,brand,color,trans,year,img)\n Cars.append([title, price,brand,color,trans,year,img])\n else:\n nextCLick=browser.find_element(by=By.CLASS_NAME,value=\"srp-carousel-next-link\")\n time.sleep(1)\n try:\n nextCLick.click()\n except :\n return json.dumps(Cars)\n tempTitle=browser.find_element(by=By.XPATH,value=\"/html/body/section/div[5]/section/header/div[1]/h1\").text\n title = tempTitle\n\n tempPrice=browser.find_element(by=By.XPATH,value=\"/html/body/section/div[5]/section/header/div[2]/span\").text\n price = tempPrice\n\n titles=tempTitle.split(' ')\n brand = titles[1]\n\n year=titles[0]\n try:\n imgDiv=browser.find_element(by=By.ID,value=\"swipe-index-0\")\n img=imgDiv.get_attribute('src')\n except :\n imgDiv=browser.find_element(by=By.CLASS_NAME,value=\"row-pic\")\n img=imgDiv.get_attribute('src')\n\n basics=browser.find_element(by=By.CLASS_NAME,value=\"fancy-description-list\")\n carAttributes=basics.text.split('\\n')\n color=carAttributes[1]\n trans=carAttributes[11]\n #car=Car(title, price,brand,color,trans,year,img)\n Cars.append([title, price,brand,color,trans,year,img])\n\n return json.dumps(Cars)\n\n@app.route('/cars/filters', methods=['get'])\ndef getCarFilters():\n with requests.get(url) as res:\n if res.status_code == 200:\n Filters= []\n browser=webdriver.Firefox()\n browser.get(url)\n brand=browser.find_element(by=By.ID,value=\"make_select\")\n options = [x for x in brand.find_elements(by=By.TAG_NAME,value=\"option\")]\n for element in options:\n Filters.append(element.get_attribute(\"value\"))\n Filters.append(\"nextfilter\")\n color=browser.find_element(by=By.ID,value=\"panel_exterior_colors\")\n options = [x for x in color.find_elements(by=By.TAG_NAME,value=\"input\")]\n for element in options:\n Filters.append(element.get_attribute(\"value\"))\n Filters.append(\"nextfilter\")\n trans=browser.find_element(by=By.ID,value=\"panel_transmissions\")\n options = [x for x in trans.find_elements(by=By.TAG_NAME,value=\"input\")]\n for element in options:\n Filters.append(element.get_attribute(\"value\"))\n Filters.append(\"nextfilter\")\n year=browser.find_element(by=By.ID,value=\"year_year_min_select\")\n options = [x for x in year.find_elements(by=By.TAG_NAME,value=\"option\")]\n for element in options:\n Filters.append(element.get_attribute(\"value\"))\n browser.close()\n return json.dumps(Filters)\n\nif __name__ == '__main__':\n app.run(debug=True)","repo_name":"ABarcin/PythonCarProject","sub_path":"PythonCarProject/module2.py","file_name":"module2.py","file_ext":"py","file_size_in_byte":8056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8206704275","text":"from flask_restx import Api, Resource, reqparse, Namespace\nfrom flask import request\nimport werkzeug\nfrom os import path, remove\n\nfrom classes import RecordedVideo\nfrom classes import apikey\nfrom classes import topics\nfrom classes import views\nfrom classes.shared import db\n\nfrom functions import cachedDbCalls\nfrom functions.scheduled_tasks import video_tasks\n\napi = Namespace(\"video\", description=\"Video Related Queries and Functions\")\n\nvideoParserPut = reqparse.RequestParser()\nvideoParserPut.add_argument(\"videoName\", type=str)\nvideoParserPut.add_argument(\"description\", type=str)\nvideoParserPut.add_argument(\"topicID\", type=int)\n\nvideoSearchPost = reqparse.RequestParser()\nvideoSearchPost.add_argument(\"term\", type=str, required=True)\n\n\n@api.route(\"/\")\nclass api_1_ListVideos(Resource):\n def get(self):\n \"\"\"\n Returns a List of All Recorded Videos\n \"\"\"\n fullVideoQuery = cachedDbCalls.getAllVideo()\n videoArray = []\n for video in fullVideoQuery:\n videoArray.append(cachedDbCalls.getVideoDict(video.id))\n return {\n \"results\": videoArray\n }\n\n\n@api.route(\"/\")\n@api.doc(params={\"videoID\": \"ID Number for the Video\"})\nclass api_1_ListVideo(Resource):\n def get(self, videoID):\n \"\"\"\n Returns Info on a Single Recorded Video\n \"\"\"\n results = []\n results.append(cachedDbCalls.getVideoDict(videoID))\n\n return {\n \"results\": results\n }\n\n @api.expect(videoParserPut)\n @api.doc(security=\"apikey\")\n @api.doc(responses={200: \"Success\", 400: \"Request Error\"})\n def put(self, videoID):\n \"\"\"\n Change a Video's Name, Description, or Topic\n \"\"\"\n if \"X-API-KEY\" in request.headers:\n requestAPIKey = apikey.apikey.query.filter_by(\n key=request.headers[\"X-API-KEY\"]\n ).first()\n if requestAPIKey is not None:\n if requestAPIKey.isValid():\n videoQuery = RecordedVideo.RecordedVideo.query.filter_by(\n id=int(videoID)\n ).first()\n if videoQuery is not None:\n if videoQuery.owningUser == requestAPIKey.userID:\n args = videoParserPut.parse_args()\n if \"videoName\" in args:\n if args[\"videoName\"] is not None:\n videoQuery.channelName = args[\"videoName\"]\n if \"topicID\" in args:\n if args[\"topicID\"] is not None:\n possibleTopics = topics.topics.query.filter_by(\n id=int(args[\"topicID\"])\n ).first()\n if possibleTopics is not None:\n videoQuery.topic = int(args[\"topicID\"])\n if \"description\" in args:\n if args[\"description\"] is not None:\n videoQuery.description = args[\"description\"]\n db.session.commit()\n return {\"results\": {\"message\": \"Video Updated\"}}, 200\n return {\"results\": {\"message\": \"Request Error\"}}, 400\n\n @api.doc(security=\"apikey\")\n @api.doc(responses={200: \"Success\", 400: \"Request Error\"})\n def delete(self, videoID):\n \"\"\"\n Deletes a Video\n \"\"\"\n if \"X-API-KEY\" in request.headers:\n requestAPIKey = apikey.apikey.query.filter_by(\n key=request.headers[\"X-API-KEY\"]\n ).first()\n if requestAPIKey is not None:\n if requestAPIKey.isValid():\n videoQuery = RecordedVideo.RecordedVideo.query.filter_by(\n id=videoID\n ).first()\n if videoQuery is not None:\n if videoQuery.owningUser == requestAPIKey.userID:\n results = video_tasks.delete_video.delay(videoQuery.id)\n return {\n \"results\": {\"message\": \"Video Queued for Deletion\"}\n }, 200\n return {\"results\": {\"message\": \"Request Error\"}}, 400\n\n\n@api.route(\"/search\")\nclass api_1_SearchVideos(Resource):\n # Video - Search Recorded Video\n @api.expect(videoSearchPost)\n @api.doc(responses={200: \"Success\", 400: \"Request Error\"})\n def post(self):\n \"\"\"\n Searches Video Names and Metadata and returns Name and Link\n \"\"\"\n args = videoSearchPost.parse_args()\n returnArray = []\n if \"term\" in args:\n finalArray = []\n returnArray = cachedDbCalls.searchVideos(args[\"term\"])\n for vid in returnArray:\n newVidObj = [vid.id, vid.channelName, vid.uuid, vid.thumbnailLocation]\n finalArray.append(newVidObj)\n return {\"results\": finalArray}\n else:\n return {\"results\": {\"message\": \"Request Error\"}}, 400\n","repo_name":"Open-Streaming-Platform/open-streaming-platform","sub_path":"blueprints/apis/video_ns.py","file_name":"video_ns.py","file_ext":"py","file_size_in_byte":5141,"program_lang":"python","lang":"en","doc_type":"code","stars":91,"dataset":"github-code","pt":"48"} +{"seq_id":"36990936292","text":"import json\nimport requests\nimport datetime\n\n\n\n# print(x)\n\nheaders = {\"Authorization\": \"Bearer ya29.a0ARrdaM_Arm1uw0fC9uzUe6CZOBtsHvcloBZiRb9oMDPsbSM31ymcEp77U6eF4QtAO3IrqOb_6b9EdV62KzhMgYBcwZH3UHRo0Hmg46A0lQejFpqS7isnQgXxlNCNbSpzGLY6BRxdlUJifwtVDUkXoVI2S06e\"}\n# x = datetime.datetime.now()\npara = {\n \"name\": \"duq940.sql\",\n # \"x\" : datetime.datetime.now()\n}\nfiles = {\n 'data': ('metadata', json.dumps(para), 'application/json; charset=UTF-8'),\n 'file': open(\"./duq.sql\", \"rb\"),\n \n}\nr = requests.post(\n \"https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart\",\n headers=headers,\n files=files \n)\nprint(r.text)\n\n# import datetime\n\n# x = datetime.datetime.now()\n\n# print(x)\n","repo_name":"MAnojSH5799/SQL-Upload-Files","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72265044305","text":"from kivy.app import App\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.properties import *\nfrom kivy.lang.builder import Builder\nimport requests\nfrom converter import converter\nfrom countrysearch import info\n\ncurrency=list(info)\nMainStr=\"\"\"\n\n:\n\torientation:'vertical'\n\tLabel:\n\t\ttext:'ONLINE CURRENCY CONVERTER'\n\t\tsize_hint_y:2\n\tLabel:\n\t\tid:amount\n\t\ttext:'enter amount:'\n\tBoxLayout:\n\t\tLabel:\n\t\t\tid : rate\n\t\t\ttext:'Conversion Rate:'\n\t\t\ttext_size:self.size\n\t\t\thalign:'left'\n\t\t\tvalign:'bottom'\n\t\tLabel:\n\t\t\tid :ans\n\t\t\ttext:'Amount:'\n\t\t\ttext_size:self.size\n\t\t\thalign:'left'\n\t\t\tvalign:'bottom'\n\n:\n\torientation:'vertical'\n\tBoxLayout:\n\t\tTextInput:\n\t\t\tid : bar\n\t\t\ttext:'Search Currency'\n\tBoxLayout:\n\t\tButton:\n\t\t\tid : pFrom\n\t\t\ttext:'Put In From:'\n\t\t\tdisabled:True\n\t\t\ton_press:root.parent.update('From')\n\t\tButton:\n\t\t\tid : pTo\n\t\t\ttext:'Put In To:'\n\t\t\tdisabled:True\n\t\t\ton_press:root.parent.update('To')\n\t\tButton:\n\t\t\tid :Search\n\t\t\ttext:'Search'\n\t\t\ton_press:root.search()\n\n:\n\tButton:\n\t\tsize_hint_x:1\n\t\ttext:'previous'\n\t\ton_press:root.ChangeCurrency('prev')\n\tBoxLayout:\n\t\torientation:'vertical'\n\t\tsize_hint_x:3\n\t\tLabel:\n\t\t\ttext_size:self.size\n\t\t\ttext:'From:'\n\t\t\thalign:'left'\n\t\t\tvalign:'top'\n\t\tLabel:\n\t\t\tid:code1\n\t\t\ttext:'INR'\n\t\tLabel:\n\t\t\tid:C_name1\n\t\t\ttext:'Indian Ruppe'\n\t\tLabel:\n\t\t\tid:Cntry1\n\t\t\ttext:'INDIA'\n\tButton:\n\t\tsize_hint_x:1\n\t\ttext:'next'\n\t\ton_press:root.ChangeCurrency('next')\n:\n\tButton:\n\t\tsize_hint_x:1\n\t\ttext:'previous'\n\t\ton_press:root.ChangeCurrency('prev')\n\tBoxLayout:\n\t\torientation:'vertical'\n\t\tsize_hint_x:3\n\t\tLabel:\n\t\t\ttext_size:self.size\n\t\t\ttext:'To:'\n\t\t\thalign:'left'\n\t\t\tvalign:'top'\n\t\tLabel:\n\t\t\tid:code2\n\t\t\ttext:'USD'\n\t\tLabel:\n\t\t\tid:C_name2\n\t\t\ttext:'US Dollar'\n\t\tLabel:\n\t\t\tid:Cntry2\n\t\t\ttext:'USA'\n\tButton:\n\t\tsize_hint_x:1\n\t\ttext:'next'\n\t\ton_press:root.ChangeCurrency('next')\n\t\t\n:\n\tBoxLayout:\n\t\torientation:'vertical'\n\t\tBoxLayout:\n\t\t\tButton:\n\t\t\t\ttext:'1'\n\t\t\t\ton_press:root.parent.take_input('1')\n\t\t\tButton:\n\t\t\t\ttext:'2'\n\t\t\t\ton_press:root.parent.take_input('2')\n\t\t\tButton:\n\t\t\t\ttext:'3'\n\t\t\t\ton_press:root.parent.take_input('3')\n\t\tBoxLayout:\n\t\t\tButton:\n\t\t\t\ttext:'4'\n\t\t\t\ton_press:root.parent.take_input('4')\n\t\t\tButton:\n\t\t\t\ttext:'5'\n\t\t\t\ton_press:root.parent.take_input('5')\n\t\t\tButton:\n\t\t\t\ttext:'6'\n\t\t\t\ton_press:root.parent.take_input('6')\n\t\tBoxLayout:\n\t\t\tButton:\n\t\t\t\ttext:'7'\n\t\t\t\ton_press:root.parent.take_input('7')\n\t\t\tButton:\n\t\t\t\ttext:'8'\n\t\t\t\ton_press:root.parent.take_input('8')\n\t\t\tButton:\n\t\t\t\ttext:'9'\n\t\t\t\ton_press:root.parent.take_input('9')\n\t\tBoxLayout:\n\t\t\tButton:\n\t\t\t\tid:decimal\n\t\t\t\tsize_hint_x:1\n\t\t\t\ttext:'.'\n\t\t\t\ton_press:root.parent.take_input('.')\n\t\t\tButton:\n\t\t\t\tsize_hint_x:1\n\t\t\t\ttext:'0'\n\t\t\t\ton_press:root.parent.take_input('0')\n\t\t\tButton:\n\t\t\t\tsize_hint_x:1\n\t\t\t\ttext:'clear'\n\t\t\t\ton_press:root.parent.clear()\n\t\tBoxLayout:\n\t\t\tButton:\n\t\t\t\ttext:'convert'\n\t\t\t\ton_press:root.parent.convert()\n\t\t\n\n:\n\torientation:'vertical'\n\tDisplayData:\n\t\tid:display\n\t\tsize_hint_y:3.5\n\tCountrySelectorFrom:\n\t\tid:From\n\t\tsize_hint_y:1.5\n\tButton:\n\t\tid:switch\n\t\tsize_hint_y:0.5\n\t\ttext:'Switch'\n\t\ton_press:root.switch()\n\tCountrySelectorTo:\n\t\tid :To\n\t\tsize_hint_y:1.5\n\tSearchBar:\n\t\tid: Sbar\n\t\tsize_hint_y:2\n\tNumPad:\n\t\tid : n_pad\n\t\tsize_hint_y:6\n\t\t\n\n\"\"\"\n\n\nBuilder.load_string(MainStr)\n\n\n\n\n\nclass MainLayout(BoxLayout):\n\tdef __init__(self,**kwargs):\n\t\tsuper(MainLayout,self).__init__(**kwargs)\n\tdef getCodes(self):\n\t\tcode1=self.ids.From.getCode()\n\t\tcode2=self.ids.To.getCode()\n\t\treturn code1,code2\n\tdef take_input(self,num):\n\t\tif num=='.':\n\t\t\tself.ids.n_pad.switch_decimal(True)\n\t\tself.ids.display.registor(num)\n\tdef clear(self):\n\t\tself.ids.display.registor('clr')\n\t\tself.ids.n_pad.switch_decimal(False)\n\tdef convert(self):\n\t\tcode1,code2=self.getCodes()\n\t\trate=converter(code1,code2)\n\t\tself.ids.display.Amount(rate)\n\tdef switch(self):\n\t\tfirst=self.ids.From.From\n\t\tsecond=self.ids.To.To\n\t\tself.ids.From.update(second)\n\t\tself.ids.To.update(first)\n\tdef update(self,str_c):\n\t\tnum=self.ids.Sbar.hold\n\t\tif str_c=='From':\n\t\t\tself.ids.From.update(num)\n\t\telse:\n\t\t\tself.ids.To.update(num)\n\nclass DisplayData(BoxLayout):\n\tdef registor(self,num):\n\t\tif num=='clr':\n\t\t\tself.ids.amount.text='enter amaount:'\n\t\t\tself.ids.ans.text='Amount:'\n\t\t\tself.ids.rate.text='Conversion Rate:'\n\t\telse:\n\t\t self.ids.amount.text+=num\n\tdef Amount(self,rate):\n\t\tself.ids.rate.text='Coversion Rate:'+str(rate)\n\t\tamount=self.ids.amount.text.split(':')\n\t\tif amount[1]!='':\n\t\t self.ids.ans.text='Amount:'+str(float(amount[1])*rate)\n\t\t \n\t\t\n\t\t\n\t\t\n\t\t\n\nclass CountrySelectorFrom(BoxLayout):\n\tdef __init__(self,**kwargs):\n\t\tsuper(CountrySelectorFrom,self).__init__(**kwargs)\n\t\tself.From=111\n\t\tself.CurrencyInfo=currency \n\tdef ChangeCurrency(self,N_or_P):\n\t\tif N_or_P=='prev':\n\t\t\tif self.From>0:\n\t\t\t\tself.From-=1\n\t\t\telse:\n\t\t\t\tself.From=len(self.CurrencyInfo)-11\n\t\telse:\n\t\t\tif self.From0:\n\t\t\t\tself.To-=1\n\t\t\telse:\n\t\t\t\tself.To=len(self.CurrencyInfo)-11\n\t\telse:\n\t\t\tif self.To highest_return:\n highest_return = avg_return\n saver = PolicySaver(agent.policy, batch_size = None)\n saver.save(model_path)\n if average_episode_length < lowest_episode_length:\n lowest_episode_length = average_episode_length\n print('step = {0}: Average Return = {1:.2f}, Average episode length = {2}'.format(step, avg_return, average_episode_length))\n returns.append(avg_return)\nbest_policy = tf.compat.v2.saved_model.load(model_path)\n\nprint('Average across all returns = {0:.2f}'.format(total_returns / total_evals))\nprint('Highest single run = {0:.2f}'.format(highest_return))\nprint('Average episode length = {0:.2f}'.format(total_episode_lengths / total_evals))\nprint('Lowest episode length = {0:.2f}'.format(lowest_episode_length))\nsecond_test_return, second_average_length = compute_avg_return(eval_env, best_policy, num_eval_episodes)\nprint('Best policy second test: R - {0:.2f}, EL - {1:.2f}'.format(second_test_return, second_average_length))\n\nsteps = range(0, num_iterations + 1, eval_interval)\nplt.plot(steps, returns)\nplt.ylabel('Average Return')\nplt.xlabel('Step')\nplt.ylim(-50, 1000)\n\nseconds = int(np.round(time.time() - start_time))\nminutes = int(np.floor(seconds / 60))\nseconds %= 60\nhours = int(np.floor(minutes / 60))\nminutes %= 60\n\nprint(\"Runtime: {0} hour(s), {1} minute(s), and {2} second(s)\".format(hours, minutes, seconds))\n\nplt.show()\n\nprint(\"Ready to watch?\")\nanswer = input()\nif answer != \"no\":\n final_env = tf_py_environment.TFPyEnvironment(environment(True))\n for i in range(final_evals):\n\n time_step = final_env.reset()\n\n while not time_step.is_last():\n\n action_step = best_policy.action(time_step)\n time_step = final_env.step(action_step.action)\n\n cv2.destroyAllWindows()\n given_name = input(\"What would you like to name this policy?\")\n if (given_name != \"no\"):\n tf.saved_model.save(best_policy, model_path + \"/.Old Policies/\" + given_name)","repo_name":"gabeht/SnakeAI","sub_path":"SnakeAI.py","file_name":"SnakeAI.py","file_ext":"py","file_size_in_byte":7922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25629048874","text":"import sys\nimport re\nimport argparse\n\n# patterns = ['(Client_(\\d+))_(read|decrypt)_wall_sum','(Client_(\\d+))_(read|decrypt)_user_sum']\npattern = '(Client_(\\d+))_(read|decrypt)_wall_sum'\nmatch_idxs = dict()\nnames = dict()\nout_lines = dict()\n\ndef readFile(fname):\n fd = open(fname, 'r')\n\n label_line = fd.readline()\n labels = label_line.split(',')\n for label in labels:\n match = re.search(pattern, label)\n if match is not None:\n cliNum = int(match.group(2))\n names[cliNum] = match.group(1)\n colIdx = labels.index(label)\n if cliNum not in match_idxs:\n match_idxs[cliNum] = [-1, -1]\n val = match_idxs[cliNum]\n if match.group(3) == \"read\":\n val[0] = colIdx\n elif match.group(3) == \"decrypt\":\n val[1] = colIdx\n match_idxs[cliNum] = val\n\n print(\"label, read_wall_sum, decrypt_wall_sum, total\")\n round_cnt = 1\n\n for line in fd:\n tokens = line.split(',')\n for k,v in sorted(match_idxs.items()):\n v1 = tokens[v[0]]\n v2 = tokens[v[1]]\n tot = float(v1) + float(v2)\n tot_str = \"%.6f\" % tot\n label = names[k] + \"_\" + str(round_cnt)\n print(\"%s, %s, %s, %s\" % (label, v1, v2, tot_str))\n round_cnt += 1\n\n # for line in fd:\n # tokens = line.split(',')\n # for k,v in sorted(match_idxs.items()):\n # v1 = tokens[v[0]]\n # v2 = tokens[v[1]]\n # tot = float(v1) + float(v2)\n # tot_str = \"%.6f\" % tot\n # if k not in out_lines:\n # out_lines[k] = [v1, v2, tot_str]\n # else:\n # val = out_lines[k]\n # val.extend([v1, v2, tot_str])\n # out_lines[k] = val\n\n # for k,v in sorted(out_lines.items()):\n # tmp = ','.join(v)\n # print(\"%s,%s\" % (names[k], tmp))\n \n\ndef main():\n parser = argparse.ArgumentParser(description='Parsing csv files')\n parser.add_argument('fname', type=str)\n # parser.add_argument('--user', action='store_true') \n args = parser.parse_args()\n # readFile(args.fname, args.user)\n readFile(args.fname)\n\nif __name__ == '__main__':\n main()\n","repo_name":"ceyhunalp/calypso_experiments","sub_path":"plot/multicli.py","file_name":"multicli.py","file_ext":"py","file_size_in_byte":2259,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29849970836","text":"import sys\nimport os\nfrom PIL import Image\nimport random\n\ndef Main():\n args = sys.argv\n cwd = os.getcwd()\n\n out_path = os.path.join(cwd,\"splited\")\n\n img = Image.open(os.path.join(cwd,args[1]))\n dn = int(img.size[0] / 10)\n\n os.makedirs(out_path,exist_ok=True)\n\n for num,slice_img in enumerate(SplitImage(img,dn),1):\n if num < 5 or num > dn-4:\n continue\n while True:\n path = out_path + \"/\" + str(random.randint(0,100)) +\".png\"\n if not os.path.isfile(path):\n slice_img.save(path,\"PNG\")\n break\n\n print(\"finish\")\n\n\ndef SplitImage(img,dn):\n width,height = img.size\n split_width = width / dn\n for w1 in range(dn):\n w2 = w1 * split_width\n yield img.crop((w2,40,split_width+w2,height-40))\n\nif __name__ == \"__main__\":\n Main()\n","repo_name":"yugu0202/QR-CTF","sub_path":"spliter.py","file_name":"spliter.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"21434593743","text":"# %%\n# ---\n# jupyter:\n# jupytext:\n# cell_metadata_filter: -all\n# custom_cell_magics: kql\n# text_representation:\n# extension: .py\n# format_name: percent\n# format_version: '1.3'\n# jupytext_version: 1.11.2\n# kernelspec:\n# display_name: .venv\n# language: python\n# name: python3\n# ---\n\n# %%\n\"\"\"simulation for the Hyperdrive market\"\"\"\nfrom __future__ import annotations\n\nimport logging\n\nimport elfpy.markets.hyperdrive.hyperdrive_actions as hyperdrive_actions\nimport elfpy.utils.outputs as output_utils\nimport elfpy.utils.post_processing as post_processing\nimport matplotlib.pyplot as plt\n\n# %%\nimport numpy as np\nimport pandas as pd\nfrom elfpy.agents.agent import Agent\nfrom elfpy.agents.policies import RandomAgent\nfrom elfpy.simulators.config import Config\nfrom elfpy.utils import sim_utils\nfrom elfpy.utils.outputs import get_gridspec_subplots\nfrom elfpy.wallet.wallet import Wallet\nfrom fixedpointmath import FixedPoint\nfrom matplotlib.axes import Axes\nfrom numpy.random._generator import Generator as NumpyGenerator\n\n# pylint: disable=line-too-long\n# pylint: disable=too-many-lines\n# pylint: disable=invalid-name\n# pyright: reportOptionalMemberAccess=false, reportGeneralTypeIssues=false\n\n# %% [markdown]\n# ## Hyperdrive Simulation\n# We use the following setup:\n# - 90 day term\n# - 200 agents, 100 randomly open and close longs, the other 100 randomly open and close shorts\n# - agents are initialized with 1 million of capital, trading 10% of their budget per trade\n# - they trade at random intervals calibrated to be roughly twice per term (1 open 1 close)\n# - there is one Liquidity Provider which deposits 500 million of liquidity\n#\n# For details on the simulation framework, please see our simulation documentation\n\n# %% [markdown]\n# ### Install repo requirements & import packages\n\n\n# %% [markdown]\n# ### Setup experiment parameters\n\n# %%\nconfig = Config()\n\nconfig.title = \"Hyperdrive demo\"\nconfig.pricing_model_name = \"Hyperdrive\" # can be yieldspace or hyperdrive\n\nconfig.num_trading_days = 90 # Number of simulated trading days\nconfig.num_blocks_per_day = 10 # Blocks in a given day (7200 means ~12 sec per block)\nconfig.num_position_days = 45\nconfig.curve_fee_multiple = 0.10 # fee multiple applied to the price slippage (1-p) collected on trades\nconfig.flat_fee_multiple = 0.005 # 5 bps\n\nnum_agents = 100 # int specifying how many agents you want to simulate\nagent_budget = 1_000_000 # max money an agent can spend\ntrade_chance = 2 / (\n config.num_trading_days * config.num_blocks_per_day\n) # on a given block, an agent will trade with probability `trade_chance`\n\nconfig.target_fixed_apr = 0.01 # target fixed APR of the initial market after the LP\nconfig.target_liquidity = 500_000_000 # target total liquidity of the initial market, before any trades\n\nconfig.log_level = logging.WARNING # Logging level, should be in [DEBUG, INFO, WARNING]\nconfig.log_filename = \"hyperdrive\" # Output filename for logging\n\n# %% [markdown]\n# ### Setup agents\n\n\n# %%\nclass RandomAgent(RandomAgent):\n \"\"\"Agent that randomly opens or closes longs or shorts\n\n Customized from the policy in that one can force the agent to only open longs or shorts\n \"\"\"\n\n def __init__(\n self,\n budget: FixedPoint = FixedPoint(\"10_000.0\"),\n rng: NumpyGenerator | None = None,\n trade_chance: FixedPoint = FixedPoint(\"1.0\"),\n ) -> None:\n \"\"\"Add custom stuff then call basic policy init\"\"\"\n self.trade_long = True # default to allow easy overriding\n self.trade_short = True # default to allow easy overriding\n super().__init__(budget, rng, trade_chance)\n\n def get_available_actions(\n self,\n wallet: Wallet,\n disallowed_actions: list[hyperdrive_actions.MarketActionType] | None = None,\n ) -> list[hyperdrive_actions.MarketActionType]:\n \"\"\"Get all available actions, excluding those listed in disallowed_actions\"\"\"\n # override disallowed_actions\n disallowed_actions = []\n if not self.trade_long: # disallow longs\n disallowed_actions += [\n hyperdrive_actions.MarketActionType.OPEN_LONG,\n hyperdrive_actions.MarketActionType.CLOSE_LONG,\n ]\n if not self.trade_short: # disallow shorts\n disallowed_actions += [\n hyperdrive_actions.MarketActionType.OPEN_SHORT,\n hyperdrive_actions.MarketActionType.CLOSE_SHORT,\n ]\n # compile a list of all actions\n all_available_actions = [\n hyperdrive_actions.MarketActionType.OPEN_LONG,\n hyperdrive_actions.MarketActionType.OPEN_SHORT,\n ]\n if wallet.longs: # if the agent has open longs\n all_available_actions.append(hyperdrive_actions.MarketActionType.CLOSE_LONG)\n if wallet.shorts: # if the agent has open shorts\n all_available_actions.append(hyperdrive_actions.MarketActionType.CLOSE_SHORT)\n # downselect from all actions to only include allowed actions\n return [action for action in all_available_actions if action not in disallowed_actions]\n\n\ndef get_example_agents(\n rng: NumpyGenerator,\n budget: int,\n new_agents: int,\n trade_chance: float,\n existing_agents: int = 0,\n direction: str | None = None,\n) -> list[Agent]:\n \"\"\"Instantiate a set of custom agents\"\"\"\n agents = []\n for address in range(existing_agents, existing_agents + new_agents):\n agent = Agent(\n wallet_address=address,\n policy=RandomAgent(\n budget=FixedPoint(budget),\n rng=rng,\n trade_chance=FixedPoint(trade_chance),\n ),\n )\n if direction is not None:\n if direction == \"short\":\n agent.trade_long = False\n elif direction == \"long\":\n agent.trade_short = False\n agent.log_status_report()\n agents += [agent]\n return agents\n\n\n# %% [markdown]\n#\n# ### Define variable apr process\n\n\n# %%\ndef DSR_historical(num_dates=90):\n \"\"\"Retuns a list of historical DSR values\n\n Parameters\n ----------\n num_dates : int, optional\n number of daily values to return, by default 90\n\n Returns\n -------\n list[float]\n A list of historical DSR values\n \"\"\"\n try:\n dsr = pd.read_csv(\n \"https://s3-sim-repo-0.s3.us-east-2.amazonaws.com/Data/HIST_DSR_D.csv\",\n index_col=0,\n infer_datetime_format=True,\n )\n dsr.index = pd.to_datetime(dsr.index)\n dsr = dsr.resample(\"D\").mean()\n min_date = dsr.index.min()\n max_date = dsr.index.max()\n date_range = max_date - min_date\n new_date_range = min_date + date_range * np.linspace(0, 1, num_dates)\n dsr_new = dsr.reindex(new_date_range, method=\"ffill\")\n dsr_new = dsr_new.reset_index(drop=True)\n return dsr_new[\"DAI_SAV_RATE\"].to_list()\n except: # pylint: disable=bare-except\n return [0.01] * config.num_trading_days\n\n\n# Define the variable apr\nconfig.variable_apr = DSR_historical(num_dates=config.num_trading_days)\nconfig.freeze() # type: ignore\n\n# %% [markdown]\n# ### Setup simulation objects\n\n# %%\n# define root logging parameters\noutput_utils.setup_logging(log_filename=config.log_filename, log_level=config.log_level)\n\n# get an instantiated simulator object\nsimulator = sim_utils.get_simulator(config)\n\n# %% [markdown]\n# ### Run the simulation\n\n# %%\n# add the random agents\nshort_agents = get_example_agents(\n rng=simulator.rng,\n budget=agent_budget,\n trade_chance=trade_chance,\n new_agents=num_agents // 2,\n existing_agents=1,\n direction=\"short\",\n)\nlong_agents = get_example_agents(\n rng=simulator.rng,\n budget=agent_budget,\n trade_chance=trade_chance,\n new_agents=num_agents // 2,\n existing_agents=1 + len(short_agents),\n direction=\"long\",\n)\nsimulator.add_agents(short_agents + long_agents)\nprint(f\"Simulator has {len(simulator.agents)} agents\")\n\n# %%\n# run the simulation\n\nsimulator.run_simulation()\n\n# %%\n# convert simulation state to a pandas dataframe\ntrades: pd.DataFrame = post_processing.compute_derived_variables(simulator)\nfor col in list(trades):\n if col.startswith(\"agent\"): # type: ignore\n divisor = 1e6 # 1 million divisor for everyone\n # pandas dataframes lets you do this syntax, but they didn't do the typing for it :/\n trades[col] = trades[col] / divisor # pylint: disable-all\n\n# %% [markdown]\n# ### Plot simulation results\n\n# %% [markdown]\n# This shows the evolution of interest rates over time. The \"variable\" APR represents a theoretical underlying variable rate. Here we've mocked it up to have the same pattern as the MakerDao DAI Saving Rate over its whole history, but condensed to a 90 day period for this simulation. The fixed rate is initialized at 1% and appears to remain unchanged.\n\n# %%\ntrades_agg = trades.groupby(\"day\").agg(\n {\n \"variable_apr\": [\"mean\"],\n \"fixed_apr\": [\"mean\"],\n \"delta_base_abs\": [\"sum\"],\n \"agent_0_pnl\": [\"mean\"],\n }\n)\ntrades_agg.columns = [\"_\".join(col).strip() for col in trades_agg.columns.values]\ntrades_agg = trades_agg.reset_index()\nax = get_gridspec_subplots()[1][0]\nplt.gcf().set_size_inches(6, 5)\nax = trades_agg.iloc[0:].plot(x=\"day\", y=\"variable_apr_mean\", ax=ax, label=\"variable\", c=\"blue\")\nax = trades_agg.iloc[0:].plot(x=\"day\", y=\"fixed_apr_mean\", ax=ax, label=\"fixed\", c=\"black\")\nax.set_title(\"Interest rates over time\")\nax.set_xlabel(\"Day\")\nax.set_ylabel(\"APR\")\nax.legend()\n\nxtick_step = 10\nax.set_xticks([0] + list(range(9, simulator.config.num_trading_days + 1, xtick_step)))\nax.set_xticklabels([\"1\"] + [str(x + 1) for x in range(9, simulator.config.num_trading_days + 1, xtick_step)])\n\nylim = ax.get_ylim()\nax.set_ylim(0, ylim[1])\nax.set_yticks(list(np.arange(ylim[0], ylim[1], 0.01)))\nax.set_yticklabels([f\"{(i):.0%}\" for i in ax.get_yticks()])\n\n# %% [markdown]\n# It may look like the black line isn't moving at all, until the end. But let's zoom in!\n#\n# This is a function of two things: random agents being too dumb to concertedly move the rate, as well as the model parameters not being optimized for this scenario.\n\n# %%\nfig = output_utils.plot_fixed_apr(trades, exclude_first_day=True, exclude_last_day=True)\nfig.set_size_inches(6, 5)\nax = plt.gca()\nax.properties()[\"children\"][0].set_color(\"black\")\nax.set_yticklabels([f\"{(i/100):.3%}\" for i in ax.get_yticks()])\nax.set_ylabel(\"APR\")\n\nxtick_step = 10\nax.set_xticks([0] + list(range(9, simulator.config.num_trading_days + 1, xtick_step)))\nax.set_xticklabels([\"1\"] + [str(x + 1) for x in range(9, simulator.config.num_trading_days + 1, xtick_step)])\n\n# %% [markdown]\n# These random agents are unable to pick smart entry points. Due to trading on coinflips only, they slowdly bleed fees out of their starting position, which in this case reduces from 1.0 million down to 0.999, a loss of $1k.\n\n\n# %%\ndef get_pnl_excluding_agent_0_no_mock_with_day(trades_df: pd.DataFrame) -> pd.DataFrame:\n \"\"\"Returns Profit and Loss Column for every agent except for agent 0 from post-processing\"\"\"\n cols_to_return = [\"day\"] + [col for col in trades_df if col.startswith(\"agent\") and col.endswith(\"pnl_no_mock\")] # type: ignore\n cols_to_return.remove(\"agent_0_pnl_no_mock\")\n return trades_df[cols_to_return]\n\n\ndef plot_pnl(pnl: pd.DataFrame, axes: Axes, label: str):\n \"\"\"Plots Profit and Loss\"\"\"\n # ax.plot(pnl.iloc[1:,:], linestyle='-', linewidth=0.5, alpha=0.5)\n # separate first half of agents, which are set to trade short\n # from second half of agents, which are set to trade long\n columns = pnl.columns.to_list()\n n = len(columns) // 2 # int\n short_pnl = pnl.loc[1:, columns[:n]].mean(axis=1)\n long_pnl = pnl.loc[1:, columns[n:]].mean(axis=1)\n axes.plot(short_pnl, c=\"red\", label=f\"Short {label}, final value={short_pnl[len(short_pnl)-1]:.5f}\", linewidth=2)\n axes.plot(long_pnl, c=\"black\", label=f\"Long {label}, final_value={long_pnl[len(long_pnl)-1]:.5f}\", linewidth=2)\n # grey area where day is last day\n axes.set_ylabel(\"PNL in millions\")\n # ax.axvspan(last_day, len(short_pnl), color='grey', alpha=0.2, label=\"Last day\")\n axes.legend()\n\n\nfig, ax = plt.subplots(1, 1, figsize=(6, 5), sharex=True, gridspec_kw={\"wspace\": 0.0, \"hspace\": 0.0})\nfirst_trade_that_is_on_last_day = min(trades.index[trades.day == max(trades.day)])\n# data_mock = post_processing.get_pnl_excluding_agent_0(trades)\n# plot_pnl(pnl=data_mock.iloc[:-1, :], ax=ax, label='Mock')\ndata_no_mock = get_pnl_excluding_agent_0_no_mock_with_day(trades).groupby(\"day\").mean()\nplot_pnl(pnl=data_no_mock.iloc[:-1, :], axes=ax, label=\"Realized Market Value\")\n\nxtick_step = 10\nax.set_xticks([0] + list(range(9, simulator.config.num_trading_days + 1, xtick_step)))\nax.set_xticklabels([\"1\"] + [str(x + 1) for x in range(9, simulator.config.num_trading_days + 1, xtick_step)])\n\nplt.gca().set_xlabel(\"Day\")\nplt.gca().set_title(\"Trader PNL over time\")\n# display(data_no_mock)\n\n# %% [markdown]\n# This plot shows being a Liquidity Provider (LP) is a profitable position, in this scenario where agents are trading randomly.\n\n# %%\nfig, ax = plt.subplots(2, 1, figsize=(6, 10))\nexclude_last_day = True\nnum_agents = 1\nstart_idx = 0\nfirst_trade_that_is_on_last_day = min(trades_agg.index[trades_agg.day == max(trades_agg.day)])\nend_idx = first_trade_that_is_on_last_day - 1 if exclude_last_day is True else len(trades_agg)\nax[0].plot(\n trades_agg.loc[start_idx:end_idx, \"day\"],\n trades_agg.loc[start_idx:end_idx, \"agent_0_pnl_mean\"],\n label=f\"mean = {trades_agg.loc[end_idx,'agent_0_pnl_mean']:.3f}\",\n)\nax[0].set_title(\"LP PNL Over Time\")\nax[0].set_ylabel(\"PNL\")\nax[0].set_xlabel(\"Day\")\ndata = trades.loc[0 : first_trade_that_is_on_last_day - 1, \"agent_0_pnl\"]\nxtick_step = 10\nax[0].set_xticks([0] + list(range(9, simulator.config.num_trading_days + 1, xtick_step)))\nax[0].set_xticklabels([\"1\"] + [str(x + 1) for x in range(9, simulator.config.num_trading_days + 1, xtick_step)])\nax[0].legend({f\"final value = {data.values[len(data)-1]:,.3f}\"})\nax[0].set_ylabel(\"PnL in millions\")\n\nexclude_first_trade = True\nexclude_last_trade = True\nstart_idx = 1 if exclude_first_trade else 0\nend_idx = first_trade_that_is_on_last_day - 1 if exclude_last_trade is True else None\nax[1].bar(trades_agg.loc[start_idx:end_idx, \"day\"], trades_agg.loc[start_idx:end_idx, \"delta_base_abs_sum\"], label=f\"mean = {trades_agg.loc[end_idx,'delta_base_abs_sum']:.3f}\") # type: ignore\nax[1].set_title(\"Market Volume\")\nax[1].set_ylabel(\"Base\")\nax[1].set_xlabel(\"Day\")\nxtick_step = 10\nax[1].set_xticks([0] + list(range(9, simulator.config.num_trading_days + 1, xtick_step)))\nax[1].set_xticklabels([\"1\"] + [str(x + 1) for x in range(9, simulator.config.num_trading_days + 1, xtick_step)])\nylim = ax[1].get_ylim()\nax[1].set_ylim(0, ylim[1])\n\n# %% [markdown]\n# ## We are constantly updating our research. Stay tuned for more!\n\n# %% [markdown]\n# TODO:\n# - parameter optimization\n# - smart agents\n# - multiple simulation trial runs to evaluate LP profitability\n# - simulate Aave, Compound, MakerDao, etc.\n","repo_name":"delvtech/elf-simulations-examples","sub_path":"examples/hyperdrive_demo_notebook.py","file_name":"hyperdrive_demo_notebook.py","file_ext":"py","file_size_in_byte":15178,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4945544640","text":"import nltk\r\nimport pdfplumber\r\nimport io\r\nfrom PIL import Image\r\nimport pytesseract\r\nfrom transformers import MarianMTModel, MarianTokenizer\r\n\r\nnltk.download(\"punkt\")\r\n\r\n\r\ndef extract_text_from_pdf(pdf_path):\r\n with pdfplumber.open(pdf_path) as pdf:\r\n text = \"\"\r\n for page_num, page in enumerate(pdf.pages, 1):\r\n # Attempt to extract text using pdfplumber\r\n text += page.extract_text()\r\n\r\n # If no meaningful text is extracted, try OCR on images\r\n if not text.strip() and page.images:\r\n for i, image in enumerate(page.images, 1):\r\n print(f\"Debug: Page {page_num}, Image {i} structure: {image}\")\r\n # Modify the next line based on the actual structure of page.images\r\n img_data = image.get(\"image_data\", None)\r\n if img_data:\r\n img = Image.open(io.BytesIO(img_data))\r\n ocr_result = pytesseract.image_to_string(img, lang=\"eng\")\r\n text += ocr_result\r\n return text\r\n\r\n\r\ndef split_into_chunks(text, max_chunk_length=500):\r\n sentences = nltk.sent_tokenize(text)\r\n chunks, current_chunk = [], \"\"\r\n\r\n for sentence in sentences:\r\n if len(current_chunk) + len(sentence) <= max_chunk_length:\r\n current_chunk += sentence + \" \"\r\n else:\r\n chunks.append(current_chunk.strip())\r\n current_chunk = sentence + \" \"\r\n\r\n # Add the last chunk\r\n if current_chunk:\r\n chunks.append(current_chunk.strip())\r\n\r\n return chunks\r\n\r\n\r\ndef translate_chinese_to_english(chinese_text):\r\n model_name = \"Helsinki-NLP/opus-mt-zh-en\" # Chinese to English translation model\r\n model = MarianMTModel.from_pretrained(model_name)\r\n tokenizer = MarianTokenizer.from_pretrained(model_name)\r\n\r\n # Split the input text into chunks\r\n chunks = split_into_chunks(chinese_text, max_chunk_length=500)\r\n\r\n # Translate each chunk and concatenate the results\r\n english_chunks = []\r\n total_chunks = len(chunks)\r\n\r\n for i, chunk in enumerate(chunks):\r\n print(f\"Processing chunk {i + 1} of {total_chunks} ({((i + 1) / total_chunks) * 100:.2f}% complete)\")\r\n input_ids = tokenizer.encode(chunk, return_tensors=\"pt\", max_length=512, truncation=True)\r\n output_ids = model.generate(input_ids)\r\n english_chunk = tokenizer.decode(output_ids[0], skip_special_tokens=True)\r\n english_chunks.append(english_chunk)\r\n\r\n english_text = \" \".join(english_chunks)\r\n return english_text\r\n\r\n\r\ndef save_text_to_file(text, file_path):\r\n with open(file_path, \"w\", encoding=\"utf-8\") as file:\r\n file.write(text)\r\n\r\n\r\n# Input and output file paths\r\ninput_pdf_path = \"C:\\\\Users\\\\jesse\\\\Desktop\\\\MT\\\\Mo_Yan\\\\Mo_Yan_Copy.pdf\"\r\noutput_file_path = \"C:\\\\Users\\\\jesse\\\\Desktop\\\\MT\\\\Mo_Yan\\\\Mo_Yan_Copy_MT.txt\"\r\n\r\n# Extract text from PDF\r\nchinese_text = extract_text_from_pdf(input_pdf_path)\r\n\r\n# Translate Chinese to English\r\nenglish_text = translate_chinese_to_english(chinese_text)\r\n\r\n# Save translated text to a new file\r\nsave_text_to_file(english_text, output_file_path)\r\n\r\nprint(f\"\\nTranslation saved to: {output_file_path}\")\r\n","repo_name":"JesseLovesGrace/MTAIT","sub_path":"Chinese_PDF_English.py","file_name":"Chinese_PDF_English.py","file_ext":"py","file_size_in_byte":3215,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"17040072474","text":"import re \nimport pprint\nimport os\nfrom collections import Counter\n\nclass join_cnt(object):\n def __init__(self, dir_name):\n self.dir_name = dir_name\n # 如果目标文件存在则删除,这是因为采用的追加模式\n # if os.path.exists(os.path.join(self.dir_name, 'res.txt')):\n # os.remove(os.path.join(self.dir_name, 'res.txt'))\n self.res_dir = os.path.join(dir_name,'res')\n # 建立一个dot文件存放每个子文件的dot文件和最终的dot文件,先判断是否存在,不存在则创建\n if not os.path.exists(self.res_dir):\n os.makedirs(self.res_dir)\n self.get_all_join_file(self.dir_name)\n self.merge_file()\n def get_join_number(self, target_file):\n with open(target_file, 'r', encoding='UTF-8') as f:\n content = \" \".join([item.rstrip() for item in f.readlines()])\n # 获取所有的SQL段\n con = re.findall(r'\"\"\"(.*?)\"\"\"',content,re.DOTALL|re.M)[1:]\n temp = []\n for item in con:\n join_count = len(re.findall(r'join',item, re.M))\n from_count = re.findall(r'from',item, re.M)\n # print(join_count)\n tm = [join_count+1]\n # temp.extend(join_count+1)\n list_group_by = re.findall(r'group by(.*?)(?=order by|limit|having|\\)|;)',item, re.M|re.DOTALL)\n if list_group_by:\n tm.extend([len(item.split(',')) for item in list_group_by])\n else:\n tm.append(0)\n temp.append(tm)\n if not temp:\n print(\"无关表{0}\".format(target_file))\n return\n # pprint.pprint(temp)\n print(\"开始写入\")\n dirname, filename = os.path.split(target_file)\n with open(os.path.join(self.res_dir, '{0}.txt'.format(filename)), 'w') as f: #os.path.join(self.dir_name, 'res.txt')\n f.write(\"file_name\\t次序\\tjoin个数\\tgroup by字段个数\\n\")\n for idx,value in enumerate(temp):\n # print('key:{0}, value:{1}'.format(key,value))\n f.write(\"{0}\\t{1}\\t{2}\\t{3}\\n\".format(filename, idx+1, *value))\n \n # pprint.pprint(d)\n def get_all_join_file(self, dir):\n \"\"\"\n 生成整个工程的dot文件\n \"\"\"\n for path, dir_list, file_list in os.walk(dir):\n for file_name in file_list: #遍历文件\n if file_name.endswith('.py'):\n print(os.path.join(path, file_name))\n self.get_join_number(os.path.join(path, file_name))\n for dir_name in dir_list:\n # if dir_name!='dot':\n print(os.path.join(dir, dir_name))\n self.get_all_join_file(os.path.join(dir, dir_name))\n\n def merge_file(self,):\n join_dict, group_dict = {},{}\n for file_name in os.listdir(self.res_dir):\n if file_name.endswith('.txt') and file_name != 'res_join.txt':\n # print(os.path.join(self.res_dir,file_name))\n with open(os.path.join(self.res_dir,file_name), 'r')as f:\n join_count_list, group_by_count_list = [],[]\n for idx,line in enumerate(f.readlines()):\n # 踢掉第一行\n if idx:\n file,idx,join_cnt, group_cnt = line.split('\\t')\n # 根据文件中的每一行,确定join个数为n的文件列表,group by的类似\n if join_cnt in join_dict:\n join_dict[join_cnt].append(file)\n else:\n join_dict[join_cnt] = [file]\n if group_cnt in group_dict:\n group_dict[group_cnt].append(file)\n else:\n group_dict[group_cnt] = [file]\n # join_count_list.append(join_cnt)\n # group_by_count_list.append(group_cnt)\n # pprint.pprint(join_dict)\n pprint.pprint(group_dict)\n with open(os.path.join(self.res_dir, 'res_join.md'), 'w', encoding='UTF-8') as f:\n row = join_dict.keys()\n out_col = set()\n # out_col.update([\"次数\"])\n out_col.update([i for item in join_dict.values() for i in item])\n # out_col.update([\"\\n\"])\n # print(out_col)\n first_line = \"|次数|\"+\"|\".join(out_col)+\"|\"\n # pprint.pprint(first_line)\n # print(\"\\n\".join([str(i) for i in d]))\n f.write(first_line)\n f.write('\\n')\n sep = ['---']*len(out_col)\n f.write(\"|---|\"+\"|\".join(sep)+\"|\")\n f.write('\\n')\n for key,value in join_dict.items():\n d = Counter(value)\n line = [key,]\n for col in out_col:\n if col in d:\n line.append(d[col])\n else:\n line.append(0)\n # line.append('\\n')\n f.write(\"|\"+\"|\".join([str(i) for i in line])+\"|\")\n f.write('\\n')\n with open(os.path.join(self.res_dir, 'res_group.md'), 'w', encoding='UTF-8') as f:\n row = group_dict.keys()\n out_col = set()\n # out_col.update([\"次数\"])\n out_col.update([i for item in group_dict.values() for i in item])\n # out_col.update([\"\\n\"])\n # print(out_col)\n first_line = \"|次数|\"+\"|\".join(out_col)+\"|\"\n # pprint.pprint(first_line)\n # print(\"\\n\".join([str(i) for i in d]))\n f.write(first_line)\n f.write('\\n')\n sep = ['---']*len(out_col)\n f.write(\"|---|\"+\"|\".join(sep)+\"|\")\n f.write('\\n')\n idx = 0\n for key,value in group_dict.items():\n d = Counter(value)\n line = [key.strip(),]\n print(idx)\n idx += 1\n # if int(key.strip())==0:\n # print(out_col)\n for col in out_col:\n if col in d:\n line.append(d[col])\n else:\n line.append(0)\n # line.append('\\n')\n f.write(\"|\"+\"|\".join([str(i) for i in line])+\"|\")\n # f.write('{0}\\n'.format(idx))\n f.write('\\n')\n\n\n\nif __name__ == \"__main__\":\n # target_file = r\n dir_name = \"\"\"D:\\gongsi_project\\product\\linezone_retail_wh_1\\Hadoop\\spark_code\"\"\"\n # file_name = r\"\"\"D:\\code\\test\\daily_code\\p_dim_source_bom.py\"\"\"\n obj = join_cnt(dir_name)\n # obj.get_join_number(file_name)","repo_name":"wugeer/daily_code","sub_path":"count_join_spark.py","file_name":"count_join_spark.py","file_ext":"py","file_size_in_byte":6751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5179612384","text":"class Solution:\n def getSum(self, a: int, b: int) -> int:\n # python integers are can be infinite in size\n # mask allows for us to treat them as 32-bit integers\n mask = 0xffffffff\n\n # the loop will continue while there is still a remainder after each xor\n while b:\n sum = (a^b) & mask # binary xor addition filtered through mask\n carry = ((a&b)<<1) & mask # gets the remainder and applies mask\n a = sum # replaced by the sum of both numbers\n b = carry # b now holds the remainder\n \n # checks if the sum is a negative number by checking if there is a 1 in the 32nd bit\n if (a>>31) & 1:\n return (a&mask) - 0x100000000 # returns negative sum by subtracting the maximum 32-bit integer plus 1\n return a # returns positive sum\n","repo_name":"hunter-meloche/leetcode-python","sub_path":"Binary/371. Sum of Two Integers.py","file_name":"371. Sum of Two Integers.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33580734461","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport datetime\n\n\ndef PreProcessing():\n data = pd.read_csv('../COVID19_data.csv')\n\n data['day_num'] = (pd.to_datetime(data['Date']) - datetime.datetime(2021, 3, 16)).dt.days # Day Number from 16th March 2021\n\n ndata = data[['Date', 'Confirmed', 'Tested', 'First Dose Administered', 'day_num']]\n\n # Test is the average number of tests done during the past 7 days (i.e., during t − 7 to t − 1)\n ndata.insert(2, 'Test', (ndata.Tested.rolling(8).sum() - ndata.Tested) / 7)\n\n ndata.insert(2, 'del_confirmed', ndata['Confirmed'].diff()) # .diff() to remove cumulative to per day data\n ndata.insert(2, 'c_bar', (ndata.del_confirmed.rolling(8).sum() - ndata.del_confirmed) / 7)\n\n ndata.insert(2, 'dV', ndata['First Dose Administered'].diff())\n\n temp = ndata[ndata['day_num'] >= 0] # data from 16 March 2021 to 26 April 2021\n df = temp[temp['day_num'] < 42]\n return df[['day_num', 'dV', 'c_bar', 'Test']]\n\n\ndef Constraints(prmts):\n N = 70000000\n if prmts[0] < 0: # Restricting Beta from being negative\n prmts[0] = 0\n\n if 0.156 * N >= prmts[4]: # R(0) constraint\n prmts[4] = 0.156 * N\n elif 0.36 * N <= prmts[4]:\n prmts[4] = 0.36 * N\n\n if 12 >= prmts[5]: # CIR(0)) constraint\n prmts[5] = 12\n elif prmts[5] >= 30:\n prmts[5] = 30\n\n return prmts\n\n\ndef run_avg(arr): # running seven-day-average\n avg = []\n\n for i in range(7): # for 1st 7 days\n x = np.mean(arr[:i + 1])\n if x < 0:\n x = 1\n avg.append(x)\n\n for i in range(7, 42): # after take avg of last 7 days\n x = np.mean(arr[i - 7:i])\n if x < 0:\n x = 1\n avg.append(x)\n\n return np.array(avg)\n\n\ndef SEIRV(init_val): # return parameters after updation for 42 days\n\n beta = init_val[0]\n S = [init_val[1]]\n E = [init_val[2]]\n I = [init_val[3]]\n R = [init_val[4]]\n# given\n alpha = 1 / 5.8\n gamma = 1 / 5\n epsilon = 0.66\n N = 70000000\n\n for t in range(0, 41):\n\n dW = 0 # conditions for ∆W(t)\n if t <= 30:\n dW = R[0] / 30\n\n dS = -beta * S[t] * I[t] / N - epsilon * dV[t] + dW\n dE = beta * S[t] * I[t] / N - alpha * E[t]\n dI = alpha * E[t] - gamma * I[t]\n dR = gamma * I[t] + epsilon * dV[t] - dW\n\n if S[t] + dS < 0: # when S(t) is negative, scale the remaining values so that the total sum is 70000000\n S.append(0)\n scale = N / (E[t] + dE + I[t] + dI + R[t] + dR)\n E.append((E[t] + dE) * scale)\n I.append((I[t] + dI) * scale)\n R.append((R[t] + dR) * scale)\n else:\n S.append(S[t] + dS)\n E.append(E[t] + dE)\n I.append(I[t] + dI)\n R.append(R[t] + dR)\n\n return [S, E, I, R]\n\n\ndef grad(prmts):\n [beta, S0, E0, I0, R0, CIR0] = prmts\n grad = []\n\n # perturb beta on either side by ±0.01,\n # perturb CIR(0) on either side by ±0.01,\n # perturb other parameters by ±1\n grad.append((loss_func([beta + 0.01, S0, E0, I0, R0, CIR0]) - loss_func(\n [beta - 0.01, S0, E0, I0, R0, CIR0])) / 0.02)\n grad.append((loss_func([beta, S0 + 1, E0, I0, R0, CIR0]) - loss_func([beta, S0 - 1, E0, I0, R0, CIR0])) / 2)\n grad.append((loss_func([beta, S0, E0 + 1, I0, R0, CIR0]) - loss_func([beta, S0, E0 - 1, I0, R0, CIR0])) / 2)\n grad.append((loss_func([beta, S0, E0, I0 + 1, R0, CIR0]) - loss_func([beta, S0, E0, I0 - 1, R0, CIR0])) / 2)\n grad.append((loss_func([beta, S0, E0, I0, R0 + 1, CIR0]) - loss_func([beta, S0, E0, I0, R0 - 1, CIR0])) / 2)\n grad.append(\n (loss_func([beta, S0, E0, I0, R0, CIR0 + 0.1]) - loss_func([beta, S0, E0, I0, R0, CIR0 - 0.1])) / 0.2)\n\n return np.array(grad)\n\n\ndef grad_desnt(prmts):\n delta = 0.01\n j = 0\n\n tdata = PreProcessing()\n # c_bar, Test, dV are made global to use them in future\n global c_bar\n global Test\n global dV\n c_bar = tdata['c_bar'].to_numpy()\n Test = tdata['Test'].to_numpy()\n dV = tdata['dV'].to_numpy()\n\n loss = loss_func(prmts)\n while (loss > delta):\n prmts = Constraints(prmts - grad(prmts) / (j + 1)) # To keep parameter within constraints\n loss = loss_func(prmts)\n j += 1\n\n print('Gradient Descent total iterations = ', j, '\\nLoss = ', loss)\n return prmts\n\n\ndef loss_func(prmts):\n\n alpha = 1 / 5.8\n CIR = prmts[5] * Test[0] * np.reciprocal(Test) # CIR(t)\n E = SEIRV(prmts)[1]\n avg = alpha * np.divide(E, CIR) # α∆e(t)\n\n avg = run_avg(avg)\n\n loss = np.log(c_bar) - np.log(avg)\n sq_error = np.square(loss).sum()\n return sq_error / 42\n\n\ndef New_Cases_Reported():\n data = pd.read_csv('../COVID19_data.csv')\n\n data['day_num'] = (pd.to_datetime(data['Date']) - datetime.datetime(2021, 3, 16)).dt.days # Day number from 16th march\n\n ndata = data[['Confirmed', 'day_num']]\n\n ndata.insert(2, 'del_confirmed', ndata['Confirmed'].diff())\n\n df = ndata[ndata['day_num'] >= 0] # Data from 16th March onwards\n\n return df['del_confirmed'].to_list()\n\n\ndef Open_Loop(prmts):\n alpha = 1 / 5.8\n gamma = 1 / 5\n epsilon = 0.66\n N = 70000000\n [beta, S0, E0, I0, R0, CIR0] = prmts\n\n S = [S0]\n E = [E0]\n I = [I0]\n R = [R0]\n\n dV = PreProcessing()['dV'].to_list() # For remaining values, took delV = 200000\n for t in range(42, 290):\n dV.append(200000)\n\n for t in range(290):\n # ∆W(t) Conditions\n dW = 0\n if t <= 30:\n dW = R[0] / 30\n if t >= 180:\n dW = (R[t - 179] - R[t - 180]) + epsilon * dV[t]\n\n dS = -beta * S[t] * I[t] / N - epsilon * dV[t] + dW\n dE = beta * S[t] * I[t] / N - alpha * E[t]\n dI = alpha * E[t] - gamma * I[t]\n dR = gamma * I[t] + epsilon * dV[t] - dW\n\n if S[t] + dS < 0:\n S.append(0)\n scale = N / (E[t] + dE + I[t] + dI + R[t] + dR)\n E.append((E[t] + dE) * scale)\n I.append((I[t] + dI) * scale)\n R.append((R[t] + dR) * scale)\n elif R[t] + dR < 0:\n R.append(0)\n scale = N / (E[t] + dE + I[t] + dI + S[t] + dS)\n E.append((E[t] + dE) * scale)\n I.append((I[t] + dI) * scale)\n S.append((S[t] + dS) * scale)\n else:\n S.append(S[t] + dS)\n E.append(E[t] + dE)\n I.append(I[t] + dI)\n R.append(R[t] + dR)\n\n return [S, E, I, R]\n\n\ndef Closed_Loop(prmts):\n [beta1, S0, E0, I0, R0, CIR0] = prmts\n\n dV = PreProcessing()['dV'].to_list() # For remaining values, took delV = 200000\n for t in range(42, 290):\n dV.append(200000)\n\n S = [S0]\n E = [E0]\n I = [I0]\n R = [R0]\n\n alpha = 1 / 5.8\n gamma = 1 / 5\n epsilon = 0.66\n N = 70000000\n\n for t in range(290):\n beta = beta1\n if t % 7 == 0 and t >= 42:\n if sum(I[t - 7:t]) / 7 < 10000:\n beta = beta1\n elif sum(I[t - 7:t]) / 7 < 25000:\n beta = 2 * beta1 / 3\n elif sum(I[t - 7:t]) / 7 < 100000:\n beta = beta1 / 2\n else:\n beta = beta1 / 3\n\n # ∆W(t) Conditions\n dW = 0\n if t <= 30:\n dW = R[0] / 30\n if t >= 180:\n dW = (R[t - 179] - R[t - 180]) + epsilon * dV[t - 180]\n\n dS = -beta * S[t] * I[t] / N - epsilon * dV[t] + dW\n dE = beta * S[t] * I[t] / N - alpha * E[t]\n dI = alpha * E[t] - gamma * I[t]\n dR = gamma * I[t] + epsilon * dV[t] - dW\n\n if S[t] + dS < 0:\n S.append(0)\n scale = N / (E[t] + dE + I[t] + dI + R[t] + dR)\n E.append((E[t] + dE) * scale)\n I.append((I[t] + dI) * scale)\n R.append((R[t] + dR) * scale)\n\n elif R[t] + dR < 0:\n R.append(0)\n scale = N / (E[t] + dE + I[t] + dI + S[t] + dS)\n E.append((E[t] + dE) * scale)\n I.append((I[t] + dI) * scale)\n S.append((S[t] + dS) * scale)\n else:\n S.append(S[t] + dS)\n E.append(E[t] + dE)\n I.append(I[t] + dI)\n R.append(R[t] + dR)\n\n return [S, E, I, R]\n\ndef Daily_Cases_plot(res1, res2, res3, res4, res5, CIR0):\n\n CIR = CIR0 * Test[0] * np.reciprocal(Test)\n CIR = sum(CIR) / 42\n\n E1 = res1[1] # E predictions till 31 December 2021\n E2 = res2[1]\n E3 = res3[1]\n E4 = res4[1]\n E5 = res5[1]\n\n alpha = 1 / 5.8\n predict1 = alpha * np.array(E1) / CIR\n predict2 = alpha * np.array(E2) / CIR\n predict3 = alpha * np.array(E3) / CIR\n predict4 = alpha * np.array(E4) / CIR\n predict5 = alpha * np.array(E5) / CIR\n d = range(291)\n\n # extrapolated data till 31st sept\n ground_truth = New_Cases_Reported()\n for i in range(188, 291):\n ground_truth.append(1000) # Took this value quite low as no.of daily cases reduced after 20th september 2021\n\n plt.figure(figsize=(12, 8))\n\n plt.plot(d, predict1)\n plt.plot(d, predict2)\n plt.plot(d, predict3)\n plt.plot(d, predict4)\n plt.plot(d, predict5)\n plt.plot(d, ground_truth)\n\n legend_name = ['open loop β', 'open loop 2β/3', 'open loop β/2', 'open loop β/3', 'closed loop control',\n 'reported cases (ground truth)']\n plt.legend(legend_name, loc=\"upper right\", fontsize=13)\n plt.xlabel('Day Number', fontsize=12)\n plt.ylabel('Daily Cases', fontsize=18)\n plt.show()\n\n\ndef Susceptible_fraction_plot(res1, res2, res3, res4, res5, CIR0):\n\n S1 = res1[0] # E predictions till 31 December 2021\n S2 = res2[0]\n S3 = res3[0]\n S4 = res4[0]\n S5 = res5[0]\n\n N = 70000000\n d = range(291)\n plt.figure(figsize=(12, 8))\n plt.xlim([0, 400])\n\n plt.plot(d, np.array(S1) / N)\n plt.plot(d, np.array(S2) / N)\n plt.plot(d, np.array(S3) / N)\n plt.plot(d, np.array(S4) / N)\n plt.plot(d, np.array(S5) / N)\n\n legend_name = ['open loop β', 'open loop 2β/3', 'open loop β/2', 'open loop β/3', 'closed loop control']\n plt.legend(legend_name, loc=\"upper right\", fontsize=13)\n plt.xlabel('Day Number', fontsize=12)\n plt.ylabel('Susceptible people fraction', fontsize=18)\n plt.show()\n\n\nif __name__ == '__main__':\n\n # Initial Parameters\n N = 70000000\n beta = 3.41243564864\n e0 = 0.0016\n i0 = 0.0039\n r0 = 0.32\n s0 = 1 - r0 - e0 - i0\n CIR0 = 29.054\n\n init_val = np.array([beta, s0 * N, e0 * N, i0 * N, r0 * N, CIR0])\n best_prmts = grad_desnt(init_val)\n print('Best Parameters = ', list(best_prmts))\n\n # Open Loop Control\n prmts = [0.49639073007972884, 47228999.99999971, 97999.9999962104, 272999.99998911645, 22399999.999999844, 29.50884124522309]\n [beta, S0, E0, I0, R0, CIR0] = prmts\n\n res1 = Open_Loop([beta, S0, E0, I0, R0, CIR0])\n\n res2 = Open_Loop([(2*beta)/3, S0, E0, I0, R0, CIR0])\n\n res3 = Open_Loop([(beta)/2, S0, E0, I0, R0, CIR0])\n\n res4 = Open_Loop([(beta)/3, S0, E0, I0, R0, CIR0])\n\n # Closed Loop Control\n res5 = Closed_Loop(best_prmts)\n\n Daily_Cases_plot(res1, res2, res3, res4, res5, CIR0)\n\n Susceptible_fraction_plot(res1, res2, res3, res4, res5, CIR0)\n\n\n\n\n","repo_name":"PratGaur/Covid19-Modelling-in-Karnataka","sub_path":"Covid-19 Modelling.py","file_name":"Covid-19 Modelling.py","file_ext":"py","file_size_in_byte":11199,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8922341109","text":"# input style\n\n\n'''\n2\n3\n1 2 3 \n4\n1 2 3 4\n'''\n\n# q = int(input())\n# for i in range(q):\n# n = int(input())\n# all = [int(i) for i in input().split()]\n\n\n'''\n4\n1 2 3 4\n5 6 7 8\n9 10 11 12\n14 15 16 17\n'''\n\nn = int(input())\nfor i in range(n):\n all = [int(i) for i in input().split()]","repo_name":"KaranKadam1/Python","sub_path":"PREP COMPANIES/INFOSYS/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"45402119692","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom .myfunctions import *\n\n\ndef index_page(request):\n # The function render will render (put together) our template blog/index_page.html\n context = {}\n if(request.method == 'POST'):\n artist_name = request.POST.get('artist', '')\n if((' ' in artist_name) == True):\n artist = list(artist_name)\n for i in range(len(artist)):\n if(' ' == artist[i]):\n artist[i] = '+'\n artist = \"\".join(artist)\n artist_site = get_url(artist)\n context['artist_name'] = artist_name.title()\n context['artist_site'] = artist_site\n else:\n artist_site = get_url(artist_name)\n context['artist_name'] = artist_name.title()\n context['artist_site'] = artist_site\n \n text = get_request_text(context['artist_site'])\n tour = on_tour(text)\n context['tour'] = tour.title()\n\n # Get the tour dates for the artists\n dates = []\n times = []\n dates, times = get_dates(tour, dates, text)\n if dates == None and times == None:\n context['venue'] = None\n else:\n venue_times = zip(dates, times)\n context['venue'] = venue_times\n #context['times'] = times\n \n return render(request, 'blog/index.html', context)","repo_name":"cesarg01/ConcertScraper","sub_path":"concertsite/blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30233981779","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 6 20:17:57 2022\n\n@author: smellor\n\"\"\"\n\nimport numpy as np\nimport pandas\nimport warnings\nimport copy\nfrom scipy.signal import butter,filtfilt, find_peaks\nfrom scipy.interpolate import interp1d\nfrom scipy.spatial.transform import Rotation as R\nimport mne\n\n# Classes for storing optitrack data\nclass Marker:\n \"\"\"\n Class for storing single OptiTrack markers\n \"\"\"\n def __init__(self, Position = [], Name = None):\n self.__position__ = Position\n self.__name__ = Name\n \n def appendPosition(self, newPos):\n if newPos.shape == (1, 3):\n newPos = np.transpose(newPos)\n if np.size(newPos,0) != 3:\n raise ValueError('Size of new position is incompatible. The row indicates x, y and z so should have 3 elements')\n self.__position__ = np.append(self.__position__, newPos, axis=1)\n \n def setPosition(self, newPos):\n self.__position__ = newPos\n \n def deletePosition(self):\n self.__position__ = []\n \n def getPosition(self):\n return self.__position__\n \n def getName(self):\n return self.__name__\n \nclass RigidBody(Marker):\n \"\"\"\n Class for storing OptiTrack rigid bodies\n \"\"\"\n def __init__(self, Position = [], Rotation = [], Name = None):\n self.__position__ = Position\n self.__rotation__ = Rotation\n self.__name__ = Name\n \n def appendRotation(self, newRot):\n if newRot.shape == (1,4):\n newRot = np.transpose(newRot)\n self.__rotation__ = np.append(self.__rotation__, newRot, axis=1)\n \n def setRotation(self, newRot):\n self.__rotation__ = newRot\n \n def deleteRotation(self):\n self.__rotation__ = [];\n \n def getRotation(self):\n return self.__rotation__\n \nclass OTobj:\n \"\"\"\n Class for storing OptiTrack data.\n \"\"\"\n \n def __init__(self, filename = None, rigidBodies = {}, markers = {}, time = None, recordingProperties = None):\n if filename is None and recordingProperties is None:\n self.rigidBodies = {}\n self.markers = {}\n self.time = []\n self.recordingProperties = {\n 'frameRate' : 120,\n 'startTime' : 0,\n 'totalFrames' : 0,\n 'rotationType' : 'Quaternion',\n 'lengthUnits' : 'm'\n }\n elif filename is None and recordingProperties != None:\n self.rigidBodies = rigidBodies\n self.markers = markers\n self.recordingProperties = recordingProperties\n self.time = time\n elif filename!= None and recordingProperties is None:\n # Start by importing data\n data = pandas.read_csv(filename, header=[1,2,4,5])\n \n # Create rigid bodies\n self.rigidBodies = {}\n if any('Rigid Body' in s for s in data.columns.levels):\n RBidx = [i for i, x in enumerate(data.columns) if x[0] == 'Rigid Body']\n RBcount = int(np.round((len(RBidx))/8))\n \n for i in range(0, RBcount):\n # Find Name\n RBlabpos = RBidx[i*8]\n name = data.columns[RBlabpos][1]\n \n # Find Position\n pos = np.zeros((3, len(data['Rigid Body', name, 'Position', 'X'])))\n pos[0,:] = data['Rigid Body', name, 'Position', 'X'].values\n pos[1,:] = data['Rigid Body', name, 'Position', 'Y'].values\n pos[2,:] = data['Rigid Body', name, 'Position', 'Z'].values\n \n # Find Rotation\n rot = np.zeros((4, len(data['Rigid Body', name, 'Rotation', 'X'])))\n rot[0,:] = data['Rigid Body', name, 'Rotation', 'X'].values\n rot[1,:] = data['Rigid Body', name, 'Rotation', 'Y'].values\n rot[2,:] = data['Rigid Body', name, 'Rotation', 'Z'].values\n rot[3,:] = data['Rigid Body', name, 'Rotation', 'W'].values\n \n self.rigidBodies[name] = RigidBody(Position=pos, Rotation=rot, Name=name)\n \n # Create Markers\n self.markers = {}\n if any('Marker' in s for s in data.columns.levels):\n Midx = [i for i, x in enumerate(data.columns) if x[0] == 'Marker']\n Mcount = int(np.round((len(Midx))/3))\n \n for i in range(0, Mcount):\n # Find name\n Mlabpos = Midx[i*3]\n name = data.columns[Mlabpos][1]\n \n # Find position\n pos = np.zeros((3, len(data['Marker', name, 'Position', 'X'])))\n pos[0,:] = data['Marker', name, 'Position', 'X'].values\n pos[1,:] = data['Marker', name, 'Position', 'Y'].values\n pos[2,:] = data['Marker', name, 'Position', 'Z'].values\n \n self.markers[name] = Marker(Position = pos, Name = name)\n \n # Save time\n tidx = [i for i, x in enumerate(data.columns) if x[3] == 'Time (Seconds)']\n cols = data.keys()\n self.time = data[cols[tidx]].values\n \n # Then import recording info\n recordTab = pandas.read_csv(filename, nrows=1, header=None)\n self.recordingProperties = {\n 'frameRate' : recordTab[[i+1 for i, x in enumerate(recordTab.values[0]) if x == 'Capture Frame Rate']].values[0,0],\n 'startTime' : recordTab[[i+1 for i, x in enumerate(recordTab.values[0]) if x == 'Capture Start Time']].values[0,0],\n 'totalFrames' : recordTab[[i+1 for i, x in enumerate(recordTab.values[0]) if x == 'Total Exported Frames']].values[0,0],\n 'rotationType' : recordTab[[i+1 for i, x in enumerate(recordTab.values[0]) if x == 'Rotation Type']].values[0,0]\n }\n if recordTab[[i+1 for i, x in enumerate(recordTab.values[0]) if x == 'Length Units']].values[0,0] == 'Millimeters':\n self.recordingProperties['lengthUnits'] = 'mm'\n elif recordTab[[i+1 for i, x in enumerate(recordTab.values[0]) if x == 'Length Units']].values[0,0] == 'Meters':\n self.recordingProperties['lengthUnits'] = 'm'\n else:\n raise Exception('Unrecognised Length Units')\n \n def listRB(self):\n \"\"\"\n Function to list rigid bodies stored in optitrack object\n \"\"\"\n rblist = list(self.rigidBodies.keys())\n return rblist\n \n def addRB(self, rigidBody):\n \"\"\"\n Function to add a rigid body to the optitrack object\n \"\"\"\n keys = self.listRB()\n if rigidBody.getName() in keys:\n raise Exception(\"Rigid Body with the same name already exists in OptiTrack object\")\n else:\n if rigidBody.__position__.shape[1] == len(self.time):\n self.rigidBodies[rigidBody.getName()] = rigidBody\n else:\n raise Exception(\"Added rigid body position has different size to time save in OptiTrack object\")\n \n def listMarkers(self):\n \"\"\"\n Function to list all the markers in an optitrack object\n \"\"\"\n markerlist = list(self.markers.keys())\n return markerlist\n \n def addMarker(self, marker):\n \"\"\"\n Function to add a marker to the optitrack object \n \"\"\"\n keys = list(self.markers.keys())\n if marker.getName() in keys:\n raise Exception(\"Marker with same name already saved in OptiTrack object\")\n else:\n if marker.__position__.shape[1] == len(self.time):\n self.markers[marker.getName()] = marker\n else:\n raise Exception(\"Added marker has different size to time as saved in OptiTrack object\")\n \n def append(self, newOTobj):\n \"\"\"\n Function to append two optitrack objects\n \"\"\"\n \n # Check recording properties are compatible\n if self.recordingProperties['rotationType'] != newOTobj.recordingProperties['rotationType']:\n raise Exception(\"OptiTrack objects have different rotation types\")\n \n # Get length of each object\n tlenSelf = len(self.time)\n tlenNew = len(newOTobj.time)\n \n if tlenSelf > 0:\n # Get marker list of self and new\n MLself = self.listMarkers()\n MLnew = newOTobj.listMarkers()\n # Create markers with NaNs in whichever object they are missing\n if sorted(MLself) != sorted(MLnew):\n # Print warning\n warnings.warn(\"Markers in original and appended optitrack objects do not match. Missing marker positions will be filled with NaNs\")\n \n # Loop through each member of MLnew and save the names which are not in MLself\n missingMLself = []\n if len(MLself) != 0:\n for i in MLnew:\n for j in MLself:\n if i == j:\n break\n elif j == len(MLself):\n missingMLself.append(i)\n else:\n missingMLself = MLnew\n missingMLnew = []\n if len(MLnew) != 0:\n for i in MLself:\n for j in MLnew:\n if i == j:\n break\n elif j == len(MLnew):\n missingMLnew.append(MLself[i])\n else:\n missingMLnew = MLself\n \n # Create new markers\n for i in missingMLself:\n self.addMarker(marker = Marker(Position=np.full((3, tlenSelf), np.nan), Name=i))\n for i in missingMLnew:\n newOTobj.addMarker(marker = Marker(Position=np.full((3,tlenNew), np.nan), Name=i))\n \n # Append all markers\n MLself = self.listMarkers()\n for i in MLself:\n self.markers[i].appendPosition(newOTobj.markers[i].getPosition())\n \n # Get rigid body lists of self and new\n RBLself = self.listRB()\n RBLnew = newOTobj.listRB()\n if sorted(RBLself) != sorted(RBLnew):\n # Print warning\n warnings.warn(\"Rigid bodies in original and appended optitrack objects do not match. Missing rigid body positions and orientations will be filled with NaNs\")\n \n # Loop through each member of RBLnew and save names which are not in RBLself\n missingRBLself = []\n for i in RBLnew:\n for j in RBLself:\n if RBLnew[i] == RBLself[j]:\n break\n elif j == len(MLself):\n missingRBLself.append(RBLnew[i])\n missingRBLnew = []\n for i in RBLself:\n for j in RBLnew:\n if RBLself[i] == RBLnew[j]:\n break\n elif j == len(RBLnew):\n missingRBLnew.append(RBLself[i])\n \n # Create new rigidbodies\n for i in missingRBLself:\n self.addRB(rigidBody = RigidBody(Position = np.full((3, tlenSelf), np.nan), \n Rotation = np.full((3, tlenSelf), np.nan), Name = i))\n for i in missingRBLnew:\n newOTobj.addRB(rigidBody = RigidBody(Position = np.full((3, tlenSelf), np.nan), \n Rotation = np.full((3, tlenSelf), np.nan), Name = i))\n # Append all rigid bodies\n RBself = self.listRB()\n for i in RBself:\n self.rigidBodies[i].appendPosition(newOTobj.rigidBodies[i].getPosition())\n self.rigidBodies[i].appendRotation(newOTobj.rigidBodies[i].getRotation())\n \n # Append Time\n self.time = np.append(self.time, newOTobj.time)\n else:\n self = copy.deepcopy(newOTobj)\n \n # Update recording properties\n self.recordingProperties['frameRate'] = np.nan\n self.recordingProperties['totalFrames'] = len(self.time)\n \n def filterOT(self, cutOffs, filtertype='lowpass'):\n \"\"\"\n Filter optitrack data. Only for pre-recorded data - not a point-by-point,\n real-time filter.\n \n Parameters\n ----------\n cutOffs : double\n Cut off frequency/ies. One number of lowpass or highpass filter, 2 \n if bandpass or bandstop filter.\n filtertype : string\n Filter type. Options are: 'lowpass', 'highpass', 'bandpass' or 'bandstop'. \n The default is 'lowpass'\n\n Returns\n -------\n None.\n\n \"\"\"\n \n # Define filter\n b, a = butter(5, cutOffs, btype=filtertype, analog=False, fs = self.recordingProperties['frameRate'])\n \n # Rigid bodies\n RBself = self.listRB()\n for i in RBself:\n currentPos = self.rigidBodies[i].getPosition()\n currentRot = self.rigidBodies[i].getRotation()\n newPos = filtfilt(b, a, currentPos)\n newRot = filtfilt(b, a, currentRot)\n self.rigidBodies[i].setPosition(newPos)\n self.rigidBodies[i].setRotation(newRot)\n \n # Markers\n MLself = self.listMarkers()\n for i in MLself:\n currentPos = self.markers[i].getPosition()\n newPos = filtfilt(b, a, currentPos)\n self.markers[i].setPosition(newPos)\n \n \n def resample(self, tnew, method='linear'):\n \"\"\"\n Resample optitrack data to fsample_new Hz\n\n Parameters\n ----------\n fsample_new : double\n new sampling frequency.\n method : string, optional\n Inerpolation method. Options match options for \"kind\" in \n scipy.interpolate.interp1d. The default is 'linear'.\n\n Returns\n -------\n None.\n\n \"\"\"\n\n # If new sampling freq is lower than original, filter data\n if 1/np.mean(np.diff(tnew)) < self.recordingProperties['frameRate']:\n warnings.warn('Optitrack data will automatically be filtered to half Nyquist limit of new sampling frequency')\n self.filterOT((1/np.mean(np.diff(tnew)))/4)\n \n # Get time arrays\n torig = np.squeeze(self.time)\n \n # Throw a warning message if tfinal and tinit are apart by more than 500 ms\n if (np.max(tnew) - np.max(torig)) > 0.5 or (np.min(tnew) - np.min(torig)) < -0.5:\n warnings.warn('Sampled times are not well matched; significant extrapolation will be required')\n \n # Rigid bodies\n for i in self.listRB():\n # Position\n currentPos = self.rigidBodies[i].getPosition()\n F = interp1d(torig, currentPos, kind=method, fill_value='extrapolate')\n newPos = F(tnew)\n self.rigidBodies[i].setPosition(newPos)\n \n # Rotation\n currentRot = self.rigidBodies[i].getRotation()\n F = interp1d(torig, currentRot, kind=method, fill_value='extrapolate')\n newRot = F(tnew)\n self.rigidBodies[i].setRotation(newRot)\n \n # Markers\n for i in self.listMarkers():\n # Position\n currentPos = self.markers[i].getPosition()\n F = interp1d(torig, currentPos, kind=method, fill_value='extrapolate')\n newPos = F(tnew)\n self.markers[i].setPosition(newPos)\n \n # Update time variable\n self.time = tnew\n \n # Update sampling frequency value\n self.recordingProperties['frameRate'] = 1/np.mean(np.diff(tnew))\n \n # Update total number of frames\n self.recordingProperties['totalFrames'] = len(tnew)\n \n def __str__(self):\n if len(self.time.shape) == 2:\n mint = self.time[0,0]\n maxt = self.time[-1,0]\n else:\n mint = self.time[0]\n maxt = self.time[-1]\n str = 'OptiTrack Data Info:\\n' + ' Rigid bodies: ' + ', '.join(self.listRB()) + \\\n '\\n Markers: ' + ', '.join(self.listMarkers()) + '\\n Time Range: ' + \\\n '{:.2f} - {:.2f} s\\n'.format(mint, maxt) + \\\n ' Sampling Frequency: {} Hz\\n Recording Start Time: {}\\n Total Frames: {}\\n Rotation Type: {}\\n Length Units: {}'\\\n .format(self.recordingProperties['frameRate'], self.recordingProperties['startTime'], \\\n self.recordingProperties['totalFrames'], self.recordingProperties['rotationType'], \\\n self.recordingProperties['lengthUnits'])\n return str\n \n \n def __removeTimePoints__(self, samplesToRemove):\n \"\"\"\n Remove time points from optitrack data\n\n Parameters\n ----------\n samplesToRemove : integer, list of integers or slice\n Time points/samples to remove from optitrack data. \n Recommend that they are all at either the start or end of the \n recording, otherwise better to replace values with NaN to avoid \n confusion with sampling frequency.\n\n Returns\n -------\n None.\n\n \"\"\"\n \n # Create boolean mask\n torig = np.squeeze(self.time)\n mask = np.ones(len(torig), dtype=bool)\n mask[samplesToRemove] = False\n \n # Get time array\n tnew = torig[mask]\n \n # Rigid bodies\n for i in self.listRB():\n # Position\n currentPos = self.rigidBodies[i].getPosition()\n newPos = currentPos[:,mask]\n self.rigidBodies[i].setPosition(newPos)\n \n # Rotation\n currentRot = self.rigidBodies[i].getRotation()\n newRot = currentRot[:,mask]\n self.rigidBodies[i].setRotation(newRot)\n \n # Markers\n for i in self.listMarkers():\n # Position\n currentPos = self.markers[i].getPosition()\n newPos = currentPos[:,mask]\n self.markers[i].setPosition(newPos)\n \n # Update time variable\n self.time = tnew\n \n # Update total number of frames\n self.recordingProperties['totalFrames'] = len(tnew)\n \n \n# Functions involving optitrack\n\n# Synchronise optitrack and opm data\ndef sync_optitrack_and_opm(opti_data, opm_data, LengthsAlreadyMatch=False, TriggerChannelName='OptiTrig', \\\n Trigger = None, ResampleOPMdata=False):\n \"\"\"\n Synchronise OPM and Optitrack recordings\n Trims and resamples each dataset. Should occur before epoching.\n \n The trigger is asssumed to be in the same time as the OPM data and by\n default the OptiTrack data is resampled to match the OPMs, rather than \n the other way around, although this can be adjusted using the\n \"ResampleOPMdata\" input option.\n\n INTPUT:\n - opti_data: the OptiTrack recordings\n - opm_data options: MNE python meeg object containing OPM data.\n - Additional Options:\n - LengthsAlreadyMatch (default: false): Boolean to determine\n whether or not to trim the OptiTrack data to match a given\n trigger. When set to true, it is assumed that the start and end\n of the OptiTrack and OPM recordings are already syncronised so\n there so any trimming of the data will be skipped.\n - TriggerChannelName (default: 'OptiTrig'): If trimming of the data\n is required and the OPM data is a meeg or FieldTrip object, you\n can specify the name of the trigger channel here. This trigger\n must be high when the OptiTrack is recording and low when it is \n off.\n - Trigger (default: None) Double array of zeros and ones for when the Optitrack is\n recording (1) or off (0). Particularly useful way to enter the\n Optitrack trigger if you either put the OPM data in as a matrix\n or recorded triggers in such a way that it wasn't a\n straightforward high-gated (optitrack on when high) trigger.\n N.B. the assumption is made that if only one change in the\n trigger is found, then this is the Optitrack turning on and the\n moment it turns off was missed by the OPMs, so the Movement\n data is also trimmed. A warning will be produced if this is the\n case.\n - ResampleOPMdata (default: false): Boolean to choose to resample\n the OPM data to match the OptiTrack data, rather than the other\n way around. All of the trimming will still match the previously\n given pattern (i.e. trim the OPM data unless only one trigger\n point is available).\n\n OUTPUT:\n - opti_data: Resampled (or untouched if ResampleOPMdata = true) \n OptiTrack recordings, output in the same format as they are input\n - opm_data: Trimmed and/or resampled OPM data, output in the same\n format as it is input\n \n \"\"\"\n \n # Copy opm_data\n opm_data = opm_data.copy()\n \n # Trim data\n if not LengthsAlreadyMatch:\n # Find optitrack trigger\n if Trigger is None:\n Trigger = opm_data.get_data(picks=[TriggerChannelName])\n \n # Find steps\n Trigger = np.squeeze(Trigger)\n trigevs, props = find_peaks(np.abs(np.diff(Trigger)), height=0.5*np.max(np.abs(np.diff(Trigger))))\n trigt = opm_data.times[trigevs]\n \n # Check length of trigevs is 2. If only one step recorded, print a warning\n if len(trigevs) > 2:\n raise ValueError('Too many steps in the trigger were found. \\nCheck that \\\n the optitrack trigger only steps up and down')\n elif len(trigevs) == 0:\n raise ValueError('No trigger steps found. Check given trigger channel')\n elif len(trigevs) == 1:\n warnings.warn(\"Only one step in the trigger was found. \\n\\\n It will be assumed that this is from the start of the Optitrack recording\")\n trigt = np.append(trigt, np.max(opm_data.times))\n elif len(trigevs) == 2:\n print('Start-End of OPM Trigger: {:.2f} s'\\\n .format(opm_data.times[trigevs[1]]-opm_data.times[trigevs[0]]))\n print('Length of Optitrack data: {:.2f} s'.format(np.ptp(opti_data.time)))\n \n # Trim OPM data\n opm_data.crop(tmin=trigt[0], tmax=trigt[1], include_tmax=True)\n \n # Trim movement data (if needed)\n if len(trigevs) == 1:\n topm = opm_data.times\n tmov = opti_data.time\n trim_mask = tmov > np.max(topm)\n opti_data.__removeTimePoints__(np.asarray(trim_mask).nonzero())\n else:\n trigevs = 0\n \n # Resample data\n if not ResampleOPMdata:\n opti_data.resample(opm_data.times)\n else:\n opm_data.resample(opti_data.recordingProperties['frameRate'])\n \n print('OPM and Optitrack Data should now be synchronised')\n \n return opti_data, opm_data, trigt\n\n# Append rigid body position and orientation to opm data (useful for plotting and noise cancallation)\ndef append_RB_to_opm_data(opm_data, opti_data, RBname=None, Quaternion=False):\n \"\"\"\n Append position and orientation of a given rigid body to the OPM data\n\n Parameters\n ----------\n opm_data : mne.io.Raw\n MNE python meeg object containing opm data.\n opti_data : OTobj\n The optitrack recordings. Must contain at least one rigid body.\n RBname : string, optional\n Name of the rigid body to append to the opm data. The default is the \n first rigid body in the data (sensible only if there is only 1 rigid \n body in the data).\n Quaternion : bool, optional\n If True, rigid body rotation is output in Quaternions. Else, it is \n output in Euler coordinates. The default is False\n\n Returns\n -------\n opm_data_out : mne.io.Raw\n opm_data with rigid body data appended as misc channel.\n\n \"\"\"\n # Copy opm_data\n opm_data_out = opm_data.copy()\n \n # Get rigid body name\n if RBname == None:\n RBname = opti_data.listRB()[0]\n \n # Get rigid body data into the right format\n rotation = opti_data.rigidBodies[RBname].getRotation()\n if Quaternion:\n chanlist = ['RB_' + RBname + '_' + s for s in ['posX', 'posY', 'posZ', 'rotX', 'rotY', 'rotZ', 'rotW']] \n if opti_data.recordingProperties['rotationType'] != 'Quaternion':\n r = R.from_euler('XYZ', rotation.T)\n rotation = r.as_quat().T\n else:\n chanlist = ['RB_' + RBname + '_' + s for s in ['posX', 'posY', 'posZ', 'rotX', 'rotY', 'rotZ']]\n if opti_data.recordingProperties['rotationType'] == 'Quaternion':\n r = R.from_quat(rotation.T)\n rotation = r.as_euler('XYZ').T\n data = np.vstack([opti_data.rigidBodies[RBname].getPosition(), rotation])\n \n # Create mne info object\n info = mne.create_info(ch_names=chanlist,\n ch_types='misc',\n sfreq=opti_data.recordingProperties['frameRate'])\n\n # Create a new mne.io.Raw object to save the rigid body data in\n opti_data_raw = mne.io.RawArray(data, info)\n \n # Append opti_data_raw to opm_data_out\n opm_data_out.add_channels([opti_data_raw], force_update_info=True)\n \n return opm_data_out\n","repo_name":"FIL-OPMEG/OPyM","sub_path":"opym/io/optitrack.py","file_name":"optitrack.py","file_ext":"py","file_size_in_byte":26142,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"43392089815","text":"# REQUIREMENTS ------------\n# pip install requests\n# -------------------------\n\n# TODO:\n# No validation done by assume everything is ok,\n# But better to write validation logic too\n\nimport requests\nimport json\nimport os\n\n# Where the API is available\napiBase = \"https://api.ce.pdn.ac.lk\"\napiIndex = apiBase + \"/projects/\"\n\nstudentSource = apiBase + \"/people/v1/students/all/\"\nprojectSource = apiBase + \"/projects/v1/all/\"\n\nstudent_dict = {}\nsupervisor_dict = {}\ntag_dict = {}\n\n# Gather Student API data\n# req_students = requests.get(studentSource)\n# if req_students.status_code==200:\n# students = json.loads(req_students.text)\n\nstudents_url = '../people/v1/students/all/index.json'\nwith open(students_url, 'r') as f:\n students = json.load(f)\n\n# Gather Project API data\n# req_projects = requests.get(projectSource)\n# if req_projects.status_code==200:\n# projects = json.loads(req_projects.text)\n\nprojects_url = '../projects/v1/all/index.json'\nwith open(projects_url, 'r') as f:\n projects = json.load(f)\n\nfor p_name in projects:\n\n # read the project information from the project's index file\n filename = projects[p_name]['api_url'].replace('https://api.ce.pdn.ac.lk', '..') + \"index.json\"\n proj_data = json.load(open(filename, \"r\"))\n print(proj_data['title'])\n\n cat_code = proj_data['category']['code']\n cat_title = proj_data['category']['title']\n\n # Prepare a subset of the project data\n proj_info = {\n 'title': proj_data['title'],\n 'category': {\n 'code': cat_code,\n 'title': cat_title,\n 'api_url': apiBase + '/projects/v1/' + cat_code + '/'\n },\n 'project_url': proj_data['project_url'],\n 'repo_url': proj_data['repo_url'],\n 'page_url': proj_data['page_url'],\n 'thumbnail_url': proj_data['thumbnail_url'],\n 'api_url': projects[p_name]['api_url']\n }\n\n # Add the project_tag info into the student indexes\n if 'team' in proj_data:\n print('\\tStudents: ' + ', '.join(proj_data['team']))\n for student in proj_data['team']:\n if student!=\"\" and student!=\"E/YY/XXX\":\n if student not in student_dict: student_dict[student] = []\n student_dict[student].append(proj_info)\n\n # Add the project_tag info into the staff indexes\n if 'supervisors' in proj_data:\n print('\\tSupervisors: ' + ', '.join(proj_data['supervisors']))\n for supervisor in proj_data['supervisors']:\n supervisor = supervisor.strip()\n if supervisor!=\"\" and supervisor!=\"#\":\n if supervisor not in supervisor_dict: supervisor_dict[supervisor] = []\n supervisor_dict[supervisor].append(proj_info)\n\n # Add the project_tag info into the tag indexes\n if 'tags' in proj_data:\n for tag in proj_data['tags']:\n if tag !=\"\":\n if tag not in tag_dict: tag_dict[tag] = []\n tag_dict[tag].append(proj_info)\n\n\n# print(json.dumps(student_dict, indent = 4))\n\n# ------------------------------------------------------------------------------\n# Sort the student dictionary according to ENumber (ASC)\nstudent_dict_sorted = {}\nfor key in sorted(student_dict):\n student_dict_sorted[key] = student_dict[key]\n\n# Write the sorted dict into the API endpoint file\nstudentFilter_filename = \"../projects/v1/filter/students/index.json\"\nos.makedirs(os.path.dirname(studentFilter_filename), exist_ok=True)\nwith open(studentFilter_filename, \"w\") as f:\n f.write(json.dumps(student_dict_sorted, indent = 4))\n\n# ------------------------------------------------------------------------------\n# Sort the staff dictionary according to Email address\nsupervisor_dict_sorted = {}\nfor key in sorted(supervisor_dict):\n supervisor_dict_sorted[key] = supervisor_dict[key]\n\n# Write the sorted dict into the API endpoint file\nstaffFilter_filename = \"../projects/v1/filter/staff/index.json\"\nos.makedirs(os.path.dirname(staffFilter_filename), exist_ok=True)\nwith open(staffFilter_filename, \"w\") as f:\n f.write(json.dumps(supervisor_dict_sorted, indent = 4))\n\n# ------------------------------------------------------------------------------\n# Sort the tag dictionary according to Tag Name (ASC)\ntag_dict_sorted = {}\nfor key in sorted(tag_dict):\n tag_dict_sorted[key] = tag_dict[key]\n\n# Write the sorted dict into the API endpoint file\ntagFilter_filename = \"../projects/v1/filter/tags/index.json\"\nos.makedirs(os.path.dirname(tagFilter_filename), exist_ok=True)\nwith open(tagFilter_filename, \"w\") as f:\n f.write(json.dumps(tag_dict_sorted, indent = 4))\n","repo_name":"cepdnaclk/api.ce.pdn.ac.lk","sub_path":"python_scripts/projects_filters.py","file_name":"projects_filters.py","file_ext":"py","file_size_in_byte":4578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36245193050","text":"\"\"\"\nsample rate: 44100\nvalues: 166671\nvalue 12345: 4435\n\"\"\"\nfrom scipy.io import wavfile\nimport pathlib\nPATH_HERE = pathlib.Path(__file__).parent\nPATH_DATA = PATH_HERE.joinpath(\"../../data\")\n\nif __name__ == \"__main__\":\n for wavFilePath in PATH_DATA.glob(\"*.wav\"):\n wavFilePath = PATH_DATA.joinpath(wavFilePath)\n samplerate, data = wavfile.read(wavFilePath)\n print(f\"{wavFilePath.name}, {samplerate}, {len(data)}\")\n","repo_name":"swharden/Spectrogram","sub_path":"dev/python/readwav.py","file_name":"readwav.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","stars":260,"dataset":"github-code","pt":"48"} +{"seq_id":"74745068944","text":"# This file contains the function called from the main.py file when Single=True\n# Functions -SingleFrequency (Solve for one value of omega)\n# Importing\nimport os\nimport sys\nimport time\nimport multiprocessing as multiprocessing\nimport tqdm.auto as tqdm\nimport cmath\nimport numpy as np\n\nimport netgen.meshing as ngmeshing\nfrom ngsolve import *\n\nsys.path.insert(0, \"Functions\")\nfrom ..Core_MPT.Theta1 import *\nfrom ..Core_MPT.Theta0 import *\nfrom ..Core_MPT.MPTCalculator import *\nfrom ..Core_MPT.imap_execution import *\nfrom ..Saving.FtoS import *\nfrom ..Saving.DictionaryList import *\nfrom ..Core_MPT.MPT_Preallocation import *\nfrom ..Core_MPT.Solve_Theta_0_Problem import *\nfrom ..Core_MPT.Calculate_N0 import *\nfrom ..Core_MPT.Theta0_Postprocessing import *\n\nsys.path.insert(0, \"Settings\")\nfrom Settings import SolverParameters\nimport gc\n\nfrom Functions.Helper_Functions.count_prismatic_elements import count_prismatic_elements\n\n\ndef SingleFrequency(Object, Order, alpha, inorout, mur, sig, Omega, CPUs, VTK, Refine, Integration_Order, Additional_Int_Order, Order_L2, sweepname,\n curve=5, theta_solutions_only=False, num_solver_threads='default'):\n\n _, Mu0, _, _, _, _, inout, mesh, mu_inv, numelements, sigma, bilinear_bonus_int_order = MPT_Preallocation([Omega], Object, [], curve, inorout, mur, sig, Order, 0, sweepname)\n # Set up the Solver Parameters\n Solver, epsi, Maxsteps, Tolerance, _, use_integral = SolverParameters()\n\n # Set up how the tensors will be stored\n N0 = np.zeros([3, 3])\n R = np.zeros([3, 3])\n I = np.zeros([3, 3])\n\n #########################################################################\n # Theta0\n # This section solves the Theta0 problem to calculate both the inputs for\n # the Theta1 problem and calculate the N0 tensor\n # Here, we have set the solver not to use the recovery mode.\n Theta0Sol, Theta0i, Theta0j, fes, ndof, evec = Solve_Theta_0_Problem(Additional_Int_Order, CPUs, Maxsteps, Order,\n Solver,\n Tolerance, alpha, epsi, inout, mesh, mu_inv,\n False, '')\n\n # Poission Projection to acount for gradient terms:\n Theta0Sol = Theta0_Postprocessing(Additional_Int_Order, Theta0Sol, fes)\n\n # Calculate the N0 tensor\n N0 = Calculate_N0(Integration_Order, N0, Theta0Sol, Theta0i, Theta0j, alpha, mesh, mu_inv)\n\n #########################################################################\n # Theta1\n # This section solves the Theta1 problem and saves the solution vectors\n\n # Setup the finite element space\n dom_nrs_metal = [0 if mat == \"air\" else 1 for mat in mesh.GetMaterials()]\n fes2 = HCurl(mesh, order=Order, dirichlet=\"outer\", complex=True, gradientdomains=dom_nrs_metal)\n # Count the number of degrees of freedom\n ndof2 = fes2.ndof\n\n # Define the vectors for the right hand side\n xivec = [CoefficientFunction((0, -z, y)), CoefficientFunction((z, 0, -x)), CoefficientFunction((-y, x, 0))]\n\n # Setup the array which will be used to store the solution vectors\n Theta1Sol = np.zeros([ndof2, 3], dtype=complex)\n\n # Set up the inputs for the problem\n Runlist = []\n nu = Omega * Mu0 * (alpha ** 2)\n for i in range(3):\n if CPUs < 3:\n NewInput = (\n fes, fes2, Theta0Sol[:, i], xivec[i], Order, alpha, nu, sigma, mu_inv, inout, Tolerance, Maxsteps, epsi, Omega,\n i + 1, 3, Solver, num_solver_threads, Additional_Int_Order, 'Theta1')\n else:\n NewInput = (\n fes, fes2, Theta0Sol[:, i], xivec[i], Order, alpha, nu, sigma, mu_inv, inout, Tolerance, Maxsteps, epsi, Omega,\n \"No Print\", 3, Solver, num_solver_threads, Additional_Int_Order, 'Theta1')\n Runlist.append(NewInput)\n\n # Run on the multiple cores\n with multiprocessing.Pool(CPUs) as pool:\n Output = list(tqdm.tqdm(pool.map(imap_version, Runlist), total=len(Runlist), desc='Solving Theta1'))\n print(' solved theta1 problem ')\n\n # Unpack the outputs\n for i, OutputNumber in enumerate(Output):\n Theta1Sol[:, i] = OutputNumber\n\n if theta_solutions_only == True:\n return Theta0Sol, Theta1Sol\n\n # Create the VTK output if required\n if VTK == True:\n print(' creating vtk output', end='\\r')\n ThetaE1 = GridFunction(fes2)\n ThetaE2 = GridFunction(fes2)\n ThetaE3 = GridFunction(fes2)\n ThetaE1.vec.FV().NumPy()[:] = Output[0]\n ThetaE2.vec.FV().NumPy()[:] = Output[1]\n ThetaE3.vec.FV().NumPy()[:] = Output[2]\n E1Mag = CoefficientFunction(\n sqrt(InnerProduct(ThetaE1.real, ThetaE1.real) + InnerProduct(ThetaE1.imag, ThetaE1.imag)))\n E2Mag = CoefficientFunction(\n sqrt(InnerProduct(ThetaE2.real, ThetaE2.real) + InnerProduct(ThetaE2.imag, ThetaE2.imag)))\n E3Mag = CoefficientFunction(\n sqrt(InnerProduct(ThetaE3.real, ThetaE3.real) + InnerProduct(ThetaE3.imag, ThetaE3.imag)))\n Sols = []\n Sols.append(dom_nrs_metal)\n Sols.append((ThetaE1 * 1j * Omega * sigma).real)\n Sols.append((ThetaE1 * 1j * Omega * sigma).imag)\n Sols.append((ThetaE2 * 1j * Omega * sigma).real)\n Sols.append((ThetaE2 * 1j * Omega * sigma).imag)\n Sols.append((ThetaE3 * 1j * Omega * sigma).real)\n Sols.append((ThetaE3 * 1j * Omega * sigma).imag)\n Sols.append(E1Mag * Omega * sigma)\n Sols.append(E2Mag * Omega * sigma)\n Sols.append(E3Mag * Omega * sigma)\n\n # Creating Save Name:\n strmur = DictionaryList(mur, False)\n strsig = DictionaryList(sig, True)\n savename = \"Results/\" + Object[:-4] + f\"/al_{alpha}_mu_{strmur}_sig_{strsig}\" + \"/om_\" + FtoS(Omega) + f\"_el_{numelements}_ord_{Order}/Data/\"\n if Refine == True:\n vtk = VTKOutput(ma=mesh, coefs=Sols,\n names=[\"Object\", \"E1real\", \"E1imag\", \"E2real\", \"E2imag\", \"E3real\", \"E3imag\", \"E1Mag\",\n \"E2Mag\", \"E3Mag\"], filename=savename + Object[:-4], subdivision=3)\n else:\n vtk = VTKOutput(ma=mesh, coefs=Sols,\n names=[\"Object\", \"E1real\", \"E1imag\", \"E2real\", \"E2imag\", \"E3real\", \"E3imag\", \"E1Mag\",\n \"E2Mag\", \"E3Mag\"], filename=savename + Object[:-4], subdivision=0)\n vtk.Do()\n\n # Compressing vtk output and sending to zip file:\n zipObj = ZipFile(savename + 'VTU.zip', 'w', ZIP_DEFLATED)\n zipObj.write(savename + Object[:-4] + '.vtu', os.path.basename(savename + Object[:-4] + '.vtu'))\n zipObj.close()\n os.remove(savename + Object[:-4] + '.vtu')\n print(' vtk output created ')\n\n #########################################################################\n # Calculate the tensor and eigenvalues\n\n # Create the inputs for the calculation of the tensors\n print(' calculating the tensor ', end='\\r')\n\n if use_integral is True:\n\n Runlist = []\n nu = Omega * Mu0 * (alpha ** 2)\n R, I = MPTCalculator(mesh, fes, fes2, Theta1Sol[:, 0], Theta1Sol[:, 1], Theta1Sol[:, 2], Theta0Sol, xivec, alpha,\n mu_inv, sigma, inout, nu, \"No Print\", 1, Order, Integration_Order)\n print(' calculated the tensor ')\n\n # Unpack the outputs\n MPT = N0 + R + 1j * I\n RealEigenvalues = np.sort(np.linalg.eigvals(N0 + R))\n ImaginaryEigenvalues = np.sort(np.linalg.eigvals(I))\n EigenValues = RealEigenvalues + 1j * ImaginaryEigenvalues\n\n else:\n Theta1Sols = np.zeros((ndof2, 1, 3), dtype=complex)\n Theta1Sols[:, 0, :] = np.asarray(np.squeeze(Theta1Sol))\n print(' Computing coefficients')\n\n # I'm aware that pre and post multiplying by identity of size ndof2 is slower than using K and A matrices outright,\n # however this allows us to reuse the Construct_Matrices function rather than add (significantly) more code.\n identity1 = sp.identity(ndof2)\n # Cteate the inputs\n Runlist = []\n\n for i in range(CPUs):\n Runlist.append((np.asarray([Omega]), mesh, fes, fes2, Theta1Sols, identity1, identity1, identity1,\n Theta0Sol, xivec, alpha, sigma, mu_inv, inout, N0, 1, [],\n False, 0, 0, Order, Integration_Order, bilinear_bonus_int_order, use_integral))\n\n # Run on the multiple cores\n # Edit James Elgy: changed how pool was generated to 'spawn': see\n # https://britishgeologicalsurvey.github.io/science/python-forking-vs-spawn/\n with multiprocessing.get_context('spawn').Pool(CPUs) as pool:\n Outputs = pool.starmap(Theta1_Lower_Sweep, Runlist)\n\n for i, Output in enumerate(Outputs):\n for j, Num in enumerate([Omega]):\n MPT = Output[0][j]\n EigenValues = Output[1][j]\n\n # del Theta1i, Theta1j, Theta0i, Theta0j, fes, fes2, Theta0Sol, Theta1Sol\n gc.collect()\n\n return MPT, EigenValues, N0, numelements, (ndof, ndof2)\n","repo_name":"MPT-Calculator/MPT-Calculator","sub_path":"Functions/FullSweep/SingleFrequency.py","file_name":"SingleFrequency.py","file_ext":"py","file_size_in_byte":9182,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"9314895437","text":"import os\nimport json\nimport sqlite3\nimport datetime\n\nimport function.tools.config_io as config_io\n\ndef timestamp_format(ts, format='%Y-%m-%d %H:%M:%S'):\n return datetime.datetime.fromtimestamp(ts).strftime(format)\n\ndef get_member_name(space_id, user_id):\n conn = sqlite3.connect('everphoto.db')\n c = conn.cursor()\n c.execute(\"SELECT json_data FROM shared_member where space_id = ?\", (space_id, ))\n data = c.fetchall()\n conn.close()\n for item in data:\n item = json.loads(item[0])\n if item['user_id'] == user_id:\n if 'deleted' in item and item['deleted'] == True:\n return f\"{user_id} (用户已删除账号)\"\n else:\n return item['nickname']\n return \"\"\n\ndef sort_shared_album(info):\n SHARE_DL_PATH = config_io.load(\"share_dl_path\")\n space_id = info['id']\n name = info['name']\n if os.path.exists(f\"{SHARE_DL_PATH}/{name}\") == False:\n os.mkdir(f\"{SHARE_DL_PATH}/{name}\")\n \n data = f'''\n 相册ID:{info['id']}\n 相册名称:{info['name']}\n 成员数量:{info['member_num']}\n 照片和视频数量:{info['asset_num']}\n 创建时间:{timestamp_format(info['created_at'])} ({info['created_at']})\n 更新时间:{timestamp_format(info['op_time'])} ({info['op_time']})\n 相册大小:{info['usage']}\n '''\n\n with open(f\"{SHARE_DL_PATH}/{name}/{name}.txt\", 'w', encoding='utf-8') as f:\n f.write(data)\n \n conn = sqlite3.connect('everphoto.db')\n c = conn.cursor()\n c.execute(\"SELECT json_data FROM shared_activity where space_id = ?\", (space_id,))\n data = c.fetchall()\n for item in data:\n item = json.loads(item[0])\n\n asset_data = \"\"\n for asset in item['asset_list']:\n asset_data += str(asset) + '\\n '\n\n comment_data = \"\"\n for comment in item['comment_list']:\n comment_data += f'''\n 评论ID:{comment['id']}\n 评论内容:{comment['content']}\n 评论者:{get_member_name(space_id, comment['creator_id'])} ({comment['creator_id']})\n '''\n if 'reply_to' in comment:\n comment_data += f'''\n 回复给:{get_member_name(space_id, comment['reply_to'])} ({comment['reply_to']})\n\n '''\n \n like_data = \"\"\n for like in item['like_list']:\n like_data += f\"{get_member_name(space_id, like)} ({like})\\n \"\n\n data = f\"\"\"\n 动态ID:{item['id']}\n 内容:{item['caption'] if 'caption' in item else ''}\n 发布者:{get_member_name(space_id, item['creator_id'])} ({item['creator_id']})\n 创建时间:{timestamp_format(item['created_at'])} ({item['created_at']})\n 是否删除:{item['is_deleted']}\n\n 照片:\n {asset_data}\n\n 评论:\n {comment_data}\n \n 点赞:\n {like_data}\n \"\"\"\n\n if os.path.exists(f\"{SHARE_DL_PATH}/{name}/{timestamp_format(item['created_at'], '%Y-%m-%d-%H-%M-%S')}\") == False:\n os.mkdir(f\"{SHARE_DL_PATH}/{name}/{timestamp_format(item['created_at'], '%Y-%m-%d-%H-%M-%S')}\")\n with open(f\"{SHARE_DL_PATH}/{name}/{timestamp_format(item['created_at'], '%Y-%m-%d-%H-%M-%S')}/动态信息.txt\", 'w', encoding='utf-8') as f:\n f.write(data)\n\n conn = sqlite3.connect('everphoto.db')\n c = conn.cursor()\n c.execute('''CREATE TABLE IF NOT EXISTS shared_move_record (source TEXT, target TEXT)''')\n conn.commit()\n\n c.execute(\"SELECT json_data FROM shared_asset where space_id = ?\", (space_id, ))\n shared_asset_list = c.fetchall()\n\n for asset_id in item['asset_list']:\n for shared_asset in shared_asset_list:\n shared_asset = json.loads(shared_asset[0])\n if shared_asset['id'] == asset_id:\n filename = f'{shared_asset[\"id\"]}.{shared_asset[\"mime\"].split(\"/\")[1]}' if shared_asset['mime'] != '' else f'{shared_asset[\"id\"]}.{shared_asset[\"subType\"]}'\n if os.path.exists(f\"{SHARE_DL_PATH}/{filename}\") == False:\n print(f\"文件 {filename} 不存在,可能之前已移动到其他动态的文件夹中。当前目标文件夹 {name}/{timestamp_format(item['created_at'], '%Y-%m-%d-%H-%M-%S')}\")\n break\n os.rename(f\"{SHARE_DL_PATH}/{filename}\", f\"{SHARE_DL_PATH}/{name}/{timestamp_format(item['created_at'], '%Y-%m-%d-%H-%M-%S')}/{filename}\")\n c.execute(\"INSERT INTO shared_move_record VALUES (?, ?)\", (f\"{filename}\", f\"{name}/{timestamp_format(item['created_at'], '%Y-%m-%d-%H-%M-%S')}/{filename}\"))\n break\n \n conn.commit()\n conn.close()\n\ndef pick_album():\n conn = sqlite3.connect('everphoto.db')\n c = conn.cursor()\n c.execute(\"SELECT json_data FROM personal_space\")\n data = c.fetchall()\n conn.close()\n for item in data:\n item = json.loads(item[0])\n if 'deleted' not in item or item['deleted'] == False :\n id = item['id']\n name = item['name']\n print(f\"正在整理共享相册:{id} {name}\")\n sort_shared_album(item)\n\ndef interface():\n os.system('cls')\n print(\"时光相册下载器\")\n print(\"当前进度:11. 整理共享相册的信息、图片、视频、动态、评论、点赞\")\n print(\"\")\n print(\"注意事项:\")\n print(\"1. 请自行确认第10步批量下载共享相册的图片是否完成\")\n print(\"2. 如果第10步未完成,可能会导致处理后缺少图片\")\n print(\"3. 因为已删除的用户、动态等情况,会有部分照片没有整理\")\n print(\"\")\n print(\"是否开始整理:\")\n print(\"1. 是\")\n print(\"2. 否\")\n choice = input(\"请输入数字:\")\n if choice == \"1\":\n pick_album()\n print(\"整理完成\")\n else:\n print(\"已取消整理\")\n input(\"按回车键继续...\")\n\nif __name__ == '__main__':\n interface()","repo_name":"1299172402/everphotoDL","sub_path":"src/function/J_sort_shared_album.py","file_name":"J_sort_shared_album.py","file_ext":"py","file_size_in_byte":6052,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"48"} +{"seq_id":"15583157711","text":"from django.shortcuts import render\n\nfrom django.http import JsonResponse, HttpResponse\n\nfrom .models import *\nfrom .serializers import *\n\nimport json\n\n# Create your views here.\ndef index_view(req):\n req.session['current_room'] = 1\n return render(req, 'index.html')\n\ndef current_room(req):\n current_room = req.session.get('current_room')\n return HttpResponse(current_room if current_room else '')\ndef get_initial_room_data(req):\n current_room = req.session.get('current_room')\n\n room_object_list = Room.objects.filter(pk=current_room)\n if room_object_list:\n room_object = room_object_list[0]\n\n room_users = UserInRoom.objects.filter(room=room_object)\n user_positions = list(map(\n lambda room_user: room_user.user_position,\n room_users\n ))\n\n # Create initial data dictionary\n initial_data = []\n for room_user in room_users:\n def user_matches_position(user_position):\n user_in_room = user_position.userinroom_set.all()[0]\n user_instance = room_user.user\n\n return user_in_room.user == user_instance\n user_position = list(filter(\n lambda room_user: user_matches_position(room_user),\n user_positions\n ))[0]\n user_id = room_user.user.id\n\n user_position_serializer = UserPositionSerializer(user_position)\n user_position_dict = user_position_serializer.data\n\n user_data = {\n 'position': user_position_dict,\n 'user_id': user_id\n }\n initial_data.append(user_data)\n else:\n initial_data = []\n\n return JsonResponse({'data': initial_data})\ndef get_user(req, id):\n if User.objects.filter(pk=id):\n # Get user details\n user = User.objects.get(pk=id)\n\n serializer = UserSerializer(user)\n user_dict = serializer.data\n\n # Get user profile details\n user_profile = user.userprofile_set.all()[0]\n user_profile_dict = UserProfileSerializer(user_profile).data\n\n user_data = {\n 'user': user_dict,\n 'user_profile': user_profile_dict\n }\n else:\n user_data = ''\n\n return JsonResponse(user_data)\n","repo_name":"anowa-eng/sympan","sub_path":"backend/venv/project/app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2275,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17145431637","text":"from types import ModuleType\nfrom itertools import chain\n\n\ndef load_config(module: ModuleType):\n dic = {}\n\n for key in [\n \"HAND\",\n \"FINGER\",\n \"POSITION_COST\",\n \"CONSECUTIVE_HAND_COST\",\n \"CONSECUTIVE_FINGER_COST\",\n \"CONSECUTIVE_KEY_COST\",\n \"KEY_LIST\",\n ]:\n if key in vars(module):\n dic[key] = vars(module)[key]\n\n return dic\n\n\ndef list_concat(lists):\n return list(chain.from_iterable(lists))\n\n","repo_name":"aoirohn/quantum_keymap","sub_path":"quantum_keymap/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"15204007673","text":"\"\"\"MetaGenScope server application.\"\"\"\n\nimport os\n\nfrom flask import jsonify, current_app, Blueprint\nfrom flask_api import FlaskAPI\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_migrate import Migrate\nfrom flask_bcrypt import Bcrypt\nfrom flask_cors import CORS\n\nfrom app.api.constants import URL_PREFIX\nfrom app.api.v1.analysis_results import analysis_results_blueprint\nfrom app.api.v1.auth import auth_blueprint\nfrom app.api.v1.organizations import organizations_blueprint\nfrom app.api.v1.ping import ping_blueprint\nfrom app.api.v1.samples import samples_blueprint\nfrom app.api.v1.sample_groups import sample_groups_blueprint\nfrom app.api.v1.users import users_blueprint\nfrom app.config import app_config\nfrom app.display_modules import all_display_modules\nfrom app.display_modules.register import register_display_module\nfrom app.extensions import mongoDB, db, migrate, bcrypt, celery\nfrom app.tool_results import all_tool_results\nfrom app.tool_results.register import register_tool_result\n\n\ndef create_app(environment=None):\n \"\"\"Create and bootstrap app.\"\"\"\n # Instantiate the app\n app = FlaskAPI(__name__)\n\n # Enable CORS\n CORS(app)\n\n # Set config\n if not environment:\n environment = os.getenv('APP_SETTINGS', 'development')\n config_object = app_config[environment]\n app.config.from_object(config_object)\n\n # Set up extensions\n mongoDB.init_app(app)\n db.init_app(app)\n bcrypt.init_app(app)\n migrate.init_app(app, db)\n\n # Register application components\n register_tool_result_modules(app)\n register_display_modules(app)\n register_blueprints(app)\n register_error_handlers(app)\n\n # Update Celery config\n update_celery_settings(celery, config_object)\n\n return app\n\n\ndef update_celery_settings(celery_app, config_class):\n \"\"\"\n Update Celery configuration.\n\n celery.config_from_object(object) isn't working so we set each option explicitly.\n \"\"\"\n celery_app.conf.update(\n broker_url=config_class.broker_url,\n result_backend=config_class.result_backend,\n result_cache_max=config_class.result_cache_max,\n result_expires=config_class.result_expires,\n task_always_eager=config_class.task_always_eager,\n task_eager_propagates=config_class.task_eager_propagates,\n task_serializer=config_class.task_serializer,\n )\n\n\ndef register_tool_result_modules(app):\n \"\"\"Register each Tool Result module.\"\"\"\n tool_result_modules_blueprint = Blueprint('tool_result_modules', __name__)\n for tool_result in all_tool_results:\n register_tool_result(tool_result, tool_result_modules_blueprint)\n app.register_blueprint(tool_result_modules_blueprint, url_prefix=URL_PREFIX)\n\n\ndef register_display_modules(app):\n \"\"\"Register each Display Module.\"\"\"\n display_modules_blueprint = Blueprint('display_modules', __name__)\n for module in all_display_modules:\n register_display_module(module, display_modules_blueprint)\n app.register_blueprint(display_modules_blueprint, url_prefix=URL_PREFIX)\n\n\ndef register_blueprints(app):\n \"\"\"Register API endpoint blueprints for app.\"\"\"\n app.register_blueprint(analysis_results_blueprint, url_prefix=URL_PREFIX)\n app.register_blueprint(auth_blueprint, url_prefix=URL_PREFIX)\n app.register_blueprint(organizations_blueprint, url_prefix=URL_PREFIX)\n app.register_blueprint(ping_blueprint, url_prefix=URL_PREFIX)\n app.register_blueprint(samples_blueprint, url_prefix=URL_PREFIX)\n app.register_blueprint(sample_groups_blueprint, url_prefix=URL_PREFIX)\n app.register_blueprint(users_blueprint, url_prefix=URL_PREFIX)\n\n\ndef register_error_handlers(app):\n \"\"\"Register JSON error handlers for app.\"\"\"\n app.register_error_handler(404, page_not_found)\n app.register_error_handler(500, internal_error)\n\n\ndef page_not_found(not_found_error):\n \"\"\"Handle 404 Not Found error.\"\"\"\n return jsonify(error=404, text=str(not_found_error)), 404\n\n\ndef internal_error(exception):\n \"\"\"Handle 500 Internal Error error.\"\"\"\n current_app.logger.exception(exception)\n return jsonify(error=500, text=str(exception)), 500\n","repo_name":"MetaGenScope/metagenscope-server","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4123,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71466077585","text":"\"\"\"\n Process dataset metadata.\n\"\"\"\n\n\nimport argparse\nimport os\nimport sys\nfrom copy import deepcopy\n\nimport numpy as np\nfrom PIL import Image\nfrom skimage.metrics import structural_similarity as ssim\n\nfrom tools.utils import (check_python_3, load_json_file, load_string_list_file,\n save_json_file)\nfrom tools.utils_dataset import (calculate_body_bounding_box,\n calculate_body_bounding_box_PIPA_relation,\n calculate_relations, fix_bounding_box,\n process_line_PIPA, process_line_PIPA_relation,\n relation_counter_PIPA)\n\n\ndef add_objects(data_processed, path_objects):\n \"\"\"Add objects annotations from the given path to processed data.\"\"\"\n\n # Progression counter\n fraction = len(data_processed) * 0.1\n porcent = 0\n\n for index, image in enumerate(data_processed):\n\n # Progression counter\n if (int(index % fraction) == 0):\n print('>> ...{0:.0%}'.format(porcent))\n porcent += 0.1\n\n path_object = os.path.join(path_objects, image.zfill(5) + '.json')\n\n # Check if annotations for current image exists\n if (os.path.isfile(path_object)):\n\n # Get image size\n image_width = data_processed[image]['width']\n image_height = data_processed[image]['height']\n\n data_object = load_json_file(path_object)\n data_final = {}\n\n # Processing information\n data_final['category'] = data_object['categories']\n data_final['bbox'] = []\n\n # Fixing boxes\n for bounding_box in data_object['bboxes']:\n fixed_box = fix_bounding_box(\n bounding_box, (image_width, image_height))\n data_final['bbox'].append(fixed_box)\n\n data_processed[image]['object'] = data_final\n\n print('>> ...{0:.0%}'.format(porcent))\n\n return data_processed\n\n\ndef build_PIPA(data_indexes, path_images_full):\n \"\"\"Build PIPA dataset from original annotations.\"\"\"\n\n data_built = {}\n\n # Progression counter\n fraction = len(data_indexes) * 0.1\n porcent = 0\n\n for index, line in enumerate(data_indexes):\n\n # Progression counter\n if (int(index % fraction) == 0):\n print('>> ...{0:.0%}'.format(porcent))\n porcent += 0.1\n\n # Getting information from each line\n str_image, original_x, original_y, original_width, original_height, identity_id, subset_id = process_line_PIPA(\n line)\n\n # Building original box\n original_bbox = [original_x, original_y,\n original_width, original_height]\n\n # Getting image id and loading it\n path_image = os.path.join(path_images_full, str_image + '.jpg')\n image = Image.open(path_image).convert('RGB')\n image_width, image_height = image.size\n\n # Calculating new face coordinates\n face_left = original_x - 1\n face_upper = original_y - 1\n\n # Fixing negative values\n if (face_left < 0):\n face_left = 0\n\n if (face_upper < 0):\n face_upper = 0\n\n face_right = face_left + original_width + 1\n face_lower = face_upper + original_height + 1\n\n # Fixing face bounding boxes\n face_bbox = fix_bounding_box(\n (face_left, face_upper, face_right, face_lower), (image_width, image_height))\n\n # Calculating body bounding boxes as 3 * width and 6 * height\n body_bbox = calculate_body_bounding_box(original_bbox)\n\n # Fixing body bounding boxes\n fixed_body_bbox = fix_bounding_box(\n body_bbox, (image_width, image_height))\n\n # For list comparison\n fixed_body_bbox[2] -= 1\n fixed_body_bbox[3] -= 1\n\n # Storing information\n if str_image not in data_built:\n\n data_dict = {}\n data_dict['original_bbox'] = []\n data_dict['face_bbox'] = []\n data_dict['body_bbox'] = []\n data_dict['identity_id'] = []\n data_dict['subset_id'] = []\n data_dict['height'] = image_height\n data_dict['width'] = image_width\n data_dict['domain'] = {}\n data_dict['relationship'] = {}\n\n data_built[str_image] = data_dict\n\n data_built[str_image]['original_bbox'].append(original_bbox)\n data_built[str_image]['face_bbox'].append(face_bbox)\n data_built[str_image]['body_bbox'].append(fixed_body_bbox)\n data_built[str_image]['identity_id'].append(identity_id)\n data_built[str_image]['subset_id'].append(subset_id)\n\n print('>> ...{0:.0%}'.format(porcent))\n\n return data_built\n\n\ndef build_PISC(\n data_image,\n data_domain,\n data_relationship,\n data_occupation\n):\n \"\"\"Build PISC dataset from annotations.\"\"\"\n\n data_built = {}\n\n # Transforming into a dictionary\n for image in data_image:\n\n # Removing id from within the data\n information = image.copy()\n del information['id']\n\n # Using id as key for processed data\n data_built[str(image['id'])] = information\n\n # Processing annotations\n for image in data_built:\n\n # Renaming keys\n data_built[image]['height'] = data_built[image].pop('imgH')\n data_built[image]['width'] = data_built[image].pop('imgW')\n data_built[image]['original_bbox'] = data_built[image].pop('bbox')\n\n # List for fixed bounding boxes\n data_built[image]['body_bbox'] = []\n\n # Fix bounding boxes\n for box in data_built[image]['original_bbox']:\n fixed_box = fix_bounding_box(\n box, (data_built[image]['width'] - 1, data_built[image]['height'] - 1))\n data_built[image]['body_bbox'].append(fixed_box)\n\n # Adding social relation ajusting labels to start from zero\n if image in data_domain:\n data_built[image]['domain'] = {\n k: (v - 1) for (k, v) in data_domain[image].items()}\n\n if image in data_relationship:\n data_built[image]['relationship'] = {\n k: (v - 1) for (k, v) in data_relationship[image].items()}\n\n # Adding occupation\n for image in data_occupation:\n\n id = image['id']\n\n if id in data_built:\n data_built[id]['occupation'] = image['occupation']\n\n return data_built\n\n\ndef process_PIPA(\n data_built,\n list_data_train,\n list_data_test,\n list_data_validation,\n path_images_face,\n path_images_body,\n path_images_full\n):\n \"\"\"Process PIPA dataset adding relationship information from PIPA-relation.\"\"\"\n\n dict_built = {}\n dict_splits = {'train': list_data_train,\n 'test': list_data_test, 'validation': list_data_validation}\n\n # Process data for each split\n # Here we also treat the wrong labeling on the PIPA-relation annotations\n for key in dict_splits:\n\n split = dict_splits[key]\n\n print('>> ' + key.capitalize() + ' split...')\n\n relation_counter_actual = relation_counter_PIPA(split[0])\n relation_counter_total = {}\n list_errors = []\n\n # Count the total number of possible relations for the split\n for image in data_built:\n relation_counter_total[image] = calculate_relations(\n len(data_built[image]['identity_id']))\n\n # Compare to the total number of relations with the actual number\n # If we dont have the full number of relations, we put it on the error list\n for image in relation_counter_actual:\n if (relation_counter_total[image] != relation_counter_actual[image]):\n list_errors.append(image)\n\n # Progression counter\n split_size = len(split[0])\n fraction = split_size * 0.1\n porcent = 0\n\n for index in range(split_size):\n\n # Progression counter\n if (int(index % fraction) == 0):\n print('>> ...{0:.0%}'.format(porcent))\n porcent += 0.1\n\n # Getting information for each person\n str_image_1, str_person_1, int_relation_1, int_domain_1 = process_line_PIPA_relation(\n split[0][index])\n str_image_2, str_person_2, int_relation_2, int_domain_2 = process_line_PIPA_relation(\n split[1][index])\n\n # Check if information is coherent\n assert str_image_1 == str_image_2, \\\n '>> [ERROR] Image ID missmatch for relation %d' % index\n\n assert int_relation_1 == int_relation_2, \\\n '>> [ERROR] Relation label missmatch for relation %d' % index\n\n assert int_domain_1 == int_domain_2, \\\n '>> [ERROR] Domain label missmatch for relation %d' % index\n\n # Get person numbers\n person_1 = int(str_person_1[1])\n person_2 = int(str_person_2[1])\n\n # If the image does not have a full relation set\n # The person number from original annotation might be wrong\n # We need to find the correct bounding boxes\n if str_image_1 in list_errors:\n\n # Getting the full image\n path_image = os.path.join(\n path_images_full, str_image_1 + '.jpg')\n image_full = Image.open(path_image).convert('L')\n\n # Getting face images from annotaded bounding boxes\n path_face_1 = os.path.join(\n path_images_face, str_person_1 + '_' + str_image_1 + '.jpg')\n path_face_2 = os.path.join(\n path_images_face, str_person_2 + '_' + str_image_2 + '.jpg')\n\n img_face_1 = np.asarray(Image.open(\n path_face_1).resize((50, 50)).convert('L'))\n img_face_2 = np.asarray(Image.open(\n path_face_2).resize((50, 50)).convert('L'))\n\n # Structural similarity\n ssim_face_1 = 0.\n ssim_face_2 = 0.\n\n # Here we use structural similarity to identify the correct boxes\n # For each box we crop it and check the similarity with the original image\n for i, bbox in enumerate(data_built[str_image_1]['face_bbox']):\n\n cropped_face = np.asarray(image_full.crop(\n (bbox[0], bbox[1], bbox[2], bbox[3])).resize((50, 50)))\n\n ssim_cropped_1 = ssim(cropped_face, img_face_1)\n ssim_cropped_2 = ssim(cropped_face, img_face_2)\n\n if (ssim_face_1 < ssim_cropped_1):\n ssim_face_1 = ssim_cropped_1\n person_1 = i + 1\n\n if (ssim_face_2 < ssim_cropped_2):\n ssim_face_2 = ssim_cropped_2\n person_2 = i + 1\n\n # Getting the full image\n path_image = os.path.join(path_images_full, str_image_1 + '.jpg')\n image_full = Image.open(path_image).convert('L')\n\n # Getting face and body images for checking\n path_face_1 = os.path.join(\n path_images_face, str_person_1 + '_' + str_image_1 + '.jpg')\n path_face_2 = os.path.join(\n path_images_face, str_person_2 + '_' + str_image_2 + '.jpg')\n\n path_body_1 = os.path.join(\n path_images_body, str_person_1 + '_' + str_image_1 + '.jpg')\n path_body_2 = os.path.join(\n path_images_body, str_person_2 + '_' + str_image_2 + '.jpg')\n\n img_face_1 = Image.open(path_face_1).convert('L')\n img_face_2 = Image.open(path_face_2).convert('L')\n\n img_body_1 = Image.open(path_body_1).convert('L')\n img_body_2 = Image.open(path_body_2).convert('L')\n\n # Crop face and body from boxes to compare\n body_box_1 = calculate_body_bounding_box_PIPA_relation(\n data_built[str_image_1]['original_bbox'][person_1 - 1])\n body_box_2 = calculate_body_bounding_box_PIPA_relation(\n data_built[str_image_1]['original_bbox'][person_2 - 1])\n\n fixed_body_box_1 = fix_bounding_box(body_box_1, image_full.size)\n fixed_body_box_2 = fix_bounding_box(body_box_2, image_full.size)\n\n cropped_face_1 = image_full.crop(\n data_built[str_image_1]['face_bbox'][person_1 - 1])\n cropped_face_2 = image_full.crop(\n data_built[str_image_2]['face_bbox'][person_2 - 1])\n\n cropped_body_1 = image_full.crop(fixed_body_box_1)\n cropped_body_2 = image_full.crop(fixed_body_box_2)\n\n # Build the string key for the relation\n str_relation = str(person_1) + ' ' + str(person_2)\n\n # Check if this is not an spurious relation\n assert str_relation not in data_built[str_image_1]['relationship'], \\\n '>> [ERROR] Spurious relation for image %s' % str_image_1\n\n # Check if the boxes for person 1 are correct\n assert (img_face_1.size == cropped_face_1.size) and (img_body_1.size == cropped_body_1.size), \\\n '>> [ERROR] Bounding Box 1 missmatch for image %s' % str_image_1\n\n # Check if the boxes for person 2 are correct\n assert (img_face_2.size == cropped_face_2.size) and (img_body_2.size == cropped_body_2.size), \\\n '>> [ERROR] Bounding Box 2 missmatch for image %s' % str_image_2\n\n # Add relation and domain information\n data_built[str_image_1]['relationship'][str_relation] = int_relation_1\n data_built[str_image_1]['domain'][str_relation] = int_domain_1\n\n print('>> ...{0:.0%}'.format(porcent))\n\n # Generating split lists\n dict_built[key] = list(relation_counter_actual.keys())\n\n return data_built, dict_built\n\n\ndef pre_process(args):\n \"\"\"Processing pipeline for PIPA and PISC metadata.\"\"\"\n\n # Check for python correct version\n check_python_3()\n\n # Generating paths\n path_dataset = os.path.join(args.path_datasets, args.dataset)\n path_save_built = os.path.join(\n path_dataset, 'built_' + args.dataset + '.json')\n path_save_final = os.path.join(path_dataset, args.dataset + '.json')\n path_annotations = os.path.join(path_dataset, 'annotations')\n path_objects = os.path.join(path_dataset, 'objects')\n path_splits = os.path.join(path_dataset, 'splits')\n path_images = os.path.join(path_dataset, 'images')\n path_images_full = os.path.join(path_images, 'full')\n path_images_face = os.path.join(path_images, 'face')\n path_images_body = os.path.join(path_images, 'body')\n path_split_domain = os.path.join(path_splits, 'domain')\n path_split_relationship = os.path.join(path_splits, 'relationship')\n\n if args.dataset == 'PIPA':\n\n print('>> [PRE-PROCESSING]')\n print('>> People in Photo Album (PIPA) relation dataset')\n\n # Generating PIPA specific paths\n path_train_1 = os.path.join(\n path_splits, 'consistency_annotator', 'single_body1_train_16.txt')\n path_train_2 = os.path.join(\n path_splits, 'consistency_annotator', 'single_body2_train_16.txt')\n # Test and validation annotations original file names have been switched!\n path_test_1 = os.path.join(\n path_splits, 'consistency_annotator', 'single_body1_eval_16.txt')\n # Test and validation annotations original file names have been switched!\n path_test_2 = os.path.join(\n path_splits, 'consistency_annotator', 'single_body2_eval_16.txt')\n # Test and validation annotations original file names have been switched!\n path_validation_1 = os.path.join(\n path_splits, 'consistency_annotator', 'single_body1_test_16.txt')\n # Test and validation annotations original file names have been switched!\n path_validation_2 = os.path.join(\n path_splits, 'consistency_annotator', 'single_body2_test_16.txt')\n path_data_indexes = os.path.join(\n path_annotations, 'original', 'index.txt')\n\n print('>> Loading dataset from: %s' % path_dataset)\n\n # Loading data\n data_indexes = load_string_list_file(path_data_indexes)\n data_train_1 = load_string_list_file(path_train_1)\n data_train_2 = load_string_list_file(path_train_2)\n data_test_1 = load_string_list_file(path_test_1)\n data_test_2 = load_string_list_file(path_test_2)\n data_validation_1 = load_string_list_file(path_validation_1)\n data_validation_2 = load_string_list_file(path_validation_2)\n\n # Generating data lists\n list_data_train = [data_train_1, data_train_2]\n list_data_test = [data_test_1, data_test_2]\n list_data_validation = [data_validation_1, data_validation_2]\n\n print('>> Building metada...')\n\n # Building PIPA metadata\n data_built = build_PIPA(data_indexes, path_images_full)\n\n print('>> ...done!')\n print('>> Adding objects information...')\n\n # Adding objects PIPA metadata\n data_built = add_objects(data_built, path_objects)\n\n print('>> ...done!')\n print('>> Saving built data to: %s' % path_save_built)\n\n # Saving built data\n save_json_file(path_save_built, data_built, args.ordered)\n\n print('>> Processing metada...')\n\n # Processing PIPA metadata\n data_built, dict_splits = process_PIPA(\n data_built, list_data_train, list_data_test, list_data_validation, path_images_face, path_images_body, path_images_full)\n\n print('>> ...done!')\n print('>> Saving final data to: %s' % path_save_final)\n\n # Saving metadata\n save_json_file(path_save_final, data_built, args.ordered)\n\n # Saving split lists\n for split in dict_splits:\n\n path_save_split_domain = os.path.join(\n path_split_domain, split + '.json')\n path_save_split_relationship = os.path.join(\n path_split_relationship, split + '.json')\n print('>> Saving ' + split + ' data to: %s' %\n path_save_split_domain)\n print('>> Saving ' + split + ' data to: %s' %\n path_save_split_relationship)\n\n save_json_file(path_save_split_domain,\n dict_splits[split], args.ordered)\n save_json_file(path_save_split_relationship,\n dict_splits[split], args.ordered)\n\n print('>> PIPA dataset processing finished!')\n\n else:\n\n print('>> [PRE-PROCESSING]')\n print('>> People in Social Context (PISC) dataset')\n\n # Generating PISC specific paths\n path_data_image = os.path.join(path_annotations, 'image_info.json')\n path_data_domain = os.path.join(path_annotations, 'domain.json')\n path_data_relationship = os.path.join(\n path_annotations, 'relationship.json')\n path_data_occupation = os.path.join(\n path_annotations, 'occupation.json')\n\n print('>> Loading dataset from: %s' % path_dataset)\n\n # Loading data\n data_image = load_json_file(path_data_image)\n data_domain = load_json_file(path_data_domain)\n data_relationship = load_json_file(path_data_relationship)\n data_occupation = load_json_file(path_data_occupation)\n\n print('>> Building metadata...')\n\n # Building PISC metadata\n data_built = build_PISC(data_image, data_domain,\n data_relationship, data_occupation)\n\n print('>> ...done!')\n print('>> Adding objects information...')\n\n # Adding objects PISC metadata\n data_final = add_objects(data_built, path_objects)\n\n print('>> ...done!')\n print('>> Saving final data to: %s' % path_save_final)\n\n # Saving final data\n save_json_file(path_save_final, data_final, args.ordered)\n\n print('>> PISC dataset processing finished!')\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser(description='Dataset pre-processing')\n parser.add_argument('path_datasets', type=str, help='path to datasets')\n parser.add_argument('dataset', type=str, help='datasets to process', choices=[\n 'PIPA',\n 'PISC'\n ])\n parser.add_argument('--ordered', action='store_true',\n help='save json ordered')\n\n args = parser.parse_args()\n pre_process(args)\n","repo_name":"verlab/Structural_Reasoning_SRR","sub_path":"social_relation_recognition/process_datasets.py","file_name":"process_datasets.py","file_ext":"py","file_size_in_byte":20594,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"} +{"seq_id":"5610058029","text":"a = int(input(\"Enter first number : \"))\nb = int(input(\"Enter second number : \"))\nflag = 0\nwhile(flag!=1):\n choice = int(input(\"1.) for addition \\n2.) for subtraction \\n3.) for multiplication \\n4.) for division \\n5.)to quit \\n:::\"))\n if(choice == 1):\n print(\"the addition of the numbers is : \",a+b)\n elif(choice == 2):\n print(\"The subtraction of the numbers is : \",a-b)\n elif(choice == 3):\n print(\"The multiplication of the numbers is : \",a*b)\n elif(choice == 4):\n print(\"The division of the numbers is : \",a/b)\n elif(choice == 5):\n flag = 1\n else:\n print(\"invalid input\")\n","repo_name":"Ash-Smithy/The_Repository","sub_path":"Sem3/Pre final/arithemetic_operations.py","file_name":"arithemetic_operations.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"70206883347","text":"'''20230605 sentinel2_extract_swir.py'''\nfrom misc import err, args, exist, run, parfor\nfrom envi import envi_header_cleanup\nimport multiprocessing as mp\nfrom osgeo import gdal\nimport numpy as np\nimport sys\nimport os\n\ndef extract(file_name):\n w = file_name.split('_') # split filename on '_'\n ds = w[2].split('T')[0] # date string\n stack_fn = file_name[:-4] + '.bin' # output stack filename\n \n if exist(stack_fn):\n print(\"Exists:\", stack_fn, \"skipping..\")\n return\n\n def ignore_warnings(x, y, z): pass\n gdal.PushErrorHandler(ignore_warnings) # suppress warnings\n \n d = gdal.Open(file_name)\n subdatasets = d.GetSubDatasets()\n desired_metadata = [{\"BANDNAME\": \"B12\"},\n {\"BANDNAME\": \"B11\"},\n {\"BANDNAME\": \"B9\"}]\n sbs={}\n arrays = {}\n selected_bands = []\n for subdataset in d.GetSubDatasets(): # select bands\n subdataset_path = subdataset[0]\n subdataset_dataset = gdal.Open(subdataset_path)\n \n for i in range(1, subdataset_dataset.RasterCount + 1):\n band = subdataset_dataset.GetRasterBand(i)\n band_metadata = band.GetMetadata()\n print(band_metadata) \n \n for k in band_metadata:\n for j in desired_metadata:\n try:\n if band_metadata[k] == j[k]: # print(\"Selected: \", band_metadata)\n selected_bands += [[band, band_metadata, subdataset_dataset]]\n sbs[band_metadata['BANDNAME']] = selected_bands[-1]\n arrays[str(band_metadata)] = band.ReadAsArray().astype(np.float32)\n except: pass\n \n selected_bands = [sbs['B12'], sbs['B11'], sbs['B9']] # reorder band selection\n \n resampled_bands = []\n target_sub_ds = selected_bands[0][2]\n geo_xform = target_sub_ds.GetGeoTransform()\n target_xs, target_ys = geo_xform[1], geo_xform[5]\n driver = gdal.GetDriverByName('ENVI')\n stack_ds = driver.Create(stack_fn, target_sub_ds.RasterXSize, target_sub_ds.RasterYSize, 3, gdal.GDT_Float32)\n stack_ds.SetProjection(target_sub_ds.GetProjection())\n stack_ds.SetGeoTransform(target_sub_ds.GetGeoTransform())\n \n bi = 1\n for [band, m, sub_dataset] in selected_bands:\n band_name = m['BANDNAME']\n geotransform = sub_dataset.GetGeoTransform()\n px_sx, px_sy = geotransform[1], geotransform[5]\n \n if band_name == \"B9\":\n mem_driver = gdal.GetDriverByName('MEM')\n input_ds = mem_driver.Create('', band.XSize, band.YSize, 1, gdal.GDT_Float32)\n input_ds.SetGeoTransform(sub_dataset.GetGeoTransform())\n input_ds.SetProjection(sub_dataset.GetProjection())\n input_ds.GetRasterBand(1).WriteArray(arrays[str(m)])\n \n resampled_geotransform = list(input_ds.GetGeoTransform())\n resampled_geotransform[1] = target_xs\n resampled_geotransform[5] = target_ys\n resampled_ds = mem_driver.Create('', target_sub_ds.RasterXSize, target_sub_ds.RasterYSize, 1, gdal.GDT_Float32)\n resampled_ds.SetGeoTransform(resampled_geotransform)\n resampled_ds.SetProjection(input_ds.GetProjection())\n \n gdal.Warp(resampled_ds, input_ds, xRes=target_xs, yRes=target_ys, resampleAlg='bilinear')\n arrays[str(m)] = resampled_ds.GetRasterBand(1).ReadAsArray()\n resampled_ds = None\n input_ds = None\n \n rb = stack_ds.GetRasterBand(bi)\n rb.WriteArray(arrays[str(m)])\n rb.SetDescription(' '.join([ds, # dates string\n str(int(px_sx)) + 'm:', # resolution\n band_name, # band name and wavelength\n str(m['WAVELENGTH']) + str(m['WAVELENGTH_UNIT'])]))\n arrays[str(m)] = None\n bi += 1\n \n stack_ds = None\n hdr_f = file_name[:-4] + '.hdr'\n envi_header_cleanup([None, hdr_f])\n xml_f = stack_fn + '.aux.xml'\n hdr_b = hdr_f + '.bak'\n for f in [xml_f, hdr_b]:\n if os.path.exists(f):\n os.remove(f)\n run('raster_zero_to_nan ' + stack_fn)\n\n\nif __name__ == \"__main__\":\n \n file_name = None\n if len(args) == 2:\n file_name = args[1]\n if not exist(file_name):\n err('could not open input file: ' + d)\n if not file_name[-4:] == '.zip':\n err('zip expected')\n extract(file_name)\n\n else:\n files = [x.strip() for x in os.popen(\"ls -1 S*MSIL2A*.zip\").readlines()]\n files += [x.strip() for x in os.popen(\"ls -1 S*MSIL1C*.zip\").readlines()]\n\n parfor(extract, files, int(mp.cpu_count()))\n","repo_name":"bcgov/wps-research","sub_path":"py/sentinel2_extract_swir.py","file_name":"sentinel2_extract_swir.py","file_ext":"py","file_size_in_byte":4729,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"48"} +{"seq_id":"16952706649","text":"import json\nfrom urllib import request\n\nfrom core.MsgTool import MsgTool as MT\nfrom core.Plugin import Plugin\n\n\"\"\"\n在下面加入你自定义的插件,自动加载本文件所有的 Plugin 的子类\n只需要写一个 Plugin 的子类,重写 match() 和 handle()\nmatch() 返回 True 则自动回调 handle()\n\"\"\"\n\n# 请自己到 `https://www.alapi.cn` 注册账号并获取token\ng_token = 'EmY3BKCuiYrt4BBS'\n\nclass TestPlugin(Plugin):\n def match(self):\n if self.context[\"post_type\"] != \"message\":\n return False\n text = MT.get_text_from_msg(self.context[\"message\"]).strip()\n if text.startswith('#快递查询'):\n self.my_number = text[len(\"#快递查询\"):].strip()\n return True\n return False\n\n def handle(self):\n url = \"https://v2.alapi.cn/api/kd?token={}&number={}&order=desc\".format(g_token,self.my_number)\n req = request.Request(url)\n res = request.urlopen(req).read().decode()\n js = json.loads(res)\n code = js['code']\n if code != 200:\n self.send_msg(MT.at(self.context[\"user_id\"]), MT.text('单号{}查询失败:{}'.format(self.my_number,code)))\n return\n js_data = js['data']\n com = js_data['com']\n state_str = ['未知','正常','派送中','已签收','退回','其他问题'][js_data['state']]\n tm = js_data['info'][0]['time']\n cont = js_data['info'][0]['content']\n ret_text = '单号{}查询成功!\\n快递公司:{}\\n状态:{}\\n时间:{}\\n{}'.format(self.my_number,com,state_str,tm,cont)\n if self.context[\"message_type\"] != 'group':\n self.send_msg(MT.text(ret_text))\n else:\n self.send_msg(MT.at(self.context[\"user_id\"]), MT.text('\\n'), MT.text(ret_text))\n","repo_name":"super1207/myvoidbot","sub_path":"plus/express_plus/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"zh","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"74563690386","text":"#!/usr/bin/python3\nimport requests\nfrom bs4 import BeautifulSoup\nimport re\n\n#url = \"http://www.runoob.com/html/html-editors.html\"\n#url = \"http://www.runoob.com/java/java-polymorphism.html\"\n#url = \"http://www.runoob.com/html/html-tutorial.html\"\n#url = \"http://www.runoob.com/html/html5-canvas.html\"\n#url = \"http://www.runoob.com/html/html5-form-input-types.html\"\nurl = \"http://www.runoob.com/vue2/vue-class-style.html\"\nsess = requests.Session()\nres = sess.get(url)\nres.encoding = 'utf-8'\nhtml_doc = res.text\nsoup = BeautifulSoup(html_doc, 'html.parser')\nregx = re.compile(\"实例\")\ndef handle(txt:str,name='default.log'):\n\tif re.match(regx,txt):\n\t\tprint(txt)\ntar = soup.find_all(id=\"content\")[0]\ntitle = \"default\"\ntitle = tar.find_all('h1')[0]\ntitle = re.sub(\" \",\"\",title.string)\nh2s = tar.find_all('h2')\nfor i in h2s:\n\thandle(str(i.string),title)\nprint('title is %s'%title)","repo_name":"fingerecho/baserouter","sub_path":"ContentCollect/get-article-intro-example-all-p-span.py","file_name":"get-article-intro-example-all-p-span.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26301893196","text":"import os \nimport joblib \nimport argparse\nimport pandas as pd \nfrom azureml.core import Run\nfrom sklearn.ensemble import RandomForestClassifier\n\n# Argument parsing \nparser = argparse.ArgumentParser()\nparser.add_argument('--num_tree', type=int, dest='num_tree', default=10)\nargs = parser.parse_args()\nn_tree = args.num_tree\n\n# Getting data \ndf = pd.read_csv('Data/iris.csv')\nX = df.copy()\ny = X.pop('y')\n\n# Training model \nmodel = RandomForestClassifier(n_estimators=n_tree)\nmodel.fit(X, y)\nacc = model.score(X, y)\n\n# Log \nrun = Run.get_context()\nrun.log('Accuracy', acc)\n\nos.makedirs('outputs', exist_ok=True)\njoblib.dump(value=model, filename='outputs/model.pkl')\n\nrun.complete()","repo_name":"roshankoirala/Azure_ML","sub_path":"script_3.py","file_name":"script_3.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41513143713","text":"# ActivitySim\n# See full license in LICENSE.txt.\nimport logging\n\nimport numpy as np\n\nfrom activitysim.abm.models.util import estimation\nfrom activitysim.core import config, expressions, inject, pipeline, simulate, tracing\n\nlogger = logging.getLogger(\"activitysim\")\n\n\n@inject.step()\ndef av_ownership(households_merged, households, chunk_size, trace_hh_id):\n \"\"\"\n This model predicts whether a household owns an autonomous vehicle.\n The output from this model is TRUE or FALSE.\n \"\"\"\n\n trace_label = \"av_ownership\"\n model_settings_file_name = \"av_ownership.yaml\"\n\n choosers = households_merged.to_frame()\n model_settings = config.read_model_settings(model_settings_file_name)\n\n logger.info(\"Running %s with %d households\", trace_label, len(choosers))\n\n estimator = estimation.manager.begin_estimation(\"av_ownership\")\n\n constants = config.get_model_constants(model_settings)\n av_ownership_alt = model_settings.get(\"AV_OWNERSHIP_ALT\", 0)\n\n # - preprocessor\n preprocessor_settings = model_settings.get(\"preprocessor\", None)\n if preprocessor_settings:\n\n locals_d = {}\n if constants is not None:\n locals_d.update(constants)\n\n expressions.assign_columns(\n df=choosers,\n model_settings=preprocessor_settings,\n locals_dict=locals_d,\n trace_label=trace_label,\n )\n\n model_spec = simulate.read_model_spec(file_name=model_settings[\"SPEC\"])\n coefficients_df = simulate.read_model_coefficients(model_settings)\n nest_spec = config.get_logit_model_settings(model_settings)\n\n if estimator:\n estimator.write_model_settings(model_settings, model_settings_file_name)\n estimator.write_spec(model_settings)\n estimator.write_coefficients(coefficients_df)\n estimator.write_choosers(choosers)\n\n # - iterative single process what-if adjustment if specified\n iterations = model_settings.get(\"AV_OWNERSHIP_ITERATIONS\", 1)\n iterations_coefficient_constant = model_settings.get(\n \"AV_OWNERSHIP_COEFFICIENT_CONSTANT\", None\n )\n iterations_target_percent = model_settings.get(\"AV_OWNERSHIP_TARGET_PERCENT\", None)\n iterations_target_percent_tolerance = model_settings.get(\n \"AV_OWNERSHIP_TARGET_PERCENT_TOLERANCE\", 0.01\n )\n\n for iteration in range(iterations):\n\n logger.info(\n \"Running %s with %d households iteration %d\",\n trace_label,\n len(choosers),\n iteration,\n )\n\n # re-read spec to reset substitution\n model_spec = simulate.read_model_spec(file_name=model_settings[\"SPEC\"])\n model_spec = simulate.eval_coefficients(model_spec, coefficients_df, estimator)\n\n choices = simulate.simple_simulate(\n choosers=choosers,\n spec=model_spec,\n nest_spec=nest_spec,\n locals_d=constants,\n chunk_size=chunk_size,\n trace_label=trace_label,\n trace_choice_name=\"av_ownership\",\n estimator=estimator,\n )\n\n if iterations_target_percent is not None:\n # choices_for_filter = choices[choosers[iterations_chooser_filter]]\n\n current_percent = (choices == av_ownership_alt).sum() / len(choosers)\n logger.info(\n \"Running %s iteration %i choosers %i current percent %f target percent %f\",\n trace_label,\n iteration,\n len(choosers),\n current_percent,\n iterations_target_percent,\n )\n\n if current_percent <= (\n iterations_target_percent + iterations_target_percent_tolerance\n ) and current_percent >= (\n iterations_target_percent - iterations_target_percent_tolerance\n ):\n logger.info(\n \"Running %s iteration %i converged with coefficient %f\",\n trace_label,\n iteration,\n coefficients_df.value[iterations_coefficient_constant],\n )\n break\n\n else:\n new_value = (\n np.log(\n iterations_target_percent / np.maximum(current_percent, 0.0001)\n )\n + coefficients_df.value[iterations_coefficient_constant]\n )\n coefficients_df.value[iterations_coefficient_constant] = new_value\n logger.info(\n \"Running %s iteration %i new coefficient for next iteration %f\",\n trace_label,\n iteration,\n new_value,\n )\n iteration = iteration + 1\n\n choices = choices == av_ownership_alt\n\n if estimator:\n estimator.write_choices(choices)\n choices = estimator.get_survey_values(choices, \"households\", \"av_ownership\")\n estimator.write_override_choices(choices)\n estimator.end_estimation()\n\n households = households.to_frame()\n households[\"av_ownership\"] = (\n choices.reindex(households.index).fillna(0).astype(bool)\n )\n\n pipeline.replace_table(\"households\", households)\n\n tracing.print_summary(\"av_ownership\", households.av_ownership, value_counts=True)\n\n if trace_hh_id:\n tracing.trace_df(households, label=trace_label, warn_if_empty=True)\n","repo_name":"camsys/SANDAG-ABM","sub_path":"src/asim/extensions/av_ownership.py","file_name":"av_ownership.py","file_ext":"py","file_size_in_byte":5376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"38521341855","text":"import argparse\nfrom infer_util import *\n\ndef main(args):\n platform = args.platform\n model_dir = args.model_dir\n batch = args.batch\n run_benchmark = args.run_benchmark\n param_type = args.param_type\n warm_up = args.warm_up\n debug = args.debug\n\n if run_benchmark == False and batch != 1:\n batch = 1\n print(\"[WARNING] if run_benchmark is False, batch must be equal 1\")\n model = None\n if platform == \"Paddle\":\n model = infer_paddle(model_dir, batch, run_benchmark, param_type, warm_up, debug)\n elif platform == \"QuakeRT\":\n model = infer_quakert(model_dir, batch, run_benchmark, param_type, warm_up, debug)\n else:\n print(\"[ERROR] Not support platform\")\n return\n\n model.run()\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Benchmark describe.')\n parser.add_argument(\n \"-p\",\n \"--platform\",\n type=str,\n default=\"Paddle\",\n help=\"Test platform type, support Paddle or QuakeRT, default is Paddle.\")\n parser.add_argument(\n \"-m\",\n \"--model_dir\",\n type = str,\n default=\"/usr/local/quake/datas/benchmark/model\",\n help=\"Test model path, default is /usr/local/quake/datas/benchmark/model.\")\n parser.add_argument(\n \"-b\",\n \"--batch\",\n type=int,\n default=1,\n help=\"Test batch size, default is 1.\")\n\n parser.add_argument(\n \"-t\",\n \"--param_type\",\n type=str,\n default=\"fp32\",\n help=\"Inference data type, support fpr32 | fp16 | int8,default is fp32.\")\n\n parser.add_argument(\n \"-r\",\n \"--run_benchmark\",\n type=bool,\n default=False,\n help=\"run benchmark test, default is False.\")\n\n parser.add_argument(\n \"-w\",\n \"--warm_up\",\n type=int,\n default=100,\n help=\"Warm-up times, default is 100.\")\n\n parser.add_argument(\n \"-d\",\n \"--debug\",\n type=bool,\n default=False,\n help=\"open debug, default is False.\")\n\n args = parser.parse_args()\n print(args)\n main(args)","repo_name":"Archermmt/yolov3_dcn_nv_hackthon2021","sub_path":"benchmark/infer.py","file_name":"infer.py","file_ext":"py","file_size_in_byte":2113,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"48"} +{"seq_id":"22624060551","text":"\"\"\" AUTOMATE AMAZON PRICE TRACKING, IF THE PRODUCT PRICE HITS THE DESIRED PRICE, SEND AN EMAIL TO SELF\"\"\"\r\nfrom bs4 import BeautifulSoup\r\nimport requests\r\nimport smtplib\r\n\r\n# Get the HTML of amazon website\r\nURL = \"https://www.amazon.com/Dell-S2721D-Ultra-Thin-DisplayPort-Certified/dp/B08G8SH4QJ/ref=sr_1_3?crid=3JSPYWW5VL\" \\\r\n \"545&dchild=1&keywords=27%2Binch%2Bmonitor%2B1440p&qid=1618346518&sprefix=27%2Binch%2Bmonitor%2B14%2Caps%2C255&\" \\\r\n \"sr=8-3&th=1\"\r\nHEADERS = {\r\n \"Accept-Encoding\": \"gzip, deflate\",\r\n \"Accept-Language\": \"en-US,en;q=0.9,es;q=0.8\",\r\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)\"\r\n \" Chrome/89.0.4389.114 Safari/537.36\",\r\n}\r\nDESIRED_PRICE = 240.00\r\n\r\nresponse = requests.get(URL, headers=HEADERS)\r\nweb_html = response.text\r\n\r\n# Create a BeautifulSoup object and scrape the price of the product\r\nsoup = BeautifulSoup(web_html, \"html.parser\")\r\nprice_tags = soup.find_all(name=\"span\",\r\n id=\"priceblock_ourprice\",\r\n class_=\"a-size-medium a-color-price priceBlockBuyingPriceString\")\r\nproduct_price = price_tags[0].getText()\r\nproduct_price = float(product_price[1:])\r\nprint(f\"The current price of the 27 inch Dell ultra-sharp monitor is: ${product_price}\")\r\n\r\n# Send an email if the product price hits the desired price\r\nmessage = f\"The current price of Dell S2721D 27 Inch 1440p QHD is ${product_price}, \\n\" \\\r\n f\"LINK: {URL}\"\r\nif product_price <= DESIRED_PRICE:\r\n connection = smtplib.SMTP(\"smtp.gmail.com\", 587)\r\n connection.starttls()\r\n sender_email = \"YOUR EMAIL ADDRESS\"\r\n g_app = \"YOUR EMAIL's PASSWORD\"\r\n try:\r\n connection.login(sender_email, g_app)\r\n except smtplib.SMTPAuthenticationError or smtplib.SMTPSenderRefused:\r\n print(\"Connection failed\")\r\n connection.sendmail(sender_email, sender_email, msg=f\"Subject: Dell S2721D 27 Inch 1440p QHD PRICE DROPPED!\\n\\n\"\r\n f\"{message}\")\r\n connection.quit()\r\n","repo_name":"armying/amazon_price_tracker","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2071,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37760601785","text":"# 틀렸던 이유 : 절대값을 고려하지 못함.\n# 내접을 구하는 코드를 쓰는 과정에서 r1 - r2가 마이너스 값이 나올 수 있다는 것을 고려하지 못함.\n# 케이스마다 다 구해야 하기 때문에 꽤 복잡한 문제인듯. \nimport math\n\nT = int(input())\n\nfor i in range(T) :\n x1, y1, r1, x2, y2, r2 = map(int, input().split())\n dist = math.sqrt((x2-x1)**2 + (y2-y1)**2)\n\n # 두 점이 같은 좌표일 때\n if x1 == x2 and y1 == y2 :\n # 두 원이 서로 완전히 겹칠 때\n if r1 == r2 :\n print(-1)\n # 원 안에 원이 겹치지 않고 포함되어 있을 때\n else :\n print(0)\n # 서로 다른 좌표일 때\n else :\n # 두 원이 완전히 떨어져 있을 때, 원 안에 원이 겹치지 않고 포함되어 있을 때\n if r1 + r2 < dist or r1 > dist + r2 or r2 > dist + r1 :\n print(0)\n # 내접 or 외접\n elif abs(r1 - r2) == dist or r1 + r2 == dist :\n print(1)\n # 그 외에는 두 원이 서로 겹칠 때\n else :\n print(2)","repo_name":"KangGeonyoung/Algorithm","sub_path":"Baekjoon/14. 기하1/1002.py","file_name":"1002.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28827197866","text":"import pytest\nfrom scripts.deploy import deploy_lottery\n\nfrom brownie import Lottery, accounts, config, network, exceptions\nfrom scripts.helpful_scripts import (\n LOCAL_BLOCKCHAIN_ENVIRONMENTS,\n get_account,\n fund_with_link,\n get_contract,\n)\n\n\n@pytest.fixture(autouse=True)\ndef lottery():\n print(\"Testing...\")\n if network.show_active() not in LOCAL_BLOCKCHAIN_ENVIRONMENTS:\n pytest.skip()\n print(\"Deploying Smart Contract...\")\n lottery = deploy_lottery()\n\n account = get_account()\n\n print(f\"You are in {network.show_active()} network\")\n\n return (lottery, account)\n","repo_name":"emrahsariboz/chainlink_lottery","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26267149071","text":"\nimport numpy as np\nfrom scipy.linalg import eigh\nimport plotly.graph_objects as go\n\n# PROGRAM DE UMA VIGA EULER-BERNOULLI\n\nclass BeamEB:\n \"\"\"Creates a beam element using Euler-Bernoulli theory, considering 2 degrees of freedom per node.\n\n Parameters\n ----------\n L : float\n Length of the beam.\n h : float\n Height of the beam\n b : float\n Width of the beam.\n E : float\n Young's modulus.\n rho : float\n Density.\n n_ef : int\n Number of finite elements.\n \n Attributes\n ----------\n matrices : tuple\n Contains the stiffness and mass global matrices, respectively.\n \"\"\" \n\n def __init__(self,L,h,b,E,rho,n_ef):\n \n self.L = L\n self.h = h\n self.b = b\n self.n_ef = n_ef\n self.n_gdl = 2\n\n self.E = E\n self.rho = rho\n \n self.A = b*h\n self.I = (b*(h**3))/12\n self.L_ef = L / n_ef\n\n self.n_nos = n_ef + 1\n \n self.n_DOF = self.n_gdl * self.n_nos\n\n self.done = False\n\n self.matrices = self.mountMatrices()\n\n def mountMatrices(self):\n \"\"\"Mounts the Stiffness and Mass global matrices.\n\n Returns\n -------\n KK : numpy.ndarray\n Stiffness global matrix.\n MM : numpy.ndarray\n Mass global matrix.\n \"\"\"\n\n mat_connect = np.zeros((self.n_ef,2))\n for ii in range(self.n_ef):\n mat_connect[ii,:] = [ii,ii+1]\n\n gdl = np.arange(0,self.n_DOF,1) # gdl = 0:1:n_DOF\n\n self.mat_gdl = np.zeros((self.n_nos,self.n_gdl))\n\n for ii in range(self.n_nos):\n self.mat_gdl[ii,:] = gdl[:self.n_gdl]\n gdl = np.delete(gdl,range(self.n_gdl))\n\n MC = np.zeros((self.n_ef,2*self.n_gdl))\n for ii in range(self.n_ef):\n MC[ii,:self.n_gdl] = self.mat_gdl[int(mat_connect[ii,0])]\n MC[ii,-self.n_gdl:] = self.mat_gdl[int(mat_connect[ii,1])]\n \n KK = np.zeros((self.n_DOF,self.n_DOF))\n MM = np.zeros((self.n_DOF,self.n_DOF))\n II = np.identity(self.n_DOF)\n\n K = self.K(self.E,self.L_ef,self.I)\n M = self.M(self.L_ef)\n\n for ii in range(self.n_ef):\n aux = II[MC.astype(int)[ii,:],:]\n\n KK = KK + (aux.T.dot(K)).dot(aux)\n MM = MM + (aux.T.dot(M)).dot(aux)\n\n return KK,MM\n\n def K(self,E, L_ef, I):\n \"\"\"Elemental stiffness matrix\n\n Parameters\n ----------\n E : float\n Young's modulus.\n L_ef : float\n Length of each element.\n I : float\n Moment of inertia.\n\n Returns\n -------\n K : numpy.ndarray\n Stiffness elemental matrix.\n \"\"\"\n K = np.array([\n [ (12*E*I)/(L_ef**3), (6*E*I)/(L_ef**2), -(12*E*I)/(L_ef**3), (6*E*I)/(L_ef**2)],\n [ (6*E*I)/(L_ef**2), (4*E*I)/L_ef, -(6*E*I)/(L_ef**2), (2*E*I)/L_ef],\n [ -(12*E*I)/(L_ef**3), -(6*E*I)/(L_ef**2), (12*E*I)/(L_ef**3), -(6*E*I)/(L_ef**2)],\n [ (6*E*I)/(L_ef**2), (2*E*I)/L_ef, -(6*E*I)/(L_ef**2), (4*E*I)/L_ef],\n ]\n )\n \n return K\n \n def M(self,L_ef):\n \"\"\"Elemental Mass matrix\n\n Parameters\n ----------\n L_ef : float\n Length of each element.\n\n Returns\n -------\n M : numpy.ndarray\n Mass elemental matrix.\n \"\"\" \n\n M = np.array([\n [ (13*L_ef)/35, (11*L_ef**2)/210, (9*L_ef)/70, -(13*(L_ef**2))/420],\n [ (11*(L_ef**2))/210, (L_ef**3)/105, (13*(L_ef**2))/420, -(L_ef**3)/140],\n [ (9*L_ef)/70, (13*(L_ef**2))/420, (13*L_ef)/35, -(11*(L_ef**2))/210],\n [ -(13*(L_ef**2))/420, -(L_ef**3)/140, -(11*(L_ef**2))/210, (L_ef**3)/105],\n ]\n )\n\n return self.rho*self.A*M\n\n def runVibrationModes(self):\n \"\"\"Executes the calculus to find the vibration modes of the beam.\n\n Paramters\n ---------\n plot : bool, optional\n Set it False not to plot the vibration modes, and True to do it. Defaults is True.\n\n Returns\n -------\n modo : numpy.ndarray\n The matrix with the vibration modes of the beam. Shape is number of elements per vibration modes.\n \"\"\"\n\n KK = self.matrices[0]\n MM = self.matrices[1]\n\n noE = 0\n ddlE = np.array([np.arange(0,self.n_gdl)],dtype=int)\n posE = self.mat_gdl[noE,ddlE].astype(int)\n\n MM = np.delete(MM,posE,0)\n MM = np.delete(MM,posE,1)\n\n KK = np.delete(KK,posE,0)\n KK = np.delete(KK,posE,1)\n\n # Análise dos modos\n\n modo = self.solveProblem(KK,MM)\n\n self.done = True\n self.modo = modo\n \n print(\"\\n Modos de Vibrar calculados! \\n\")\n\n return modo\n\n def solveProblem(self,KK,MM):\n \"\"\"Executes the solution the eigenvalues and eigenvector's problem.\n\n Parameters\n ----------\n KK : numpy.ndarray\n Stiffness global matrix.\n MM : numpy.ndarray\n Mass global matrix.\n\n Returns\n -------\n modo : numpy.ndarray\n Eigenvectors matrix.\n \"\"\"\n\n U, D = eigh(KK,MM)\n\n v = np.arange(0,len(D[:,0]),self.n_gdl)\n\n modo = D[v.astype(int),:]\n modo = modo/modo[-1]\n\n return modo\n\n def plot(self, qtd_modos=5):\n\n if self.done:\n \n fig = go.Figure()\n\n Lo = np.arange(0,self.L,self.L_ef)\n\n for mode in range(qtd_modos):\n fig.add_trace(go.Scatter(x=Lo,y=self.modo[:,mode],name=f\"{mode + 1} modo de vibrar\", showlegend=True))\n\n fig.update_layout(title=\"Viga de Euler-Bernoulli e seus modos de vibrar\")\n fig.show()\n else:\n raise Exception(\"You need to run the vibration modes before plotting!\")\n\nif __name__ == '__main__':\n\n viga1 = BeamEB(0.35,0.02,0.06,7e10,2780,100)\n modo = viga1.runVibrationModes()\n viga1.plot()\n","repo_name":"LMEst-Rotor/tutorial-git","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6249,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"39092278144","text":"# _*_ coding:utf-8 _*_\n\nfrom flask import render_template, request, send_from_directory, g\nimport json\nimport doc_dal\nfrom . import doc\nfrom utils.is_json import is_json\nfrom utils.post_json import post_json\nfrom auth.user_dal import UserDal\nimport utils.jwt_utils as jwt_utils\nimport os\n\n\n# 通过id获取文档路由\n@doc.route('/get_doc_by_id', methods=['GET', 'POST'])\ndef get_doc_by_id():\n if request.method == 'GET':\n return post_json('error', '请使用post方法')\n elif request.method == 'POST':\n if is_json(request.get_data()):\n data = json.loads(request.get_data())\n if 'doc_id' in data.keys():\n doc_dict = doc_dal.DocDal.get_doc_by_id(data)\n else:\n return post_json('error', '输入参数不完整或者不正确')\n else:\n return post_json('error', '输入参数不完整或者不正确')\n if doc_dict is not None:\n return post_json('success', data=doc_dict)\n else:\n return post_json('error', '获取文档出错')\n else:\n return render_template('404.html')\n\n\n# 获取用户文档列表路由\n@doc.route('/doc_list', methods=['GET', 'POST'])\ndef get_doc_list():\n if request.method == 'GET':\n return post_json('error', '请使用post方法')\n elif request.method == 'POST':\n if g.string == 'token认证失败':\n return post_json('error', g.string)\n uid = jwt_utils.get_uid_token(request)[0]\n doc_list = doc_dal.DocDal().get_doc_list({'uid': uid})\n return post_json('success', data=doc_list)\n\n else:\n return render_template('404.html')\n\n\n# 获取文档类型\n@doc.route('/doc_temp', methods=['GET', 'POST'])\ndef doc_temp():\n if request.method == 'GET':\n return post_json('error', '请使用post方法')\n elif request.method == 'POST':\n if g.string == 'token认证失败':\n return post_json('error', g.string)\n doc_typeinfo = doc_dal.DocDal().get_doc_typeinfo()\n return post_json('success', data=dict(doctypeinfo=doc_typeinfo))\n else:\n return render_template('404.html')\n\n\n# 新建路由\n@doc.route('/doc_create', methods=['GET', 'POST'])\ndef doc_create():\n if request.method == 'GET':\n return post_json('error', '请使用post方法')\n elif request.method == 'POST':\n if g.string == 'token认证失败':\n return post_json('error', g.string)\n if is_json(request.get_data()):\n data = json.loads(request.get_data())\n uid = jwt_utils.get_uid_token(request)[0]\n data.update({'uid': uid})\n if 'docname' in data.keys() and 'doctype' in data.keys():\n new_doc = doc_dal.DocDal().insert_doc_and_get_doc(data)\n if new_doc is not None:\n # doc_id = new_doc['doc_id']\n # return post_json('success', data=dict(docid=doc_id))\n doc_dal.DocDal().copy_file(new_doc['doc_type'], new_doc['doc_id'])\n return post_json('success', '新建文档成功')\n else:\n return post_json('error', '新建文档出错')\n else:\n return post_json('error', '输入参数不完整或者不正确')\n else:\n return post_json('error', '输入参数不完整或者不正确')\n else:\n return render_template('404.html')\n\n\n# 删除文档路由\n@doc.route('/doc_delete', methods=['GET', 'POST'])\ndef doc_delete():\n if request.method == 'GET':\n return post_json('error', '请使用post方法')\n elif request.method == 'POST':\n if g.string == 'token认证失败':\n return post_json('error', g.string)\n if is_json(request.get_data()):\n data = json.loads(request.get_data())\n uid = jwt_utils.get_uid_token(request)[0]\n data.update({'uid': uid})\n if 'docid' in data.keys():\n rowcount = doc_dal.DocDal().delete_doc(data)\n if rowcount > 0:\n return post_json('success', '删除文档成功')\n else:\n return post_json('success', '删除文档出错')\n else:\n return post_json('error', '输入参数不完整或者不正确')\n else:\n return post_json('error', '输入参数不完整或者不正确')\n else:\n return render_template('404.html')\n\n\n# 获取文档章节目录路由\n@doc.route('/doc_chapter', methods=['GET', 'POST'])\ndef doc_chapter():\n if request.method == 'GET':\n return post_json('error', '请使用post方法')\n elif request.method == 'POST':\n if is_json(request.get_data()):\n data = json.loads(request.get_data())\n if 'uid' in data.keys() and 'docid' in data.keys():\n if UserDal.check_uid(data) is not None:\n result = doc_dal.DocDal().doc_chapter(data)\n if result is not None:\n doc_dict = result[0]\n doc_chapter_list = result[1]\n data = dict(\n docid=doc_dict['docid'],\n docname=doc_dict['docname'],\n doctype=doc_dict['doctype'],\n chapters=doc_chapter_list,\n )\n return post_json('success', data=data)\n else:\n return post_json('success', '提取目录出错')\n else:\n return post_json('error', '用户校验出错')\n else:\n return post_json('error', '输入参数不完整或者不正确')\n else:\n return post_json('error', '输入参数不完整或者不正确')\n else:\n return render_template('404.html')\n\n\n# 获取所有标签\n@doc.route('/doc_keywords', methods=['GET', 'POST'])\ndef doc_keywords():\n if request.method == 'GET':\n return post_json('error', '请使用post方法')\n elif request.method == 'POST':\n if is_json(request.get_data()):\n data = json.loads(request.get_data())\n if 'doctype' in data.keys():\n keywords = doc_dal.DocDal().get_doc_keywords(data)\n return post_json('success', data=keywords)\n else:\n return post_json('error', '输入参数不完整或者不正确')\n else:\n return post_json('error', '输入参数不完整或者不正确')\n else:\n return render_template('404.html')\n\n\n# 获取文档类型关键字返回内容\n@doc.route('/doc_type_keyword', methods=['GET', 'POST'])\ndef doc_type_keyword():\n if request.method == 'GET':\n return post_json('error', '请使用post方法')\n elif request.method == 'POST':\n if is_json(request.get_data()):\n data = json.loads(request.get_data())\n if 'doctype' in data.keys() and 'keyword' in data.keys():\n if 'page' in data.keys():\n if str(data['page']).isdigit() and int(data['page']) > 0:\n contentlist = doc_dal.DocDal().get_doc_type_keyword(data)\n return post_json('success', data=contentlist)\n else:\n return post_json('error', '输入参数不完整或者不正确')\n else:\n result = doc_dal.DocDal().get_doc_type_keyword(data)\n return post_json('success', data=result)\n else:\n return post_json('error', '输入参数不完整或者不正确')\n else:\n return post_json('error', '输入参数不完整或者不正确')\n else:\n return render_template('404.html')\n\n\n\n# 章节模块查询路由\n@doc.route('/doc_cl_check', methods=['GET', 'POST'])\ndef get_doc_cl_check():\n if request.method == 'GET':\n return post_json('error', '请使用post方法')\n elif request.method == 'POST':\n if is_json(request.get_data()):\n data = json.loads(request.get_data())\n if 'uid' in data.keys() and 'docid' in data.keys() and 'cpcode' in data.keys():\n if UserDal.check_uid(data) is not None:\n doc_cl_check = doc_dal.DocDal().get_doc_cl_check(data)\n if doc_cl_check is not None:\n return post_json('success', data=doc_cl_check)\n else:\n return post_json('error', '章节模块查询出错')\n else:\n return post_json('error', '用户校验出错')\n else:\n return post_json('error', '输入参数不完整或者不正确')\n else:\n return post_json('error', '输入参数不完整或者不正确')\n else:\n return render_template('404.html')\n\n\n# 计算数字标签数值\n@doc.route('/calc_nl_value', methods=['GET', 'POST'])\ndef calc_nl_value():\n if request.method == 'GET':\n return post_json('error', '请使用post方法')\n elif request.method == 'POST':\n if is_json(request.get_data()):\n data = json.loads(request.get_data())\n if 'uid' in data.keys() and 'docid' in data.keys() and 'cpcode' in data.keys() \\\n and 'llist' in data.keys():\n if UserDal.check_uid(data) is not None:\n calc_nl_value = doc_dal.DocDal().calc_nl_value(data)\n if calc_nl_value is not None:\n return post_json('success', data=calc_nl_value)\n else:\n return post_json('error', '标签提交出错')\n else:\n return post_json('error', '用户校验出错')\n else:\n return post_json('error', '输入参数不完整或者不正确')\n else:\n return post_json('error', '输入参数不完整或者不正确')\n else:\n return render_template('404.html')\n\n\n# 模块查询路由\n@doc.route('/doc_check_t', methods=['GET', 'POST'])\ndef doc_check_t():\n if request.method == 'GET':\n return post_json('error', '请使用post方法')\n elif request.method == 'POST':\n if is_json(request.get_data()):\n data = json.loads(request.get_data())\n if 'uid' in data.keys() and 'docid' in data.keys() and 'cpcode' in data.keys() \\\n and 'tmcode' in data.keys() and 'tminputcode' in data.keys():\n if UserDal.check_uid(data) is not None:\n tcontentlist = doc_dal.DocDal().doc_check_t(data)\n if doc_check_t is not None:\n return post_json('success', data=tcontentlist)\n else:\n return post_json('error', '模板查询出错')\n else:\n return post_json('error', '用户校验出错')\n else:\n return post_json('error', '输入参数不完整或者不正确')\n else:\n return post_json('error', '输入参数不完整或者不正确')\n else:\n return render_template('404.html')\n\n\n# 文档暂存路由\n@doc.route('/doc_save', methods=['GET', 'POST'])\ndef doc_save():\n if is_json(request.get_data()):\n data = json.loads(request.get_data())\n # with open(\"1.txt\", \"a\") as code:\n # code.write(request.path+\"\\n\"+request.url+\"\\n\"+request.get_data()+\"\\n\")\n if 'status' in data.keys() and 'url' in data.keys() and 'key' in data.keys():\n if data['status'] == 2:\n doc_path = doc_dal.DocDal().get_doc_path_by_key(data['key'])\n url = data['url']\n doc_dal.DocDal().save_file(url, doc_path, data['key'])\n return post_json('success', '保存成功')\n else:\n return \"{\\\"error\\\":0}\"\n else:\n return \"{\\\"error\\\":0}\"\n else:\n return \"{\\\"error\\\":0}\"\n\n\n# 文档保存路由\n@doc.route('/doc_save_temp', methods=['GET', 'POST'])\ndef doc_save_temp():\n if request.method == 'GET':\n return post_json('error', '请使用post方法')\n elif request.method == 'POST':\n if is_json(request.get_data()):\n data = json.loads(request.get_data())\n if 'uid' in data.keys() and 'docid' in data.keys() and 'cpcode' in data.keys() \\\n and 'cpcontent' in data.keys():\n if UserDal.check_uid(data) is not None:\n doc_save_return = doc_dal.DocDal().doc_save_temp(data)\n if doc_save_return is not None:\n return post_json('success', '暂存数据成功')\n else:\n return post_json('error', '数据暂存出错')\n else:\n return post_json('error', '用户校验出错')\n else:\n return post_json('error', '输入参数不完整或者不正确')\n else:\n return post_json('error', '输入参数不完整或者不正确')\n else:\n return render_template('404.html')\n\n\n# 获取文档下载地址路由\n@doc.route('/doc_download', methods=['GET', 'POST'])\ndef doc_download():\n if request.method == 'GET':\n return post_json('error', '请使用post方法')\n elif request.method == 'POST':\n if is_json(request.get_data()):\n data = json.loads(request.get_data())\n if 'uid' in data.keys() and 'docid' in data.keys():\n if UserDal.check_uid(data) is None:\n return post_json('error', '用户校验出错')\n if doc_dal.DocDal.get_doc_by_id(data) is None:\n return post_json('error', '该文档不存在或已删除')\n doc_url = doc_dal.DocDal().get_doc_url(data, request)\n if doc_url is not None:\n return post_json('success', data=doc_url)\n else:\n return post_json('error', '文档下载出错')\n else:\n return post_json('error', '输入参数不完整或者不正确')\n else:\n return post_json('error', '输入参数不完整或者不正确')\n else:\n return render_template('404.html')\n\n# 下载路由\n@doc.route('/download_file', methods=['GET', 'POST'])\ndef download_file():\n if request.method == 'POST':\n return post_json('error', '请使用get方法')\n elif request.method == 'GET':\n downloadFile = request.args.get('downloadFile')\n user_doc_dir = os.path.abspath(os.path.dirname(__file__) + '/' + '..' + '/' + '..' + '/user-doc')\n return send_from_directory(user_doc_dir, downloadFile, as_attachment=True)\n else:\n return render_template('404.html')\n","repo_name":"352doctools/document_tools_v2","sub_path":"app/doc/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":14835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"27229660602","text":"import time\nfrom uuid import uuid4\nfrom typing import Dict, Optional, Tuple, Sequence, Callable, Awaitable\nimport recurrent\nimport dateparser\nimport discord\nfrom discord.ext import commands as dc\nfrom watdo import dt\nfrom watdo.errors import CancelCommand\nfrom watdo.models import Profile, Task, ScheduledTask, DueT\nfrom watdo.safe_data import Timestamp\nfrom watdo.collections import TasksCollection\nfrom watdo.discord import Bot\nfrom watdo.discord.cogs import BaseCog\nfrom watdo.discord.embeds import Embed, TaskEmbed, PagedEmbed\n\n\nclass Tasks(BaseCog):\n @dc.hybrid_command() # type: ignore[arg-type]\n async def summary(self, ctx: dc.Context[Bot]) -> None:\n \"\"\"Show the summary of all your tasks.\"\"\"\n profile = await self.get_profile(ctx)\n tasks = await Task.get_tasks_of_profile(self.db, profile)\n\n embed = Embed(self.bot, \"TASKS SUMMARY\")\n\n total = 0\n is_important = 0\n overdue = 0\n recurring = 0\n one_time = 0\n done = 0\n max_categ_len = 0\n categories: Dict[str, int] = {}\n\n for task in tasks:\n total += 1\n\n if task.importance.value:\n is_important += 1\n\n if isinstance(task, ScheduledTask):\n if task.is_overdue:\n overdue += 1\n\n if isinstance(task, ScheduledTask) and task.is_recurring:\n recurring += 1\n else:\n one_time += 1\n\n if task.is_done:\n done += 1\n\n if len(task.category.value) > max_categ_len:\n max_categ_len = len(task.category.value)\n\n try:\n categories[task.category.value] += 1\n except KeyError:\n categories[task.category.value] = 1\n\n embed.add_field(name=\"Total\", value=total)\n embed.add_field(name=\"Important\", value=is_important)\n embed.add_field(name=\"Overdue\", value=overdue)\n embed.add_field(name=\"Recurring\", value=recurring)\n embed.add_field(name=\"One-Time\", value=one_time)\n embed.add_field(name=\"Done\", value=done)\n\n if categories:\n c = \"\\n\".join(\n f\"{k.ljust(max_categ_len)} {v}\" for k, v in categories.items()\n )\n embed.add_field(\n name=\"Categories\", value=f\"```\\n{c[:1000]}\\n```\", inline=False\n )\n\n await BaseCog.send(ctx, embed=embed)\n\n async def _send_tasks(\n self,\n ctx: dc.Context[Bot],\n tasks_getter: Callable[[], Awaitable[Sequence[Task]]],\n *,\n as_text: bool,\n is_simple: bool = False,\n ) -> None:\n async def embeds_getter() -> Tuple[discord.Embed, ...]:\n return tuple(\n TaskEmbed(self.bot, task, is_simple=is_simple)\n for task in await tasks_getter()\n )\n\n if as_text:\n tasks = await tasks_getter()\n\n if not tasks:\n await BaseCog.send(ctx, \"No tasks.\")\n return\n\n await BaseCog.send(ctx, self.tasks_to_text(tasks))\n return\n\n paged_embed = PagedEmbed(ctx, embeds_getter)\n await paged_embed.send()\n\n @dc.hybrid_command() # type: ignore[arg-type]\n async def list(\n self,\n ctx: dc.Context[Bot],\n category: Optional[str] = None,\n as_text: bool = False,\n ) -> None:\n \"\"\"Show your tasks list.\"\"\"\n\n async def tasks_getter() -> Sequence[Task]:\n tasks = await Task.get_tasks_of_profile(\n self.db, profile, category=category or None\n )\n tasks.sort_by_priority()\n return tasks.items\n\n profile = await self.get_profile(ctx)\n await self._send_tasks(ctx, tasks_getter, as_text=as_text)\n\n def _parse_due(self, ctx: dc.Context[Bot], due: str, utc_offset: float) -> DueT:\n tz = dt.utc_offset_to_tz(utc_offset)\n date = dateparser.parse(\n due,\n settings={\n \"RETURN_AS_TIMEZONE_AWARE\": True,\n \"TIMEZONE\": tz.tzname(dt.date_now(utc_offset)) or \"\",\n },\n )\n\n if date is not None:\n return date.timestamp() # type: ignore[return-value]\n\n rr: Optional[str | dt.datetime] = recurrent.parse(\n due,\n now=dt.date_now(utc_offset),\n )\n\n if isinstance(rr, str):\n if \"DTSTART:\" not in rr:\n date_now = dt.date_now(utc_offset)\n d = date_now.strftime(\"%Y%m%dT%H%M%S\")\n rr = f\"DTSTART:{d}\\n{rr}\"\n\n return rr # type: ignore[return-value]\n\n if isinstance(rr, dt.datetime_type):\n return rr.timestamp() # type: ignore[return-value]\n\n self.bot.loop.create_task(BaseCog.send(ctx, f\"Failed to parse `{due}`\"))\n raise CancelCommand()\n\n async def _update_task(\n self,\n ctx: dc.Context[Bot],\n profile: Profile,\n existing_task: Task,\n *,\n title: str,\n category: str,\n importance: float,\n energy: float,\n due: Optional[str],\n description: Optional[str],\n has_reminder: bool,\n is_auto_done: bool,\n ) -> None:\n if due is None:\n task = Task(\n # Copy from existing task\n existing_task.db,\n profile=existing_task.profile,\n profile_id=existing_task.profile_id.value,\n last_done=existing_task.last_done.value\n if existing_task.last_done\n else None,\n uuid=existing_task.uuid.value,\n created_at=existing_task.created_at.value,\n created_by=existing_task.created_by.value,\n channel_id=ctx.channel.id,\n #\n # From user input\n title=title,\n category=category,\n importance=importance,\n energy=energy,\n description=description,\n )\n else:\n task = ScheduledTask(\n # Copy from existing task\n existing_task.db,\n profile=existing_task.profile,\n profile_id=existing_task.profile_id.value,\n last_done=existing_task.last_done.value\n if existing_task.last_done\n else None,\n uuid=existing_task.uuid.value,\n created_at=existing_task.created_at.value,\n created_by=existing_task.created_by.value,\n channel_id=ctx.channel.id,\n #\n # From user input\n title=title,\n category=category,\n importance=importance,\n energy=energy,\n due=self._parse_due(ctx, due, profile.utc_offset.value),\n description=description,\n has_reminder=has_reminder,\n is_auto_done=is_auto_done,\n )\n\n task.next_reminder = Timestamp(task.due_date.timestamp())\n\n await task.save()\n await BaseCog.send(ctx, \"Task updated ✅\", embed=TaskEmbed(self.bot, task))\n\n async def _add_task(\n self,\n ctx: dc.Context[Bot],\n profile: Profile,\n *,\n title: str,\n category: str,\n importance: float,\n energy: float,\n due: Optional[str],\n description: Optional[str],\n has_reminder: bool,\n is_auto_done: bool,\n ) -> None:\n if due is None:\n task = Task(\n self.db,\n profile=profile,\n profile_id=profile.uuid.value,\n last_done=None,\n uuid=uuid4().hex,\n created_at=time.time(),\n created_by=ctx.author.id,\n channel_id=ctx.channel.id,\n #\n # From user input\n title=title,\n category=category,\n importance=importance,\n energy=energy,\n description=description,\n )\n else:\n task = ScheduledTask(\n self.db,\n profile=profile,\n profile_id=profile.uuid.value,\n last_done=None,\n uuid=uuid4().hex,\n created_at=time.time(),\n created_by=ctx.author.id,\n channel_id=ctx.channel.id,\n #\n # From user input\n title=title,\n category=category,\n importance=importance,\n energy=energy,\n due=self._parse_due(ctx, due, profile.utc_offset.value),\n description=description,\n has_reminder=has_reminder,\n is_auto_done=is_auto_done,\n )\n\n task.next_reminder = Timestamp(task.due_date.timestamp())\n\n await task.save()\n await BaseCog.send(ctx, \"Task added ✅\", embed=TaskEmbed(self.bot, task))\n\n @dc.hybrid_command() # type: ignore[arg-type]\n async def todo(\n self,\n ctx: dc.Context[Bot],\n title: str,\n category: str,\n importance: float,\n energy: float,\n due: Optional[str] = dc.parameter(\n default=None,\n description='**Examples:**\\n\"tomorrow at 5PM\"\\n\"every morning\"\\n\"in 3 hours\"',\n ),\n description: Optional[str] = None,\n has_reminder: bool = True,\n is_auto_done: bool = False,\n ) -> None:\n \"\"\"Add a task to do.\n **Use this please: https://nietsuu.github.io/watdo**\n If the title is a duplicate, the old task will be overwritten.\"\"\"\n\n if due == \"\":\n due = None\n\n profile = await self.get_profile(ctx)\n existing_task = await Task.from_title(self.db, profile, title)\n\n if existing_task is not None:\n await self._update_task(\n ctx,\n profile,\n existing_task,\n title=title,\n category=category,\n importance=importance,\n energy=energy,\n due=due,\n description=description,\n has_reminder=has_reminder,\n is_auto_done=is_auto_done,\n )\n else:\n await self._add_task(\n ctx,\n profile,\n title=title,\n category=category,\n importance=importance,\n energy=energy,\n due=due,\n description=description,\n has_reminder=has_reminder,\n is_auto_done=is_auto_done,\n )\n\n async def _get_do_tasks(\n self,\n ctx: dc.Context[Bot],\n category: Optional[str] = None,\n ) -> TasksCollection:\n profile = await self.get_profile(ctx)\n tasks = await Task.get_tasks_of_profile(\n self.db,\n profile,\n category=category or None,\n ignore_done=True,\n )\n return tasks\n\n @dc.hybrid_command(aliases=[\"do\"]) # type: ignore[arg-type]\n async def do_priority(\n self,\n ctx: dc.Context[Bot],\n category: Optional[str] = None,\n as_text: bool = False,\n ) -> None:\n \"\"\"Show priority tasks.\"\"\"\n\n async def tasks_getter() -> Sequence[Task]:\n tasks = await self._get_do_tasks(ctx, category)\n tasks.sort_by_priority()\n return tasks.items\n\n await self._send_tasks(ctx, tasks_getter, as_text=as_text, is_simple=True)\n\n @dc.hybrid_command(aliases=[\"dailies\"]) # type: ignore[arg-type]\n async def do_dailies(\n self,\n ctx: dc.Context[Bot],\n category: Optional[str] = None,\n as_text: bool = False,\n ) -> None:\n \"\"\"Show overdue daily tasks sorted by priority.\"\"\"\n\n async def tasks_getter() -> Sequence[Task]:\n tasks = await self._get_do_tasks(ctx, category)\n tasks.sort_by_priority()\n return tasks.get_dailies()\n\n await self._send_tasks(ctx, tasks_getter, as_text=as_text, is_simple=True)\n\n async def _confirm_task_action(\n self, ctx: dc.Context[Bot], title: str\n ) -> Tuple[Optional[discord.Message], Optional[Task]]:\n profile = await self.get_profile(ctx)\n task = await Task.from_title(self.db, profile, title=title)\n\n if task is None:\n await BaseCog.send(ctx, f'Task \"{title}\" not found ❌')\n return None, None\n\n message = await BaseCog.send(\n ctx,\n \"Are you sure?\",\n embed=TaskEmbed(self.bot, task),\n )\n is_confirm = await self.wait_for_confirmation(ctx, message)\n\n if is_confirm:\n return message, task\n\n return None, None\n\n @dc.hybrid_command() # type: ignore[arg-type]\n async def done(self, ctx: dc.Context[Bot], title: str) -> None:\n \"\"\"Mark a task as done. If the task is not a recurring task, it will get removed.\"\"\"\n task = await self.task_from_title(ctx, title)\n\n try:\n await task.done()\n except ValueError as error:\n await BaseCog.send(ctx, str(error))\n else:\n await BaseCog.send(ctx, embed=TaskEmbed(self.bot, task, is_simple=True))\n\n @dc.hybrid_command() # type: ignore[arg-type]\n async def cancel(self, ctx: dc.Context[Bot], title: str) -> None:\n \"\"\"Remove a task.\"\"\"\n message, task = await self._confirm_task_action(ctx, title)\n\n if (message is not None) and (task is not None):\n await task.delete()\n await message.edit(\n content=\"Cancelled ✅\",\n embed=TaskEmbed(self.bot, task),\n )\n\n @dc.hybrid_command() # type: ignore[arg-type]\n async def showdesc(self, ctx: dc.Context[Bot], title: str) -> None:\n \"\"\"Show the description of a task.\"\"\"\n task = await self.task_from_title(ctx, title)\n description = task.description.escaped if task.description else \" \"\n await BaseCog.send(ctx, f\"```\\n{description}\\n```\")\n\n\nasync def setup(bot: Bot) -> None:\n await bot.add_cog(Tasks(bot, bot.db))\n","repo_name":"nietsuu/watdo","sub_path":"watdo/discord/cogs/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":14224,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"7918476155","text":"import numpy as np\nimport pytest\n\nfrom genomicsurveillance.utils import create_spline_basis, sort_lineages\nfrom genomicsurveillance.utils.epiestim import epiestim_discretise_serial_interval\nfrom genomicsurveillance.utils.lineages import alias_lineages\n\n\ndef test_create_spline_basis():\n x = np.arange(100)\n _, B = create_spline_basis(x, num_knots=5, add_intercept=False)\n\n assert B.ndim == 3\n assert B.shape[0] == 2\n assert B.shape[1] == 100\n assert B.shape[2] == 5 + 2\n\n\ndef test_alias_lineages():\n test_lineages = [\"B.1\", \"B.1.2\", \"B.1.34\", \"B.1.1.234.1\"]\n aliases = {\"B.1.1.234.1\": \"B.1.1.234\"}\n aliased_lineages = alias_lineages(test_lineages, aliases)\n\n assert len(aliased_lineages) == 4\n assert \"B.1.1.234.1\" not in aliased_lineages\n assert \"B.1.1.234\" in aliased_lineages\n\n test_lineages = [\"B.1\", \"B.1.2\", \"B.1.34\", \"B.1.1.234.1\"]\n aliases = {\"B.1.1.234.1\": \"B.1.1\"}\n aliased_lineages = alias_lineages(test_lineages, aliases)\n\n assert len(aliased_lineages) == 4\n assert \"B.1.1.234.1\" not in aliased_lineages\n assert \"B.1.1\" in aliased_lineages\n\n test_lineages = [\"B.1\", \"B.1.2\", \"B.1.34\", \"B.1.1.234.1\"]\n aliases = {\"B.1.1.234.134\": \"B.1.1\"}\n aliased_lineages = alias_lineages(test_lineages, aliases)\n\n assert len(aliased_lineages) == 4\n assert \"B.1.1.234.1\" in aliased_lineages\n assert \"B.1.1\" not in aliased_lineages\n\n\ndef test_alias_lineages_assertion():\n test_lineages = [\"B.1\", \"B.1.2\", \"B.1.34\", \"B.1.1.234.1\"]\n aliases = {\"B.1.1.234.1\": \"B.1\"}\n\n with pytest.raises(AssertionError):\n alias_lineages(test_lineages, aliases)\n\n test_lineages = [\"B.1\", \"B.1.2\", \"B.1.34\", \"B.1.1.234.1\"]\n aliases = {\"B.1.1.234.1\": \"B.1.1.234\", \"B.1.34\": \"B.1.1.234\"}\n\n with pytest.raises(AssertionError):\n alias_lineages(test_lineages, aliases)\n\n\ndef test_sort_lineages(lineage_list):\n ordered_lineages, other_lineages = sort_lineages(lineage_list)\n\n assert len(ordered_lineages) == len(lineage_list) - 1\n assert len(other_lineages) == 1\n assert ordered_lineages == [\n \"A.18\",\n \"A.25\",\n \"B\",\n \"B.1.1\",\n \"B.1.1.25\",\n \"B.1.1.39\",\n \"B.1.1.50\",\n \"B.1.1.51\",\n \"B.1.1.54\",\n \"B.1.1.141\",\n \"B.1.1.189\",\n \"B.1.1.227\",\n \"B.1.1.235\",\n \"B.1.1.255\",\n \"B.1.1.277\",\n \"B.1.1.286\",\n \"B.1.1.288\",\n \"B.1.1.305\",\n \"B.1.2\",\n \"B.1.36\",\n \"B.1.36.16\",\n \"B.1.36.17\",\n \"B.1.149\",\n \"B.1.177\",\n \"B.1.235\",\n \"B.1.258\",\n \"B.1.258.3\",\n \"B.1.416.1\",\n \"B.1.505\",\n ]\n\n ordered_lineages, other_lineages = sort_lineages(lineage_list + [\"LineageX\"])\n\n assert len(ordered_lineages) == len(lineage_list) - 1\n assert len(other_lineages) == 2\n assert ordered_lineages == [\n \"A.18\",\n \"A.25\",\n \"B\",\n \"B.1.1\",\n \"B.1.1.25\",\n \"B.1.1.39\",\n \"B.1.1.50\",\n \"B.1.1.51\",\n \"B.1.1.54\",\n \"B.1.1.141\",\n \"B.1.1.189\",\n \"B.1.1.227\",\n \"B.1.1.235\",\n \"B.1.1.255\",\n \"B.1.1.277\",\n \"B.1.1.286\",\n \"B.1.1.288\",\n \"B.1.1.305\",\n \"B.1.2\",\n \"B.1.36\",\n \"B.1.36.16\",\n \"B.1.36.17\",\n \"B.1.149\",\n \"B.1.177\",\n \"B.1.235\",\n \"B.1.258\",\n \"B.1.258.3\",\n \"B.1.416.1\",\n \"B.1.505\",\n ]\n\n\ndef test_sort_lineages_assertions():\n test_lineages = [\"B.1\", \"B.1.2\", \"B.1\", \"B.1.34\", \"B.1.1.234.1\"]\n\n with pytest.raises(AssertionError):\n sort_lineages(test_lineages)\n\n\ndef test_discretise():\n d2 = [epiestim_discretise_serial_interval(i, mu=6.2, cv=0.62) for i in range(25)]\n assert len(d2) == 25\n","repo_name":"sagar87/genomicsurveillance","sub_path":"tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":3752,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"7803562124","text":"import cupy\nimport chainer.functions as F\nfrom chainer import Variable\nfrom input_gradient_keeper import InputGradientKeeper\nimport numpy as np\n\ndef as_mat(x):\n return x.reshape(x.shape[0], x.size // x.shape[0])\n\ndef normalize_axis1(x):\n xp = cupy.get_array_module(*x)\n abs_x = abs(x)\n x = x / (1e-6 + abs_x.max(axis=1,keepdims=True))\n x_norm_2 = x**2\n return x / xp.sqrt(1e-6 + x_norm_2.sum(axis=1,keepdims=True))\n\n\ndef perturbation_with_L2_norm_constraint(x,norm):\n return norm * normalize_axis1(x)\n\ndef perturbation_with_max_norm_constraint(x,norm):\n xp = cupy.get_array_module(*x)\n return norm * xp.sign(x)\n\nclass AdversarialTrainer(object):\n\n def __init__(self, model, epsilon=1.0, norm_constraint_type='L2', lamb=1.0):\n self.model = model\n self.epsilon = epsilon\n self.norm_constraint_type = norm_constraint_type\n self.lamb = lamb\n\n def accuracy(self, x_data, t):\n return self.model.accuracy(x_data, t, train=False)\n\n # def accuracy_for_adversarial_examples(self,x,t):\n # xadv,loss = self.get_adversarial_examples(x,t,test=True)\n # return F.accuracy(self.nn.y_given_x(xadv,test=True),t)\n\n def cost_fitness(self, x, t, train=True):\n \"\"\"\n :param x_data: input\n :param t: target\n :return: standard fitness loss ( cross entropy )\n \"\"\"\n return self.model.loss(x.data, t, train)\n\n def cost_adversarial_training(self, x_data, t, train=True):\n xadv, ptb, cost_fitness = self.get_adversarial_examples(x_data, t, train=train)\n cost_fitness_adv = self.cost_fitness(xadv, t, train=train)\n return cost_fitness, self.lamb*cost_fitness_adv\n\n def get_adversarial_examples(self, x_data, t, train=True):\n x = Variable(x_data)\n input_gradient_keeper = InputGradientKeeper()\n x_ = input_gradient_keeper(x)\n cost_fitness = self.cost_fitness(x_, t, train=train)\n cost_fitness.backward()\n gx = input_gradient_keeper.gx\n if (self.norm_constraint_type == 'L2'):\n ptb = perturbation_with_L2_norm_constraint(gx, self.epsilon)\n else:\n ptb = perturbation_with_max_norm_constraint(gx, self.epsilon)\n xadv = x + ptb.reshape(x.data.shape)\n return xadv, ptb, cost_fitness","repo_name":"OminiaVincit/YelpAnomalyAnalysis","sub_path":"Classify/Chainer/src_af_20151215/classification/utils/adversarial_trainer.py","file_name":"adversarial_trainer.py","file_ext":"py","file_size_in_byte":2294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42403923842","text":"from django.urls import include, path, re_path\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n # path('login', views.login, name='login')\n path('username', views.username_testpage, name='username'),\n path('dashboard///', views.dashboard, name='dashboard'),\n # path('dashboard///', views.dashboard2, name='dashboard2'),\n path('get_token', views.get_token, name='get_token'),\n re_path(r'^login/(?P\\w)/(?P\\w)$', views.login, name='login'),\n path('finish_login/', views.finish_login, name='finish_login'),\n\n # pieces:\n]","repo_name":"LaithTahboub/stilltheory","sub_path":"stilltheory_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"33990050301","text":"class Solution:\n # @param A : list of integers\n # @return a list of list of integers\n def subsets(self, A):\n A.sort()\n subsets = [[]]\n for num in A:\n subsets += [sub + [num] for sub in subsets]\n\n return sorted(subsets)\n","repo_name":"curiousTauseef/CodePath-Alumni-Interview-Prep-Course","sub_path":"interviewbit-backtracking-subset.py","file_name":"interviewbit-backtracking-subset.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"5511824548","text":"#!/usr/bin/env python\n\nfrom setuptools import setup, find_packages\nfrom codecs import open\nfrom os import path\nimport ssiwebd\n\nhere = path.abspath(path.dirname(__file__))\nwith open(path.join(here, 'README.rst'), encoding='utf-8') as f:\n long_description = f.read()\n\nsetup(\n name = 'ssiwebd',\n version = ssiwebd.__version__,\n description = 'Server Side Include Webd',\n long_description=long_description,\n author = 'Solomon Huang',\n author_email = 'kaichan@gmail.com',\n url = 'https://github.com/solomonhuang/ssiwebd',\n license='BSD',\n keywords = 'ssi webd',\n packages=find_packages(exclude=['dist']),\n classifiers = [\n 'Development Status :: 3 - Alpha',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: BSD License',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n ],\n entry_points = {\n 'console_scripts': [\n 'ssiwebd=ssiwebd:main',\n ],\n },\n)\n","repo_name":"solomonhuang/ssiwebd","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74630922706","text":"from graphics import*\n\n\ndef main(x,y,point):\n\n x = x\n y = y\n\n # y = x + (y-x)\n # y = -x + (y+x)\n\n # y intercept for equation 1\n # y intercept for equation 2\n eq1_int = y-x\n eq2_int = y+x\n\n # y* = x + y - 80\n # x* = x - y - 80\n #first\n line1 = Line(Point(x,y),Point(x+70,y-70))\n #second\n line2 = Line(Point(x,y),Point(x+70,y+70))\n #third\n line3 = Line(Point(x,y),Point(x-70,y+70))\n #last\n line4 = Line(Point(x,y),Point(x-70,y-70))\n\n\n p = point\n x = p.getX()\n y = p.getY()\n\n if x>=280 and y >=280:\n return None\n elif y<=x+eq1_int and y>=-x+eq2_int:\n return 'right'\n elif y<=x+eq1_int and y<=-x+eq2_int:\n return 'up'\n elif y>=x+eq1_int and y<=-x+eq2_int:\n return 'left'\n elif y>=x+eq1_int and y>=-x+eq2_int:\n return 'down'\n \n\n","repo_name":"EnjoyWorkTrue/Python","sub_path":"GcalProject/hi.py","file_name":"hi.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1930162180","text":"#!/usr/bin/env python\n\nimport os\nimport argparse\nimport h5py\nimport numpy as np\nimport pandas as pd\nimport shutil\n\nimport comptools as comp\nfrom comptools.composition_encoding import (composition_group_labels,\n encode_composition_groups)\n\n\ndef extract_vector_series(store, key, sim):\n values, index = [], []\n grouped = store[key].groupby(['Run', 'Event', 'SubEvent'])\n for name, group in grouped:\n values.append(group['item'].values)\n index.append('{}_{}_{}_{}'.format(sim, *name))\n # For data\n # index.append('{}_{}_{}_{}'.format(config, *name))\n series = pd.Series(data=values, index=index)\n return series\n\n\ndef make_hist(tank_x, tank_y, tank_charge):\n\n bins = np.linspace(-1000, 1000, 25, dtype=float)\n hist, _, _ = np.histogram2d(tank_x, tank_y,\n bins=[bins, bins],\n weights=tank_charge)\n return hist\n\n\ndef extract_charge_df(input_file):\n with pd.HDFStore(input_file, mode='r') as store:\n sim_num = int(os.path.basename(input_file).split('_')[1])\n tank_x = extract_vector_series(store, key='tank_x', sim=sim_num)\n tank_y = extract_vector_series(store, key='tank_y', sim=sim_num)\n tank_charge = extract_vector_series(store, key='tank_charge', sim=sim_num)\n\n df = pd.DataFrame({'tank_x': tank_x,\n 'tank_y': tank_y,\n 'tank_charge': tank_charge})\n return df\n\ndef save_hdf_file(df, outfile):\n num_events = df.shape[0]\n event_ids, hists = [], []\n for event_id, row in df.iterrows():\n hist = make_hist(row['tank_x'], row['tank_y'], row['tank_charge'])\n hists.append(hist)\n event_ids.append(event_id)\n\n with h5py.File(outfile, 'w') as f:\n event_id_dset = f.create_dataset('event_id', data=np.asarray(event_ids))\n hist_dset = f.create_dataset('charge_dist', data=np.asarray(hists))\n\n return\n\n\ndef process_i3_hdf(input_file, outfile):\n df = extract_charge_df(input_file)\n save_hdf_file(df, outfile)\n\n return\n\n\nif __name__ == \"__main__\":\n\n description = ('Converts input hdf5 files (from save_hdf.py) to a '\n 'well-formatted pandas dataframe object')\n parser = argparse.ArgumentParser(description=description)\n parser.add_argument('-c', '--config',\n dest='config',\n default='IC86.2012',\n help='Detector configuration')\n parser.add_argument('--type',\n dest='type',\n choices=['data', 'sim'],\n default='sim',\n help='Option to process simulation or data')\n parser.add_argument('-i', '--input',\n dest='input',\n help='Path to input hdf5 file')\n parser.add_argument('-o', '--output',\n dest='output',\n help='Path to output hdf5 file')\n args = parser.parse_args()\n\n # Validate input config\n if (args.type == 'sim' and\n args.config not in comp.simfunctions.get_sim_configs()):\n raise ValueError(\n 'Invalid simulation config {} entered'.format(args.config))\n elif (args.type == 'data' and\n args.config not in comp.datafunctions.get_data_configs()):\n raise ValueError('Invalid data config {} entered'.format(args.config))\n\n # Check if running on condor. If so, write to a local directory on the\n # worker node and copy after output file is written.\n comp.check_output_dir(args.output)\n if os.getenv('_CONDOR_SCRATCH_DIR'):\n on_condor = True\n local_outdir = os.getenv('_CONDOR_SCRATCH_DIR')\n outfile = os.path.join(local_outdir, os.path.basename(args.output))\n else:\n on_condor = False\n outfile = args.output\n\n process_i3_hdf(input_file=args.input, outfile=outfile)\n\n # If on condor, transfer from worker machine to desired destination\n if on_condor:\n comp.check_output_dir(args.output)\n shutil.move(outfile, args.output)\n","repo_name":"jrbourbeau/cr-composition","sub_path":"processing/legacy/save_images.py","file_name":"save_images.py","file_ext":"py","file_size_in_byte":4120,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"13527731404","text":"numeros = ('zero', 'um', 'dois', 'três', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove', 'dez',\n 'onze', 'doze', 'treze', 'quatorze', 'quinze', 'dezesseis', 'dezessete', 'dezoito', 'dezenove', 'vinte')\n\nn = int(input('Digite um número entre 0 e 20: '))\nif n < 0 or n > 20:\n while True:\n n = int(input('Tente novamente. Digite um número entre 0 e 20: '))\n if 0 <= n <= 20:\n break\n\nfor c in range(0, len(numeros)):\n if n == c:\n print(f'Você digitou o número {numeros[c]}')\n\n\n\n","repo_name":"MPCruz89/Python_Exercicios","sub_path":"Ex072 - Número por extenso.py","file_name":"Ex072 - Número por extenso.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34545064487","text":"import os\nimport glob\nimport json\nimport torch\nimport random\nimport numpy as np\nfrom PIL import Image\nfrom tqdm import tqdm\nfrom typing import Dict, List, Union\nfrom torch.utils.data import Dataset\nimport torchvision.transforms.functional as tv_F\n\nfrom utils.logging import print_and_log\n\nclass ORBITDataset(Dataset):\n \"\"\"\n Base class for ORBIT dataset.\n \"\"\"\n def __init__(self, root, way_method, object_cap, shot_methods, shots, video_types, subsample_factor, clip_methods, clip_length, frame_size, frame_norm_method, annotations_to_load, filter_by_annotations, test_mode, with_cluster_labels, with_caps, logfile=None):\n \"\"\"\n Creates instance of ORBITDataset.\n :param root: (str) Path to train/validation/test folder in ORBIT dataset root folder.\n :param way_method: (str) If 'random', select a random number of objects per user. If 'max', select all objects per user.\n :param object_cap: (int or str) Cap on number of objects per user. If 'max', leave uncapped.\n :param shot_methods: (str, str) Method for sampling videos for context and target sets.\n :param shots: (int, int) Number of videos to sample for context and target sets.\n :param video_types: (str, str) Video types to sample for context and target sets.\n :param subsample_factor: (int) Factor to subsample video frames if sampling frames uniformly.\n :param clip_methods: (str, str) Method for sampling clips of contiguous frames from videos for context and target sets.\n :param clip_length: (int) Number of contiguous frames per video clip.\n :param frame_size: (int) Size in pixels of loaded frames.\n :param frame_norm_method: (str) Method to normalise frame pixel data.\n :param annotations_to_load: (list::str) Types of frame annotations to load from disk and return per task.\n :param filter_by_annotations (list::str) Types of frame annotations to filter by for context and target sets.\n :param test_mode: (bool) If True, returns task with target set grouped by video, otherwise returns task with target set as clips.\n :param with_cluster_labels: (bool) If True, use object cluster labels, otherwise use raw object labels.\n :param with_caps: (bool) If True, impose caps on the number of videos per object, otherwise leave uncapped.\n :param logfile: (file object) File for printing out loaded data summaries.\n :return: Nothing.\n \"\"\"\n self.root = root\n self.mode = os.path.basename(self.root)\n self.way_method = way_method\n self.shot_method_context, self.shot_method_target = shot_methods\n self.shot_context, self.shot_target = shots\n self.context_type, self.target_type = video_types\n self.subsample_factor = subsample_factor\n self.context_clip_method, self.target_clip_method = clip_methods\n self.clip_length = clip_length\n self.frame_size = frame_size\n self.frame_norm_method = frame_norm_method\n self.test_mode = test_mode\n self.with_cluster_labels = with_cluster_labels\n self.with_caps = with_caps\n self.logfile = logfile\n self.annotations_to_load = sorted(annotations_to_load)\n filter_context, filter_target = filter_by_annotations\n self.filter_context = sorted(filter_context)\n self.filter_target = sorted(filter_target)\n self.with_annotations = True if annotations_to_load else False\n self.with_frame_filtering = True if self.filter_context or self.filter_target else False\n \n if self.with_frame_filtering:\n print_and_log(self.logfile, f\"Filtering context frames {self.filter_context}.\")\n print_and_log(self.logfile, f\"Filtering target frames {self.filter_target}.\") \n\n if self.with_annotations or self.with_frame_filtering:\n self.annotation_dims = {'object_bounding_box': 4 }\n self.annotation_root = os.path.join(os.path.dirname(self.root), \"annotations\", f\"{self.mode}\") # e.g. /data/orbit_benchmark/annotations/{train,validation,test}\n if not os.path.isdir(self.annotation_root):\n raise IOError(f\"Annotation directory {self.annotation_root} does not exist.\")\n\n self.object_cap = object_cap\n self.context_shot_cap = 15\n self.target_shot_cap = 15\n self.clip_cap = 200 # limit number of clips sampled from any one video\n self.frame_cap = 1000 # limit number of frames in any one video\n self.original_frame_size = 1080\n if self.frame_norm_method == 'imagenet':\n self.normalize_stats = {'mean' : [0.485, 0.456, 0.406], 'std' : [0.229, 0.224, 0.225]} # imagenet pixel stats\n elif self.frame_norm_method == 'imagenet_inception':\n self.normalize_stats = {'mean' : [0.5, 0.5, 0.5], 'std' : [0.5, 0.5, 0.5]} # imagenet inception pixel stats\n elif self.frame_norm_method == 'openai_clip':\n self.normalize_stats = {'mean' : [0.48145466, 0.4578275, 0.40821073], 'std': [0.26862954, 0.26130258, 0.27577711]} # clip pixel stats\n\n # Setup empty collections.\n self.users = [] # List of users (str)\n self.user2objs = {} # Dictionary of user (str): list of object ids (int)\n self.obj2user = {} # Dictionary of object id (int) to user ids (str)\n self.obj2name = {} # Dictionary of object id (int) to object label (str)\n self.obj2vids = {} # Dictionary of dictionaries: {\"clean\": list of video paths (str), \"clutter\": list of video paths (str)}\n self.video2id = {} # Dictionary of video path (str): video id (int)\n self.frame2anns = {} # Dictionary of frame id (str): annotation information (dict of str to tensor)\n self.frame2crops = {} # Dictionary of frame id (str): valid crops (list)\n self.vid2frames = {} # Dictionary of video id (str) to list of valid frame paths\n if self.with_cluster_labels:\n self.obj2cluster = [] # List of object id (int) to cluster id (int)\n\n self.__load_all_users() \n \n def __load_all_users(self) -> None:\n \n if self.with_cluster_labels: # setup clusters if we're using object clusters as labels.\n # Load cluster labels for this folder.\n cluster_label_path = os.path.join('data', f\"orbit_{self.mode}_object_cluster_labels.json\")\n with open(cluster_label_path, 'r') as cluster_label_file:\n # This dictionary shows what cluster each video in the given root belongs to.\n vid2cluster = json.load(cluster_label_file)\n\n # Get a sorted list of class ints for each cluster.\n # Model output will give index into this list.\n cluster_classes = sorted(set(vid2cluster.values()))\n\n # We want a list where each object id corresponds to a specific cluster label\n cluster_id_map = self.get_label_map(cluster_classes) #TODO potentially might be an issue with filtering\n \n # set up filter criteria per object\n self.filter_params = { \n 'context': \n { \n 'criteria': self.filter_context, \n 'min_video_frames': 1, \n 'video_type': self.context_type \n },\n 'target' : \n {\n 'criteria': self.filter_target, \n 'min_video_frames': 50, \n 'video_type': self.target_type \n }\n }\n\n obj_id, vid_id = 0, 0\n context_video_counter, target_video_counter = 0, 0\n video_types = {'context': self.context_type, 'target': self.target_type}\n for user in tqdm(sorted(os.listdir(self.root)), desc=f\"Loading {self.mode} users from {self.root}\"): # loop over users\n user_path = os.path.join(self.root, user)\n obj_ids = []\n\n # loop over objects per user\n for obj_name in sorted(os.listdir(user_path)):\n obj_path = os.path.join(user_path, obj_name)\n all_videos_by_set = {'context': [], 'target': []}\n filtered_videos_by_set = {'context': [], 'target': []}\n filtered_vid2frames = {}\n \n # get correct video types for context and target sets\n clean_videos_dir = os.path.join(obj_path, 'clean')\n if self.context_type == 'clean' and self.target_type == 'clean':\n clean_video_paths = sorted(list(os.listdir(clean_videos_dir)))\n split = min(5, len(clean_video_paths)-1) # aim for 5 context videos, leaving at least 1 target video\n all_videos_by_set['context'] = clean_video_paths[:split]\n all_videos_by_set['target'] = clean_video_paths[split:]\n elif self.context_type == 'clean' and self.target_type == 'clutter':\n clutter_videos_dir = os.path.join(obj_path, 'clutter')\n all_videos_by_set['context'] = sorted(list(os.listdir(clean_videos_dir)))\n all_videos_by_set['target'] = sorted(list(os.listdir(clutter_videos_dir)))\n \n # loop over each set [context, target]\n for set_type, video_names in all_videos_by_set.items():\n # loop over videos in set\n for video_name in video_names:\n video_path = os.path.join(obj_path, video_types[set_type], video_name)\n frames = glob.glob(os.path.join(video_path, \"*.jpg\"))\n\n if self.with_annotations or self.filter_params[set_type]['criteria']:\n video_annotations = self.__load_video_annotations(video_name)\n self.frame2anns.update(video_annotations)\n if self.filter_params[set_type]['criteria']:\n frames = self.__filter_video_frames(frames, video_annotations, self.filter_params[set_type]['criteria'])\n \n # only add if a minimum number of frames exist for the video\n if len(frames) >= self.filter_params[set_type]['min_video_frames']:\n filtered_videos_by_set[set_type].append(video_path)\n filtered_vid2frames[video_path] = sorted(frames)\n \n context_set_valid = len(filtered_videos_by_set['context']) > 0\n target_set_valid = len(filtered_videos_by_set['target']) > 0\n if context_set_valid and target_set_valid: # object is valid\n obj_ids.append(obj_id)\n self.obj2user[obj_id] = user\n self.obj2name[obj_id] = obj_name\n self.obj2vids[obj_id] = filtered_videos_by_set\n obj_id += 1\n for video_path in filtered_videos_by_set['context'] + filtered_videos_by_set['target']:\n self.video2id[video_path] = vid_id\n self.vid2frames[video_path] = filtered_vid2frames[video_path]\n vid_id += 1\n if self.with_cluster_labels:\n self.obj2cluster[obj_id] = cluster_id_map[vid2cluster[video_name]]\n context_video_counter += len(filtered_videos_by_set['context'])\n target_video_counter += len(filtered_videos_by_set['target'])\n\n user_valid = len(obj_ids) > 0\n if user_valid:\n self.users.append(user)\n self.user2objs[user] = obj_ids \n \n self.num_users = len(self.users)\n self.num_objects = len(self.obj2name)\n self.print_frame_count_bounds()\n print_and_log(self.logfile, f\"Loaded data summary: {self.num_users} users, {self.num_objects} objects, {len(self.video2id)} videos (#context: {context_video_counter}, #target: {target_video_counter})\")\n \n def print_frame_count_bounds(self):\n \n current_bound = {\n 'min': {'context': {'frame_count': None, 'user': [], 'obj' : []}, 'target': {'frame_count': None, 'user': [], 'obj' : []}},\n 'max': {'context': {'frame_count': None, 'user': [], 'obj' : []}, 'target': {'frame_count': None, 'user': [], 'obj' : []}}\n }\n\n for user, objs in self.user2objs.items(): # users\n for obj in objs: # objects\n for video_type, videos in self.obj2vids[obj].items(): # context/target\n frame_count = sum([len(self.vid2frames[video]) for video in videos]) # all frames (of current video_type) for current object\n for bound_type in ['min', 'max']:\n if bound_type == 'min':\n update_bound = current_bound[bound_type][video_type]['frame_count'] is None or frame_count < current_bound[bound_type][video_type]['frame_count']\n elif bound_type == 'max':\n update_bound = current_bound[bound_type][video_type]['frame_count'] is None or frame_count > current_bound[bound_type][video_type]['frame_count']\n append_to_bound = current_bound[bound_type][video_type]['frame_count'] is not None and frame_count == current_bound[bound_type][video_type]['frame_count']\n \n if update_bound:\n current_bound[bound_type][video_type]['obj'] = [self.obj2name[obj]]\n current_bound[bound_type][video_type]['user'] = [user]\n current_bound[bound_type][video_type]['frame_count'] = frame_count\n\n if append_to_bound: # append objects that equal the current bound\n current_bound[bound_type][video_type]['obj'].append(self.obj2name[obj])\n current_bound[bound_type][video_type]['user'].append(user)\n\n min_context_summary = \", \".join([f\"{u} '{o}'\" for u,o in zip(current_bound['min']['context']['user'], current_bound['min']['context']['obj'])])\n max_context_summary = \", \".join([f\"{u} '{o}'\" for u,o in zip(current_bound['max']['context']['user'], current_bound['max']['context']['obj'])])\n min_target_summary = \", \".join([f\"{u} '{o}'\" for u,o in zip(current_bound['min']['target']['user'], current_bound['min']['target']['obj'])])\n max_target_summary = \", \".join([f\"{u} '{o}'\" for u,o in zip(current_bound['max']['target']['user'], current_bound['max']['target']['obj'])])\n print_and_log(self.logfile, f\"Min context frames/obj: {current_bound['min']['context']['frame_count']} ({min_context_summary})\")\n print_and_log(self.logfile, f\"Min target frames/obj: {current_bound['min']['target']['frame_count']} ({min_target_summary})\")\n print_and_log(self.logfile, f\"Max context frames/obj: {current_bound['max']['context']['frame_count']} ({max_context_summary})\")\n print_and_log(self.logfile, f\"Max target frames/obj: {current_bound['max']['target']['frame_count']} ({max_target_summary})\")\n\n def __filter_video_frames(self, frames: List[str], video_annotations, filter_criteria: List[str]=[]) -> List[str]:\n filtered_frames = filter(lambda seq: self.is_criteria_satisfied(seq, video_annotations, filter_criteria), frames)\n return list(filtered_frames)\n\n def is_criteria_satisfied(self, frame_path: str, video_annotations: Dict[str, Dict[str, Union[bool, torch.Tensor]]], filter_criteria: List[str]=[]) -> List[str]:\n frame_name = os.path.basename(frame_path)\n\n # get all annotations for current frame\n frame_annotations = [ann for ann, value in video_annotations[frame_name].items() if value == True ]\n frame_annotations += [f'no_{ann}' for ann, value in video_annotations[frame_name].items() if value == False ]\n\n # filter frame_annotations by those that match the annotations in filter_criteria \n criteria_present = set(frame_annotations) & set(filter_criteria)\n return True if criteria_present else False \n \n def __load_video_annotations(self, video_name: str) -> Dict[str, Dict[str, Union[bool, torch.Tensor]]]:\n annotation_path = os.path.join(self.annotation_root, f\"{video_name}.json\")\n with open(annotation_path, 'r') as annotation_file:\n video_annotations = json.load(annotation_file)\n\n if 'object_bounding_box' in self.annotations_to_load or 'object_bounding_box' in self.filter_context + self.filter_target:\n video_annotations = self.__preprocess_bounding_boxes(video_annotations)\n \n return video_annotations\n \n def __preprocess_bounding_boxes(self, video_annotations: Dict[str, Dict[str, Union[bool, torch.Tensor]]]) -> Dict[str, Dict[str, Union[bool, torch.Tensor]]]:\n\n for frame_id, annotation_dict in video_annotations.items():\n if \"object_bounding_box\" in annotation_dict and annotation_dict[\"object_bounding_box\"] is not None:\n bbox = annotation_dict[\"object_bounding_box\"]\n bbox = torch.tensor([bbox[\"x\"], bbox[\"y\"], bbox[\"w\"], bbox[\"h\"]])\n # Resize to fit current frame size.\n bbox = ((bbox / self.original_frame_size) * self.frame_size).int()\n # Clamp box to fit within frame.\n bbox[0:2] = torch.clamp(bbox[0:2], 0, self.frame_size - 1)\n bbox[2:4] = torch.clamp(bbox[2:4], 1, self.frame_size)\n video_annotations[frame_id][\"object_bounding_box\"] = bbox\n\n return video_annotations\n\n def __len__(self):\n return self.num_users\n\n def get_user_objects(self, user):\n return self.user2objs[ self.users[user] ]\n\n def compute_way(self, num_objects):\n \"\"\"\n Function to compute the number of objects to sample for a user.\n :param num_objects: (int) Total number of objects for current user.\n :return: (int) Total number if self.object_cap == 'max' otherwise returns a random number between 2 and total number.\n \"\"\"\n # all user's objects if object_cap == 'max' else capped by self.object_cap\n max_objects = min(num_objects, self.object_cap)\n min_objects = 2\n if self.way_method == 'random':\n return random.choice(range(min_objects, max_objects + 1))\n elif self.way_method == 'max':\n return max_objects\n\n def sample_videos(self, object_videos):\n \"\"\"\n Function to sample context and target video paths for a given object.\n :param object_videos: (dict::list::str) Dictionary of context and target video paths for an object.\n :return: (list::str, list::str) Sampled context and target video paths for given object according to self.context_type (clean) and self.target_type (clean/clutter).\n \"\"\"\n context = self.choose_videos(object_videos['context'], self.shot_context, self.shot_method_context, self.context_shot_cap)\n target = self.choose_videos(object_videos['target'], self.shot_target, self.shot_method_target, self.target_shot_cap)\n return context, target\n \n def choose_videos(self, videos, required_shots, shot_method, shot_cap):\n \"\"\"\n Function to choose video paths from a list of video paths according to required shots, shot method, and shot cap.\n :param videos: (list::str) List of video paths.\n :param required_shots: (int) Number of videos to select.\n :param shot_method: (str) Method to select videos with options for specific/fixed/random/max - see comments below.\n :param shot_cap: (int) Cap on number of videos to select.\n :return: (list::str) List of selected video paths.\n \"\"\"\n required_shots = min(required_shots, shot_cap) # first cap for memory purposes\n num_videos = len(videos)\n available_shots = min(required_shots, num_videos) # next cap for video availability purposes\n\n if shot_method == 'specific': # sample specific videos (1 required_shots = 1st video; 2 required_shots = 1st, 2nd videos, ...)\n return videos[:available_shots]\n elif shot_method == 'fixed': # randomly sample fixed number of videos\n return random.sample(videos, available_shots)\n elif shot_method == 'random': # randomly sample a random number of videos between 1 and num_videos\n max_shots = min(num_videos, shot_cap) # capped for memory reasons\n random_shots = random.choice(range(1, max_shots+1))\n return random.sample(videos, random_shots)\n elif shot_method == 'max': # samples all videos\n max_shots = min(num_videos, shot_cap) # capped for memory reasons\n return random.sample(videos, max_shots)\n\n def sample_clips_from_videos(self, video_paths: List[str], sample_method: str):\n \"\"\"\n Function to sample clips from a list of videos.\n :param video_paths: (list::str) List of video paths.\n :param sample_method: (str) Method to sample clips from each video.\n :return: (list::torch.Tensor, list::np.ndarray, list::torch.Tensor, list::int) Frame data, paths, and annotations organised in clips of self.clip_length contiguous frames, and video ID for each sampled clip.\n \"\"\"\n clips, paths, video_ids = [], [], []\n annotations = { ann: [] for ann in self.annotations_to_load }\n for video_path in video_paths:\n frame_paths = np.array(self.vid2frames[video_path])\n sampled_idxs = self.sample_clips_from_a_video(frame_paths, sample_method)\n sampled_paths = frame_paths[sampled_idxs].reshape(-1, self.clip_length)\n paths.extend(sampled_paths)\n\n sampled_clips = self.load_clips(sampled_paths)\n clips += sampled_clips\n \n if self.with_annotations:\n sampled_annotations = self.load_annotations(sampled_paths)\n annotations = self.extend_ann_dict(annotations, sampled_annotations)\n\n video_ids.extend([self.video2id[video_path]] * len(sampled_paths))\n\n return clips, paths, video_ids, annotations\n \n def extend_ann_dict(self, dest_dict, src_dict):\n \"\"\"\n Function to extend all lists within annotation dictionary.\n :param dest_dict: (dict::list) Dictionary of lists to extend.\n :param src_dict: (dict::list) Dictionary of lists to add.\n :return: (dict::list) Dictionary of extended lists.\n \"\"\"\n for ann in dest_dict.keys():\n dest_dict[ann].extend(src_dict[ann])\n\n return dest_dict\n\n def load_clips(self, paths: np.ndarray) -> torch.Tensor:\n \"\"\"\n Function to load clips from disk into tensors.\n :param paths: (np.ndarray::str) Frame paths organised in clips of self.clip_length contiguous frames.\n :return: (torch.Tensor) Clip data.\n \"\"\"\n num_clips, clip_length = paths.shape\n assert clip_length == self.clip_length\n loaded_clips = torch.zeros(num_clips, clip_length, 3, self.frame_size, self.frame_size)\n\n for clip_idx in range(num_clips):\n for frame_idx in range(clip_length):\n frame_path = paths[clip_idx, frame_idx]\n loaded_clips[clip_idx, frame_idx] = self.load_and_transform_frame(frame_path)\n\n return loaded_clips\n \n def load_annotations(self, paths: np.ndarray, without_clip_history=True) -> torch.Tensor:\n \"\"\"\n Function to load frame annotations, arrange in clips.\n :param paths: (np.ndarray::str) Frame paths organised in clips of self.clip_length contiguous frames.\n :param without_clip_history: (bool) If True, only load annotations for last frame in every clip.\n :return: (torch.Tensor) Frame annotations arranged in clips.\n \"\"\"\n num_clips, clip_length = paths.shape\n frames_per_clip = 1 if without_clip_history else clip_length\n assert clip_length == self.clip_length\n\n loaded_annotations = {\n annotation : torch.empty(num_clips, frames_per_clip, self.annotation_dims.get(annotation, 1)) # The dimension defaults to 1 unless specified.\n for annotation in self.annotations_to_load }\n\n for clip_idx in range(num_clips):\n frames_to_load = [clip_length-1] if without_clip_history else range(clip_length)\n for frame_idx in frames_to_load:\n frame_path = paths[clip_idx, frame_idx]\n frame_name = os.path.basename(frame_path)\n for annotation in self.annotations_to_load:\n if self.frame2anns[frame_name][annotation] is not None:\n frame_anns = self.frame2anns[frame_name]\n loaded_annotations[annotation][clip_idx, frame_idx] = frame_anns[annotation]\n else:\n loaded_annotations[annotation][clip_idx, frame_idx] = float('nan')\n\n return loaded_annotations\n \n def load_and_transform_frame(self, frame_path):\n \"\"\"\n Function to load and transform frame.\n :param frame_path: (str) Path to frame.\n :return: (torch.Tensor) Loaded and transformed frame.\n \"\"\"\n frame = Image.open(frame_path)\n frame = tv_F.to_tensor(frame)\n frame = tv_F.normalize(frame, mean=self.normalize_stats['mean'], std=self.normalize_stats['std'])\n return frame\n\n def sample_clips_from_a_video(self, frame_paths: np.ndarray, sample_method: str) -> np.ndarray:\n \"\"\"\n Function to sample frame IDs from a list of frame paths.\n :param frame_paths: (np.ndarray::str) List of frame paths.\n :param sample_method: (str) Method to sample clips from each video.\n :return: (np.ndarray) Frame IDs organised in clips of self.clip_length contiguous frames.\n \"\"\"\n frame_idxs = np.arange(len(frame_paths)) # get frame IDs\n frame_idxs = frame_idxs[:self.frame_cap] # cap number of frames to self.frame_cap\n \n\t# if not divisible by self.clip_length, pad with last frame until it is\n spare_frames = len(frame_idxs) % self.clip_length\n if spare_frames > 0:\n frame_idxs = np.append(frame_idxs, [frame_idxs[-1]]*(self.clip_length-spare_frames))\n\n num_frames = len(frame_idxs)\n max_num_clips = num_frames // self.clip_length\n assert num_frames % self.clip_length == 0\n clip_idxs = frame_idxs.reshape(max_num_clips, self.clip_length) # view as clips\n \n if sample_method == 'max': # select all non_overlapping clips\n sampled_idxs = clip_idxs[:max_num_clips]\n elif sample_method == 'random': # select random number of non-overlapping clips up to cap\n capped_num_clips = min(max_num_clips, self.clip_cap)\n num_sampled_clips = random.choice(range(1, capped_num_clips+1))\n sampled_idxs = random.sample(range(max_num_clips), num_sampled_clips)\n elif sample_method == 'random_200': # select random 200 clips if there are enough\n capped_num_clips = min(max_num_clips, 200)\n sampled_idxs = random.sample(range(max_num_clips), capped_num_clips)\n elif sample_method == 'uniform': # select clips uniformly up based on self.subsample_factor up to a cap\n capped_num_clips = min(max_num_clips, self.clip_cap)\n subsample_factor = min(self.subsample_factor, max_num_clips) # in case subsample_factor > max_num_clips\n sampled_idxs = range(0, max_num_clips, subsample_factor)[:capped_num_clips]\n else:\n raise ValueError(f\"Clip sampling method {sample_method} not valid\")\n\n return np.array(sampled_idxs, dtype=np.int64).reshape(-1)\n \n def prepare_set(self, clips, paths, labels, annotations, video_ids, test_mode=False):\n \"\"\"\n Function to prepare context/target set for a task.\n :param clips: (list::torch.Tensor) List of frame data organised in clips of self.clip_length contiguous frames.\n :param paths: (list::np.ndarray::str) List of frame paths organised in clips of self.clip_length contiguous frames.\n :param labels: (list::int) List of object labels for each clip.\n :param annotations: (dict::list::torch.Tensor) Dictionary of annotations for each clip.\n :param video_ids: (list::int) List of videos IDs corresponding to paths.\n :param test_mode: (bool) If False, do not shuffle task, otherwise shuffle.\n :return: (torch.Tensor or list::torch.Tensor, np.ndarray::str or list::np.ndarray, torch.Tensor or list::torch.Tensor, dict::torch.Tensor or list::dict::torch.Tensor) Frame data, paths, video-level labels and annotations organised in clips (if train) or grouped and flattened by video (if test/validation).\n \"\"\"\n clips = torch.stack(clips)\n paths = np.array(paths)\n labels = torch.tensor(labels)\n annotations = { ann: torch.stack(annotations[ann]) for ann in self.annotations_to_load }\n\n if test_mode: # group by video\n frames_by_video, paths_by_video, labels_by_video, annotations_by_video = [], [], [], []\n unique_video_ids = np.unique(video_ids)\n for video_id in unique_video_ids:\n # get all clips belonging to current video\n idxs = video_ids == video_id\n # flatten frames and paths from current video (assumed to be sorted)\n video_frames = clips[idxs].flatten(end_dim=1)\n video_paths = paths[idxs].reshape(-1)\n frames_by_video.append(video_frames)\n paths_by_video.append(video_paths)\n # all clips from the same video have the same label, so just return 1\n video_label = labels[idxs][0]\n labels_by_video.append(video_label)\n # get all frame annotations for current video\n video_anns = { ann : annotations[ann][idxs].flatten(end_dim=1) for ann in self.annotations_to_load } if self.with_annotations else None\n annotations_by_video.append(video_anns)\n return frames_by_video, paths_by_video, labels_by_video, annotations_by_video\n else:\n return self.shuffle_set(clips, paths, labels, annotations)\n\n def shuffle_set(self, clips, paths, labels, annotations):\n \"\"\"\n Function to shuffle clips and their object labels.\n :param clips: (torch.Tensor) Frame data organised in clips of self.clip_length contiguous frames.\n :param paths: (np.ndarray::str) Frame paths organised in clips of self.clip_length contiguous frames.\n :param labels: (torch.Tensor) Object labels for each clip.\n :param annotations: (dict::torch.Tensor) Frame annotations organised in clips of self.clip_length contiguous frames.\n :return: (torch.Tensor, np.ndarray::str, torch.Tensor, dict::torch.Tensor) Shuffled clips and their corresponding paths, object labels and annotations.\n \"\"\"\n idxs = np.arange(len(paths))\n random.shuffle(idxs)\n if self.with_annotations:\n return clips[idxs], paths[idxs], labels[idxs], { ann : annotations[ann][idxs] for ann in self.annotations_to_load }\n else:\n return clips[idxs], paths[idxs], labels[idxs], annotations\n\n def get_label_map(self, objects, with_cluster_labels=False):\n \"\"\"\n Function to get object-to-label map according to if with_cluster_labels is True.\n :param objects: (list::int) List of objects for current user.\n :param with_cluster_labels: (bool) If True, use object cluster labels, otherwise use raw object labels.\n :return: (dict::int) Dictionary mapping objects to labels.\n \"\"\"\n if with_cluster_labels:\n return self.obj2cluster\n else:\n map_dict = {}\n new_labels = range(len(objects))\n for i, old_label in enumerate(objects):\n map_dict[old_label] = new_labels[i]\n return map_dict\n\n def sample_task(self, task_objects: List[int], task_id: str) -> Dict:\n\n # select way (number of classes/objects) randomly\n num_objects = len(task_objects)\n way = self.compute_way(num_objects)\n selected_objects = sorted(random.sample(task_objects, way)) # without replacement\n label_map = self.get_label_map(selected_objects, self.with_cluster_labels)\n\n # set caps, for memory purposes (used in training)\n if self.with_caps:\n self.context_shot_cap = 5 if way >=6 else 10\n self.target_shot_cap = 4 if way >=6 else 8\n\n # for each object, sample context and target sets\n obj_list = []\n context_clips, target_clips = [], []\n context_paths, target_paths = [], []\n context_labels, target_labels = [], []\n context_video_ids, target_video_ids = [], []\n context_annotations = { ann : [] for ann in self.annotations_to_load}\n target_annotations = { ann : [] for ann in self.annotations_to_load}\n for obj in selected_objects:\n label = label_map[obj]\n obj_name = self.obj2name[obj]\n obj_list.append(obj_name)\n\n context_videos, target_videos = self.sample_videos(self.obj2vids[obj])\n cc, cp, cvi, ca = self.sample_clips_from_videos(context_videos, self.context_clip_method)\n context_clips.extend(cc)\n context_paths.extend(cp)\n context_labels.extend([label for _ in range(len(cp))])\n context_video_ids.extend(cvi)\n context_annotations = self.extend_ann_dict(context_annotations, ca)\n\n tc, tp, tvi, ta = self.sample_clips_from_videos(target_videos, self.target_clip_method)\n target_clips.extend(tc)\n target_paths.extend(tp)\n target_labels.extend([label for _ in range(len(tp))])\n target_video_ids.extend(tvi)\n target_annotations = self.extend_ann_dict(target_annotations, ta)\n\n context_clips, context_paths, context_labels, context_annotations = self.prepare_set(context_clips, context_paths, context_labels, context_annotations, context_video_ids)\n target_clips, target_paths, target_labels, target_annotations = self.prepare_set(target_clips, target_paths, target_labels, target_annotations, target_video_ids, test_mode=self.test_mode)\n\n task_dict = {\n # Data required for train / test\n 'context_clips': context_clips, # Tensor of shape (num_context_clips, clip_length, channels, height, width), dtype float32\n 'context_paths': context_paths, # Numpy array of shape (num_context_clips, clip_length), dtype str\n 'context_labels': context_labels, # Tensor of shape (num_context_clips,), dtype int64\n 'context_annotations': context_annotations, # Dictionary. Empty if no annotations present. TODO: Add info for when annotations are present.\n 'target_clips': target_clips, # If train, tensor of shape (num_target_clips, clip_length, channels, height, width), dtype float32. If test/validation, list of length (num_target_videos_for_user) of tensors, each of shape (num_video_frames, channels, height, width), dtype float32\n 'target_paths': target_paths, # If train, numpy array of shape (num_target_clips, clip_length), dtype str. If test/validation, list of length (num_target_videos_for_user) of numpy arrays, each of shape (num_video_frames,), dtype str\n 'target_labels': target_labels, # If train, tensor of shape (num_target_clips,), dtype int64. If test/validation, list of length (num_target_videos_for_user) of tensors, each of shape (1,), dtype int64\n 'target_annotations': target_annotations, # Dictionary. Empty if no annotations present. TODO: Add info for when annotations are present.\n # Extra information, to be used in logging and results.\n 'object_list': obj_list, # Ordered list of strings for all objects in this task.\n 'task_id': task_id # User ID if UserEpisodicORBITDataset else object name if ObjectEpisodicORBITDataset, dtype string\n }\n return task_dict\n\nclass UserEpisodicORBITDataset(ORBITDataset):\n \"\"\"\n Class for user-centric episodic sampling of ORBIT dataset.\n \"\"\"\n def __init__(self, root, way_method, object_cap, shot_methods, shots, video_types, subsample_factor, clip_methods, clip_length, frame_size, frame_norm_method, annotations_to_load, filter_by_annotations, test_mode, with_cluster_labels, with_caps, logfile):\n \"\"\"\n Creates instance of UserEpisodicORBITDataset.\n \"\"\"\n ORBITDataset.__init__(self, root, way_method, object_cap, shot_methods, shots, video_types, subsample_factor, clip_methods, clip_length, frame_size, frame_norm_method, annotations_to_load, filter_by_annotations, test_mode, with_cluster_labels, with_caps, logfile)\n\n def __getitem__(self, index):\n \"\"\"\n Function to get a user-centric task as a set of (context and target) clips and labels.\n :param index: (tuple) Task index.\n :return: (dict) Context and target set data for task.\n \"\"\"\n user = self.users[index] # get user (each task == user id)\n user_objects = self.user2objs[user] # get user's objects\n return self.sample_task(user_objects, user)\n\nclass ObjectEpisodicORBITDataset(ORBITDataset):\n \"\"\"\n Class for object-centric episodic sampling of ORBIT dataset.\n \"\"\"\n def __init__(self, root, way_method, object_cap, shot_methods, shots, video_types, subsample_factor, clip_methods, clip_length, frame_size, frame_norm_method, annotations_to_load, filter_by_annotations, test_mode, with_cluster_labels, with_caps, logfile):\n \"\"\"\n Creates instance of ObjectEpisodicORBITDataset.\n \"\"\"\n ORBITDataset.__init__(self, root, way_method, object_cap, shot_methods, shots, video_types, subsample_factor, clip_methods, clip_length, frame_size, frame_norm_method, annotations_to_load, filter_by_annotations, test_mode, with_cluster_labels, with_caps, logfile)\n\n def __getitem__(self, index):\n \"\"\"\n Function to get a object-centric task as a set of (context and target) clips and labels.\n :param index: (tuple) Task index.\n :return: (dict) Context and target set data for task.\n \"\"\"\n all_objects = range(0, len(self.obj2vids)) # task can consider all possible objects, not just 1 user's objects\n return self.sample_task(all_objects)\n","repo_name":"microsoft/ORBIT-Dataset","sub_path":"data/datasets.py","file_name":"datasets.py","file_ext":"py","file_size_in_byte":39062,"program_lang":"python","lang":"en","doc_type":"code","stars":80,"dataset":"github-code","pt":"48"} +{"seq_id":"1368724210","text":"#\n# @lc app=leetcode id=44 lang=python3\n#\n# [44] Wildcard Matching\n#\n\n# @lc code=start\nclass Solution:\n # def backtracking(self, s, p) :\n # if p == '*' : return True\n # if not s : \n # if not p: return True\n # else : return False\n # if not p : return False\n\n \n # if s[0] == p[0] or p[0] == '?': \n # return self.backtracking(s[1:], p[1:])\n\n # if p[0] == '*' :\n # if len(p) > 1 and p[1:] == '*' :\n # return self.backtracking(s, p[1:])\n # for i in range(len(s)) :\n\n # return False\n\n def iter_method(self, s, p) :\n s_idx, p_idx, match, start_idx = 0, 0, 0, -1\n while s_idx < len(s) :\n if p_idx < len(p) and (p[p_idx] == s[s_idx] or p[p_idx] == '?') :\n p_idx, s_idx = p_idx + 1, s_idx + 1\n elif p_idx < len(p) and p[p_idx] == '*' :\n start_idx = p_idx\n match = s_idx\n p_idx += 1\n elif start_idx != -1 :\n p_idx = start_idx + 1\n match += 1\n s_idx = match\n else :\n return False\n while p_idx < len(p) and p[p_idx] == '*' :\n p_idx += 1\n return len(p) == p_idx\n\n def dp(self, s, p) :\n dp = [[True for _ in range(len(p))] for _ in range(len(s))]\n for i in range(len(s)) :\n for j in range(len(p)) :\n s_idx = len(s) - i\n p_idx = len(p) - i\n if s_idx == len(s) and p_idx == len(p) : continue\n first_match = s_idx < len(s) and p_idx < len(p) \\\n and (p[p_idx] == s[s_idx] or p[p_idx] == '?' or p[p_idx] == '*')\n if p_idx < len(p) and p[p_idx] == '*' :\n d[i][j] = dp[i][j + 1] or (first_match and dp[i + 1][j])\n else :\n d[i][j] = first_match and dp[i + 1][j + 1]\n return dp[0][0]\n\n\n\n def isMatch(self, s: str, p: str) -> bool:\n return self.dp(s, p)\n \n# @lc code=end\n\n","repo_name":"quixoteji/Leetcode","sub_path":"solutions/44.wildcard-matching.py","file_name":"44.wildcard-matching.py","file_ext":"py","file_size_in_byte":2090,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"15151259382","text":"#\n#\n#\n# New Scraper for WebHelp\n# Link to this company jobs ---> https://jobs.webhelp.com/job-search/?keyword=&country=Romania\n#\nfrom A_OO_get_post_soup_update_dec import DEFAULT_HEADERS, update_peviitor_api\n#\nfrom L_00_logo import update_logo\n#\nimport requests\nfrom bs4 import BeautifulSoup\n#\nimport uuid\n#\n\n\ndef collect_data_from_webhelp() -> list:\n \"\"\"\n Collect data from webHelp.\n \"\"\"\n\n response = requests.get(\n url=f'https://jobs.webhelp.com/job-search/?keyword=&country=Romania',\n headers=DEFAULT_HEADERS\n )\n\n soup = BeautifulSoup(response.text, 'lxml')\n soup_data = soup.find_all('div', class_='job')\n\n lst_with_data = []\n for sd in soup_data:\n link = sd.find('a')['href']\n title = sd.find('h3').text.encode('utf-8').decode('utf-8')\n location = sd.find('div', class_='job-meta').text.split('\\n')[1].split(',')[0].encode('utf-8').decode('utf-8')\n\n if 'webhelp' not in link:\n continue\n\n lst_with_data.append({\n \"id\": str(uuid.uuid4()),\n \"job_title\": title,\n \"job_link\": link,\n \"company\": \"webhelp\",\n \"country\": \"Romania\",\n \"city\": location\n })\n\n return lst_with_data\n\n\n# update data on peviitor!\n@update_peviitor_api\ndef scrape_and_update_peviitor(company_name, data_list):\n \"\"\"\n Update data on peviitor API!\n \"\"\"\n\n return data_list\n\n\ncompany_name = 'webhelp'\ndata_list = collect_data_from_webhelp()\nscrape_and_update_peviitor(company_name, data_list)\n\nprint(update_logo('webhelp',\n 'https://jobs.webhelp.com/wp-content/themes/jobswh/img/logo.svg'\n ))\n","repo_name":"peviitor-ro/Scrapers_start_with_digi","sub_path":"sites/webhelp_scraper.py","file_name":"webhelp_scraper.py","file_ext":"py","file_size_in_byte":1683,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"48"} +{"seq_id":"14656624809","text":"from sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.cluster import KMeans\nfrom sklearn.cluster import AffinityPropagation\nfrom sklearn.cluster import MeanShift\nfrom sklearn.cluster import SpectralClustering\nfrom sklearn.cluster import AgglomerativeClustering\nfrom sklearn.cluster import DBSCAN\nfrom sklearn.mixture import GaussianMixture\nfrom sklearn import metrics\n\n#####data process#######\nf1=open(\"Tweets.txt\")\ntweets=f1.readlines()\nnumOfDocuments=len(tweets) # number of total documents in this dataset\n#print(numOfDocuments)\ncate_tweets=[]#documents with the sign of cluster\nfor i in range(150):\n cate_tweets.append(0)\n\nfor tweet in tweets:\n splitTweet=tweet.split(\":\")\n body=splitTweet[1].split(\",\")\n content=body[0].strip('\\\"')\n content=content.strip(' \\\"')\n cluster=splitTweet[2].strip(\"\\n\")\n cluster=int(cluster.strip(\"}\"))\n #print(cluster)\n if(cate_tweets[cluster]==0):\n cate_tweets[cluster]=[]\n cate_tweets[cluster].append(content)\n else:\n cate_tweets[cluster].append(content)\n#print(cate_tweets)\n\npure_doc=[] #Pure documents without the sign of cluster\nfor i in range(len(cate_tweets)):\n if cate_tweets[i]==0:\n continue\n else:\n for doc in cate_tweets[i]:\n pure_doc.append(doc)\n\ntfidf_vectorizer=TfidfVectorizer()\n\ntfidf_matrix = tfidf_vectorizer.fit_transform(pure_doc)\n\n#f2=open(\"tfidf_matrix_sklearn.txt\",\"w\")\n#for item in tfidf_matrix:\n #f2.write(\"%s\\n\"%item)\n#f2.close()\n\n#####data process finished#######\n\n#true labels#\nff=open(\"category.txt\")\ncate_content=ff.readlines()\ncategory=[]\nfor cate in cate_content:\n category.append(int(cate.strip(\"\\n\")))\nprint(category)\nlabels_true=category\n\n#kmeans#\nnum_clusters = 89\nkm_cluster = KMeans(n_clusters=num_clusters, max_iter=300, n_init=40, init='k-means++', n_jobs=-1)\n#labels generated by clustering#\nresult = km_cluster.fit_predict(tfidf_matrix)\nlabels_pred=result\nf2=open(\"kmeans_cluster_sklearn.txt\",\"w\")\nfor res in result:\n f2.write(\"%s\\n\"%res)\nf2.close()\n\n#evaluation using NMI#\nkmeans_score=metrics.normalized_mutual_info_score(labels_true,labels_pred)\nprint(\"Kmeans:%s\"%kmeans_score)\n\n#AffinityPropagation\nap_cluster=AffinityPropagation()\nresult=ap_cluster.fit_predict(tfidf_matrix)\nlabels_pred=result\nf3=open(\"AffinityPropagation_cluster_sklearn.txt\",\"w\")\nfor res in result:\n f3.write(\"%s\\n\"%res)\nf3.close()\n\n#evaluation using NMI#\nap_score=metrics.normalized_mutual_info_score(labels_true,labels_pred)\nprint(\"AffinityPropagation:%s\"%ap_score)\n\n#MeanShift\nms_cluster=MeanShift()\ntfidf_matrix=tfidf_matrix.toarray()\nresult=ms_cluster.fit_predict(tfidf_matrix)\nlabels_pred=result\nf4=open(\"MeanShift_cluster_sklearn.txt\",\"w\")\nfor res in result:\n f4.write(\"%s\\n\"%res)\nf4.close()\n\n#evaluation using NMI#\nms_score=metrics.normalized_mutual_info_score(labels_true,labels_pred)\nprint(\"MeanShift:%s\"%ms_score)\n\n#SpectralClustering\nsc_cluster=SpectralClustering()\nresult=sc_cluster.fit_predict(tfidf_matrix)\nlabels_pred=result\nf5=open(\"SpectralClustering_cluster_sklearn.txt\",\"w\")\nfor res in result:\n f5.write(\"%s\\n\"%res)\nf5.close()\n\n#evaluation using NMI#\nsc_score=metrics.normalized_mutual_info_score(labels_true,labels_pred)\nprint(\"SpectralClustering:%s\"%sc_score)\n\n#Ward hierarchical clustering\nn_clusters=89\nwh_cluster=AgglomerativeClustering(n_clusters=n_clusters,linkage='ward')\ntfidf_matrix=tfidf_matrix.toarray()\nresult=wh_cluster.fit_predict(tfidf_matrix)\nlabels_pred=result\nf5=open(\"WardHierarchical_cluster_sklearn.txt\",\"w\")\nfor res in result:\n f5.write(\"%s\\n\"%res)\nf5.close()\n\n#evaluation using NMI#\nwh_score=metrics.normalized_mutual_info_score(labels_true,labels_pred)\nprint(\"WardHierarchical:%s\"%wh_score)\n\n\n#AgglomerativeClustering\nn_clusters=89\nagg_cluster=AgglomerativeClustering(n_clusters=n_clusters,linkage=\"average\")\ntfidf_matrix=tfidf_matrix.toarray()\nresult=agg_cluster.fit_predict(tfidf_matrix)\nlabels_pred=result\nf5=open(\"AgglomerativeClustering_cluster_sklearn.txt\",\"w\")\nfor res in result:\n f5.write(\"%s\\n\"%res)\nf5.close()\n\n#evaluation using NMI#\nagg_score=metrics.normalized_mutual_info_score(labels_true,labels_pred)\nprint(\"AgglomerativeClustering:%s\"%agg_score)\n\n#DBSCAN\ndb_cluster=DBSCAN(eps=1,min_samples=0.5)\nresult=db_cluster.fit_predict(tfidf_matrix)\nlabels_pred=result\nf5=open(\"DBSCAN_cluster_sklearn.txt\",\"w\")\nfor res in result:\n f5.write(\"%s\\n\"%res)\nf5.close()\n\n#evaluation using NMI#\ndb_score=metrics.normalized_mutual_info_score(labels_true,labels_pred)\nprint(\"DBSCAN:%s\"%db_score)\n\n#Gaussian Mixture\ntfidf_matrix=tfidf_matrix.toarray()\ngauss_cluster=GaussianMixture(n_components=89,covariance_type='full').fit(tfidf_matrix)\n\nresult=gauss_cluster.predict(tfidf_matrix)\nlabels_pred=result\nf5=open(\"Gauss_cluster_sklearn.txt\",\"w\")\nfor res in result:\n f5.write(\"%s\\n\"%res)\nf5.close()\n\n#evaluation using NMI#\ngauss_score=metrics.normalized_mutual_info_score(labels_true,labels_pred)\nprint(\"Gauss:%s\"%gauss_score)\n\n\n","repo_name":"Chen-Bao/201814800BaoChen","sub_path":"SKLearn/sktest.py","file_name":"sktest.py","file_ext":"py","file_size_in_byte":4946,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"29677899681","text":"\"\"\"Backend for suggestions command.\"\"\"\nimport datetime\n\nimport discord\n\nfrom bot.utils.constants import EmbedColour, VoteEmoji\n\n\nasync def send_to_suggestions(\n channel: discord.TextChannel, *, embed: discord.Embed\n) -> None:\n \"\"\"Send the suggestion embed to the guild's suggestions channel and add vote reactions.\"\"\"\n m = await channel.send(embed=embed)\n for e in VoteEmoji:\n await m.add_reaction(e.value)\n\n\ndef build_embed(suggestion: str, author: discord.Member) -> discord.Embed:\n e = discord.Embed(description=suggestion, color=EmbedColour.Info.value)\n e.set_author(name=author.display_name, icon_url=author.avatar_url)\n e.timestamp = datetime.datetime.utcnow()\n return e\n\n\nasync def get_guild_suggestions_channel(\n bot: discord.ext.commands.Bot, guild: int\n) -> discord.TextChannel:\n \"\"\"\n Gets the guild's suggestions channnel.\n \"\"\"\n # implement this once db is set up\n return bot.get_channel(849987442089787442)\n","repo_name":"anand2312/utilitybot","sub_path":"bot/backend/suggestions.py","file_name":"suggestions.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4032222473","text":"from .flow_base import FlowBase\nfrom models import Inventory\nimport util.prompts as prompts\nimport util.sql as sql\n\n\nclass InventoryCreate(FlowBase):\n prompt_text = \"Create or modify an inventory to use in your games.\"\n\n def prompt_for_inventory_option(self, inventories):\n # The options are rename inventory, modify inventory or create a new one\n options = []\n descriptions = []\n\n for inventory in inventories:\n options.append(('modify', inventory))\n descriptions.append('Modify %s' % inventory.name)\n options.append(('rename', inventory))\n descriptions.append('Rename %s' % inventory.name)\n\n options.append(('create', None))\n descriptions.append('Create a new inventory')\n\n return prompts.select_from_list(options, descriptions,\n \"What would you like to do? Please choose an option from this list.\",\n interactive_with_single_option=True)\n\n def prompt_for_name(self):\n while True:\n chosen_name = prompts.get_input_value_with_quit(\"Please choose a name: \")\n\n with self.connection.cursor() as cursor:\n cursor.execute(\"SELECT count(*) FROM inventories WHERE username=%(username)s AND name=%(name)s\", {\n \"username\": self.player.username,\n \"name\": chosen_name\n })\n count = cursor.fetchone()[0]\n\n if count == 0:\n return chosen_name\n\n print(\"This name is already in use by another one of your inventories, please choose a different name.\")\n\n def rename_inventory(self, inventory):\n print(\"What would you like to rename %s to?\" % inventory.name)\n new_name = self.prompt_for_name()\n\n with self.connection.cursor() as cursor:\n cursor.execute(\"UPDATE inventories SET name=%(new_name)s WHERE username=%(username)s AND name=%(old_name)s\",\n {\n \"username\": self.player.username,\n \"old_name\": inventory.name,\n \"new_name\": new_name\n })\n\n self.connection.commit()\n print(\"Inventory renamed successfully!\")\n\n def create_new_inventory(self):\n print(\"Please choose a name for your new inventory!\")\n new_name = self.prompt_for_name()\n\n with self.connection.cursor() as cursor:\n query = sql.insert_query(\n 'inventories',\n ('username', 'name'),\n [(self.player.username, new_name)],\n return_fields='*'\n )\n cursor.execute(query)\n inventory = next(sql.objects(cursor))\n return Inventory(self.connection, inventory)\n\n def add_item_menu(self, inventory):\n # Add a nil_type so that the NOT IN clause always has a valid syntax if there are no weapons in the\n # inventory\n weapon_types = [w.type for w in inventory.weapons()] + ['nil_type']\n fetch_armors = len(inventory.armors()) == 0\n\n weapons_query = \"\"\"\n SELECT items.*, weapons.* FROM weapons\n INNER JOIN items ON weapons.item_id = items.id\n WHERE weapons.type NOT IN {0}\n AND weapons.item_id IN (SELECT item_id FROM owns WHERE username=%(username)s)\n \"\"\".format(sql.sql_format_tuple(weapon_types))\n\n armors_query = \"\"\"\n SELECT items.*, armors.* FROM armors\n INNER JOIN items ON armors.item_id = items.id\n WHERE armors.item_id IN (SELECT item_id FROM owns WHERE username=%(username)s)\n \"\"\"\n\n armors = []\n\n with self.connection.cursor() as cursor:\n cursor.execute(weapons_query, {\n \"username\": self.player.username\n })\n weapons = list(sql.objects(cursor))\n\n if fetch_armors:\n cursor.execute(armors_query, {\n \"username\": self.player.username\n })\n armors = list(sql.objects(cursor))\n\n options = weapons + armors\n descriptions = []\n\n for weapon in weapons:\n descriptions.append('%s -- %s, weight: %d, range: %d, damage: %d' %\n (weapon.name, weapon.type, weapon.weight, weapon.range, weapon.damage))\n\n for armor in armors:\n descriptions.append('%s -- Armor, weight: %d, protection: %d' %\n (armor.name, armor.weight, armor.protection))\n\n if len(options) == 0:\n print(\"Your inventory is already full! Please remove items first\"\n \" if you want to add a different weapon or armor.\")\n else:\n new_item = prompts.select_from_list(options, descriptions, \"Please select an item from this list to add\"\n \" to your inventory\",\n interactive_with_single_option=True)\n with self.connection.cursor() as cursor:\n cursor.execute(\"INSERT INTO inventory_contains (username, name, item_id)\"\n \"VALUES (%(username)s, %(name)s, %(item_id)s)\", {\n \"username\": self.player.username,\n \"name\": inventory.name,\n \"item_id\": new_item.id\n })\n\n def remove_item_menu(self, inventory):\n options = inventory.weapons() + inventory.armors()\n descriptions = [item.name for item in options]\n\n item_to_remove = prompts.select_from_list(options, descriptions, \"Choose an item to remove:\",\n interactive_with_single_option=True)\n delete_query = \"\"\"\n DELETE FROM inventory_contains\n WHERE username=%(username)s AND name=%(name)s AND item_id=%(item_id)s\n \"\"\"\n with self.connection.cursor() as cursor:\n cursor.execute(delete_query, {\n \"username\": self.player.username,\n \"name\": inventory.name,\n \"item_id\": item_to_remove.id\n })\n\n print(\"Item successfully removed!\")\n\n def add_new_attachment(self, inventory, weapon, current_attachments):\n query = \"\"\"\n SELECT items.id, items.name, items.weight FROM attachments\n INNER JOIN items ON attachments.item_id = items.id\n WHERE attachments.attaches_to_id = %(weapon_item_id)s\n AND attachments.item_id NOT IN (\n SELECT item_id AS id FROM inventory_contains\n WHERE username=%(username)s AND name=%(name)s\n )\n AND attachments.item_id IN (\n SELECT item_id AS id FROM owns\n WHERE username=%(username)s\n )\n \"\"\"\n\n with self.connection.cursor() as cursor:\n cursor.execute(query, {\n \"weapon_item_id\": weapon.id,\n \"username\": self.player.username,\n \"name\": inventory.name\n })\n attachments = list(sql.objects(cursor))\n\n if len(attachments) == 0:\n print(\"You don't own any additional attachments for this item!\")\n else:\n print(\"Which attachment would you like to add.\")\n descriptions = [\"%s, weight: %d\" % (a.name, a.weight) for a in attachments]\n attachment = prompts.select_from_list(attachments, descriptions, \"Choose a number from this list:\",\n interactive_with_single_option=True)\n with self.connection.cursor() as cursor:\n cursor.execute(\"INSERT INTO inventory_contains (username, name, item_id)\"\n \"VALUES (%(username)s, %(name)s, %(item_id)s)\", {\n \"username\": self.player.username,\n \"name\": inventory.name,\n \"item_id\": attachment.id\n })\n\n def remove_attachment(self, inventory, current_attachments):\n print(\"Which attachment would you like to remove?\")\n attachment = prompts.select_from_list(\n current_attachments,\n [a.name for a in current_attachments],\n \"Enter a number from this list:\",\n interactive_with_single_option=True\n )\n\n with self.connection.cursor() as cursor:\n cursor.execute(\"DELETE FROM inventory_contains WHERE \"\n \"username=%(username)s AND name=%(name)s AND item_id=%(item_id)s\", {\n \"username\": self.player.username,\n \"name\": inventory.name,\n \"item_id\": attachment.id\n })\n\n print(\"Attachment removed!\")\n\n def modify_attachments_menu(self, inventory):\n descriptions = [w.name for w in inventory.weapons()]\n print(\"Which weapon would you like to modify attachments for?\")\n weapon = prompts.select_from_list(inventory.weapons(), descriptions, \"Choose a weapon from this list: \",\n interactive_with_single_option=True)\n\n while True:\n current_attachments = [a for a in inventory.attachments() if a.attaches_to_id == weapon.id]\n\n options = ['add_new']\n descriptions = ['Add a new attachment']\n\n if len(current_attachments) > 0:\n options.append('remove')\n descriptions.append('Remove an attachment')\n\n options.append('finished')\n descriptions.append('Exit to previous menu.')\n\n print(\"What would you like to do?\")\n option = prompts.select_from_list(options, descriptions, \"Please select a number from this list: \",\n interactive_with_single_option=True)\n\n if option == 'add_new':\n self.add_new_attachment(inventory, weapon, current_attachments)\n elif option == 'remove':\n self.remove_attachment(inventory, current_attachments)\n else:\n return\n\n inventory.invalidate_cache()\n self.connection.commit()\n\n def inventory_modify_menu(self, inventory):\n\n while True:\n print()\n print(inventory.describe_current_inventory())\n\n print(\"What would you like to do to this inventory?\")\n options = ['add_item', 'remove_item', 'modify_attachments', 'finished']\n descriptions = [\n 'Add a weapon or armor',\n 'Remove a weapon or armor',\n 'Modify attachments for a weapon',\n 'Finish modifying, go back to main menu.'\n ]\n\n option = prompts.select_from_list(options, descriptions, \"Please choose an option from this list.\",\n interactive_with_single_option=True)\n\n if option == 'add_item':\n self.add_item_menu(inventory)\n elif option == 'remove_item':\n self.remove_item_menu(inventory)\n elif option == 'modify_attachments':\n self.modify_attachments_menu(inventory)\n elif option == 'finished':\n return\n\n self.connection.commit()\n inventory.invalidate_cache()\n\n def run(self):\n print(\"Creating an inventory!\")\n\n inventories = Inventory.get_for_player(self.connection, self.player.username)\n option, inventory = self.prompt_for_inventory_option(inventories)\n\n if option == 'rename':\n self.rename_inventory(inventory)\n else:\n if option == 'create':\n inventory = self.create_new_inventory()\n\n self.inventory_modify_menu(inventory)\n","repo_name":"rebeccajaubert/CS421","sub_path":"COMP421-Project-master/flows/inventory_create.py","file_name":"inventory_create.py","file_ext":"py","file_size_in_byte":12005,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"24505301370","text":"# @Time : 2021/4/116:54\n# @Author : 周云鹏\n# @File : area.PY\n\nimport requests\nimport lxml.html\nimport pandas as pd\n\n# data 获取所有的省市县\ndata = []\nbase_url = 'http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2020/'\nheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '\n 'Chrome/89.0.4389.90 Safari/537.36'}\n\nprovince_urls_responses = requests.get(base_url + 'index.html', headers=headers)\nprovince_urls_responses.encoding = 'gb2312'\nprovince_urls_etree = lxml.html.etree.HTML(province_urls_responses.text)\nprovince_urls = province_urls_etree.xpath('//tr[@class=\"provincetr\"]/td/a/@href')\nprovinces = province_urls_etree.xpath('//tr[@class=\"provincetr\"]/td/a/text()')\ndata += provinces # 添加省数据\n# 爬取省下地级市\nfor i in province_urls:\n city_url = base_url + i\n city_responses = requests.get(city_url, headers=headers)\n city_responses.encoding = 'gb2312'\n county_urls_etree = lxml.html.etree.HTML(city_responses.text)\n # print(city_responses.text)\n county_urls = county_urls_etree.xpath(\"//tr[@class='citytr']/td[2]/a/@href\")\n cities = county_urls_etree.xpath(\"//tr[@class='citytr']/td[2]/a/text()\")\n # print(cities)\n data += cities # 添加市数据\n # 爬出地级市下县区\n for j in county_urls:\n county_url = base_url + j\n county_responses = requests.get(county_url, headers=headers)\n county_responses.encoding = 'gb2312'\n r_urls_etree = lxml.html.etree.HTML(county_responses.text)\n # county_urls = r_urls_etree.xpath(\"//tr[@class='citytr']/td[2]/a/@href\")\n county = r_urls_etree.xpath(\"//tr[@class='countytr']/td[2]/a/text()\")\n print(f'正在爬取{county}')\n data += county\n\npd.DataFrame(columns=['area'], data=data).to_csv('area.csv')\n","repo_name":"zyp521/python","sub_path":"数据分析/行政区县爬取_国家统计局/area.py","file_name":"area.py","file_ext":"py","file_size_in_byte":1844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5986840893","text":"import os\nimport xks\nimport dask\nimport cftime\nimport shutil\nimport zipfile\nimport itertools\nimport numpy as np\nimport pandas as pd\nimport xarray as xr\nimport dask.bag as db\nimport xskillscore as xs\n\n\n# =======================================================================\n# I/O\n# =======================================================================\n\ndef open_zarr(path, variables=None, region=None, preprocess=None, open_zarr_kwargs={}):\n \"\"\" Open variables from a zarr collection. Varaibles that don't exist are ignored\n without warning\n \"\"\"\n def _get_variables(ds):\n \"\"\"Return variables that are in dataset\"\"\"\n return ds[list(set(ds.data_vars) & set(variables))]\n try:\n ds = xr.open_zarr(path, consolidated=True, **open_zarr_kwargs)\n except KeyError:\n # Try zip file\n ds = xr.open_zarr(\n f'{path}{os.path.extsep}zip', consolidated=True, **open_zarr_kwargs)\n if preprocess is not None:\n ds = preprocess(ds) \n if variables is not None:\n ds = _get_variables(ds)\n if region is not None:\n ds = get_region(ds, region)\n return ds\n\n\ndef open_zarr_forecasts(paths, variables=None, region=None, preprocess=None, convert_time_to_lead=True,\n time_name='time', open_zarr_kwargs={}):\n \"\"\" Open multiple forecast zarr collections and stack by initial date and lead time\"\"\"\n datasets = []; aux_coords = []\n for path in paths:\n ds = open_zarr(path, variables, region, preprocess, open_zarr_kwargs)\n init_date = ds[time_name].values[0]\n lead_time = range(len(ds[time_name]))\n if convert_time_to_lead:\n aux_coords.append(\n ds[time_name].rename({time_name: 'lead_time'}\n ).assign_coords({'lead_time': lead_time}))\n datasets.append(\n ds.rename({time_name: 'lead_time'}\n ).assign_coords({'lead_time': lead_time,\n 'init_date': init_date}))\n else:\n aux_coords.append(\n xr.DataArray(lead_time,\n coords={time_name: ds[time_name]}).assign_coords(\n {'init_date': init_date}))\n datasets.append(\n ds.assign_coords({'init_date': init_date}))\n if convert_time_to_lead:\n aux_coord = xr.concat(aux_coords, dim='init_date')\n dataset = xr.concat(datasets, dim='init_date')\n return dataset.assign_coords({time_name: aux_coord})\n else:\n # Broadcasting times when stacking by init_date generates large chunks so stack manually\n def _pad(ds, times):\n \"\"\" Pad with nans to fill out time dimension \"\"\"\n times_pad = times[~np.in1d(times, ds.time)]\n template = ds.isel(time=0, drop=True).expand_dims(\n time=times_pad)\n if ds.chunks is not None:\n template = template.chunk({'time': ds.chunks['time'][0]})\n padding = xr.full_like(template, fill_value=np.nan, dtype=np.float32)\n return xr.concat([ds, padding], dim='time')\n times = np.sort(np.unique(np.concatenate([d.time for d in datasets])))\n times = xr.DataArray(times, dims=['time'], coords={'time': times})\n aux_coord = xr.concat([_pad(ds, times) for ds in aux_coords], dim='init_date')\n dataset = xr.concat([_pad(ds, times) for ds in datasets], dim='init_date')\n return dataset.assign_coords({'lead_time': aux_coord})\n\n\ndef to_zarr(ds, filename, zip=True, clobber=False):\n \"\"\" Write to zarr file and read back \"\"\"\n def _zip_zarr(zarr_filename):\n \"\"\" Zip a zarr collection\"\"\"\n filename = f'{zarr_filename}{os.path.extsep}zip'\n with zipfile.ZipFile(\n filename, \"w\", \n compression=zipfile.ZIP_STORED, \n allowZip64=True) as fh:\n for root, _, filenames in os.walk(zarr_filename):\n for each_filename in filenames:\n each_filename = os.path.join(root, each_filename)\n fh.write(\n each_filename,\n os.path.relpath(each_filename, zarr_filename))\n if isinstance(ds, xr.DataArray):\n is_DataArray = True\n name = ds.name\n ds = ds.to_dataset(name=name)\n else:\n is_DataArray = False\n for var in ds.variables:\n ds[var].encoding = {}\n if zip:\n filename_open = f'{filename}{os.path.extsep}zip'\n else:\n filename_open = filename\n if (not os.path.exists(filename_open)) | clobber==True:\n ds.to_zarr(filename, mode='w', compute=True, consolidated=True)\n if zip:\n _zip_zarr(filename)\n shutil.rmtree(filename)\n ds = xr.open_zarr(filename_open, consolidated=True)\n return ds[name] if is_DataArray else ds\n\n\n# =======================================================================\n# Calculation of indices\n# =======================================================================\n\ndef calc_drought_factor(precip_20day, dim):\n return (-10 * (precip_20day - \n precip_20day.min(dim)) / \n (precip_20day.max(dim) - \n precip_20day.min(dim)) + 10).rename('drought_factor')\n\n\ndef calc_FFDI(D, T, H, W):\n \"\"\" Calculate the Forest Fire Danger Index as in Richardson 2021\n D is the drought factor computed from the 20 day accumulated total precipitation as\n D = -10 * (P20 - min(P20)) / (max(P20) - min(P20)) + 10\n where the min and max are over time\n T is the daily maximum 2m temperature \n H is the daily maximum 2m relative humidity\n W is the daily maximum 10m wind speed\n \"\"\"\n return (( D ** 0.987 ) * np.exp( 0.0338 * T - 0.0345 * H + 0.0234 * W + 0.243147 )).rename('FFDI')\n\n\ndef calc_nino34(sst_anom, area=None, lat_dim='lat', lon_dim='lon'):\n \"\"\" Return Nino 3.4 index \"\"\"\n box = [-5.0, 5.0, 190.0, 240.0]\n \n return lat_lon_average(sst_anom, box, area, lat_dim, lon_dim)\n\n\ndef calc_dmi(sst_anom, area=None, lat_dim='lat', lon_dim='lon'):\n \"\"\" Return DMI index \"\"\"\n boxW = [-10.0,10.0,50.0,70.0]\n boxE = [-10.0,0.0,90.0,110.0]\n \n da_W = lat_lon_average(sst_anom, boxW, area, lat_dim, lon_dim)\n da_E = lat_lon_average(sst_anom, boxE, area, lat_dim, lon_dim)\n \n return (da_W - da_E)\n\n\ndef calc_sam(slp, clim_period, slp_for_clim=None,\n lat_dim='lat', lon_dim='lon', groupby_dim='time'):\n \"\"\" Returns southern annular mode index as defined by Gong, D. and Wang, S., 1999\n If you wish to use a different dataset to normalise the index, provide this as slp_for_clim\n \"\"\"\n def _normalise(group, clim_group):\n \"\"\" Return the anomalies normalize by their standard deviation \"\"\"\n month = group[groupby_dim].dt.month.values[0]\n months, _ = zip(*list(clim_group))\n clim_group_month = list(clim_group)[months.index(month)][1]\n clim_over = [groupby_dim, 'ensemble'] if 'ensemble' in group.dims else groupby_dim\n return (group - clim_group_month.mean(clim_over)) / clim_group_month.std(clim_over)\n\n slp_40 = slp.interp({lat_dim: -40}).mean(lon_dim)\n slp_65 = slp.interp({lat_dim: -65}).mean(lon_dim)\n \n clim_period_ = pd.date_range(clim_period.start, clim_period.stop, periods=2)\n period_start = cftime.datetime(\n clim_period_[0].year, clim_period_[0].month, clim_period_[0].day)\n period_end = cftime.datetime(\n clim_period_[1].year, clim_period_[1].month, clim_period_[1].day)\n \n if slp_for_clim is not None:\n period_mask = (slp_for_clim['time'] >= period_start) & (slp_for_clim['time'] <= period_end)\n slp_40_for_clim = slp_for_clim.interp(\n {lat_dim: -40}).mean(lon_dim).where(period_mask, drop=True)\n slp_65_for_clim = slp_for_clim.interp(\n {lat_dim: -65}).mean(lon_dim).where(period_mask, drop=True)\n else:\n period_mask = (slp['time'] >= period_start) & (slp['time'] <= period_end)\n slp_40_for_clim = slp_40.where(period_mask, drop=True)\n slp_65_for_clim = slp_65.where(period_mask, drop=True)\n\n slp_40_group = slp_40.groupby(groupby_dim+'.month')\n slp_40_group_clim = slp_40_for_clim.groupby(groupby_dim+'.month')\n slp_65_group = slp_65.groupby(groupby_dim+'.month')\n slp_65_group_clim = slp_65_for_clim.groupby(groupby_dim+'.month')\n\n norm_40 = slp_40_group.map(_normalise, clim_group=slp_40_group_clim)\n norm_65 = slp_65_group.map(_normalise, clim_group=slp_65_group_clim)\n \n return norm_40 - norm_65\n\n\n# =======================================================================\n# Forecast tools\n# =======================================================================\n\ndef forecast_clim(fcst):\n \"\"\" Get the lead-dependent forecast model climatology \n \"\"\"\n def _forecast_clim(ds):\n stack_dim = [d for d in ds.dims if 'stacked_' in d][0]\n ds = ds.copy().assign_coords(\n {stack_dim: ds[stack_dim].init_date})\n return ds.groupby(f'{stack_dim}.month').mean(stack_dim)\n \n return fcst.groupby(fcst.lead_time).apply(_forecast_clim)\n\n\ndef get_bias(fcst, obsv):\n \"\"\" Get the lead-dependent model bias relative to the observed mean value \n \"\"\"\n fcst_clim = forecast_clim(fcst)\n obsv_clim = obsv.mean()\n\n return fcst_clim - obsv_clim\n\n\ndef remove_bias(fcst, bias):\n \"\"\" Remove the lead-dependent model bias \"\"\"\n def _remove_bias(ds):\n stack_dim = [d for d in ds.dims if 'stacked_' in d][0]\n stack_coord = ds[stack_dim]\n ds = ds.copy().assign_coords(\n {stack_dim: ds[stack_dim].init_date})\n lead = np.unique(ds.lead_time)\n assert len(lead) == 1\n lead = lead[0]\n bc = ds.groupby(f'{stack_dim}.month') - bias.sel(lead_time=lead)\n return bc.assign_coords({stack_dim: stack_coord})\n \n return fcst.groupby(fcst.lead_time).apply(_remove_bias).drop('month')\n\n\ndef reindex_forecast(ds, init_date_dim='init_date', lead_time_dim='lead_time', time_dim='time', dropna=False):\n \"\"\" Restack by time (lead_time) a forecast dataset stacked by lead_time (time) \n Only works on DataArrays at the moment\n \"\"\"\n if lead_time_dim in ds.dims:\n index_dim = lead_time_dim\n reindex_dim = time_dim\n elif time_dim in ds.dims:\n index_dim = time_dim\n reindex_dim = lead_time_dim\n else:\n raise ValueError(\"Neither a time nor lead_time dimension can be found\")\n swap = {index_dim: reindex_dim}\n \n reindex_coord = np.sort(np.unique(ds[reindex_dim]))\n reindex_coord = xr.DataArray(\n reindex_coord, dims=[reindex_dim], coords={reindex_dim: reindex_coord})\n reindex_coord = reindex_coord[reindex_coord.notnull()] # Using \"where\" here cast datetime dtypes badly\n \n def _pad(ds, reindex):\n \"\"\" Pad with nans to fill out reindex dimension \"\"\"\n reindex_pad = reindex[~np.in1d(reindex, ds[reindex_dim])]\n if len(reindex_pad) > 0:\n template = ds.isel(\n {reindex_dim: len(reindex_pad)*[0]}, drop=True).assign_coords(\n {reindex_dim: reindex_pad})\n if ds.chunks is not None:\n ax = ds.get_axis_num(reindex_dim)\n template = template.chunk({reindex_dim: ds.chunks[ax][0]})\n padding = xr.full_like(template, np.nan, ds.dtype)\n # Force index dim to be nans where padded\n padding = padding.assign_coords(\n {index_dim: xr.full_like(template[index_dim].compute(), np.nan, ds.dtype)})\n return xr.concat([ds, padding], dim=reindex_dim)\n else:\n return ds\n\n to_concat = []\n for init_date in ds[init_date_dim]:\n fcst = ds.sel({init_date_dim: init_date})\n fcst = fcst.where(fcst[reindex_dim].notnull(), drop=True)\n # Broadcasting times when stacking by init_date generates large chunks so stack manually\n fcst_padded = _pad(fcst.swap_dims(swap), reindex_coord)\n to_concat.append(fcst_padded)\n \n concat = xr.concat(to_concat, dim=init_date_dim)\n if dropna:\n return concat.where(concat.notnull(), drop=True)\n else:\n return concat\n \n \ndef stack_super_ensemble(ds, by_lead):\n \"\"\" Stack into super ensemble \"\"\"\n def _stack(ds, sample_dims):\n for dim in sample_dims:\n ds = ds.assign_coords({dim: range(len(ds[dim]))})\n ds_stack = ds.stack(sample=sample_dims).dropna('sample').drop('lead_time')\n return ds_stack.assign_coords({'sample': range(len(ds_stack['sample']))})\n \n if by_lead:\n sample_dims = ['stacked_init_date_time', 'ensemble']\n return ds.groupby(ds.lead_time).map(\n _stack, sample_dims=sample_dims)\n else:\n sample_dims = ['init_date', 'time', 'ensemble']\n return _stack(ds, sample_dims)\n\n\n# =======================================================================\n# Statistical testing\n# =======================================================================\n\ndef mean_correlation_ensemble_combinations(ds, dim='init_date', ensemble_dim='ensemble'):\n \"\"\" Compute all combinations of correlations between ensemble \n members and return the mean\n \"\"\"\n combinations = np.array(\n list(itertools.combinations(range(len(ds[ensemble_dim])), 2)))\n e1 = ds.isel(\n ensemble=combinations[:,0]).assign_coords(\n {ensemble_dim: range(combinations.shape[0])})\n e2 = ds.isel(\n ensemble=combinations[:,1]).assign_coords(\n {ensemble_dim: range(combinations.shape[0])})\n corr_combinations = xs.spearman_r(e1, e2, dim=dim, skipna=True)\n mean_corr = corr_combinations.mean(ensemble_dim)\n return mean_corr\n\n\ndef random_resample(*args, samples,\n function=None, function_kwargs=None, bundle_args=True,\n replace=True):\n \"\"\"\n Randomly resample from provided xarray args and return the results of the subsampled dataset passed through \\\n a provided function\n \n Parameters\n ----------\n *args : xarray DataArray or Dataset\n Objects containing data to be resampled. The coordinates of the first object are used for resampling and the \\\n same resampling is applied to all objects\n samples : dictionary\n Dictionary containing the dimensions to subsample, the number of samples and the continuous block size \\\n within the sample. Of the form {'dim1': (n_samples, block_size), 'dim2': (n_samples, block_size)}. The first \\\n object in args must contain all dimensions listed in samples, but subsequent objects need not.\n function : function object, optional\n Function to reduced the subsampled data\n function_kwargs : dictionary, optional\n Keyword arguments to provide to function\n bundle_args : boolean, optional\n If True, pass all resampled objects to function together, otherwise pass each object through function \\\n separately\n replace : boolean, optional\n Whether the sample is with or without replacement\n \n Returns\n -------\n sample : xarray DataArray or Dataset\n Array containing the results of passing the subsampled data through function\n \"\"\"\n samples_spec = samples.copy() # copy because use pop below\n args_sub = [obj.copy() for obj in args]\n dim_block_1 = [d for d, s in samples_spec.items() if s[1] == 1]\n\n # Do all dimensions with block_size = 1 together\n samples_block_1 = { dim: samples_spec.pop(dim) for dim in dim_block_1 }\n random_samples = {dim: \n np.random.choice(\n len(args_sub[0][dim]),\n size=n,\n replace=replace)\n for dim, (n, _) in samples_block_1.items()}\n args_sub = [obj.isel(\n {dim: random_samples[dim] \n for dim in (set(random_samples.keys()) & set(obj.dims))}) for obj in args_sub]\n\n # Do any remaining dimensions\n for dim, (n, block_size) in samples_spec.items():\n n_blocks = int(n / block_size)\n random_samples = [slice(x,x+block_size) \n for x in np.random.choice(\n len(args_sub[0][dim])-block_size+1, \n size=n_blocks,\n replace=replace)]\n args_sub = [xr.concat([obj.isel({dim: random_sample}) \n for random_sample in random_samples],\n dim=dim) \n if dim in obj.dims else obj \n for obj in args_sub]\n\n if function:\n if bundle_args:\n if function_kwargs is not None:\n res = function(*args_sub, **function_kwargs)\n else:\n res = function(*args_sub)\n else:\n if function_kwargs is not None:\n res = tuple([function(obj, **function_kwargs) for obj in args_sub])\n else:\n res = tuple([function(obj) for obj in args_sub])\n else:\n res = tuple(args_sub,)\n\n if isinstance(res, tuple):\n if len(res) == 1:\n return res[0]\n else:\n return res\n \n \ndef n_random_resamples(*args, samples, n_repeats, \n function=None, function_kwargs=None, bundle_args=True, \n replace=True, with_dask=True):\n \"\"\"\n Repeatedly randomly resample from provided xarray objects and return the results of the subsampled dataset passed \\\n through a provided function\n \n Parameters\n ----------\n args : xarray DataArray or Dataset\n Objects containing data to be resampled. The coordinates of the first object are used for resampling and the \\\n same resampling is applied to all objects\n samples : dictionary\n Dictionary containing the dimensions to subsample, the number of samples and the continuous block size \\\n within the sample. Of the form {'dim1': (n_samples, block_size), 'dim2': (n_samples, block_size)}\n n_repeats : int\n Number of times to repeat the resampling process\n function : function object, optional\n Function to reduced the subsampled data\n function_kwargs : dictionary, optional\n Keyword arguments to provide to function\n replace : boolean, optional\n Whether the sample is with or without replacement\n bundle_args : boolean, optional\n If True, pass all resampled objects to function together, otherwise pass each object through function \\\n separately\n with_dask : boolean, optional\n If True, use dask to parallelize across n_repeats using dask.delayed\n \n Returns\n -------\n sample : xarray DataArray or Dataset\n Array containing the results of passing the subsampled data through function\n \"\"\"\n\n if with_dask & (n_repeats > 500):\n n_args = itertools.repeat(args[0], times=n_repeats)\n b = db.from_sequence(n_args, npartitions=100)\n rs_list = b.map(random_resample, *(args[1:]), \n **{'samples':samples, 'function':function, \n 'function_kwargs':function_kwargs, 'replace':replace}).compute()\n else: \n resample_ = dask.delayed(random_resample) if with_dask else random_resample\n rs_list = [resample_(*args,\n samples=samples,\n function=function,\n function_kwargs=function_kwargs,\n bundle_args=bundle_args,\n replace=replace) for _ in range(n_repeats)] \n if with_dask:\n rs_list = dask.compute(rs_list)[0]\n \n if all(isinstance(r, tuple) for r in rs_list):\n return tuple([xr.concat([r.unify_chunks() for r in rs], dim='k') for rs in zip(*rs_list)])\n else:\n return xr.concat([r.unify_chunks() for r in rs_list], dim='k')\n \n \ndef fidelity_KS_univariate(fcst, obsv, max_period, by_lead):\n \"\"\" Perform a Kolmogorov-Smirnov test on univariate data \"\"\"\n def _get_KS_statistic(fcst_ds, obsv_ds, by_lead=False):\n if by_lead:\n # Applied per lead_time within groupby\n stack_dim = [d for d in fcst_ds.dims if 'stacked_' in d][0]\n fcst_ds = fcst_ds.assign_coords({stack_dim: fcst_ds[stack_dim].time})\n fcst_ds = fcst_ds.rename({stack_dim: 'time'})\n sample_dims = ['ensemble','time']\n else:\n sample_dims = ['ensemble','init_date','time']\n\n # Adjust period to range of available data\n min_overlap_year = max(\n fcst_ds.time.dt.year.min().item(),\n obsv_ds.time.dt.year.min().item())\n max_overlap_year = min(\n fcst_ds.time.dt.year.max().item(),\n obsv_ds.time.dt.year.max().item())\n period = slice(str(min_overlap_year), str(max_overlap_year))\n\n fcst_ds_samples = fcst_ds.sel(time=period).stack(\n sample=sample_dims).dropna('sample')\n obsv_ds_samples = obsv_ds.sel(time=period).rename({'time': 'sample'})\n\n K, p = xks.ks1d2s(obsv_ds_samples, fcst_ds_samples, 'sample')\n\n if isinstance(K, xr.Dataset):\n data_vars = K.data_vars\n K = K.rename({ d: f'{d}_K_obs' for d in data_vars })\n p = p.rename({ d: f'{d}_p-value' for d in data_vars })\n D = xr.merge([K, p])\n D['period_start'] = int(period.start)\n D['period_end'] = int(period.stop)\n else:\n D = K.to_dataset(name='K_obs')\n D['p-value'] = p\n D['period_start'] = int(period.start)\n D['period_end'] = int(period.stop)\n \n return D\n \n fcst_ds = fcst.sel(time=max_period)\n obsv_ds = obsv.sel(time=max_period)\n\n if by_lead:\n return fcst_ds.groupby(fcst_ds.lead_time).map(\n _get_KS_statistic, obsv_ds=obsv_ds, by_lead=by_lead)\n else:\n return _get_KS_statistic(fcst_ds, obsv_ds, by_lead=by_lead)\n \n \ndef fidelity_KS_bivariate(fcst_var1, fcst_var2, obsv_var1, obsv_var2, max_period, by_lead, n_bootstraps=10_000):\n \"\"\" Perform a Kolmogorov-Smirnov test on bivariate data \"\"\"\n def _get_KS_statistic(fcst_ds, obsv_ds, by_lead=False):\n if by_lead:\n # Applied per lead_time within groupby\n stack_dim = [d for d in fcst_ds.dims if 'stacked_' in d][0]\n fcst_ds = fcst_ds.assign_coords({stack_dim: fcst_ds[stack_dim].time})\n fcst_ds = fcst_ds.rename({stack_dim: 'time'})\n sample_dims = ['ensemble','time']\n else:\n sample_dims = ['ensemble','init_date','time']\n\n # Adjust period to range of available data\n min_overlap_year = max(\n fcst_ds.time.dt.year.min().item(),\n obsv_ds.time.dt.year.min().item())\n max_overlap_year = min(\n fcst_ds.time.dt.year.max().item(),\n obsv_ds.time.dt.year.max().item())\n period = slice(str(min_overlap_year), str(max_overlap_year))\n\n fcst_ds_samples = fcst_ds.sel(time=period).stack(\n sample=sample_dims).dropna('sample')\n obsv_ds_samples = obsv_ds.sel(time=period).rename({'time': 'sample'})\n\n D = xks.ks2d2s(obsv_ds_samples, fcst_ds_samples, 'sample')\n D_mc = n_random_resamples(fcst_ds_samples,\n samples={'sample': (len(obsv_ds_samples.sample), 1)}, \n n_repeats=n_bootstraps,\n function=xks.ks2d2s,\n function_kwargs={'ds2': fcst_ds_samples, 'sample_dim': 'sample'},\n with_dask=True)\n\n D = D.to_dataset(name='K_obs')\n D['K'] = D_mc\n D['period_start'] = int(period.start)\n D['period_end'] = int(period.stop)\n return D\n\n assert fcst_var1.sizes == fcst_var2.sizes\n assert obsv_var1.sizes == obsv_var2.sizes\n\n if isinstance(fcst_var1, xr.DataArray):\n # Assume all are DataArrays\n assert fcst_var1.name == obsv_var1.name\n assert fcst_var2.name == obsv_var2.name\n \n elif isinstance(fcst_var1, xr.Dataset):\n # Assume all are Datasets\n fcst_var1_vars = list(fcst_var1.data_vars)\n fcst_var2_vars = list(fcst_var2.data_vars)\n obsv_var1_vars = list(obsv_var1.data_vars)\n obsv_var2_vars = list(obsv_var2.data_vars)\n assert len(fcst_var1_vars) == 1\n assert len(fcst_var2_vars) == 1\n assert fcst_var1_vars == obsv_var1_vars\n assert fcst_var2_vars == obsv_var2_vars\n else:\n raise InputError('Input arrays must be xarray DataArrays or Datasets')\n\n fcst_ds = xr.merge([fcst_var1.sel(time=max_period), fcst_var2.sel(time=max_period)])\n obsv_ds = xr.merge([obsv_var1.sel(time=max_period), obsv_var2.sel(time=max_period)])\n\n if by_lead:\n return fcst_ds.groupby(fcst_ds.lead_time).map(\n _get_KS_statistic, obsv_ds=obsv_ds, by_lead=by_lead)\n else:\n return _get_KS_statistic(fcst_ds, obsv_ds, by_lead=by_lead)\n \n\ndef likelihoods_of_exceedance(*variables, event=None, with_dask=False):\n \"\"\" Get empirical likelihoods of exceeding all combinations of the input variables.\n If event is provided, it should be a list of the same length as the number of\n variables\n For now, inputs should be one-dimensional\n \"\"\"\n def _loe(reference):\n mask = variables[0] >= reference[0]\n for i in range(1,len(reference)):\n mask &= variables[i] >= reference[i]\n return 100 * mask.mean().values\n \n if event is None:\n references = zip(*variables)\n single_event = False\n else:\n if not isinstance(event, list):\n raise ValueError('event should be a list of the same length as the number of variables')\n assert len(variables) == len(event)\n references = [event]\n single_event = True\n\n if with_dask & (single_event == False):\n b = db.from_sequence(references, npartitions=100)\n likelihoods = np.array(b.map(_loe).compute())\n else:\n likelihoods = np.array([_loe(reference) for reference in references])\n \n # Package back up as xarray object\n dim = variables[0].dims[0]\n if event is None:\n coords = {v.name: ([dim], v.values) for v in variables}\n coords = {**coords, dim: ([dim], range(len(variables[0][dim])))}\n else:\n coords = {v.name: ([dim], [v.item()]) for v in event}\n coords = {**coords, dim: ([dim], [0])}\n return xr.DataArray(likelihoods, dims=[dim], coords=coords)\n\n \n# =======================================================================\n# Utilities\n# =======================================================================\n\ndef get_region(ds, region):\n \"\"\" Return a region from a provided DataArray or Dataset\n \n Parameters\n ----------\n region_mask: xarray DataArray or list\n Boolean mask of the region to keep\n \"\"\"\n return ds.where(region, drop=True)\n\n\ndef sum_min_samples(ds, dim, min_samples):\n \"\"\" Return sum only if there are more than min_samples along dim \"\"\"\n s = ds.sum(dim, skipna=False)\n # Reference lead_time coord to final lead in sample\n if 'lead_time' in ds.coords:\n if dim in ds['lead_time'].dims:\n l = ds['lead_time'].max(dim, skipna=False)\n s = s.assign_coords({'lead_time': l if len(ds[dim]) >= min_samples else np.nan*l})\n return s if len(ds[dim]) >= min_samples else np.nan*s\n\n\ndef mean_min_samples(ds, dim, min_samples):\n \"\"\" Return mean only if there are more than min_samples along dim \"\"\"\n m = ds.mean(dim, skipna=False)\n # Reference lead_time coord to final lead in sampl\n if 'lead_time' in ds.coords:\n if dim in ds['lead_time'].dims:\n l = ds['lead_time'].max(dim, skipna=False)\n m = m.assign_coords({'lead_time': l if len(ds[dim]) >= min_samples else np.nan*l})\n return m if len(ds[dim]) >= min_samples else np.nan*m\n\n\ndef resample_months_in_year(ds, months, method, time_dim='time', lead_time_dim='lead_time'):\n \"\"\" Resample monthly forecasts to a set of months for each year \n This approach is hoaky but much faster/more memory efficient than using resample\n \"\"\"\n # Clip to first instance of first month\n min_date = ds[time_dim].min()\n min_year = min_date.dt.year.values\n min_month = min_date.dt.month.values\n start_time = f'{min_year}-{months[0]:02d}' if min_month <= months[0] else f'{min_year+1}-{months[0]:02d}'\n ds = ds.copy().sel({time_dim:slice(start_time, None)})\n\n # Create mask of months to keep\n keep = ds[time_dim].dt.month == months[0]\n for month in months[1:]:\n keep = keep | (ds[time_dim].dt.month == month)\n ds = ds.where(keep, drop=True)\n \n # Use coarsen to do resampling\n return getattr(\n ds.coarsen(\n {time_dim: len(months)}, \n boundary='trim',\n coord_func={time_dim: 'max',\n lead_time_dim: 'max'}), \n method)(skipna=False)\n\n\ndef calc_DEC_average(ds):\n \"\"\" Return the Dec average from daily data, excluding incomplete months \"\"\"\n ds_mon = ds.resample(\n time=\"M\", label='right').apply(\n mean_min_samples, dim='time', min_samples=31)\n return ds_mon.where(ds_mon.time.dt.month == 12, drop=True)\n# return _resample_months_in_year(ds, months=[12]).apply(\n# mean_min_samples, dim='time', min_samples=31)\n\n\ndef calc_ANN_accum(ds):\n \"\"\" Return the Jan-Dec accumulation from daily data, excluding incomplete months \"\"\"\n return ds.resample(\n time=\"A-DEC\", label='right').apply(\n sum_min_samples, dim='time', min_samples=365)\n\n\ndef truncate_latitudes(ds):\n for dim in ds.dims:\n if 'lat' in dim:\n ds = ds.assign_coords({dim: ds[dim].round(decimals=10)})\n return ds\n\n\ndef round_to_end_of_month(ds, dim='time'):\n from xarray.coding.cftime_offsets import MonthEnd\n return ds.assign_coords({dim: ds[dim].dt.floor('D') + MonthEnd()})\n\n\ndef interpolate_na_times(ds, coord='time'):\n \"\"\" Linearly interpolate any NaNs in time coordinate \"\"\"\n def _date2num(time, units, calendar, has_year_zero):\n if time != time:\n return time\n else:\n return cftime.date2num(time, units, calendar, has_year_zero)\n \n _vdate2num = np.vectorize(_date2num)\n\n def _num2date(time, units, calendar, has_year_zero):\n return cftime.num2date(time, units, calendar, has_year_zero)\n \n _vnum2date = np.vectorize(_num2date)\n\n ds_cpy = ds.copy()\n\n units = 'days since 1900-01-01'\n # Assumes all calendar entries are the same\n calendar = ds_cpy[coord].values.flat[0].calendar\n has_year_zero = ds_cpy[coord].values.flat[0].has_year_zero\n \n ds_cpy.time.values = _vdate2num(ds_cpy.time.values, units, calendar, has_year_zero)\n ds_cpy = ds_cpy.assign_coords(\n {'time': ds_cpy.time.interpolate_na(dim='lead_time', \n method=\"linear\", \n fill_value=\"extrapolate\")})\n ds_cpy.time.values = _vnum2date(ds_cpy.time.values, units, calendar, has_year_zero)\n \n # Check that all values that changed were nans\n assert ds.time.where(ds_cpy.time != ds.time).isnull().all()\n \n return ds_cpy\n\n\ndef estimate_cell_areas(ds, lon_dim='lon', lat_dim='lat'):\n \"\"\"\n Calculate the area of each grid cell\n \n Stolen/adapted from: https://towardsdatascience.com/the-correct-way-to-average-the-globe-92ceecd172b7\n \"\"\"\n \n def _earth_radius(lat):\n \"\"\" Calculate radius of Earth assuming oblate spheroid defined by WGS84\n \"\"\"\n from numpy import deg2rad, sin, cos\n\n # define oblate spheroid from WGS84\n a = 6378137\n b = 6356752.3142\n e2 = 1 - (b**2/a**2)\n\n # convert from geodecic to geocentric\n # see equation 3-110 in WGS84\n lat = xr.ufuncs.deg2rad(lat)\n lat_gc = xr.ufuncs.arctan( (1-e2)*xr.ufuncs.tan(lat) )\n\n # radius equation\n # see equation 3-107 in WGS84\n return ((a * (1 - e2)**0.5) \n / (1 - (e2 * xr.ufuncs.cos(lat_gc)**2))**0.5)\n\n R = _earth_radius(ds[lat_dim])\n\n dlat = xr.ufuncs.deg2rad(ds[lat_dim].diff(lat_dim))\n dlon = xr.ufuncs.deg2rad(ds[lon_dim].diff(lon_dim))\n\n dy = dlat * R\n dx = dlon * R * xr.ufuncs.cos(xr.ufuncs.deg2rad(ds[lat_dim]))\n\n return dy * dx\n\n\ndef lat_lon_average(ds, box, area, lat_dim='lat', lon_dim='lon'):\n \"\"\" Get average over lat lon region \"\"\"\n def _get_lat_lon_region(ds, box, lat_dim, lon_dim):\n region = (\n (ds[lat_dim] >= box[0]) & (ds[lat_dim] <= box[1])\n ) & (\n (ds[lon_dim] >= box[2]) & (ds[lon_dim] <= box[3]))\n return ds.where(region)\n \n ds = ds.assign_coords({lon_dim: (ds[lon_dim] + 360) % 360})\n\n if area is None:\n area = estimate_cell_areas(ds, lon_dim, lat_dim)\n \n if (lat_dim in ds.dims) and (lon_dim in ds.dims):\n # lat and lon are dims so use isel to get regions\n lon_inds = np.where(\n np.logical_and(ds[lon_dim].values>=box[2], \n ds[lon_dim].values<=box[3]))[0]\n lat_inds = np.where(\n np.logical_and(ds[lat_dim].values>=box[0], \n ds[lat_dim].values<=box[1]))[0]\n return ds.isel(\n {lon_dim: lon_inds, lat_dim: lat_inds}).weighted(\n area).mean(\n dim=[lat_dim, lon_dim])\n elif (lat_dim in ds.dims) and (lon_dim not in ds.dims):\n return _get_lat_lon_region(\n ds, box, lat_dim, lon_dim).weighted(\n area).mean(\n dim=set([lat_dim, *ds[lon_dim].dims]))\n elif (lat_dim not in ds.dims) and (lon_dim in ds.dims):\n return _get_lat_lon_region(\n ds, box, lat_dim, lon_dim).weighted(\n area).mean(\n dim=set([*ds[lat_dim].dims, lon_dim]))\n else:\n return _get_lat_lon_region(\n ds, box, lat_dim, lon_dim).weighted(\n area).mean(\n dim=set([*ds[lat_dim].dims, *ds[lon_dim].dims]))\n","repo_name":"dougiesquire/Squire_2021_fire_susceptibility","sub_path":"myfuncs.py","file_name":"myfuncs.py","file_ext":"py","file_size_in_byte":34418,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"10412845834","text":"from selenium import webdriver\nimport time\nimport csv\nfrom selenium.webdriver.support.ui import Select\nfrom selenium.webdriver.common.keys import Keys\n\nclass MiralinksParser:\n\n def __init__(self):\n options = webdriver.ChromeOptions()\n prefs = {'profile.default_content_setting_values': {'images': 2}}\n options.add_experimental_option(\"prefs\", prefs)\n self.driver = webdriver.Chrome(executable_path='/Users/macbook/Desktop/Work/parser-miralinks/chromedriver', options=options)\n self.transin_to_site()\n self.login_in_site()\n self.transin_to_catalog()\n # self.see_all_list()\n pages = 1\n while pages <= 661:\n print(pages, '________________________________', pages)\n self.pars_table()\n pagination = self.driver.find_element_by_class_name('next')\n pagination.click()\n pages += 1\n time.sleep(2)\n\n def transin_to_site(self):\n self.driver.maximize_window()\n self.driver.get(\"https://www.miralinks.ru/\")\n\n def login_in_site(self):\n email = self.driver.find_element_by_xpath('//*[@id=\"loginForm\"]/div/div[1]/input')\n email.send_keys('aal940722r')\n passw = self.driver.find_element_by_xpath('//*[@id=\"loginForm\"]/div/div[2]/input')\n passw.send_keys('vold6SOPT-shog_shif')\n login = self.driver.find_element_by_xpath('//*[@id=\"loginForm\"]/div/div[4]/a/span/span')\n login.click()\n time.sleep(1)\n\n def transin_to_catalog(self):\n self.driver.get('https://www.miralinks.ru/catalog')\n time.sleep(5)\n\n # def see_all_list(self):\n # self.driver.find_element_by_xpath('/html/body/div[21]/section/div/div/div/div[3]/div[6]/div[4]/div[3]/a[2]').click()\n # time.sleep(9)\n\n def pars_table(self):\n table_id = self.driver.find_element_by_id('Catalog_50479333')\n tbody = table_id.find_element_by_tag_name('tbody')\n rows = tbody.find_elements_by_tag_name('tr')\n for row in rows:\n cells = row.find_elements_by_tag_name(\"td\")\n all_td = [(cells[i].text) for i in range(len(cells))]\n #print(all_td)\n with open(\"miralinks.csv\", mode=\"a\", encoding='utf-8') as w_file:\n file_writer = csv.writer(w_file, delimiter=\",\", lineterminator=\"\\r\\n\")\n file_writer.writerow([(cells[i].text) for i in range(len(cells))])\n\ndef main():\n gp= MiralinksParser()\n\nif __name__ == '__main__':\n main()","repo_name":"alex-lbv/learn_parser-miralinks","sub_path":"pars.py","file_name":"pars.py","file_ext":"py","file_size_in_byte":2495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20892768420","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# Problem\n# \n# After identifying the exons and introns of an RNA string, we only need to delete the introns and concatenate the exons to form a new string ready for translation.\n# \n# Given: A DNA string s\n# (of length at most 1 kbp) and a collection of substrings of s\n# \n# acting as introns. All strings are given in FASTA format.\n# \n# Return: A protein string resulting from transcribing and translating the exons of s\n# \n# . (Note: Only one solution will exist for the dataset provided.)\n# Sample Dataset\n# \n# >Rosalind_10\n# ATGGTCTACATAGCTGACAAACAGCACGTAGCAATCGGTCGAATCTCGAGAGGCATATGGTCACATGATCGGTCGAGCGTGTTTCAAAGTTTGCGCCTAG\n# >Rosalind_12\n# ATCGGTCGAA\n# >Rosalind_15\n# ATCGGTCGAGCGTGT\n# \n# Sample Output\n# \n# MVYIADKQHVASREAYGHMFKVCA\n# \n\n# In[1]:\n\n\n#Je parse\ndef parse_fasta(file):\n #On ouvre le file et on créer un dictionnaire et une variable header qui stock les indices du dico\n file = open(file, \"r\")\n header = ''\n dico = {}\n\n #On boucle sur les ligne du file\n for line in file:\n \n #On stock le nom de la séquence dans la variable header sans le > et on la stock dans le dico en face d'une case vide\n if line.startswith(\">\"):\n header = line[1:-1]\n dico[header] = \"\"\n #on remplis la case vide avec la bonne séquence, attention au [:-1] qui est important pour une raison qui m'échappe un peu (pour pas tenir compte du \\n ?)\n else:\n dico[header] += line[:-1]\n \n return dico \n\nq = parse_fasta('file/rosalind_splc.txt')\n\n\n# In[2]:\n\n\n#Je prends les sequences dans mon dico\nseq_list=[]\nfor i in q.values():\n seq_list.append(i) \n\n#je créer une str de la première séquence\nall_gene = seq_list[0]\n\n\n# In[3]:\n\n\nindex1 = []\nindex2 = []\nspliced_gene = ''\n\n#je récupère dans les liste 1 et 2 les positions de début et de fin des sequences à splicer.\n#Attention, les introns sont pas donné dans l'ordre donc il faut trier les index\n\nfor i in seq_list[1:]:\n for k,j in enumerate(all_gene):\n if all_gene[k:k+len(i)] == i:\n a= k+len(i)\n index1.append(int(k))\n index2.append(int(a))\n \nindex1=sorted(index1)\nindex2=sorted(index2)\n \n#je créer mon nouveau gène grâce aux indices stocké dans index1 et index2.\nfor j, i in enumerate(index1):\n if spliced_gene == '':\n spliced_gene += all_gene[0:i]\n else :\n b = index2[j-1]\n spliced_gene += all_gene[b:i]\n\n\n#il manque la fin du gène, du dernier indice2 à la fin de all_gene\nspliced_gene += all_gene[index2[-1]:]\n\n\n#mon jolie gene splicé\nprint(spliced_gene)\n\n\n# In[4]:\n\n\n#Je traduis \n\nstring = \"\"\"TTT F CTT L ATT I GTT V\nTTC F CTC L ATC I GTC V\nTTA L CTA L ATA I GTA V\nTTG L CTG L ATG M GTG V\nTCT S CCT P ACT T GCT A\nTCC S CCC P ACC T GCC A\nTCA S CCA P ACA T GCA A\nTCG S CCG P ACG T GCG A\nTAT Y CAT H AAT N GAT D\nTAC Y CAC H AAC N GAC D\nTAA Stop CAA Q AAA K GAA E\nTAG Stop CAG Q AAG K GAG E\nTGT C CGT R AGT S GGT G\nTGC C CGC R AGC S GGC G\nTGA Stop CGA R AGA R GGA G\nTGG W CGG R AGG R GGG G\"\"\"\n\ncoded = spliced_gene\ndecoded = ''\n\ntraL = string.split()\ntraDict = dict(zip(traL[0::2], traL[1::2]))\n\nfor i in range(0, len(coded)-3, 3):\n decoded += traDict[coded[i:i+3]]\n\nprint (decoded)\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"cedricusureau/Rosalind","sub_path":"RNA Splicing.py","file_name":"RNA Splicing.py","file_ext":"py","file_size_in_byte":3527,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14867407828","text":"def factorial1(x):\n result = x\n for i in range(1, x):\n result *= i\n return result\n\n\ndef factorial2(x):\n if x == 1:\n result = 1\n else:\n result = x * factorial2(x-1)\n # print(result)\n return result\n\n\nprint('循环实现阶乘的结果:' + str(factorial1(5)))\nprint('递归实现阶乘的结果:' + str(factorial2(5)))\n","repo_name":"YDXiao/PythonStudy","sub_path":"hello/factorial.py","file_name":"factorial.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39356498082","text":"def principal():\r\n \"\"\"Gets the principal amount.\"\"\"\r\n while True:\r\n while True:\r\n try:\r\n P = int(input('Enter the principal amount:\\n')) #Principal amount\r\n except ValueError:\r\n print('You did not enter an amount.')\r\n continue\r\n break\r\n if P <= 0:\r\n continue\r\n else:\r\n return P\r\n\r\n\r\ndef interest_rate():\r\n \"\"\"Gets the interest rate and makes sure that it is a decimal.\"\"\"\r\n while True:\r\n try:\r\n R = float(input('Enter the annual interest rate as a percentage or decimal:\\n')) #Annual interest rate as a decimal\r\n except ValueError:\r\n print('You did not enter an amount.')\r\n continue\r\n break\r\n if R >= 1:\r\n r = R / 100\r\n else: \r\n r = R\r\n return r\r\n \r\ndef time():\r\n \"\"\"Gets the calculation time in years.\"\"\"\r\n while True:\r\n while True:\r\n try:\r\n t = int(input('Enter the number of years:\\n')) #Time in years\r\n except ValueError:\r\n print('You did not enter an amount.')\r\n continue\r\n break\r\n if t <= 0:\r\n print('Time in years must be a positive number.')\r\n continue\r\n else:\r\n return t\r\n\r\n\r\n","repo_name":"benjaminpritchard230/compound_interest_calculator","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26866817256","text":"#!/usr/bin/env python3\n\n#####################################################################################\n# Macro to fit the higgs recoil mass out of FlatNtuples produced by FCCAnalysis #\n# Author: Clement Helsens (clement.helsens@cern.ch) #\n# Date: November 2020 #\n#####################################################################################\n\nimport ROOT as r\nimport sys\n\nif len(sys.argv)!=4 and len(sys.argv)!=6:\n print ('usage: python massFit.py BASEDIR HISTONAME SELECTION BINLOW=120 BINHIGH=140')\n print ('example: python massFit.py /eos/experiment/fcc/ee/analyses/case-studies/higgs/mH-recoil/FlatNtuples/ZH_Zee/ leptonic_recoil_m_zoom3 sel1')\n print ('example: python massFit.py /eos/experiment/fcc/ee/analyses/case-studies/higgs/mH-recoil/FlatNtuples/ZH_Zmumu/ leptonic_recoil_m_zoom4 sel0 122 128')\n sys.exit(3)\n\nbasedir=sys.argv[1]\nhname=sys.argv[2]\nselection=sys.argv[3]\nbinlow=120\nbinhigh=140\n\nif len(sys.argv)==6:\n binlow=float(sys.argv[4])\n binhigh=float(sys.argv[5])\n\nif basedir[-1]!='/':\n basedir+='/'\n\ninfile=basedir+'p8_ee_ZH_ecm240_{}_histo.root'.format(selection)\nprint (infile)\ntfsig=r.TFile(infile)\nhistosig=tfsig.Get(hname)\n\ninfile=basedir+'p8_ee_ZZ_ecm240_{}_histo.root'.format(selection)\ntfbg1=r.TFile(infile)\nhistobg1=tfbg1.Get(hname)\nprint (infile)\n\ninfile=basedir+'p8_ee_WW_ecm240_{}_histo.root'.format(selection)\ntfbg2=r.TFile(infile)\nhistobg2=tfbg2.Get(hname)\nprint (infile)\n\n\nhistosig.Add(histobg1)\nhistosig.Add(histobg2)\n\n#Scale to lumi\nhistosig.Scale(5.0e+06)\n\n#bins for the fit\nx = r.RooRealVar(\"recoil\", \"M_{recoil} [GeV]\", binlow, binhigh)\n\n# data is breit-wigner convoluted with a gaussian, taken from histogram\ndhData = r.RooDataHist(\"dhData\", \"dhData\", r.RooArgList(x), r.RooFit.Import(histosig))\n\ncbmean = r.RooRealVar(\"cbmean\", \"cbmean\" , 125.0, 120., 130.0)\ncbsigma = r.RooRealVar(\"cbsigma\", \"cbsigma\" , 0.2, 0.0, 0.6)\nn = r.RooRealVar(\"n\",\"n\", 0.9,0.,100.0)\nalpha = r.RooRealVar(\"alpha\",\"alpha\", -1.2,-5.,-0.0001)\ncball = r.RooCBShape(\"cball\", \"crystal ball\", x, cbmean, cbsigma, alpha, n)\n\nlam = r.RooRealVar(\"lam\",\"lam\",-1e-3,-1,-1e-10)\nbkg = r.RooExponential(\"bkg\",\"bkg\",x,lam)\n\nnsig = r.RooRealVar(\"nsig\", \"number of signal events\", 10000, 0., 10000000)\nnbkg = r.RooRealVar(\"nbkg\", \"number of background events\", 50000, 0, 10000000)\nmodel = r.RooAddPdf(\"model\",\"(g1+g2)+a\",r.RooArgList(bkg,cball),r.RooArgList(nbkg,nsig))\n\nresult = model.fitTo(dhData,r.RooFit.Save(),r.RooFit.NumCPU(8,0),r.RooFit.Extended(True),r.RooFit.Optimize(False),r.RooFit.Offset(True),r.RooFit.Minimizer(\"Minuit2\",\"migrad\"),r.RooFit.Strategy(2))\n\nframe = x.frame(r.RooFit.Title(\"recoil \"), )\ndhData.plotOn(frame,r.RooFit.Name(\"data\"))\nmodel.plotOn(frame,r.RooFit.Name(\"model\"))\n\nras_bkg = r.RooArgSet(bkg)\nmodel.plotOn(frame, r.RooFit.Components(ras_bkg), r.RooFit.LineStyle(r.kDashed), r.RooFit.Name(\"ras_bkg\"))\n\nras_sig = r.RooArgSet(cball)\nmodel.plotOn(frame, r.RooFit.LineColor(r.kRed), r.RooFit.Components(ras_sig), r.RooFit.LineStyle(r.kDashed), r.RooFit.Name(\"ras_sig\"))\n\n\nc = r.TCanvas()\nframe.Draw()\n\nleg = r.TLegend(0.6,0.7,0.89,0.89)\nleg.AddEntry(frame.findObject(\"data\"),\"FCC IDEA Delphes\",\"ep\")\nleg.AddEntry(frame.findObject(\"model\"),\"S+B fit\",\"l\")\nleg.AddEntry(frame.findObject(\"ras_sig\"),\"Signal\",\"l\")\nleg.AddEntry(frame.findObject(\"ras_bkg\"),\"background\",\"l\")\n\nleg.Draw()\n\nr.gPad.SaveAs(\"fitResult.pdf\")\nr.gPad.SaveAs(\"fitResult.png\")\n\n\n\nfCB = r.TF1(\"fCB\",\"crystalball\")\n\nfCB.SetParameter(0, 1.)\nfCB.SetParameter(1, 125.)\nfCB.SetParameter(2, 0.5)\nfCB.SetParameter(3, -1.)\nfCB.SetParameter(4, 1.)\nfCB.SetRange(120.,128.)\n\n\n\n\nc = r.TCanvas()\n#c.SetLogy()\nhistosig.Draw()\nhistosig.Fit(fCB)\n","repo_name":"HEP-FCC/FCCeePhysicsPerformance","sub_path":"case-studies/higgs/mH-recoil/analysis/massFit.py","file_name":"massFit.py","file_ext":"py","file_size_in_byte":3770,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"} +{"seq_id":"33906913094","text":"from django.urls.base import reverse\nfrom django.utils.dateparse import parse_datetime\nimport json\nimport mock\nimport pytz\nimport responses\nfrom settings import AIRTABLE_URL\n\nfrom seqr.models import Project\nfrom seqr.views.apis.report_api import seqr_stats, get_category_projects, discovery_sheet, anvil_export, \\\n sample_metadata_export, gregor_export\nfrom seqr.views.utils.test_utils import AuthenticationTestCase, AnvilAuthenticationTestCase\n\n\nPROJECT_GUID = 'R0001_1kg'\nNON_PROJECT_GUID ='NON_GUID'\nPROJECT_EMPTY_GUID = 'R0002_empty'\nCOMPOUND_HET_PROJECT_GUID = 'R0003_test'\nNO_ANALYST_PROJECT_GUID = 'R0004_non_analyst_project'\n\nEXPECTED_DISCOVERY_SHEET_ROW = \\\n {'project_guid': 'R0001_1kg', 'pubmed_ids': '34415322; 33665635', 'posted_publicly': '',\n 'solved': 'TIER 1 GENE', 'head_or_neck': 'N', 'analysis_complete_status': 'complete',\n 'cardiovascular_system': 'N', 'n_kindreds_overlapping_sv_similar_phenotype': '2',\n 'biochemical_function': 'Y', 'omim_number_post_discovery': '615120,615123',\n 'genome_wide_linkage': 'NA 2', 'metabolism_homeostasis': 'N', 'growth': 'N',\n 't0': '2017-02-05T06:42:55.397Z', 'months_since_t0': 38, 'sample_source': 'CMG',\n 'integument': 'N', 'voice': 'N', 'skeletal_system': 'N',\n 'expected_inheritance_model': 'Autosomal recessive inheritance',\n 'extras_variant_tag_list': ['21-3343353-GAGA-G RP11 tier 1 - novel gene and phenotype'],\n 'protein_interaction': 'N', 'n_kindreds': '1', 'num_individuals_sequenced': 3,\n 'musculature': 'Y', 'sequencing_approach': 'WES', 'neoplasm': 'N',\n 'collaborator': '1kg project n\\xe5me with uni\\xe7\\xf8de',\n 'actual_inheritance_model': 'de novo', 'novel_mendelian_gene': 'Y',\n 'endocrine_system': 'N', 'patient_cells': 'N', 'komp_early_release': 'N',\n 'connective_tissue': 'N', 'prenatal_development_or_birth': 'N', 'rescue': 'N',\n 'family_guid': 'F000001_1', 'immune_system': 'N',\n 'analysis_summary': '*\\r\\nF\\u00e5mily analysis summ\\u00e5ry.\\r\\n*; Some additional follow up',\n 'gene_count': 'NA', 'gene_id': 'ENSG00000135953', 'abdomen': 'N', 'limbs': 'N',\n 'blood': 'N', 'phenotype_class': 'KNOWN', 'submitted_to_mme': 'Y',\n 'n_unrelated_kindreds_with_causal_variants_in_gene': '3',\n 'row_id': 'F000001_1ENSG00000135953', 'eye_defects': 'N', 'omim_number_initial': '12345',\n 'p_value': 'NA', 'respiratory': 'N', 'nervous_system': 'Y', 'ear_defects': 'N',\n 'thoracic_cavity': 'N', 'non_patient_cell_model': 'N',\n 't0_copy': '2017-02-05T06:42:55.397Z', 'extras_pedigree_url': '/media/ped_1.png',\n 'family_id': '1', 'genitourinary_system': 'N', 'coded_phenotype': 'myopathy',\n 'animal_model': 'N', 'non_human_cell_culture_model': 'N', 'expression': 'N',\n 'gene_name': 'RP11', 'breast': 'N'}\n\nEXPECTED_DISCOVERY_SHEET_COMPOUND_HET_ROW = {\n 'project_guid': 'R0003_test', 'pubmed_ids': '', 'posted_publicly': '', 'solved': 'TIER 1 GENE', 'head_or_neck': 'N',\n 'analysis_complete_status': 'complete', 'cardiovascular_system': 'Y',\n 'n_kindreds_overlapping_sv_similar_phenotype': 'NA', 'biochemical_function': 'N', 'omim_number_post_discovery': 'NA',\n 'genome_wide_linkage': 'NA', 'metabolism_homeostasis': 'N', 'growth': 'N', 't0': '2017-02-05T06:42:55.397Z',\n 'months_since_t0': 38, 'sample_source': 'CMG', 'integument': 'N', 'voice': 'N', 'skeletal_system': 'N',\n 'expected_inheritance_model': 'multiple', 'num_individuals_sequenced': 2, 'sequencing_approach': 'REAN',\n 'extras_variant_tag_list': ['1-248367227-TC-T OR4G11P tier 1 - novel gene and phenotype',\n 'prefix_19107_DEL OR4G11P tier 1 - novel gene and phenotype'], 'protein_interaction': 'N', 'n_kindreds': '1',\n 'neoplasm': 'N', 'collaborator': 'Test Reprocessed Project', 'actual_inheritance_model': 'AR-comphet',\n 'novel_mendelian_gene': 'Y', 'endocrine_system': 'N', 'komp_early_release': 'N', 'connective_tissue': 'N',\n 'prenatal_development_or_birth': 'N', 'rescue': 'N', 'family_guid': 'F000012_12', 'immune_system': 'N',\n 'analysis_summary': '', 'gene_count': 'NA', 'gene_id': 'ENSG00000240361', 'abdomen': 'N', 'limbs': 'N',\n 'phenotype_class': 'New', 'submitted_to_mme': 'Y', 'n_unrelated_kindreds_with_causal_variants_in_gene': '1',\n 'blood': 'N', 'row_id': 'F000012_12ENSG00000240361', 'eye_defects': 'N', 'omim_number_initial': 'NA',\n 'p_value': 'NA', 'respiratory': 'N', 'nervous_system': 'N', 'ear_defects': 'N', 'thoracic_cavity': 'N',\n 'non_patient_cell_model': 'N', 't0_copy': '2017-02-05T06:42:55.397Z', 'extras_pedigree_url': '',\n 'family_id': '12', 'genitourinary_system': 'N', 'coded_phenotype': '', 'animal_model': 'N', 'expression': 'N',\n 'non_human_cell_culture_model': 'N', 'gene_name': 'OR4G11P', 'breast': 'N', 'musculature': 'N', 'patient_cells': 'N',}\n\nAIRTABLE_SAMPLE_RECORDS = {\n \"records\": [\n {\n \"id\": \"rec2B6OGmQpAkQW3s\",\n \"fields\": {\n \"SeqrCollaboratorSampleID\": \"VCGS_FAM203_621_D1\",\n \"CollaboratorSampleID\": \"NA19675\",\n \"Collaborator\": [\"recW24C2CJW5lT64K\"],\n \"dbgap_study_id\": \"dbgap_stady_id_1\",\n \"dbgap_subject_id\": \"dbgap_subject_id_1\",\n \"dbgap_sample_id\": \"SM-A4GQ4\",\n \"SequencingProduct\": [\n \"Mendelian Rare Disease Exome\"\n ],\n \"dbgap_submission\": [\n \"WES\",\n \"Array\"\n ]\n },\n \"createdTime\": \"2019-09-09T19:21:12.000Z\"\n },\n {\n \"id\": \"rec2Nkg10N1KssPc3\",\n \"fields\": {\n \"SeqrCollaboratorSampleID\": \"HG00731\",\n \"CollaboratorSampleID\": \"NA20885\",\n \"Collaborator\": [\"reca4hcBnbA2cnZf9\"],\n \"dbgap_study_id\": \"dbgap_stady_id_2\",\n \"dbgap_subject_id\": \"dbgap_subject_id_2\",\n \"dbgap_sample_id\": \"SM-JDBTT\",\n \"SequencingProduct\": [\n \"Standard Germline Exome v6 Plus GSA Array\"\n ],\n \"dbgap_submission\": [\n \"WES\",\n \"Array\"\n ]\n },\n \"createdTime\": \"2019-07-16T18:23:21.000Z\"\n }\n]}\n\nPAGINATED_AIRTABLE_SAMPLE_RECORDS = {\n 'offset': 'abc123',\n 'records': [{\n 'id': 'rec2B6OGmQpfuRW5z',\n 'fields': {\n 'CollaboratorSampleID': 'NA19675',\n 'Collaborator': ['recW24C2CJW5lT64K'],\n 'dbgap_study_id': 'dbgap_study_id_2',\n 'dbgap_subject_id': 'dbgap_subject_id_1',\n 'dbgap_sample_id': 'SM-A4GQ4',\n 'SequencingProduct': [\n 'Mendelian Rare Disease Exome'\n ],\n 'dbgap_submission': [\n 'WES',\n 'Array'\n ]\n },\n 'createdTime': '2019-09-09T19:21:12.000Z'\n }\n]}\n\nAIRTABLE_COLLABORATOR_RECORDS = {\n \"records\": [\n {\n \"id\": \"recW24C2CJW5lT64K\",\n \"fields\": {\n \"CollaboratorID\": \"Hildebrandt\",\n }\n },\n {\n \"id\": \"reca4hcBnbA2cnZf9\",\n \"fields\": {\n \"CollaboratorID\": \"Seidman\",\n }\n }\n ]\n}\n\n\nAIRTABLE_GREGOR_SAMPLE_RECORDS = {\n \"records\": [\n {\n \"id\": \"rec2B6OGmQpAkQW3s\",\n \"fields\": {\n \"SeqrCollaboratorSampleID\": \"VCGS_FAM203_621_D1\",\n \"CollaboratorSampleID\": \"NA19675_1\",\n 'SMID': 'SM-AGHT',\n 'Recontactable': 'Yes',\n },\n },\n {\n \"id\": \"rec2Nkg10N1KssPc3\",\n \"fields\": {\n \"SeqrCollaboratorSampleID\": \"HG00731\",\n \"CollaboratorSampleID\": \"VCGS_FAM203_621_D2\",\n 'SMID': 'SM-JDBTM',\n },\n }\n]}\nAIRTABLE_GREGOR_RECORDS = {\n \"records\": [\n {\n \"id\": \"rec2B6OGmQpAkQW3s\",\n \"fields\": {\n 'SMID': 'SM-JDBTM',\n 'seq_library_prep_kit_method': 'Kapa HyperPrep',\n 'read_length': '151',\n 'experiment_type': 'exome',\n 'targeted_regions_method': 'Twist',\n 'targeted_region_bed_file': 'gs://fc-eb352699-d849-483f-aefe-9d35ce2b21ac/SR_experiment.bed',\n 'date_data_generation': '2022-08-15',\n 'target_insert_size': '385',\n 'sequencing_platform': 'NovaSeq',\n 'aligned_dna_short_read_file': 'gs://fc-eb352699-d849-483f-aefe-9d35ce2b21ac/Broad_COL_FAM1_1_D1.cram',\n 'aligned_dna_short_read_index_file': 'gs://fc-eb352699-d849-483f-aefe-9d35ce2b21ac/Broad_COL_FAM1_1_D1.crai',\n 'md5sum': '129c28163df082',\n 'reference_assembly': 'GRCh38',\n 'alignment_software': 'BWA-MEM-2.3',\n 'mean_coverage': '42.4',\n 'analysis_details': 'DOI:10.5281/zenodo.4469317',\n 'called_variants_dna_short_read_id': 'SX2-3',\n 'aligned_dna_short_read_set_id': 'BCM_H7YG5DSX2',\n 'called_variants_dna_file': 'gs://fc-fed09429-e563-44a7-aaeb-776c8336ba02/COL_FAM1_1_D1.SV.vcf',\n 'caller_software': 'gatk4.1.2',\n 'variant_types': 'SNV',\n },\n },\n {\n \"id\": \"rec2B6OGmCVzkQW3s\",\n \"fields\": {\n 'SMID': 'SM-AGHT',\n },\n },\n]}\n\nEXPECTED_NO_AIRTABLE_SAMPLE_METADATA_ROW = {\n \"project_guid\": \"R0003_test\",\n \"num_saved_variants\": 2,\n \"solve_state\": \"Tier 1\",\n \"sample_id\": \"NA20889\",\n \"Gene_Class-1\": \"Tier 1 - Candidate\",\n \"Gene_Class-2\": \"Tier 1 - Candidate\",\n \"inheritance_description-1\": \"Autosomal recessive (compound heterozygous)\",\n \"inheritance_description-2\": \"Autosomal recessive (compound heterozygous)\",\n \"hpo_absent\": \"\",\n \"novel_mendelian_gene-1\": \"Y\",\n \"novel_mendelian_gene-2\": \"Y\",\n \"hgvsc-1\": \"c.3955G>A\",\n \"date_data_generation\": \"2017-02-05\",\n \"Zygosity-1\": \"Heterozygous\",\n \"Zygosity-2\": \"Heterozygous\",\n \"variant_genome_build-1\": \"GRCh37\",\n \"variant_genome_build-2\": \"GRCh37\",\n \"Ref-1\": \"TC\",\n \"sv_type-2\": \"Deletion\",\n \"sv_name-2\": \"DEL:chr12:49045487-49045898\",\n \"ancestry_detail\": \"Ashkenazi Jewish\",\n \"maternal_id\": \"\",\n \"paternal_id\": \"\",\n \"hgvsp-1\": \"c.1586-17C>G\",\n \"entity:family_id\": \"12\",\n \"entity:discovery_id\": \"NA20889\",\n \"project_id\": \"Test Reprocessed Project\",\n \"Pos-1\": \"248367227\",\n \"data_type\": \"WES\",\n \"family_guid\": \"F000012_12\",\n \"congenital_status\": \"Unknown\",\n \"family_history\": \"Yes\",\n \"hpo_present\": \"HP:0011675 (Arrhythmia)|HP:0001509 ()\",\n \"Transcript-1\": \"ENST00000505820\",\n \"ancestry\": \"Ashkenazi Jewish\",\n \"phenotype_group\": \"\",\n \"sex\": \"Female\",\n \"entity:subject_id\": \"NA20889\",\n \"entity:sample_id\": \"NA20889\",\n \"Chrom-1\": \"1\",\n \"Alt-1\": \"T\",\n \"Gene-1\": \"OR4G11P\",\n \"pmid_id\": None,\n \"phenotype_description\": None,\n \"affected_status\": \"Affected\",\n \"family_id\": \"12\",\n \"MME\": \"Y\",\n \"subject_id\": \"NA20889\",\n \"proband_relationship\": \"\",\n \"consanguinity\": \"None suspected\",\n \"sequencing_center\": \"Broad\",\n}\nEXPECTED_SAMPLE_METADATA_ROW = {\n \"dbgap_submission\": \"No\",\n \"dbgap_study_id\": \"\",\n \"dbgap_subject_id\": \"\",\n \"sample_provider\": \"\",\n \"multiple_datasets\": \"No\",\n}\nEXPECTED_SAMPLE_METADATA_ROW.update(EXPECTED_NO_AIRTABLE_SAMPLE_METADATA_ROW)\n\nMOCK_DATA_MODEL_URL = 'http://raw.githubusercontent.com/gregor_data_model.json'\nMOCK_DATA_MODEL = {\n 'name': 'test data model',\n 'tables': [\n {\n 'table': 'subject',\n 'required': True,\n 'columns': [{'column': 'subject_id', 'required': True}],\n },\n {\n 'table': 'participant',\n 'required': True,\n 'columns': [\n {'column': 'participant_id', 'required': True},\n {'column': 'internal_project_id'},\n {'column': 'gregor_center', 'required': True, 'enumerations': ['BCM', 'BROAD', 'UW']},\n {'column': 'consent_code', 'required': True, 'enumerations': ['GRU', 'HMB']},\n {'column': 'recontactable', 'enumerations': ['Yes', 'No', 'Unknown']},\n {'column': 'prior_testing'},\n {'column': 'family_id', 'required': True},\n {'column': 'paternal_id'},\n {'column': 'maternal_id'},\n {'column': 'proband_relationship', 'required': True},\n {'column': 'sex', 'required': True, 'enumerations': ['Male', 'Female', 'Unknown']},\n {'column': 'reported_race', 'enumerations': ['Asian', 'White', 'Black', 'Unknown']},\n {'column': 'reported_ethnicity', 'enumerations': ['Hispanic', 'Not Hispanic', 'Unknown']},\n {'column': 'ancestry_metadata'},\n {'column': 'affected_status', 'required': True, 'enumerations': ['Affected', 'Unaffected', 'Unknown']},\n {'column': 'phenotype_description'},\n {'column': 'age_at_enrollment'},\n ],\n },\n {\n 'table': 'aligned_dna_short_read_set',\n 'columns': [\n {'column': 'aligned_dna_short_read_set_id', 'required': True},\n {'column': 'aligned_dna_short_read_id', 'required': True},\n ],\n },\n {\n 'table': 'dna_read_data',\n 'columns': [{'column': 'analyte_id', 'required': True}],\n },\n ]\n}\n\n\ndef _get_list_param(call, param):\n query_params = call.url.split('?')[1].split('&')\n param_str = f'{param}='\n return [p.replace(param_str, '') for p in query_params if p.startswith(param_str)]\n\n\nclass ReportAPITest(object):\n\n def _get_zip_files(self, mock_zip, filenames):\n mock_write_zip = mock_zip.return_value.__enter__.return_value.writestr\n self.assertEqual(mock_write_zip.call_count, len(filenames))\n mock_write_zip.assert_has_calls([mock.call(file, mock.ANY) for file in filenames])\n\n return (\n [row.split('\\t') for row in mock_write_zip.call_args_list[i][0][1].split('\\n') if row]\n for i in range(len(filenames))\n )\n\n def _assert_expected_airtable_call(self, call_index, filter_formula, fields, additional_params=None):\n expected_params = {\n 'fields[]': mock.ANY,\n 'pageSize': '100',\n 'filterByFormula': filter_formula,\n }\n if additional_params:\n expected_params.update(additional_params)\n self.assertDictEqual(responses.calls[call_index].request.params, expected_params)\n self.assertListEqual(_get_list_param(responses.calls[call_index].request, 'fields%5B%5D'), fields)\n\n def test_seqr_stats(self):\n no_access_project = Project.objects.get(id=2)\n no_access_project.workspace_namespace = None\n no_access_project.save()\n\n url = reverse(seqr_stats)\n self.check_analyst_login(url)\n\n response = self.client.get(url)\n self.assertEqual(response.status_code, 200)\n response_json = response.json()\n self.assertSetEqual(set(response_json.keys()), {'projectsCount', 'individualsCount', 'familiesCount', 'sampleCountsByType'})\n self.assertDictEqual(response_json['projectsCount'], self.STATS_DATA['projectsCount'])\n self.assertDictEqual(response_json['individualsCount'], self.STATS_DATA['individualsCount'])\n self.assertDictEqual(response_json['familiesCount'], self.STATS_DATA['familiesCount'])\n self.assertDictEqual(response_json['sampleCountsByType'], self.STATS_DATA['sampleCountsByType'])\n\n self.check_no_analyst_no_access(url)\n\n def test_get_category_projects(self):\n url = reverse(get_category_projects, args=['GREGoR'])\n self.check_analyst_login(url)\n\n response = self.client.get(url)\n self.assertEqual(response.status_code, 200)\n response_json = response.json()\n self.assertListEqual(list(response_json.keys()), ['projectGuids'])\n self.assertSetEqual(set(response_json['projectGuids']), {PROJECT_GUID, COMPOUND_HET_PROJECT_GUID})\n\n self.check_no_analyst_no_access(url)\n\n @mock.patch('seqr.views.apis.report_api.timezone')\n def test_discovery_sheet(self, mock_timezone):\n non_project_url = reverse(discovery_sheet, args=[NON_PROJECT_GUID])\n self.check_analyst_login(non_project_url)\n\n mock_timezone.now.return_value = pytz.timezone(\"US/Eastern\").localize(parse_datetime(\"2020-04-27 20:16:01\"), is_dst=None)\n response = self.client.get(non_project_url)\n self.assertEqual(response.status_code, 400)\n self.assertEqual(response.reason_phrase, 'Invalid project {}'.format(NON_PROJECT_GUID))\n response_json = response.json()\n self.assertEqual(response_json['error'], 'Invalid project {}'.format(NON_PROJECT_GUID))\n\n unauthorized_project_url = reverse(discovery_sheet, args=[NO_ANALYST_PROJECT_GUID])\n response = self.client.get(unauthorized_project_url)\n self.assertEqual(response.status_code, 403)\n\n empty_project_url = reverse(discovery_sheet, args=[PROJECT_EMPTY_GUID])\n\n response = self.client.get(empty_project_url)\n self.assertEqual(response.status_code, 200)\n response_json = response.json()\n self.assertSetEqual(set(response_json.keys()), {'rows', 'errors'})\n self.assertListEqual(response_json['rows'], [])\n self.assertListEqual(response_json['errors'], [\"No data loaded for project: Empty Project\"])\n\n url = reverse(discovery_sheet, args=[PROJECT_GUID])\n response = self.client.get(url)\n self.assertEqual(response.status_code, 200)\n response_json = response.json()\n self.assertSetEqual(set(response_json.keys()), {'rows', 'errors'})\n self.assertListEqual(response_json['errors'], ['No data loaded for family: 9. Skipping...', 'No data loaded for family: no_individuals. Skipping...'])\n self.assertEqual(len(response_json['rows']), 10)\n self.assertIn(EXPECTED_DISCOVERY_SHEET_ROW, response_json['rows'])\n\n # test compound het reporting\n url = reverse(discovery_sheet, args=[COMPOUND_HET_PROJECT_GUID])\n response = self.client.get(url)\n self.assertEqual(response.status_code, 200)\n response_json = response.json()\n self.assertSetEqual(set(response_json.keys()), {'rows', 'errors'})\n self.assertListEqual(response_json['errors'], [\n 'HPO category field not set for some HPO terms in 11', 'HPO category field not set for some HPO terms in 12',\n ])\n self.assertEqual(len(response_json['rows']), 2)\n self.assertIn(EXPECTED_DISCOVERY_SHEET_COMPOUND_HET_ROW, response_json['rows'])\n\n self.check_no_analyst_no_access(url)\n\n # @mock.patch('seqr.views.utils.export_utils.zipfile.ZipFile')\n # @mock.patch('seqr.views.utils.airtable_utils.is_google_authenticated')\n # @responses.activate\n # def test_anvil_export(self, mock_google_authenticated, mock_zip):\n # mock_google_authenticated.return_value = False\n # url = reverse(anvil_export, args=[PROJECT_GUID])\n # self.check_analyst_login(url)\n #\n # unauthorized_project_url = reverse(anvil_export, args=[NO_ANALYST_PROJECT_GUID])\n # response = self.client.get(unauthorized_project_url)\n # self.assertEqual(response.status_code, 403)\n # self.assertEqual(response.json()['error'], 'Permission Denied')\n #\n # response = self.client.get(url)\n # self.assertEqual(response.status_code, 403)\n # self.assertEqual(response.json()['error'], 'Permission Denied')\n # mock_google_authenticated.return_value = True\n #\n # responses.add(responses.GET, '{}/app3Y97xtbbaOopVR/Samples'.format(AIRTABLE_URL), json=AIRTABLE_SAMPLE_RECORDS, status=200)\n # response = self.client.get(url)\n # self.assertEqual(response.status_code, 200)\n # self.assertEqual(\n # response.get('content-disposition'),\n # 'attachment; filename=\"1kg project nme with unide_AnVIL_Metadata.zip\"'\n # )\n #\n # subject_file, sample_file, family_file, discovery_file = self._get_zip_files(mock_zip, [\n # '1kg project n\\xe5me with uni\\xe7\\xf8de_PI_Subject.tsv',\n # '1kg project n\\xe5me with uni\\xe7\\xf8de_PI_Sample.tsv',\n # '1kg project n\\xe5me with uni\\xe7\\xf8de_PI_Family.tsv',\n # '1kg project n\\xe5me with uni\\xe7\\xf8de_PI_Discovery.tsv',\n # ])\n #\n # self.assertEqual(subject_file[0], [\n # 'entity:subject_id', '01-subject_id', '02-prior_testing', '03-project_id', '04-pmid_id',\n # '05-dbgap_study_id', '06-dbgap_subject_id', '07-multiple_datasets',\n # '08-family_id', '09-paternal_id', '10-maternal_id', '11-twin_id', '12-proband_relationship', '13-sex',\n # '14-ancestry', '15-ancestry_detail', '16-age_at_last_observation', '17-phenotype_group', '18-disease_id',\n # '19-disease_description', '20-affected_status', '21-congenital_status', '22-age_of_onset', '23-hpo_present',\n # '24-hpo_absent', '25-phenotype_description', '26-solve_state'])\n # self.assertIn([\n # 'NA19675_1', 'NA19675_1', '-', u'1kg project nme with unide', '34415322', 'dbgap_stady_id_1',\n # 'dbgap_subject_id_1', 'No', '1', 'NA19678', 'NA19679', '-', 'Self', 'Male', 'Other', 'Middle Eastern', '-',\n # '-', 'OMIM:615120;OMIM:615123', 'Myasthenic syndrome; congenital; 8; with pre- and postsynaptic defects;',\n # 'Affected', 'Adult onset', '-', 'HP:0001631|HP:0002011|HP:0001636', 'HP:0011675|HP:0001674|HP:0001508',\n # 'myopathy', 'Tier 1'], subject_file)\n #\n # self.assertEqual(sample_file[0], [\n # 'entity:sample_id', '01-subject_id', '02-sample_id', '03-dbgap_sample_id', '04-sequencing_center',\n # '05-sample_source', '06-tissue_affected_status',])\n # self.assertIn(\n # ['NA19675_1', 'NA19675_1', 'NA19675', 'SM-A4GQ4', 'Broad', '-', '-'],\n # sample_file,\n # )\n #\n # self.assertEqual(family_file[0], [\n # 'entity:family_id', '01-family_id', '02-consanguinity', '03-consanguinity_detail', '04-pedigree_image',\n # '05-pedigree_detail', '06-family_history', '07-family_onset'])\n # self.assertIn([\n # '1', '1', 'Present', '-', '-', '-', '-', '-',\n # ], family_file)\n #\n # self.assertEqual(len(discovery_file), 6)\n # self.assertEqual(discovery_file[0], [\n # 'entity:discovery_id', '01-subject_id', '02-sample_id', '03-Gene', '04-Gene_Class',\n # '05-inheritance_description', '06-Zygosity', '07-variant_genome_build', '08-Chrom', '09-Pos',\n # '10-Ref', '11-Alt', '12-hgvsc', '13-hgvsp', '14-Transcript', '15-sv_name', '16-sv_type',\n # '17-significance', '18-discovery_notes'])\n # self.assertIn([\n # 'HG00731', 'HG00731', 'HG00731', 'RP11', 'Known', 'Autosomal recessive (homozygous)',\n # 'Homozygous', 'GRCh37', '1', '248367227', 'TC', 'T', '-', '-', '-', '-', '-', '-', '-'], discovery_file)\n # self.assertIn([\n # 'NA19675_1', 'NA19675_1', 'NA19675', 'RP11', 'Tier 1 - Candidate', 'de novo',\n # 'Heterozygous', 'GRCh37', '21', '3343353', 'GAGA', 'G', 'c.375_377delTCT', 'p.Leu126del', 'ENST00000258436',\n # '-', '-', '-', '-'], discovery_file)\n # self.assertIn([\n # 'HG00733', 'HG00733', 'HG00733', 'OR4G11P', 'Known', 'Unknown / Other', 'Heterozygous', 'GRCh38.p12', '19',\n # '1912633', 'G', 'T', '-', '-', 'ENST00000371839', '-', '-', '-',\n # 'The following variants are part of the multinucleotide variant 19-1912632-GC-TT '\n # '(c.586_587delinsTT, p.Ala196Leu): 19-1912633-G-T, 19-1912634-C-T'],\n # discovery_file)\n # self.assertIn([\n # 'HG00733', 'HG00733', 'HG00733', 'OR4G11P', 'Known', 'Unknown / Other', 'Heterozygous', 'GRCh38.p12', '19',\n # '1912634', 'C', 'T', '-', '-', 'ENST00000371839', '-', '-', '-',\n # 'The following variants are part of the multinucleotide variant 19-1912632-GC-TT (c.586_587delinsTT, '\n # 'p.Ala196Leu): 19-1912633-G-T, 19-1912634-C-T'],\n # discovery_file)\n #\n # self.check_no_analyst_no_access(url)\n #\n # # Test non-broad analysts do not have access\n # self.login_pm_user()\n # response = self.client.get(url)\n # self.assertEqual(response.status_code, 403)\n # self.assertEqual(response.json()['error'], 'Permission Denied')\n #\n # @mock.patch('seqr.views.utils.airtable_utils.MAX_OR_FILTERS', 4)\n # @mock.patch('seqr.views.utils.airtable_utils.AIRTABLE_API_KEY', 'mock_key')\n # @mock.patch('seqr.views.utils.airtable_utils.is_google_authenticated')\n # @responses.activate\n # def test_sample_metadata_export(self, mock_google_authenticated):\n # mock_google_authenticated.return_value = False\n # url = reverse(sample_metadata_export, args=[COMPOUND_HET_PROJECT_GUID])\n # self.check_analyst_login(url)\n #\n # unauthorized_project_url = reverse(sample_metadata_export, args=[NO_ANALYST_PROJECT_GUID])\n # response = self.client.get(unauthorized_project_url)\n # self.assertEqual(response.status_code, 403)\n # self.assertEqual(response.json()['error'], 'Permission Denied')\n #\n # response = self.client.get(url)\n # self.assertEqual(response.status_code, 403)\n # self.assertEqual( response.json()['error'], 'Permission Denied')\n # mock_google_authenticated.return_value = True\n #\n # # Test invalid airtable responses\n # responses.add(responses.GET, '{}/app3Y97xtbbaOopVR/Samples'.format(AIRTABLE_URL), status=402)\n # response = self.client.get(url)\n # self.assertEqual(response.status_code, 402)\n #\n # responses.reset()\n # responses.add(responses.GET, '{}/app3Y97xtbbaOopVR/Samples'.format(AIRTABLE_URL), status=200)\n # response = self.client.get(url)\n # self.assertEqual(response.status_code, 500)\n # self.assertIn(response.json()['error'], ['Unable to retrieve airtable data: No JSON object could be decoded',\n # 'Unable to retrieve airtable data: Expecting value: line 1 column 1 (char 0)'])\n #\n # responses.reset()\n # responses.add(responses.GET, '{}/app3Y97xtbbaOopVR/Samples'.format(AIRTABLE_URL),\n # json=PAGINATED_AIRTABLE_SAMPLE_RECORDS, status=200)\n # responses.add(responses.GET, '{}/app3Y97xtbbaOopVR/Samples'.format(AIRTABLE_URL),\n # json=AIRTABLE_SAMPLE_RECORDS, status=200)\n # responses.add(responses.GET, '{}/app3Y97xtbbaOopVR/Collaborator'.format(AIRTABLE_URL),\n # json=AIRTABLE_COLLABORATOR_RECORDS, status=200)\n # response = self.client.get(url)\n # self.assertEqual(response.status_code, 500)\n # self.assertEqual(\n # response.json()['error'],\n # 'Found multiple airtable records for sample NA19675 with mismatched values in field dbgap_study_id')\n # self.assertEqual(len(responses.calls), 3)\n # first_formula = \"OR({CollaboratorSampleID}='NA20885',{CollaboratorSampleID}='NA20888',{CollaboratorSampleID}='NA20889',\" \\\n # \"{SeqrCollaboratorSampleID}='NA20885')\"\n # expected_params = {\n # 'fields[]': mock.ANY,\n # 'filterByFormula': first_formula,\n # }\n # expected_fields = [\n # 'SeqrCollaboratorSampleID', 'CollaboratorSampleID', 'Collaborator', 'dbgap_study_id', 'dbgap_subject_id',\n # 'dbgap_sample_id', 'SequencingProduct', 'dbgap_submission',\n # ]\n # self.assertDictEqual(responses.calls[0].request.params, expected_params)\n # self.assertListEqual(_get_list_param(responses.calls[0].request, 'fields%5B%5D'), expected_fields)\n # expected_offset_params = {'offset': 'abc123'}\n # expected_offset_params.update(expected_params)\n # self.assertDictEqual(responses.calls[1].request.params, expected_offset_params)\n # self.assertListEqual(_get_list_param(responses.calls[1].request, 'fields%5B%5D'), expected_fields)\n # expected_params['filterByFormula'] = \"OR({SeqrCollaboratorSampleID}='NA20888',{SeqrCollaboratorSampleID}='NA20889')\"\n # self.assertDictEqual(responses.calls[2].request.params, expected_params)\n # self.assertListEqual(_get_list_param(responses.calls[2].request, 'fields%5B%5D'), expected_fields)\n #\n # # Test success\n # response = self.client.get(url)\n # self.assertEqual(response.status_code, 200)\n # response_json = response.json()\n # self.assertListEqual(list(response_json.keys()), ['rows'])\n # self.assertIn(EXPECTED_SAMPLE_METADATA_ROW, response_json['rows'])\n # self.assertEqual(len(responses.calls), 6)\n # self.assertDictEqual(responses.calls[-1].request.params, {\n # 'fields[]': 'CollaboratorID',\n # 'filterByFormula': \"OR(RECORD_ID()='recW24C2CJW5lT64K',RECORD_ID()='reca4hcBnbA2cnZf9')\",\n # })\n # self.assertSetEqual({call.request.headers['Authorization'] for call in responses.calls}, {'Bearer mock_key'})\n #\n # # Test empty project\n # empty_project_url = reverse(sample_metadata_export, args=[PROJECT_EMPTY_GUID])\n # response = self.client.get(empty_project_url)\n # self.assertEqual(response.status_code, 200)\n # self.assertDictEqual(response.json(), {'rows': []})\n #\n # self.check_no_analyst_no_access(url)\n #\n # # Test non-broad analysts do not have access\n # self.login_pm_user()\n # response = self.client.get(url)\n # self.assertEqual(response.status_code, 403)\n # self.assertEqual(response.json()['error'], 'Permission Denied')\n #\n # @mock.patch('seqr.views.apis.report_api.datetime')\n # @mock.patch('seqr.views.utils.export_utils.zipfile.ZipFile')\n # @responses.activate\n # def test_gregor_export(self, mock_zip, mock_datetime):\n # mock_datetime.now.return_value.year = 2020\n #\n # url = reverse(gregor_export, args=['HMB'])\n # self.check_analyst_login(url)\n #\n # response = self.client.get(url)\n # self.assertEqual(response.status_code, 200)\n # self.assertEqual(\n # response.get('content-disposition'),\n # 'attachment; filename=\"GREGoR Reports HMB.zip\"'\n # )\n #\n # files = self._get_zip_files(mock_zip, [\n # 'participant.tsv', 'family.tsv', 'phenotype.tsv', 'analyte.tsv', 'experiment_dna_short_read.tsv',\n # 'aligned_dna_short_read.tsv', 'aligned_dna_short_read_set.tsv', 'called_variants_dna_short_read.tsv',\n # ])\n # participant_file, family_file, phenotype_file, analyte_file, experiment_file, read_file, read_set_file, called_file = files\n #\n # self.assertEqual(len(participant_file), 14)\n # self.assertEqual(participant_file[0], [\n # 'participant_id', 'internal_project_id', 'gregor_center', 'consent_code', 'recontactable', 'prior_testing',\n # 'pmid_id', 'family_id', 'paternal_id', 'maternal_id', 'twin_id', 'proband_relationship',\n # 'proband_relationship_detail', 'sex', 'sex_detail', 'reported_race', 'reported_ethnicity', 'ancestry_detail',\n # 'age_at_last_observation', 'affected_status', 'phenotype_description', 'age_at_enrollment',\n # ])\n # self.assertIn([\n # 'Broad_NA19675_1', 'Broad_1kg project nme with unide', 'Broad', 'HMB', '', 'IKBKAP|CCDC102B',\n # '34415322|33665635', 'Broad_1', 'Broad_NA19678', 'Broad_NA19679', '', 'Self', '', 'Male', '',\n # 'Middle Eastern or North African', 'Unknown', '', '21', 'Affected', 'myopathy', '18',\n # ], participant_file)\n #\n # self.assertEqual(len(family_file), 10)\n # self.assertEqual(family_file[0], [\n # 'family_id', 'consanguinity', 'consanguinity_detail', 'pedigree_file', 'pedigree_file_detail',\n # 'family_history_detail',\n # ])\n # self.assertIn(['Broad_1', 'Present', '', '', '', ''], family_file)\n #\n # self.assertEqual(len(phenotype_file), 10)\n # self.assertEqual(phenotype_file[0], [\n # 'phenotype_id', 'participant_id', 'term_id', 'presence', 'ontology', 'additional_details',\n # 'onset_age_range', 'additional_modifiers',\n # ])\n # self.assertIn([\n # '', 'Broad_NA19675_1', 'HP:0002011', 'Present', 'HPO', '', 'HP:0003593', 'HP:0012825|HP:0003680',\n # ], phenotype_file)\n # self.assertIn([\n # '', 'Broad_NA19675_1', 'HP:0001674', 'Absent', 'HPO', 'originally indicated', '', '',\n # ], phenotype_file)\n #\n # self.assertEqual(len(analyte_file), 14)\n # self.assertEqual(analyte_file[0], [\n # 'analyte_id', 'participant_id', 'analyte_type', 'analyte_processing_details', 'primary_biosample',\n # 'primary_biosample_id', 'primary_biosample_details', 'tissue_affected_status', 'age_at_collection',\n # 'participant_drugs_intake', 'participant_special_diet', 'hours_since_last_meal', 'passage_number',\n # 'time_to_freeze', 'sample_transformation_detail',\n # ])\n # self.assertIn(\n # ['Broad_NA19675_1', 'Broad_NA19675_1', 'DNA', '', 'UBERON:0003714', '', '', 'No', '', '', '', '', '', '', ''],\n # analyte_file)\n #\n # self.assertEqual(len(experiment_file), 1)\n # self.assertEqual(experiment_file[0], [\n # 'experiment_dna_short_read_id', 'analyte_id', 'experiment_sample_id', 'seq_library_prep_kit_method',\n # 'read_length', 'experiment_type', 'targeted_regions_method', 'targeted_region_bed_file',\n # 'date_data_generation', 'target_insert_size', 'sequencing_platform',\n # ])\n #\n # self.assertEqual(len(experiment_file), 1)\n # self.assertEqual(read_file[0], [\n # 'aligned_dna_short_read_id', 'experiment_dna_short_read_id', 'aligned_dna_short_read_file',\n # 'aligned_dna_short_read_index_file', 'md5sum', 'reference_assembly', 'alignment_software', 'mean_coverage',\n # 'analysis_details',\n # ])\n #\n # self.assertEqual(len(experiment_file), 1)\n # self.assertEqual(read_set_file[0], ['aligned_dna_short_read_set_id', 'aligned_dna_short_read_id'])\n #\n # self.assertEqual(len(experiment_file), 1)\n # self.assertEqual(called_file[0], [\n # 'called_variants_dna_short_read_id', 'aligned_dna_short_read_set_id', 'called_variants_dna_file', 'md5sum',\n # 'caller_software', 'variant_types', 'analysis_details',\n # ])\n #\n # self.check_no_analyst_no_access(url)\n\n\nclass LocalReportAPITest(AuthenticationTestCase, ReportAPITest):\n fixtures = ['users', '1kg_project', 'reference_data', 'report_variants']\n ADDITIONAL_SAMPLES = ['NA21234']\n STATS_DATA = {\n 'projectsCount': {'non_demo': 3, 'demo': 1},\n 'familiesCount': {'non_demo': 12, 'demo': 2},\n 'individualsCount': {'non_demo': 16, 'demo': 4},\n 'sampleCountsByType': {\n 'WES__VARIANTS': {'demo': 1, 'non_demo': 7},\n 'WGS__MITO': {'non_demo': 1},\n 'WES__SV': {'non_demo': 3},\n 'WGS__SV': {'non_demo': 1},\n 'RNA__VARIANTS': {'non_demo': 3},\n },\n }\n\n\n# class AnvilReportAPITest(AnvilAuthenticationTestCase, ReportAPITest):\n# fixtures = ['users', 'social_auth', '1kg_project', 'reference_data', 'report_variants']\n# ADDITIONAL_SAMPLES = []\n# STATS_DATA = {\n# 'projectsCount': {'internal': 1, 'external': 1, 'no_anvil': 1, 'demo': 1},\n# 'familiesCount': {'internal': 11, 'external': 1, 'no_anvil': 0, 'demo': 2},\n# 'individualsCount': {'internal': 14, 'external': 2, 'no_anvil': 0, 'demo': 4},\n# 'sampleCountsByType': {\n# 'WES__VARIANTS': {'internal': 7, 'demo': 1},\n# 'WGS__MITO': {'internal': 1},\n# 'WES__SV': {'internal': 3},\n# 'WGS__SV': {'external': 1},\n# 'RNA__VARIANTS': {'internal': 3},\n# },\n# }\n","repo_name":"populationgenomics/seqr","sub_path":"seqr/views/apis/report_api_tests.py","file_name":"report_api_tests.py","file_ext":"py","file_size_in_byte":35779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"35291770824","text":"import requests\nfrom lxml import etree\nimport os\nimport re\nfrom urllib import request\n\n\"\"\"\n 爬取最新斗图图片,网址:http://www.doutula.com/\n 方式:单线程\n 编写爬取代码时网页代码见resource/斗图网页.html\n\"\"\"\n\ndef parse_page(url):\n headers = {\n \"User-Agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36\"\n }\n response = requests.get(url,headers=headers)\n text = response.text\n html = etree.HTML(text)\n images = html.xpath('//div[@class=\"page-content text-center\"]//img[@class!=\"gif\"]')\n for image in images:\n # print(etree.tostring(image))\n image_url = image.get(\"data-original\")\n alt = image.get(\"alt\")\n alt = re.sub(r\"[\\??,。!,!]\",\"\",alt)\n suffix = os.path.splitext(image_url)[1]\n fileName = alt + suffix\n # print(fileName)\n request.urlretrieve(image_url,\"images/\"+fileName)\n print(fileName,\"已成功下载\")\n\ndef main():\n for x in range(1,11):\n url = \"http://www.doutula.com/photo/list/?page=%d\" % x\n print(\"=============正在下载第%d页的图片===================\" %x)\n parse_page(url)\n\nif __name__ == '__main__':\n main()","repo_name":"wyp001/ajax_spider_demo","sub_path":"com/example/Demo1.py","file_name":"Demo1.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21824006136","text":"import os\nimport argparse\nimport numpy as np\nimport nibabel as nib\nfrom utils.utils import ORGAN_NAME_OVERLAP,TEMPLATE,ORGAN_NAME_LOW\nfrom utils.utils import entropy_post_process,std_post_process,get_key\nfrom tqdm import tqdm\nimport csv\n\ndef write_attention_size(args):\n dataset_name_list = [1,2,3]\n organ_target = TEMPLATE['target']\n attention_size = []\n case_name = []\n z_size = []\n for item in args.dataset_list:\n with open(os.path.join(args.data_txt_path,item + '.txt'), \"r\") as fl:\n all_lines = fl.readlines()\n for line in tqdm(range(len(all_lines))):\n dataset_name = all_lines[line].strip().split()[0].split('/')[0]\n if int(dataset_name[0:2]) == 10:\n template_key = get_key(all_lines[line].strip().split()[0].split('.')[0])\n else: \n template_key = get_key(dataset_name)\n task_folder = os.path.join(args.data_root_path,dataset_name)\n current_case_name = all_lines[line].split()[0].split('.')[0].split('/')[-1]\n case_name.append(current_case_name)\n total_attention_size = 0\n organ_dataset = TEMPLATE[template_key]\n organ_index = [organ for organ in organ_target if organ not in organ_dataset]\n print('calculate attention map size for %s'%(current_case_name))\n\n if int(dataset_name[0:2]) in dataset_name_list:\n uncertainty_path = os.path.join(task_folder,current_case_name,'average','uncertainty')\n overlap_path = os.path.join(task_folder,current_case_name,'average','overlap')\n for idx in tqdm(range(len(organ_index))):\n organ_name = ORGAN_NAME_LOW[organ_index[idx]-1]\n uncertainty = nib.load(os.path.join(uncertainty_path,organ_name+'.nii.gz')).get_fdata()\n overlap = nib.load(os.path.join(overlap_path,organ_name+'.nii.gz')).get_fdata()\n attention = uncertainty/255+overlap\n attention = attention/np.max(attention)\n attention[np.isnan(attention)] = 0\n total_attention_size += np.sum(attention)\n else: \n attention_path = os.path.join(task_folder,current_case_name,'average','attention')\n for idx in tqdm(range(len(organ_index))):\n organ_name = ORGAN_NAME_LOW[organ_index[idx]-1]\n attention = nib.load(os.path.join(attention_path,organ_name+'.nii.gz')).get_fdata()\n attention = attention/255\n attention = attention/np.max(attention)\n attention[np.isnan(attention)] = 0\n total_attention_size += np.sum(attention)\n attention_size.append(total_attention_size)\n z_size.append(attention.shape[2])\n \n normalize_attention = np.array(attention_size)/np.array(z_size)\n attention_size_sorted_idx = np.argsort(-normalize_attention)\n print('sort case complete')\n if os.path.isfile(os.path.join(args.csv_save_path,dataset_name,args.csv_name+'.csv')):\n os.remove(os.path.join(args.csv_save_path,dataset_name,args.csv_name+'.csv'))\n for index in attention_size_sorted_idx:\n row = [case_name[index],normalize_attention[index]]\n with open(os.path.join(args.csv_save_path,dataset_name,args.csv_name+'.csv'),'a',newline='') as f:\n writer = csv.writer(f,delimiter=',', quotechar='\"')\n writer.writerow(row)\n \n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--dataset_list', nargs='+', default=['PAOT_123457891213', 'PAOT_10_inner']) # 'PAOT', 'felix'\n parser.add_argument('--data_txt_path', default='./dataset/dataset_list/', help='data txt path')\n parser.add_argument('--data_root_path', default='/ccvl/net/ccvl15/chongyu/LargePseudoDataset/', help='data root path')\n parser.add_argument('--csv_save_path',default = '/ccvl/net/ccvl15/chongyu/LargePseudoDataset/', help='csv save path')\n parser.add_argument('--csv_name',default = 'attention_size',help='attention size csv file name')\n args = parser.parse_args()\n\n write_attention_size(args)\nif __name__ == \"__main__\":\n main()","repo_name":"MrGiovanni/AbdomenAtlas","sub_path":"utils/calculate_attention.py","file_name":"calculate_attention.py","file_ext":"py","file_size_in_byte":4220,"program_lang":"python","lang":"en","doc_type":"code","stars":53,"dataset":"github-code","pt":"48"} +{"seq_id":"7312298185","text":"import time\n\nimport requests\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nfrom selenium.webdriver.common.service import Service\nfrom selenium.webdriver.common.by import By\n\n\n# 提取每页的内容\ndef extract_contents(page_content):\n soup = BeautifulSoup(page_content, 'html.parser')\n # 定位目标元素\n target_elements = soup.select(\n 'body .sysu-contents .contents .main-content table tbody .sx_conter_item .sx_pa a')\n\n # 提取目标内容\n contents = []\n for element in target_elements:\n content = element.get_text()\n contents.append(content)\n\n print(contents)\n time.sleep(3)\n\n\ndef login_and_wait():\n url = \"https://ehall.scnu.edu.cn/taskcenter/workflow/doing\"\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '\n 'Chrome/73.0.3683.86 Safari/537.36',\n }\n # 创建Chrome浏览器的实例\n driver = webdriver.Chrome()\n driver.get(url) # 替换成实际登录页面的URL\n\n # 等待页面加载完成\n time.sleep(1)\n\n # 定位账号输入框并输入账号\n account_input = driver.find_element(By.ID, 'account') # 替换成实际的账号输入框ID\n account_input.send_keys('账号') # 替换成实际的账号\n\n password_input = driver.find_element(By.ID, 'password') # 替换成实际的密码输入框ID\n password_input.send_keys('密码') # 替换成实际的密码\n\n time.sleep(1)\n login_button = driver.find_element(By.CLASS_NAME,\n 'btn.btn-primary.btn-block.auth-login-btn') # 使用 By.CLASS_NAME 进行定位\n login_button.click()\n time.sleep(1)\n\n # 点击登录后\n print(\"ok\")\n driver.switch_to.window(driver.window_handles[-1])\n confirm_button = driver.find_element(By.CSS_SELECTOR, 'span.login-check-comfirm a.btn.btn-danger')\n confirm_button.click()\n time.sleep(2)\n\n page_content = driver.page_source\n extract_contents(page_content)\n\n driver.quit()\n\n\n# 调用函数进行登录和等待\nlogin_and_wait()\n","repo_name":"kixuan/Crawling-around","sub_path":"网上办事大厅/01登录.py","file_name":"01登录.py","file_ext":"py","file_size_in_byte":2096,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21632297841","text":"#from django.shortcuts import render\nfrom rest_framework import status\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework.parsers import MultiPartParser\nimport csv\nimport io\nfrom .serializers import DealsSerializer\nfrom .models import Deal\nfrom django.db.models import Sum\nfrom django.views.decorators.cache import cache_control\n\nclass UploadData(APIView):\n\tparser_classes = (MultiPartParser,)\n\n\tdef post(self, request, format=None):\n\t\tdecoded_file = request.data['data'].read().decode('utf-8')\n\t\tio_string = io.StringIO(decoded_file)\n\t\tdict_csv = list(csv.DictReader(io_string))\n\n\t\tserializer = DealsSerializer(data=dict_csv, many=True)\n\n\t\tif serializer.is_valid():\n\t\t\tDeal.objects.all().delete()\n\t\t\tserializer.save()\n\t\t\treturn Response('Файл был обработан без ошибок', status=status.HTTP_200_OK)\n\t\telse:\n\t\t\treturn Response('Error, Desc:' + str(serializer.errors) + '- в процессе обработки файла произошла ошибка', status=status.HTTP_400_BAD_REQUEST)\n\nclass GetData(APIView):\n\n\t@cache_control(must_revalidate=True, max_age=3600)\n\tdef get(self, request, format=None):\n\t\t#find top 5 customers by spent money\n\t\tdeals = Deal.objects.values('customer').annotate(spent_money=Sum('total')).order_by('-spent_money')[:5]\n\t\t\n\t\t#create list of dictionaries of customers with name, spent money \n\t\t#and list of all gems bought by customer\n\t\tcustomers = []\n\t\tfor deal in deals: \n\t\t\tcustomer = {'customer':deal['customer'], 'spent_money': deal['spent_money'], 'gems':[]}\n\n\t\t\t#get all gems that customer bought\n\t\t\tcustomers_from_db = Deal.objects.filter(customer=customer['customer']).values('item').distinct()\n\t\t\tfor row in customers_from_db:\n\t\t\t\tcustomer['gems'].append(row['item'])\n\t\t\tcustomers.append(customer)\n\n\t\tresult = []\n\t\tfor customer in customers:\n\t\t\tfor gem in customer['gems']:\n\t\t\t\tgem_has_duplicate = False\n\t\t\t\t#iterate through every customer gems\n\t\t\t\t#and compare it with every other customer gem_list\t\n\t\t\t\tfor c in customers:\n\t\t\t\t\t#ignore if it's a same customer\n\t\t\t\t\tif customer['customer'] != c['customer']:\n\t\t\t\t\t\t#if other customer has gem in his list\n\t\t\t\t\t\tif gem in c['gems']:\n\t\t\t\t\t\t\t#then mark it\n\t\t\t\t\t\t\tgem_has_duplicate = True\n\t\t\t\t\t\t\t#and exit loop for this gem\n\t\t\t\t\t\t\tbreak\n\t\t\t\t#if wasn't able to find second gem in any other\n\t\t\t\t#customer gem list then delete this gem\n\t\t\t\tif not gem_has_duplicate:\n\t\t\t\t\tcustomer['gems'].remove(gem)\n\t\t\tresult.append(customer)\n\n\t\treturn Response(result, status=status.HTTP_200_OK)","repo_name":"Rimasko/restapi_app","sub_path":"app/rest_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"22011544941","text":"import uuid\nimport logging\nfrom typing import Protocol\nfrom django.db import transaction\nfrom django.db.models import QuerySet\nfrom rest_framework.generics import get_object_or_404\n\nfrom payments import models, choices\nfrom orders import models as order_models\nfrom orders import choices as orders_choices\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass BillReposInterface(Protocol):\n\n @staticmethod\n def pay_bill(order_id: uuid.UUID) -> None:\n ...\n\n @staticmethod\n def get_bill(order_id: uuid.UUID) -> models.Bill:\n ...\n\n\nclass BillReposV1:\n\n @staticmethod\n def pay_bill(order_id: uuid.UUID) -> None:\n with transaction.atomic():\n try:\n bill = BillReposV1.get_bill(order_id=order_id)\n bill.status = choices.BillStatusChoices.Paid\n bill.save()\n bill.order.status = orders_choices.OrderStatusChoices.Paid\n bill.order.save()\n\n models.Transaction.objects.create(\n bill=bill,\n amount=bill.total,\n transaction_type=choices.TransactionTypeChoices.Charge,\n )\n logger.info(f'bill with id {order_id} is successfully paid!')\n except models.Bill.DoesNotExist:\n logger.error(f'bill with id {order_id} not found')\n\n @staticmethod\n def get_bill(order_id: uuid.UUID) -> models.Bill:\n bill = get_object_or_404(\n models.Bill.objects.filter(\n order=order_id,\n status=choices.BillStatusChoices.New,\n ),\n )\n return bill\n","repo_name":"abolatuly/car-rental","sub_path":"payments/repos.py","file_name":"repos.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"3116102546","text":"import threading\nfrom concurrent import futures\n\nimport grpc\nimport time\nimport sys\n\nimport chat_pb2 as chat\nimport chat_pb2_grpc as rpc\n\nfrom utils.input_output_util import get_input\nfrom utils.input_output_util import print_msg\nfrom utils.input_output_util import log_error\nfrom utils.input_output_util import log_info\nfrom utils.input_output_util import print_take_input_msg\nfrom utils.input_output_util import log_forwarding_info\nfrom utils.input_output_util import print_file_info\n\nfrom utils.file_utils import get_file_chunks\nfrom utils.file_utils import write_file_chunks\nfrom utils.file_utils import get_total_file_chunks\n\nchats = []\nfile_buffer = []\n\nclass Client:\n def __init__(self, username, server_address, server_port):\n\n self.username = username\n self.msg_id = 0\n self.messageTimes ={}\n\n # create a gRPC channel + stub\n channel = grpc.insecure_channel(server_address + ':' + str(server_port))\n self.conn = rpc.DataTransferServiceStub(channel)\n # self._ping()\n # create new listening thread for when new message streams come in\n threading.Thread(target=self._ping, daemon=True).start()\n\n for msg in get_input():\n msg = msg.split()\n if len(msg) <= 2:\n log_error(\"invalid message format: \")\n return\n\n if msg[0] == \"text\":\n self._send_message(msg[1], msg[2:])\n elif msg[0] == \"file\":\n self._tranfer_file(msg[1], msg[2])\n else:\n log_error(\"invalid message type: supported msg type text, file\")\n\n def _next_msg_id(self):\n self.msg_id = self.msg_id + 1\n return self.msg_id\n\n def _ping(self):\n user = chat.User()\n user.name = self.username\n\n while True:\n try:\n print_take_input_msg()\n for message in self.conn.Ping(user):\n if message.destination == self.username:\n\n if message.type == chat.File:\n write_file_chunks(message)\n print_file_info(message)\n if message.origin == self.username:\n print(\"round time for \",message.id,\" part \",message.seqnum,\"/\",message.seqmax,\" : \",time.time()-self.messageTimes[message.id])\n\n if message.type == chat.Text:\n print_msg(message)\n\n print_take_input_msg()\n elif message.origin == self.username:\n log_info(\"destination \" + message.destination + \" not found..\")\n else:\n log_forwarding_info(message)\n # log_info(\n # \"forwarding message \\\"\" + str(message.id) + \"\\\" from \" + message.origin + \" to \" + message.destination + \"....\")\n # time.sleep(1)\n chats.append(message)\n\n except grpc.RpcError as e:\n log_error(\"Fail to connect...\")\n time.sleep(1)\n\n def _send_message(self, destination, msg):\n\n message = chat.Message()\n message.id = self._next_msg_id()\n message.type = chat.Text\n message.data = str.encode(\" \".join(msg))\n message.destination = destination\n message.origin = self.username\n message.timestamp = int(time.time())\n message.hops = 0\n message.seqnum = 1\n message.seqmax = 1\n\n chats.append(message)\n\n def _tranfer_file(self, destination, filename):\n\n print(\"transferring file... \" + filename + \" to \" + destination)\n\n try:\n msg_id = self._next_msg_id()\n \n self.messageTimes[msg_id] = time.time()\n\n total_chunk = get_total_file_chunks(filename)\n current_chunk = 1\n\n for file_buffer in get_file_chunks(filename):\n message = chat.Message()\n message.id = msg_id\n message.type = chat.File\n message.data = file_buffer\n message.destination = destination\n message.origin = self.username\n message.timestamp = int(time.time())\n message.hops = 0\n message.seqnum = current_chunk\n message.seqmax = total_chunk\n current_chunk += 1\n \n chats.append(message)\n\n except FileNotFoundError as e:\n print(\"File not found:\", e)\n \n\ndef start_client(username, server_address, server_port):\n c = Client(username, server_address, server_port)\n\n\n# server\n\nclass ChatServer(rpc.DataTransferServiceServicer):\n def __init__(self):\n pass\n\n def Ping(self, request: chat.User, context):\n print(\"[{}] from Ping in server\".format(request.name))\n lastindex = 0\n while True:\n # Check if there are any new messages\n while len(chats) > lastindex:\n n = chats[lastindex]\n lastindex += 1\n yield n\n\n def Send(self, request: chat.Message, context):\n # print_msg(request)\n\n # Add it to the chat history\n ack = chat.Ack()\n ack.id = request.id\n chats.append(request)\n return ack\n\ndef main(argv):\n my_port = argv[1]\n # create a gRPC server\n server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))\n rpc.add_DataTransferServiceServicer_to_server(ChatServer(), server)\n\n print('Starting server. Listening...')\n server.add_insecure_port('[::]:' + str(my_port))\n server.start()\n\n # client\n server_address = argv[2]\n server_port = argv[3]\n username = argv[4]\n\n threading.Thread(target=start_client, args=(username, server_address, server_port), daemon=True).start()\n\n # Server starts in background (another thread) so keep waiting\n while True:\n time.sleep(64 * 64 * 100)\n\n\nif __name__ == '__main__':\n main(sys.argv[:])\n\n","repo_name":"arpitm91/CMPE-275-Project1","sub_path":"samples/ring/ring_node.py","file_name":"ring_node.py","file_ext":"py","file_size_in_byte":6057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29771769923","text":"class Student:\r\n def __init__(self, name, age, grade):\r\n self.name = name\r\n self.age = age\r\n self.grade = grade\r\n\r\n# Creating a student\r\nstudent1 = Student(\"Student1\", 13, 8)\r\n\r\n# To delete objects you can use the del keyword\r\ndel student1.age\r\n\r\nprint(student1.age)\r\n# Running this program will give you an error because we deleted student.age","repo_name":"Nepul321/Classes-in-python","sub_path":"classes5.py","file_name":"classes5.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6506766846","text":"\"\"\"\nTest some of the basic model use cases\n\n\"\"\"\nfrom candidates.tests.helpers import TmpMediaRootMixin\nfrom django.conf import settings\nfrom django.core.files.storage import DefaultStorage\nfrom django.test import TestCase\n\nfrom .factories import PartyEmblemFactory, PartyFactory\n\n\nclass TestPartyModels(TmpMediaRootMixin, TestCase):\n def setUp(self):\n self.storage = DefaultStorage()\n PartyFactory.reset_sequence()\n\n def test_party_str(self):\n party = PartyFactory()\n self.assertEqual(str(party), \"Party 0 (PP0)\")\n\n def test_party_emblem(self):\n party = PartyFactory()\n PartyEmblemFactory.create_batch(3, party=party)\n self.assertEqual(party.emblems.count(), 3)\n first_emblem = party.emblems.first()\n self.assertEqual(\n first_emblem.image.url,\n f\"{settings.MEDIA_ROOT}/emblems/PP0/{first_emblem.ec_emblem_id}_example.jpg\",\n )\n\n # Add a default image and assert it's the deafult on the party\n PartyEmblemFactory(party=party, __sequence=99, default=True)\n self.assertEqual(\n party.default_emblem.image.url,\n f\"{settings.MEDIA_ROOT}/emblems/PP0/99_example.jpg\",\n )\n","repo_name":"DemocracyClub/yournextrepresentative","sub_path":"ynr/apps/parties/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"48"} +{"seq_id":"6284282407","text":"import os\nimport yaml\nimport argparse\nfrom easydict import EasyDict as edict\n\nfrom src.train import train\nfrom src.test import test\nfrom src.predict import predict\nfrom src.bicubic import test_bicubic, predict_bicubic\nfrom src.tranfer_learning import tranfer_learning\n\n\ndef load_config(path='configs/config.yaml'):\n stream = open(path, 'r')\n return edict(yaml.safe_load(stream))\n\n\ndef find_config(experiment_path):\n yaml_in_path = list(filter(lambda x: x[-5:] == '.yaml', os.listdir(experiment_path)))\n \n if len(yaml_in_path) == 1:\n return yaml_in_path[0]\n\n if len(yaml_in_path) == 0:\n print(\"ERROR: config.yaml wasn't found in\", experiment_path)\n \n if len(yaml_in_path) > 0:\n print(\"ERROR: a lot a .ymal was found in\", experiment_path)\n \n exit()\n\n\ndef main(options):\n if options['mode'] == 'train':\n config = load_config(options['config_path'])\n train(config)\n \n elif options['mode'] == 'test':\n config_path = os.path.join(options['path'], find_config(options['path']))\n config = load_config(config_path)\n test(options['path'], config)\n\n elif options['mode'] == 'predict':\n config_path = os.path.join(options['path'], find_config(options['path']))\n config = load_config(config_path)\n predict(options['path'], config)\n \n elif options['mode'] == 'resumetrain':\n config_path = os.path.join(options['path'], find_config(options['path']))\n config = load_config(config_path)\n train(config, resume_training=options['path'])\n\n elif options['mode'] == 'bicubic':\n config = load_config(options['config_path'])\n test_bicubic(config)\n \n elif options['mode'] in ['tf', 'tranfer_learning']:\n previous_config_path = os.path.join(options['path'], find_config(options['path']))\n previous_config = load_config(previous_config_path)\n tranfer_learning(previous_config, options['path'], options['new_upscale_factor'])\n\n elif options['mode'] == 'predict_bicubic':\n config = load_config(options['config_path'])\n predict_bicubic(config)\n\n else:\n print('ERROR: mode incorect. You chose: ' + options['mode'] + '. Please chose a mode between:')\n print('- train')\n print('- resumetrain')\n print('- tf or transfer_learning')\n print('- test')\n print('- predict')\n print('- bicubic')\n print('- predict_bicubic')\n exit()\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n\n # Options\n parser.add_argument('--mode', default=None, type=str, help=\"choose a mode between 'train', 'test', 'predict', 'bicubic' and 'resumetrain'\")\n parser.add_argument('--config_path', default=os.path.join('config', 'config.yaml'), type=str, help=\"path to config (for training)\")\n parser.add_argument('--path', type=str, help=\"experiment path (for test, prediction or resume previous training)\")\n parser.add_argument('--new_upscale_factor', type=int, help=\"new upscale factor for a tranfere learning\")\n\n args = parser.parse_args()\n options = vars(args)\n\n main(options)","repo_name":"Highdrien/image_super_resolution","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3129,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42317243972","text":"#!/usr/bin/env python\n\n\"\"\"applications.ecommerce URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\n\nfrom django.contrib import admin\nfrom django.urls import path\nfrom applications.ecommerce.views import *\nfrom django.contrib.auth import views as auth_views\n\nurlpatterns = [\n\n path('login/', auth_views.LoginView.as_view(\n template_name='ecommerce/login.html', \n redirect_authenticated_user=True, \n redirect_field_name='index'\n ), name='login'),\n\n path('logout/', auth_views.LogoutView.as_view(\n next_page='/ecommerce/', \n redirect_field_name='index'), name='logout'),\n \n path('signup/', register, name = 'register'),\n\n # NOTE: Site pages\n path('', IndexView.as_view(), name='index'), # Index view\n \n path('tutorial/', TutorialView.as_view(), name='tutorial'), # Index view\n \n]","repo_name":"InoveAlumnos/ecommerce_backend_python","sub_path":"marvel/applications/ecommerce/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"357128184","text":"from PIL import Image\nimport os\n\n# Resizes all of the images, train and test, to 200x200 dimensions\ndef resize(path):\n for folder in os.listdir(path):\n for subfolder in os.listdir(path +folder):\n for item in os.listdir(path+folder+ \"/\" + subfolder):\n if item.endswith(\".jpg\"):\n image = Image.open(path + folder + \"/\" + subfolder + \"/\" + item)\n imResize = image.resize((200,200), Image.ANTIALIAS)\n imResize.save(path + folder + \"/\" + subfolder + \"/\" + item, 'jpeg', quality=90)\n","repo_name":"elleAI/ios-ml-app","sub_path":"resizeDataset.py","file_name":"resizeDataset.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"28079698056","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[8]:\n\n\nget_ipython().system(' jupyter nbconvert --to python poc.ipynb')\n\n\n# In[11]:\n\n\nimport pandas as pd\nimport requests\nimport plotly\nimport plotly.graph_objs as go\n\n\n# In[31]:\n\n\nurl = \"https://pt.wikipedia.org/wiki/Predefinição:Tabela_Covid-19_Portugal_região/dia_(DGS)\"\n\nr = requests.get(url, auth=('user', 'pass'))\nwebsite = r.text\ntables = pd.read_html( website, encoding=\"UTF-8\")\ntable = tables[0]\n\n\n# In[32]:\n\n\ntable\n\n\n# In[33]:\n\n\n# select relevant columns and drop last helper rows\ntable = table[['data','Madeira']].drop(table.tail(4).index)\ntable \n\n\n# In[34]:\n\n\n# drop unneeded levels \ntable.columns = table.columns.droplevel([0,1])\ntable\n\n\n# In[35]:\n\n\ntable = table.loc[:,['Σ', 'Δ']]\n\n\n# In[36]:\n\n\ntable\n\n\n# In[37]:\n\n\n# create new, proper date column, starting from March 1st; assuming update each day\nstart_date = '2020-03-03'\nend_date = pd.to_datetime(start_date) + pd.DateOffset(days=len(table)-1)\ndates = pd.date_range(start_date, end=end_date)\n\n\n# In[38]:\n\n\ntable['date'] = pd.Series(dates, index=table.index).values\ntable\n\n\n# In[39]:\n\n\ntrace = go.Scatter(x=table['date'], y=table['Σ'], name='sum of COVID cases')\ndata = [trace]\n\nupdatemenus = list([\n dict(active=1,\n buttons=list([\n dict(label='Log Scale',\n method='update',\n args=[{'visible': [True]},\n {'title': 'Log scale',\n 'yaxis': {'type': 'log'}}]),\n dict(label='Linear Scale',\n method='update',\n args=[{'visible': [True]},\n {'title': 'Linear scale',\n 'yaxis': {'type': 'linear'}}])\n ]),\n )\n ])\n\nlayout = dict(updatemenus=updatemenus, title='Linear scale')\nfig = go.Figure(data=data, layout=layout)\n\nplotly.offline.iplot(fig)\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"t8ch/covid-by-regions","sub_path":"poc.py","file_name":"poc.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4887887261","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Nov 29 15:16:49 2019\r\n\r\n@author: furkan\r\n\"\"\"\r\n\r\n#%%\r\n\r\nimport pandas as pd\r\nimport random\r\nimport numpy as np\r\nimport math\r\nimport matplotlib.pyplot as plt\r\nfrom mpl_toolkits import mplot3d\r\nimport sys\r\nfrom sklearn import preprocessing\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense\r\nfrom keras.optimizers import SGD\r\nfrom keras import losses\r\n\r\n#%% activation functions \r\n\r\ndef relu(x):\r\n y = np.copy(x)\r\n for i in range(len(y)):\r\n y[i] = max(0 ,y[i])\r\n return y\r\ndef sigmoid(x):\r\n y = np.copy(x)\r\n for i in range(len(y)):\r\n y[i] = 1/(1+math.exp(-y[i]))\r\n\r\n return y\r\ndef empty(x):\r\n return x\r\n\r\n # derivations of the activation functions\r\n\r\ndef d_relu(x):\r\n y = np.copy(x)\r\n for i in range(len(y)):\r\n if(y[i]>0):\r\n y[i] = 1\r\n else:\r\n y[i] = 0\r\n return y\r\ndef d_sigmoid(x):\r\n return np.multiply(sigmoid(x),np.multiply(sigmoid(x),-1)+1)\r\ndef d_empty(x):\r\n return 0\r\n\r\n\r\n#%%\r\nclass Sequence:\r\n\r\n def __init__(self):\r\n self.w = []\r\n self.b = []\r\n self.func = []\r\n self.act = {'relu' : relu,'sigmoid' : sigmoid, 'empty' : empty}\r\n self.d_act = {'relu' : d_relu,'sigmoid' : d_sigmoid, 'empty' : d_empty}\r\n self.err = []\r\n self.inputs = []\r\n self.errorRate = []\r\n self.sum = []\r\n self.averageError = sys.maxsize\r\n\r\n # adding layers that are initialized in dense function to the corresponding lists \r\n\r\n def add(self,w,b,func,err):\r\n self.w.append(w)\r\n self.b.append(b)\r\n self.func.append(func)\r\n self.err.append(err)\r\n \r\n # initializing the layers, inputs and outputs\r\n\r\n def Dense(self, numberOfNodes = 2, input = 0, activation = 'relu'):\r\n if (input == 0):\r\n input = self.w[-1].shape[0]\r\n w = np.random.rand(numberOfNodes, input)\r\n b = np.resize(np.random.rand(numberOfNodes,1),(numberOfNodes,))\r\n func = activation\r\n err = np.zeros((numberOfNodes,1))\r\n return w,b,func,err\r\n\r\n # feedforward is generate output from input\r\n\r\n def feedForward(self, input):\r\n self.inputs = []\r\n self.sum = []\r\n for i in range(len(self.w)):\r\n self.inputs.append(np.resize(input,(len(input),1)))\r\n summed = np.add((self.w[i]@input) , self.b[i] )\r\n summed = np.resize(summed,(len(summed),1))\r\n \r\n self.sum.append(summed)\r\n input = self.act[ self.func[i] ](summed)\r\n return input\r\n\r\n # error function for neural network\r\n\r\n def calculateError(self, target, output):\r\n error = np.sum(np.multiply(np.subtract(output,target),np.subtract(output,target))) / len(target)\r\n \r\n self.err[len(self.err)-1] = np.multiply( self.d_act[self.func[len(self.func)-1]](self.sum[len(self.sum)-1]), error)\r\n self.err[len(self.err)-1] = np.resize(self.err[len(self.err)-1], (self.err[len(self.err)-1].shape[0],1))\r\n for i in range((len(self.err)-2),-1,-1):\r\n dot = np.transpose(self.w[i+1])@self.err[i+1]\r\n self.err[i] = np.negative(np.multiply(self.d_act[self.func[len(self.func)-1]](self.sum[i]), np.resize(dot, (dot.shape[0],1))))\r\n\r\n return np.subtract(output,target)\r\n \r\n# def backpropogateError(self,lr):\r\n# for i in range(len(self.inputs)):\r\n# self.w[i] = np.subtract(self.w[i], np.multiply(self.err[i]@np.transpose(self.inputs[i]),lr))\r\n# self.b[i] = np.resize(np.subtract(np.resize(self.b[i], (self.b[i].shape[0],1)), np.multiply(self.err[i],lr)) , (self.b[i].shape[0],))\r\n \r\n # backpropogation for updating neural network's weight and biases\r\n\r\n def backpropogateError(self,lr):\r\n for i in range(len(self.inputs)):\r\n self.w[i] = np.subtract(self.w[i], np.multiply(self.err[i]@np.transpose(self.inputs[i]),lr))\r\n self.b[i] = np.resize(np.subtract(np.resize(self.b[i], (self.b[i].shape[0],1)), np.multiply(self.err[i],lr)) , (self.b[i].shape[0],))\r\n\r\n # calculate error for updating error rate\r\n\r\n def calculateErrorRate(self,errorRate, iteration):\r\n errorRate = np.asarray(errorRate)\r\n self.averageError = (self.averageError*(iteration-1) + math.sqrt(np.sum(np.multiply(errorRate,errorRate))))/iteration\r\n self.errorRate.append(self.averageError)\r\n return self.averageError\r\n \r\n # train and test functions to train the model and evaluate it\r\n\r\n def train(self, x_train, y_train, error = 0.01, learning_rate = 0.1, epoch_l = 200000):\r\n self.errorRate = []\r\n errorRate = sys.maxsize\r\n epoch = 0\r\n iteration = 0\r\n i = 0\r\n target = y_train[i]\r\n output = target*2\r\n #print(\"train: errorRate: \" + str(errorRate))\r\n while((errorRate > error) and epoch < epoch_l):\r\n iteration += 1\r\n if(i < len(x_train)-1):\r\n i += 1\r\n else:\r\n i = 0\r\n epoch += 1\r\n output = self.feedForward(x_train[i])\r\n errorRate = self.calculateErrorRate(self.calculateError(y_train[i], output), iteration)\r\n print(\"x,y: \" + str(x_train[i]) + \" | output generated: \" + str(output) + \" <- y_train: \"+ str(y_train[i]))\r\n self.backpropogateError(learning_rate)\r\n print(\"-- epoch: \" + str(epoch) + \" -- iter: \" + str(iteration) + \" errorRate: \" + str(errorRate))\r\n return self.errorRate\r\n \r\n def test(self, x_test, y_test, error = 0.01):\r\n perc = 0\r\n for i in range(len(x_test)):\r\n output = self.feedForward(x_test[i])\r\n errorRate = self.calculateError(y_test[i], output)\r\n e = np.sum(np.multiply(errorRate,errorRate))/len(errorRate)\r\n if(e <= error):\r\n perc += 1\r\n print(\"-- x_test --\")\r\n print(x_test[i])\r\n print(\"output\")\r\n print(output)\r\n \r\n perc /= len(x_test)\r\n return perc*100\r\n\r\n# split function for spliting the data to train and test sets\r\n\r\n def split(self, x, y, percentage = 0.2):\r\n x_train = np.asarray(x.head(int(x.shape[0]*(1-percentage))).values)\r\n y_train = np.asarray(y.head(int(y.shape[0]*(1-percentage))).values)\r\n x_test = np.asarray(x.tail(int(y.shape[0]*percentage)).values)\r\n y_test = np.asarray(y.tail(int(y.shape[0]*percentage)).values)\r\n return x_train, y_train, x_test, y_test\r\n \r\n\r\n\r\n\r\n\r\n\r\n#%% Data Spesifications are given by the Neural Network Course Project\r\n\r\ndef f(x , y):\r\n return (x*x) + (y*y)\r\n\r\ndef generateData(n):\r\n df = pd.DataFrame(columns = ['x', 'y', 'result'])\r\n for i in np.linspace((-1)*n,n,2*n+1):\r\n for j in np.linspace((-1)*n,n,2*n+1):\r\n x = i\r\n y = j\r\n result = f(x,y)\r\n df = df.append({'x' : x, 'y' : y, 'result' : result}, ignore_index = True)\r\n df = df.sample(frac=1).reset_index(drop=True)\r\n return df\r\n\r\n#%% Data Generation, Normalization, Splitting Data to train and test sets\r\n\r\ndf = generateData(5)\r\n\r\nscaler = preprocessing.MinMaxScaler()\r\n\r\nx = df[['x', 'y']]\r\ny = df[[\"result\"]]\r\n\r\n#scaled_x = scaler.fit_transform(x)\r\nscaled_y = scaler.fit_transform(y)\r\n\r\n#scaled_x = pd.DataFrame(scaled_x, columns=['x', 'y'])\r\nscaled_y = pd.DataFrame(scaled_y, columns=['result'])\r\n\r\nx_train, y_train, x_test, y_test = model.split(x,scaled_y)\r\n\r\n#%% Model with my library\r\n\r\nmodel = Sequence()\r\n\r\nw,b,func,err = model.Dense(3,2,'relu')\r\nmodel.add(w,b,func, err)\r\n\r\nw,b,func,err = model.Dense(4,0,'sigmoid')\r\nmodel.add(w,b,func, err)\r\n\r\nw,b,func,err = model.Dense(2,0,'sigmoid')\r\nmodel.add(w,b,func, err)\r\n\r\nw,b,func,err = model.Dense(1,0,'sigmoid')\r\nmodel.add(w,b,func, err)\r\n\r\n\r\n#%% train and test with my library\r\n\r\nerror = model.train(x_train, y_train, error =0.01, learning_rate = 0.01, epoch_l = 800)\r\nmodel.test(x_test,y_test,error = 0.05)\r\n\r\n\r\n\r\n\r\n#%% Model with keras\r\n\r\n\r\nmodel_k = Sequential()\r\nmodel_k.add(Dense(16, input_dim=2, activation='relu'))\r\n\r\nmodel_k.add(Dense(1, activation='sigmoid'))\r\n \r\nsgd = SGD(lr=0.01, momentum=0.0, nesterov=False)\r\nmodel_k.compile(loss=losses.mean_squared_error, optimizer='sgd')\r\n\r\n\r\n#%% train and test with keras\r\n\r\nmodel_k.fit(x_train, y_train, epochs=500, batch_size=1)\r\naccuracy = model_k.evaluate(x_test, y_test)\r\nprint('Accuracy: %.2f' % (accuracy*100))\r\n","repo_name":"furkanaksit/university-Neural-Network-Library","sub_path":"mlp.py","file_name":"mlp.py","file_ext":"py","file_size_in_byte":8184,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"30869179489","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nfrom __future__ import print_function\nfrom silvaengine_utility import Utility\nfrom .types import ResourceType, ResourcesType\nfrom .models import ResourceModel\n\n__author__ = \"bl\"\n\n\ndef resolve_resources(info, **kwargs):\n limit = kwargs.get(\"limit\")\n last_evaluated_key = kwargs.get(\"last_evaluated_key\")\n resource_id = kwargs.get(\"resource_id\")\n filter_invisibles = lambda resource: resource.visible != False\n resources = []\n\n if resource_id:\n results = ResourceModel.query(str(resource_id).strip(), None)\n\n for resource in results:\n if str(resource.resource_id).strip() == str(resource_id).strip():\n resource.operations.query = list(\n filter(filter_invisibles, resource.operations.query)\n )\n resource.operations.mutation = list(\n filter(filter_invisibles, resource.operations.mutation)\n )\n\n if (\n len(resource.operations.query) + len(resource.operations.mutation)\n > 0\n ):\n resources.append(\n ResourceType(\n **Utility.json_loads(\n Utility.json_dumps(\n resource.__dict__[\"attribute_values\"]\n )\n )\n )\n )\n\n else:\n results = ResourceModel.scan(\n limit=int(limit),\n filter_condition=(ResourceModel.apply_to == info.context.get(\"channel\")),\n last_evaluated_key=last_evaluated_key,\n )\n\n for resource in results:\n resource.operations.query = list(\n filter(filter_invisibles, resource.operations.query)\n )\n resource.operations.mutation = list(\n filter(filter_invisibles, resource.operations.mutation)\n )\n\n if len(resource.operations.query) + len(resource.operations.mutation) > 0:\n resources.append(\n ResourceType(\n **Utility.json_loads(\n Utility.json_dumps(\n dict(**resource.__dict__[\"attribute_values\"])\n )\n )\n )\n )\n\n if results.total_count < 1:\n return None\n\n return ResourcesType(\n items=resources,\n last_evaluated_key=Utility.json_loads(\n Utility.json_dumps(results.last_evaluated_key)\n ),\n )\n","repo_name":"ideabosque/silvaengine_resouces","sub_path":"silvaengine_resource/resource/queries.py","file_name":"queries.py","file_ext":"py","file_size_in_byte":2664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73300121104","text":"\"\"\"\nFile: weightsfile_manager.py\n\nDescription: Helper module for interaction with the weights file.\n\nNOTE: This is currently not actually used because the current storage\nimplementation is using cPickle (I am very lazy).\n\"\"\"\n\nimport numpy\n\n\ndef save_weights(weight_sets, filename):\n save_string = \"\"\n for weight_set in weight_sets:\n for weights in weight_set:\n save_string += \" \".join(list(map(str, weights))) + \"\\n\"\n save_string += \"-\\n\"\n\n save_file = open(filename, \"w\")\n save_file.write(save_string)\n save_file.close()\n\n\ndef load_weights(filename):\n load_file = open(filename, \"r\")\n data = load_file.read()\n load_file.close()\n\n weight_sets = data.split(\"-\\n\")[:-1]\n weight_sets = [weights.split(\"\\n\")[:-1] for weights in weight_sets]\n for weight_set in weight_sets:\n for weights_index in xrange(len(weight_set)):\n weight_set[weights_index] = map(float, weight_set[weights_index].split())\n weight_sets = [numpy.array(weights) for weights in weight_sets]\n\n return weight_sets\n\n\nif __name__ == \"__main__\":\n pass\n","repo_name":"xtevenx/reversi-bot","sub_path":"weightsfile_manager.py","file_name":"weightsfile_manager.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22547847554","text":"import RPi.GPIO as GPIO\nimport math\nimport time\nimport threading\n\n#GPIO\n\nGPIO.setwarnings(False)\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(18, GPIO.OUT)\nGPIO.setup(16, GPIO.IN)\n\ndef turn_light_on ():\n GPIO.output(18, GPIO.HIGH)\n \ndef turn_light_off ():\n GPIO.output(18, GPIO.LOW)\n\ndef toggle_light ():\n if GPIO.input(18): \n GPIO.output(18, GPIO.LOW)\n else:\n GPIO.output(18, GPIO.HIGH)\n\ndef is_light_on ():\n return GPIO.input(18)\n\ndef is_button_pressed ():\n return GPIO.input(16)\n\ncurrent_level = 1\n\ncurrently_interruptable_sequences = []\n\n\n\ndef cancel_animation_on_press (currently_interruptable_sequences):\n while not is_button_pressed():\n time.sleep(.001)\n for sequence in currently_interruptable_sequences:\n sequence.stop()\n\nth_button = threading.Thread(target=cancel_animation_on_press, args=[currently_interruptable_sequences])\nth_button.daemon = True \nth_button.start()\n\n\ndef make_blink_animation_curve (animation_duration, start_blink_duration, end_blink_duration):\n if start_blink_duration < end_blink_duration:\n x = animation_duration\n y = end_blink_duration\n h = 0\n k = start_blink_duration\n else: \n x = 0\n y = start_blink_duration\n h = animation_duration\n k = end_blink_duration\n\n a = (y - k) / (x - h) ** 2\n return lambda time: a * (time - h) ** 2 + k\n\n\nclass Step:\n def __init__ (self, action, duration):\n self.action = action\n self.duration = duration\n\nclass StepSequence:\n active_timer = None\n\n def __init__ (self, step_list = []):\n self.step_list = step_list\n self.timers = []\n self.done = False\n\n def run (self, index = 0):\n step = self.step_list[index]\n step.action()\n\n if index != len(self.step_list) - 1:\n timer = threading.Timer(step.duration, lambda: self.run(index + 1))\n timer.daemon = True\n timer.start()\n active_timer = timer\n else:\n self.done = True\n\n while not self.done:\n pass\n time.sleep(.01)\n\n def stop (self):\n if self.active_timer:\n self.active_timer.cancel()\n\n def __add__ (self, other):\n self.step_list += other.step_list\n return self\n\n\ndef make_blink_sequence (duration):\n return StepSequence([\n Step(turn_light_on, duration),\n Step(turn_light_off, duration)\n ])\n\n\ndef make_pause_sequence (duration):\n return StepSequence([\n Step(lambda: None, duration)\n ])\n\n\ndef make_steady_blink_sequence (number_of_blinks, blink_duration):\n sequence = StepSequence()\n for _ in range(number_of_blinks):\n sequence += make_blink_sequence(blink_duration)\n sequence += make_pause_sequence(blink_duration)\n return sequence \n\ndef make_blink_curve_sequence (sequence_duration, curve):\n sequence_duration_so_far = 0\n sequence = StepSequence()\n while sequence_duration_so_far < sequence_duration:\n current_step_duration = curve(sequence_duration_so_far)\n sequence += make_blink_sequence(curve(sequence_duration_so_far))\n sequence_duration_so_far += current_step_duration\n return sequence \n\ntest_animation_curve = make_blink_animation_curve(1, .05, .165)\n\nprint(\"1\")\nmake_blink_sequence(.5).run()\nprint(\"2\")\n\nwhile True:\n pass\n","repo_name":"mnbroatch/one-button","sub_path":"one-button.py","file_name":"one-button.py","file_ext":"py","file_size_in_byte":3344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34198579183","text":"# -*- encoding: utf-8 -*-\n\n__author__ = \"haha\"\n\nclass Properties(object):\n\n def __init__(self, fileName):\n self.fileName = fileName\n self.properties = {}\n\n def __getDict(self, strSrc, dict, value):\n if(strSrc.find('.') > 0):\n k = strSrc.split('.')[0]\n dict.setdefault(k, {})\n return self.__getDict(strSrc[len(k) + 1:], dict[k], value)\n else:\n dict[strSrc] = value\n return\n\n def getProperties(self):\n with open(self.fileName, 'Ur') as pro_file:\n for line in pro_file.readlines():\n line = line.strip().replace('\\n', '')\n # \"#\"在properties文件中是注释\n if line.find(\"#\") != -1:\n line = line[0: line.find('#')]\n if line.find('=') > 0:\n strs = line.split('=')\n strs[1] = line[len(strs[0]) + 1:]\n # strip方法,去前面和后面的空格,但是中间的空格依然保留\n self.__getDict(strs[0].strip(), self.properties, strs[1].strip())\n return self.properties\n\n\nclass ObjectOrDictFormatter(object):\n\n # >>> class Foo(object):\n # ... bar = 'hello'\n # ... baz = 'world'\n # ...\n # >>> f = Foo()\n # >>> [name for name in dir(f) if not name.startswith('__')]\n # [ 'bar', 'baz' ]\n # >>> dict((name, getattr(f, name)) for name in dir(f) if not name.startswith('__'))\n # { 'bar': 'hello', 'baz': 'world' }\n\n def obj2dict(obj):\n # names = name in dir(obj) if not name.startWith('__'):\n d = dict(\n (name, getattr(obj, name)\n ) for name in dir(obj) if not name.startswith('__')\n )\n return d\n\n # 可以改进上述方法,只返回数据属性,不包括方法:\n # dict(\n # (name, getattr(obj, name)) for name in dir(obj) if not name.startswith('__') and not callable(value)\n # )\n\n\n # 或者:\n def obj2prop(obj):\n p = {}\n for name in dir(obj):\n value = getattr(obj, name)\n if not name.startswith('__') and not callable(value):\n p[name] = value\n return p\n\n # >>> d = {\n # 'a': 1,\n # 'b': {'c': 2},\n # 'd': ['hi', {'foo': 'bar'}]\n # }\n # >>> x = dict2obj(d)\n # >>> x.a\n # 1\n # >>> x.b.c\n # 2\n # >>> x.d[1].foo\n # 'bar'\n @classmethod\n def dict2obj(d):\n obj = type('new', (object,), d)\n seqs = tuple, list, set, frozenset\n for i, j in d.items():\n if isinstance(j, dict):\n setattr(obj, i, dict2obj(j))\n elif isinstance(j, seqs):\n setattr(obj, i,\n type(j)(dict2obj(sj) if isinstance(sj, dict) else sj for sj in j))\n else:\n setattr(obj, i, j)\n return obj\n\n\n","repo_name":"PeachWtw/PigFarming","sub_path":"mysite/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22002398799","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchsummary import summary\nfrom tqdm import tqdm\n\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net,self).__init__()\n self.conv1 = nn.Conv2d(1, 16,kernel_size=3, bias=False)\n self.bn1 = nn.BatchNorm2d(16)\n\n self.conv2 = nn.Conv2d(16, 16,kernel_size=3, bias=False)\n self.bn2 = nn.BatchNorm2d(16)\n \n self.conv3 = nn.Conv2d(16, 16,kernel_size=3, bias=False)\n self.bn3 = nn.BatchNorm2d(16)\n \n self.conv4 = nn.Conv2d(16, 16, kernel_size=3, bias=False)\n self.bn4 = nn.BatchNorm2d(16)\n\n self.conv5 = nn.Conv2d(16, 16, kernel_size=3, bias=False)\n self.bn5 = nn.BatchNorm2d(16)\n\n self.conv6 = nn.Conv2d(16, 16, kernel_size=3, bias=False)\n self.bn6 = nn.BatchNorm2d(16)\n\n self.conv7 = nn.Conv2d(16, 16, kernel_size=3, bias=False)\n self.bn7 = nn.BatchNorm2d(16)\n\n self.conv8 = nn.Conv2d(16,10, kernel_size=1, bias=False)\n self.bn8 = nn.BatchNorm2d(10)\n \n self.gap = nn.AvgPool2d(4)\n\n\n def forward(self, x):\n # C1:n_i = 28, n_o = 26, s = 1, j_i = 1, j_o = 1, r_i = 1, r_o = 3\n x = F.relu(self.conv1(x)) # C1\n x = self.bn1(x) # BN1\n\n # C2:n_i = 26, n_o = 24, s = 1, j_i = 1, j_o = 1, r_i = 3, r_o = 5\n x = F.relu(self.conv2(x)) # C2\n x = self.bn2(x) # BN2\n \n # C3:n_i = 24, n_o = 22, s = 1, j_i = 1, j_o = 1, r_i = 5, r_o = 7\n x = F.relu(self.conv3(x)) # C3\n x = self.bn3(x) # BN3\n \n # C4:n_i = 22, n_o = 20, s = 1, j_i = 1, j_o = 1, r_i = 7, r_o = 9\n x = F.relu(self.conv4(x)) # C4\n x = self.bn4(x) # BN4\n\n # MP:n_i = 20, n_o = 10, s = 2, j_i = 1, j_o = 2, r_i = 9, r_o = 10\n x = F.relu(F.max_pool2d(x,2)) # MP1\n\n # C5:n_i = 10, n_o = 8, s = 1, j_i = 2, j_o = 2, r_i = 10, r_o = 14\n x = F.relu(self.conv5(x)) # C5 \n x = self.bn5(x) # BN5\n\n # C6:n_i = 8, n_o = 6, s = 1, j_i = 2, j_o = 2, r_i = 14, r_o = 18\n x = F.relu(self.conv6(x)) # C6\n x = self.bn6(x) # BN6\n\n # C7:n_i = 6, n_o = 4, s = 1, j_i = 2, j_o = 2, r_i = 18, r_o = 22\n x = F.relu(self.conv7(x)) # C7 \n x = self.bn7(x) # BN7\n\n # C8:n_i = 4, n_o = 4, s = 1, j_i = 2, j_o = 2, r_i = 22, r_o = 22\n x = F.relu(self.conv8(x)) # C8 \n x = self.bn8(x) # BN8\n\n\n x = self.gap(x)\n x = x.view(-1,10)\n return F.log_softmax(x,dim=1)\n\n\ndef model_summary(model, input_size):\n summary(model, input_size = input_size)\n\n\n\ndef model_train(model, device, train_loader, optimizer, train_acc, train_losses):\n model.train()\n pbar = tqdm(train_loader)\n train_loss = 0\n correct = 0\n processed = 0\n for batch_idx, (data, target) in enumerate(pbar):\n data, target = data.to(device), target.to(device)\n optimizer.zero_grad()\n output = model(data)\n loss = F.nll_loss(output, target)\n train_loss+=loss.item()\n loss.backward()\n optimizer.step()\n correct+= output.argmax(dim=1).eq(target).sum().item()\n processed+= len(data)\n pbar.set_description(desc= f'loss={loss.item()} batch_id={batch_idx} Accuracy = {100*correct/processed:0.2f}')\n\n train_acc.append(100*correct/processed)\n train_losses.append(train_loss/len(train_loader))\n\n\n\ndef model_test(model, device, test_loader, test_acc, test_losses):\n model.eval()\n test_loss = 0\n correct = 0\n with torch.no_grad():\n for data, target in test_loader:\n data, target = data.to(device), target.to(device)\n output = model(data)\n test_loss += F.nll_loss(output, target, reduction='sum').item() # sum up batch loss\n pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability\n correct += pred.eq(target.view_as(pred)).sum().item()\n\n test_loss /= len(test_loader.dataset)\n test_acc.append(100.*correct/len(test_loader.dataset))\n\n print('\\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.2f}%)\\n'.format(\n test_loss, correct, len(test_loader.dataset),\n 100. * correct / len(test_loader.dataset)))\n test_losses.append(test_loss)","repo_name":"jyanivaddi/ERA_V1","sub_path":"session_6/s6_model.py","file_name":"s6_model.py","file_ext":"py","file_size_in_byte":4260,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39100929183","text":"import numpy as np, random, operator\n\nclass GA: \n def __init__(self, data, populationSize, children, mutationRate, iterations, dimension, totalGenerations):\n self.data = data\n self.populationSize = populationSize\n self.children = children\n self.mutationRate = mutationRate\n self.iterations = iterations\n self.dimension = dimension \n self.totalGenerations = totalGenerations\n self.population = self.initializePopultaion()\n\n def initializePopultaion(self):\n population = []\n for i in range(0, self.populationSize):\n population.append(self.createChromosome())\n return population\n\n #problem specific function\n #implemented in specific problem's class\n def createChromosome(self):\n pass\n\n #problem specific function\n #implemented in specific problem's class\n def calcFitness(self, chromosome):\n pass\n \n #problem specific function\n #implemented in specific problem's class\n def mutate(self, chromosome):\n pass\n\n\n def crossOver(self, parents):\n child=[]\n childA=[]\n childB=[] \n geneA=int(random.random()* len(parents[0]))\n geneB=int(random.random()* len(parents[0]))\n \n start = min(geneA,geneB)\n end = max(geneA,geneB)\n for i in range(start,end):\n childA.append(parents[0][i]) \n childB=[gene for gene in parents[1] if gene not in childA]\n child = childA + childB\n return child\n\n \n def selection(self, selectType, n):\n \"\"\"\n n = number of individuals to be selected\n selectType = the name of selection scheme to be applied\n \"\"\"\n selected = []\n if (selectType == 'BT'):\n for i in range(n):\n selected.append(self.binaryTournament())\n if (selectType == 'rand'):\n for i in range(n):\n selected.append(self.random())\n if (selectType == 'truncate'):\n return self.truncate(n)\n if (selectType == 'FPS'):\n return self.FPS(n)\n if (selectType == 'RBS'):\n return self.RBS(n)\n return selected\n\n\n def binaryTournament(self):\n individual1 = self.population[np.random.randint(0, len(self.population))] #randomly select the first chromosome\n individual2 = self.population[np.random.randint(0, len(self.population))] #randomly select the second chromosome\n fitness1 = self.calcFitness(individual1) #calculate fitness for the first chromosome\n fitness2 = self.calcFitness(individual2) #calculate fitness for the second chromosome\n if (fitness1 >= fitness2): #return the fittest individual\n return individual1\n else:\n return individual2\n\n def truncate(self, n): #returns top n fittest chromosomes \n fitnessResult = {}\n for i in range(len(self.population)):\n #calculate fitness for all the chromosomes\n fitnessResult[i] = self.calcFitness(self.population[i])\n #sort in descending order based on fitness\n sortedFitness = sorted(fitnessResult.items(), key = operator.itemgetter(1), reverse=True)\n finalResult = []\n for i in range(n):\n #select top n fittest chromosomes\n finalResult.append(self.population[sortedFitness[i][0]]) \n return finalResult\n\n def FPS(self, n):\n fitnessResult = {}\n selected = []\n for i in range(len(self.population)):\n #calculate fitness for all the chromosomes\n fitnessResult[i] = self.calcFitness(self.population[i])\n fitnessSum = sum(fitnessResult.values())\n #divide each fitness value by the sum\n for i in range(len(self.population)):\n j = i - 1\n fitnessResult[i] = fitnessResult[i] / fitnessSum\n if (j >= 0):\n #find the cumulative fitness for each\n fitnessResult[i] += fitnessResult[j] \n for i in range(n):\n #find the cumulative fitness closest to the generated random number\n result = min(fitnessResult.values(), key=lambda x:abs(random.random()))\n #find the chromosome index with the closest value that we found\n for key,value in fitnessResult.items():\n if value == result:\n index=key\n break\n selected.append(self.population[index])\n return selected\n\n def RBS(self, n):\n fitnessResult = {}\n selected = []\n for i in range(len(self.population)):\n #calculate fitness for all the chromosomes\n fitnessResult[i] = self.calcFitness(self.population[i])\n #sort in ascending order based on fitness\n sortedFitness = sorted(fitnessResult, key = fitnessResult.get) #returns the sorted list of index\n rankSum = sum(range(self.populationSize + 1))\n for i in range(len(sortedFitness)):\n j = i - 1\n #divide each rank by rankSum\n rankedFitness = (i+1)/rankSum\n fitnessResult[sortedFitness[i]] = rankedFitness\n #find the cumulative fitness for each\n if (j >=0):\n fitnessResult[sortedFitness[i]] += fitnessResult[sortedFitness[j]] \n for i in range(n):\n #find the cumulative fitness closest to the generated random number\n result = min(fitnessResult.values(), key=lambda x:abs(random.random()))\n #find the chromosome index with the closest value that we found\n for key,value in fitnessResult.items():\n if value == result:\n index=key\n break\n selected.append(self.population[index])\n return selected\n \n\n def random(self):\n #randomly select the chromosome\n return self.population[np.random.randint(0, len(self.population))]\n\n #will run steps for each generation\n def newGeneration(self):\n offsprings = []\n mutatedPop = []\n for i in range(self.iterations):\n parents = self.selection('BT', 2)\n offsprings.append(self.crossOver(parents))\n for i in offsprings:\n mutatedPop.append(self.mutate(i))\n self.population += mutatedPop\n survivors = self.selection('truncate', self.populationSize)\n # print(\"Offsprings:\", offsprings)\n # print(\"mutated:\", mutatedPop)\n # print(\"newPop\", self.population[0])\n # print(\"Survive\", len(survivors))\n return survivors\n\n #will run total generations\n def evolve(self):\n # Initial = {}\n # for i in range(len(self.population)):\n # #calculate fitness for all the chromosomes\n # Initial[i] = self.calcFitness(self.population[i])\n # sortedIni = sorted(Initial.items(), key = operator.itemgetter(1), reverse=True)\n # ini = 1/sortedIni[0][1]\n # print(\"Initial\", ini)\n\n for i in range(self.totalGenerations):\n print(\"Generation number:\", i)\n self.population = self.newGeneration()\n fitnessResult = {}\n for i in range(len(self.population)):\n #calculate fitness for all the chromosomes\n fitnessResult[i] = self.calcFitness(self.population[i])\n print(fitnessResult)\n sortedFitness = sorted(fitnessResult.items(), key = operator.itemgetter(1), reverse=True)\n fittest = sortedFitness[0][1]\n print(\"fitness\", fittest)\n \n # print(self.population)\n # print(len(self.population))\n\n \n\n \n\n\n\n\n\n\n\n","repo_name":"MaheenAnees/CI-Evolutionary-Algorithms","sub_path":"question2/geneticAlgo.py","file_name":"geneticAlgo.py","file_ext":"py","file_size_in_byte":7677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39669353090","text":"from cProfile import label\nimport torch\nfrom . import networks\nfrom os.path import join\nfrom util.util import seg_accuracy, print_network\nfrom tabulate import tabulate as tb\nimport sklearn.metrics as skm\nimport numpy as np\n\nclass ClassifierModel:\n \"\"\" Class for training Model weights\n\n :args opt: structure containing configuration params\n e.g.,\n --dataset_mode -> classification / segmentation)\n --arch -> network type\n \"\"\"\n def __init__(self, opt):\n self.opt = opt\n self.gpu_ids = opt.gpu_ids\n self.is_train = opt.is_train\n self.device = torch.device('cuda:{}'.format(self.gpu_ids[0])) if self.gpu_ids else torch.device('cpu')\n self.save_dir = join(opt.checkpoints_dir, opt.name)\n self.optimizer = None\n self.edge_features = None\n self.labels = None\n self.mesh = None\n self.soft_label = None\n self.loss = None\n\n #\n self.nclasses = opt.nclasses\n\n # For classification statistics...\n self.x_test = []\n self.pred_y_test = []\n self.y_test = []\n\n # load/define networks\n self.net = networks.define_classifier(opt.input_nc, opt.ncf, opt.ninput_edges, opt.nclasses, opt,\n self.gpu_ids, opt.arch, opt.init_type, opt.init_gain)\n self.net.train(self.is_train)\n self.criterion = networks.define_loss(opt).to(self.device)\n\n if self.is_train:\n if (opt.optimizer == 'adam'):\n self.optimizer = torch.optim.Adam(self.net.parameters(), lr=opt.lr, betas=(opt.beta1, 0.999), amsgrad=opt.amsgrad)\n if (opt.optimizer == 'rmsprop'):\n self.optimizer = torch.optim.RMSprop(self.net.parameters(), lr=opt.lr)\n if (opt.optimizer == 'sgd'):\n self.optimizer = torch.optim.SGD(self.net.parameters(), lr=opt.lr)\n if (opt.optimizer == 'adagrad'):\n self.optimizer = torch.optim.Adagrad(self.net.parameters(), lr=opt.lr)\n\n self.scheduler = networks.get_scheduler(self.optimizer, opt)\n print_network(self.net)\n\n if not self.is_train or opt.continue_train:\n self.load_network(opt.which_epoch)\n\n def set_input(self, data):\n input_edge_features = torch.from_numpy(data['edge_features']).float()\n labels = torch.from_numpy(data['label']).long()\n # set inputs\n self.edge_features = input_edge_features.to(self.device).requires_grad_(self.is_train)\n self.labels = labels.to(self.device)\n self.mesh = data['mesh']\n if self.opt.dataset_mode == 'segmentation' and not self.is_train:\n self.soft_label = torch.from_numpy(data['soft_label'])\n self.classIdx = dict(map(reversed, data['classIdx'][0].items()))\n self.classTags = list(data['classIdx'][0].keys())\n\n\n def forward(self):\n out = self.net(self.edge_features, self.mesh)\n return out\n\n def backward(self, out):\n self.loss = self.criterion(out, self.labels)\n self.loss.backward()\n\n def optimize_parameters(self):\n self.optimizer.zero_grad()\n out = self.forward()\n self.backward(out)\n self.optimizer.step()\n\n\n##################\n\n def load_network(self, which_epoch):\n \"\"\"load model from disk\"\"\"\n save_filename = '%s_net.pth' % which_epoch\n load_path = join(self.save_dir, save_filename)\n net = self.net\n if isinstance(net, torch.nn.DataParallel):\n net = net.module\n print('loading the model from %s' % load_path)\n # PyTorch newer than 0.4 (e.g., built from\n # GitHub source), you can remove str() on self.device\n state_dict = torch.load(load_path, map_location=str(self.device))\n if hasattr(state_dict, '_metadata'):\n del state_dict._metadata\n net.load_state_dict(state_dict)\n\n\n def save_network(self, which_epoch):\n \"\"\"save model to disk\"\"\"\n save_filename = '%s_net.pth' % (which_epoch)\n save_path = join(self.save_dir, save_filename)\n if len(self.gpu_ids) > 0 and torch.cuda.is_available():\n torch.save(self.net.module.cpu().state_dict(), save_path)\n self.net.cuda(self.gpu_ids[0])\n else:\n torch.save(self.net.cpu().state_dict(), save_path)\n\n def update_learning_rate(self):\n \"\"\"update learning rate (called once every epoch)\"\"\"\n self.scheduler.step()\n lr = self.optimizer.param_groups[0]['lr']\n print('learning rate = %.7f' % lr)\n\n def test(self, verbose=False, confusion=False):\n \"\"\"tests model\n returns: number correct and total number\n \"\"\"\n actLoss = 0\n with torch.no_grad():\n out = self.forward()\n actLoss = self.criterion(out, self.labels)\n # compute number of correct\n pred_class = out.data.max(1)[1]\n label_class = self.labels\n\n if(verbose or confusion):\n for i, mesh in enumerate(self.mesh):\n self.x_test.append(mesh.filename)\n self.y_test.append(int(label_class[i]))\n self.pred_y_test.append(int(pred_class[i]))\n\n self.export_segmentation(pred_class.cpu())\n correct = self.get_accuracy(pred_class, label_class)\n return correct, len(label_class), actLoss\n\n def getTestLoss(self):\n out = self.forward()\n\n def printMetrics(self, verbose, confusion):\n\n if(verbose):\n meshes = []\n for i, mesh in enumerate(self.x_test):\n meshes.append([mesh, self.classIdx[self.pred_y_test[i]], self.classIdx[self.y_test[i]]])\n print(tb(meshes, headers=[\"Mesh\", \"Prediction\", \"Actual\"]))\n\n if(confusion): \n #print(\"Matriz de Confusión: \\n\")\n #print(skm.confusion_matrix(self.y_test, self.pred_y_test), \"\\n\")\n\n print(\"Reporte de clasificación:\")\n print(skm.classification_report(self.y_test, self.pred_y_test, target_names=self.classTags))\n\n def get_accuracy(self, pred, labels):\n \"\"\"computes accuracy for classification / segmentation \"\"\"\n if self.opt.dataset_mode == 'classification':\n correct = pred.eq(labels).sum()\n elif self.opt.dataset_mode == 'segmentation':\n correct = seg_accuracy(pred, self.soft_label, self.mesh)\n return correct\n\n def export_segmentation(self, pred_seg):\n if self.opt.dataset_mode == 'segmentation':\n for meshi, mesh in enumerate(self.mesh):\n mesh.export_segments(pred_seg[meshi, :])\n","repo_name":"RhinoBlindado/tfg","sub_path":"networks/MeshCNNPlus/development/meshcnn/models/mesh_classifier.py","file_name":"mesh_classifier.py","file_ext":"py","file_size_in_byte":6639,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"22917999539","text":"from time import sleep\n\nfrom datetime import datetime, time\n\nfrom crawler import WebsiteCrawler\nfrom helpers import convert_string_to_time\nfrom settings import config\nfrom telegram_bot import send_telegram\n\ninterval_minutes = config.getint(\"general\", \"interval_minutes\")\n\nsend_live_bits = config.getboolean(\"general\", \"send_live_bits\")\nlive_bit_only_on_weekdays = [1, 2, 3, 4, 5, 6, 7]\n\nraw_start_time = config.get(\"general\", \"start_time\")\n\nstart_time = convert_string_to_time(config.get(\"general\", \"start_time\"))\nend_time = convert_string_to_time(config.get(\"general\", \"end_time\"))\n\nif __name__ == '__main__':\n crawler = WebsiteCrawler()\n\n send_telegram(\"Service gestartet\")\n\n previous_day = -1\n while True:\n\n try:\n now_time = datetime.now().time()\n\n # check website between this time\n if start_time <= now_time <= end_time:\n crawler.compare()\n\n if send_live_bits \\\n and datetime.now().isoweekday() != previous_day \\\n and datetime.now().isoweekday() in live_bit_only_on_weekdays:\n previous_day = datetime.now().isoweekday()\n send_telegram(\n f\"Starte Überprüfung des Corona Ergebnisses alle {interval_minutes} Minuten im Zeitraum von {start_time} bis {end_time}\")\n\n sleep(interval_minutes * 60)\n\n except Exception as e:\n send_telegram(f\"WebsiteCrawler Error: {e} \\nDas Programm wird beendet\")\n exit()\n","repo_name":"s1m0n1996/CovidTestResultCrawler","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2526026913","text":"import logging\nfrom localsettings import *\n\nimport requests\nimport pandas as pd\n\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n level=logging.INFO)\n\n\nclass Telegram:\n\n def __init__(self, token=telegram_token):\n self.token = token\n self.api_url = \"https://api.telegram.org/bot{}/\".format(telegram_token)\n\n def get_updates(self, offset=None, timeout=30):\n method = 'getUpdates'\n params = {'timeout': timeout, 'offset': offset}\n resp = requests.get(self.api_url + method, params)\n result_json = resp.json()['result']\n return result_json\n\n @classmethod\n def messagepermitted(cls, msg):\n match_id, alert_type, msg_text = msg\n\n messages = pd.read_csv(path + 'messages.csv')\n sent_messages = messages[\n (messages['match_id'].astype(str) == match_id) & (messages['alert_type'].astype(str) == alert_type)]\n\n return sent_messages.empty\n\n def send_message(self, chat_id, msg):\n\n #print('trying to send a Telegram about {}'.format(msg[2]))\n\n resp= ''\n messages = pd.read_csv(path + 'messages.csv')\n\n if Telegram.messagepermitted(msg):\n match_id, alert_type, msg_text = msg\n\n params = {'chat_id': chat_id, 'text': msg_text}\n method = 'sendMessage'\n resp = requests.post(self.api_url + method, params)\n\n row = list(map(str.strip, [match_id, alert_type, '']))\n messages = messages.append(pd.DataFrame([row], columns=['match_id', 'alert_type', 'user_id']), ignore_index=True)\n\n messages.to_csv(path + 'messages.csv', index=False)\n\n return resp\n\n def get_last_update(self):\n\n get_result = self.get_updates()\n if len(get_result) > 0:\n last_update = get_result[-1]\n else:\n last_update = get_result[len(get_result)]\n\n return last_update\n\n\n","repo_name":"viktorpetrov/footballscraper","sub_path":"Telegram.py","file_name":"Telegram.py","file_ext":"py","file_size_in_byte":1967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8091184915","text":"\"\"\"\nCMO-PMO Dashbaord report generation.\nReads daily metric data from blob storage and uploads\n\"\"\"\nimport time\nimport pandas as pd\n\nfrom datetime import datetime, date, timedelta\nfrom pathlib import Path\n\nfrom dataproducts.util.utils import post_data_to_blob, create_json, get_tenant_info, get_data_from_blob, push_metric_event\n\n\nclass CMODashboard:\n def __init__(self, data_store_location, execution_date, org_search):\n self.data_store_location = Path(data_store_location)\n self.execution_date = execution_date\n self.org_search = org_search\n\n\n def data_wrangling(self, result_loc_, date_):\n \"\"\"\n Extract last 30 days' daily metrics data from date of run.\n :param result_loc_: Path object for file path\n :param date_: datetime object for date sorting\n :return: None\n \"\"\"\n df = pd.read_csv(result_loc_)[['Date', 'Total Content Plays']]\n df.index = pd.to_datetime(df.Date, format='%d-%m-%Y')\n df = df.loc[(date_ - timedelta(days=30)).strftime('%Y-%m-%d'):date_.strftime('%Y-%m-%d')]\n df.to_csv(result_loc_.parent.joinpath('cmo_dashboard.csv'), index=False)\n if result_loc_.parent.name == 'overall':\n result_loc_.parent.parent.joinpath('public').mkdir(exist_ok=True)\n df.to_csv(result_loc_.parent.parent.joinpath('public', 'cmo_dashboard.csv'), index=False)\n\n\n def init(self):\n start_time_sec = int(round(time.time()))\n print(\"START:CMO Dashboard\")\n data_store_location = self.data_store_location.joinpath('portal_dashboards')\n data_store_location.mkdir(exist_ok=True)\n analysis_date = datetime.strptime(self.execution_date, \"%d/%m/%Y\")\n data_store_location.joinpath('public').mkdir(exist_ok=True)\n get_data_from_blob(data_store_location.joinpath('overall', 'daily_metrics.csv'))\n self.data_wrangling(result_loc_=data_store_location.joinpath('overall', 'daily_metrics.csv'), date_=analysis_date)\n create_json(data_store_location.joinpath('public', 'cmo_dashboard.csv'), last_update=True)\n post_data_to_blob(data_store_location.joinpath('public', 'cmo_dashboard.csv'))\n get_tenant_info(result_loc_=data_store_location.parent.joinpath('textbook_reports'), org_search_=self.org_search,\n date_=analysis_date)\n board_slug = pd.read_csv(\n data_store_location.parent.joinpath('textbook_reports', analysis_date.strftime('%Y-%m-%d'), 'tenant_info.csv'))\n slug_list = board_slug['slug'].unique().tolist()\n for slug in slug_list:\n try:\n get_data_from_blob(result_loc_=data_store_location.joinpath(slug, 'daily_metrics.csv'))\n self.data_wrangling(result_loc_=data_store_location.joinpath(slug, 'daily_metrics.csv'), date_=analysis_date)\n create_json(read_loc_=data_store_location.joinpath(slug, 'cmo_dashboard.csv'), last_update=True)\n post_data_to_blob(result_loc_=data_store_location.joinpath(slug, 'cmo_dashboard.csv'))\n except:\n pass\n print(\"END:CMO Dashboard\")\n\n end_time_sec = int(round(time.time()))\n time_taken = end_time_sec - start_time_sec\n metrics = [\n {\n \"metric\": \"timeTakenSecs\",\n \"value\": time_taken\n },\n {\n \"metric\": \"date\",\n \"value\": analysis_date.strftime(\"%Y-%m-%d\")\n }\n ]\n push_metric_event(metrics, \"CMO Dashboard\")","repo_name":"Sunbird-Ed/sunbird-data-products","sub_path":"python-scripts/src/main/python/dataproducts/services/consumption/cmo_dashboard.py","file_name":"cmo_dashboard.py","file_ext":"py","file_size_in_byte":3526,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"42975306593","text":"#!/usr/bin/env python\n# QAP Gemini\n#\n# adcc.py\n# ------------------------------------------------------------------------------\n\"\"\"\nAutomated Dataflow Coordination Center\n\n\"\"\"\nimport sys\n\nfrom argparse import ArgumentParser\n\nfrom recipe_system import __version__\n\nfrom recipe_system.adcc.adcclib import ADCC\n# ------------------------------------------------------------------------------\ndef buildArgs():\n parser = ArgumentParser(description=\"Automated Data Communication Center \"\n \"(ADCC), v{}\".format(__version__))\n\n parser.add_argument(\"-d\", \"--dark\", dest=\"dark\", action=\"store_true\",\n help=\"Use the adcc faceplate 'dark' theme.\")\n\n parser.add_argument(\"-v\",\"--verbose\", dest=\"verbosity\", action=\"store_true\",\n help=\"increase HTTP client messaging on GET requests.\")\n\n parser.add_argument(\"--startup-report\", dest=\"adccsrn\", default=\"adccReport\",\n help = \"file name for adcc startup report.\")\n\n parser.add_argument(\"--http-port\", dest=\"httpport\", default=8777, type=int,\n help=\"Response port for the web interface. \"\n \"i.e. http://localhost:. \"\n \"Default is 8777.\")\n\n args = parser.parse_args()\n return args\n\n# ------------------------------------------------------------------------------\nif __name__ == '__main__':\n adcc = ADCC(buildArgs())\n sys.exit(adcc.main())\n","repo_name":"GeminiDRSoftware/DRAGONS","sub_path":"recipe_system/scripts/adcc.py","file_name":"adcc.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"48"} +{"seq_id":"31871946997","text":"# Counter=0\n\n# while Counter<=100:\n# print(Counter)\n# Counter+=int(Counter)\n# Counter+=2\n\n\n# fruits = [\"apple\", \"banana\", \"cherry\", \"strawbery\", \"mango\",\"abc\"]\n \n# for i in fruits:\n# if len(i)>=5:\n# print(i)\nproducts = [\n{\"name\":\"bread\", \"price\": 2},\n{\"name\":\"milk\", \"price\": 5},\n{\"name\":\"sugar\", \"price\": 1},\n{\"name\":\"oil\", \"price\": 25},\n{\"name\":\"salt\", \"price\": 1}\n]\n\n\n\n","repo_name":"python1818/python_principles","sub_path":"11/Loops.py","file_name":"Loops.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32502160272","text":"alcool = 0\ngasolina = 0\ndiesel = 0\nwhile True:\n num = int(input())\n if 0 < num < 4:\n if num == 1:\n alcool += 1\n elif num == 2:\n gasolina += 1\n else:\n diesel += 1\n elif num == 4:\n break\nprint('MUITO OBRIGADO')\nprint(f'Alcool: {alcool}')\nprint(f'Gasolina: {gasolina}')\nprint(f'Diesel: {diesel}')\n ","repo_name":"lucas-albuq/URI---Python","sub_path":"beginner/1134.py","file_name":"1134.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20685315764","text":"from flask import Flask, render_template, session, redirect, url_for\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_wtf import FlaskForm\nfrom flask_bootstrap import Bootstrap\nfrom wtforms import StringField, SubmitField, BooleanField, SelectMultipleField\nfrom wtforms.validators import Required\nfrom markupsafe import Markup\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'hard to guess'\napp.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:@127.0.0.1:3306/public_course'\napp.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True\nbootstrap = Bootstrap(app)\ndb = SQLAlchemy(app)\n\n\nclass Course_info(db.Model):\n __tablename__ = \"course_info\"\n Cno = db.Column(db.String(8), primary_key=True) #课程号\n Cname = db.Column(db.String(23)) #课程名称\n no = db.Column(db.String(2), primary_key=True) #课序号\n Cca = db.Column(db.String(3)) #课容量\n Chour = db.Column(db.String(5)) #课程班总学时\n Ccredit = db.Column(db.String(7)) #课程学分\n CTeacher = db.Column(db.String(9)) #主讲教师姓名\n Cfaculty = db.Column(db.String(18)) #主讲教师所在系\n Cstudent = db.Column(db.String(114)) #开课对象\n Ctinfo = db.Column(db.String(1035)) #教师简介\n Cinfo = db.Column(db.String(879)) #课程简介\n comment = db.Column(db.String(222)) #备注\n CTags = db.Column(db.String(255))\n\n def to_json(self):\n return {\n 'Cno': self.Cno,\n 'Cname': self.Cname,\n 'no': self.no,\n 'Cca': self.Cca,\n 'Chour': self.Chour,\n 'Ccredit': self.Ccredit,\n 'CTeacher': self.CTeacher,\n 'Cfaculty': self.Cfaculty,\n 'Cstudent': self.Cstudent,\n 'Ctinfo': self.Ctinfo,\n 'Cinfo': self.Cinfo,\n 'comment': self.comment,\n 'CTags': self.CTags,\n }\n\n def __repr__(self):\n return ''.format(self.Cno)\n\nclass Course_tags(db.Model):\n __tablename__ = \"course_tags\"\n Tno = db.Column(db.String(11), primary_key=True) #tag序号,自增\n Tname = db.Column(db.String(255)) #tag名\n Tcount = db.Column(db.String(11)) #出现次数\n Trelatives = db.Column(db.String(1023)) #一级关联标签\n Tcourses = db.Column(db.String(1023)) #有这个标签的课程\n Tteachers = db.Column(db.Numeric(255)) #有这个标签的课程的老师\n Tflag = db.Column(db.String(15)) #标签词性\n def to_json(self):\n return {\n 'Tno': self.Tno,\n 'Tname': self.Tname,\n 'Tcount': self.Tcount,\n 'Trelatives': self.Trelatives,\n 'Tcourses': self.Tteachers,\n 'Tteachers': str(self.Ccredit),\n 'Tflag': self.Tflag\n }\n\n def __repr__(self):\n return ''.format(self.Cno)\n\n\nclass Course_time(db.Model):\n __tablename__ = \"course_time\"\n Cno = db.Column(db.String(8), primary_key=True) #课程号\n Cname = db.Column(db.String(23)) #课程名称\n no = db.Column(db.String(1), primary_key=True) #课序号\n Cca = db.Column(db.String(3)) #课容量\n Chour = db.Column(db.String(2)) #课程班总学时\n Ccredit = db.Column(db.Numeric(2,1)) #课程学分\n Cteacher = db.Column(db.String(3)) #主讲教师姓名\n Cteacher_2 = db.Column(db.String(6)) #合讲教师\n Cweek = db.Column(db.String(8)) #周次分布\n Cday = db.Column(db.Integer) #星期(一二三四五六七)\n Ctime = db.Column(db.String(6)) #节次\n Cweek_2 = db.Column(db.String(14)) #周次分布_2\n Cday_2 = db.Column(db.String(1)) #星期_2\n Ctime_2 = db.Column(db.String(6)) #节次_2\n\n def to_json(self):\n return {\n 'Cno': self.Cno,\n 'Cname': self.Cname,\n 'no': self.no,\n 'Cca': self.Cca,\n 'Chour': self.Chour,\n 'Ccredit': str(self.Ccredit),\n 'Cteacher': self.Cteacher,\n 'Cteacher_2': self.Cteacher_2,\n 'Cweek': self.Cweek,\n 'Cday': self.Cday,\n 'Ctime': self.Ctime,\n 'Cweek_2': self.Cweek_2,\n 'Cday_2': self.Cday_2,\n 'Ctime_2': self.Ctime_2,\n }\n\n def __repr__(self):\n return ''.format(self.Cno)\n\n@app.route('/viz')\ndef viz():\n courseType = ['A', 'H', 'E', 'S', 'J', 'P', 'L']\n courseSum = [0] * 7 # 该分类下课程总数\n capacitySum = [0] * 7 # 该分类下课容量求和\n hoursSum = [0] * 7 # 该分类下总课时求和\n rateSum = [0] * 7 # 该分类下每门课程总学分与总课时比值求和,所谓“效率比”\n for i in range(len(courseType)):\n filter = \"%\" + courseType[i] + \"%\"\n result = Course_info.query.filter(Course_info.Cno.like(filter)).all()\n for rs in result:\n courseSum[i] += 1\n hoursSum[i] += int(rs.Chour)\n capacitySum[i] += int(rs.Cca)\n rateSum[i] += float(rs.Ccredit) / int(rs.Chour)\n\n return render_template('viz.html',courseSum=courseSum,\\\n capacitySum=capacitySum,hoursSum=hoursSum,rateSum=rateSum)\n\n@app.route('/')\ndef index():\n rsT = Course_time.query.all()\n rsI = Course_info.query.all()\n\n tempT = []\n tempI = []\n for x in rsT:\n tempT.append(x.to_json())\n for x in rsI:\n tempI.append(x.to_json())\n return render_template(\"PublicCourse3.html\",CourseT=Markup(tempT),CourseI=Markup(tempI))\n\nresult_info = Course_info.query.filter().all()\n#参考http://by.cuc.edu.cn/jxdw学校教学机构单位\n#faculty2teacher\nf2t = {'动画与数字艺术学院': [], '计算机学院': [], '马克思主义学院': [], '广告学院': [], '电视学院': [], \\\n '艺术研究院': [], '文法学部': [], '理学院': [], '音乐与录音艺术学院': [], '新闻传播学部': [], '传播研究院': [], \\\n '戏剧影视学院': [], '艺术学部': [], '文化发展研究院': [], '华中科技大学、理工学部': [], '理工学部': [], \\\n '协同创新中心': [], '经济与管理学院': [], '体育部': [], '教育体卫艺司、教务处': [], '信息工程学院': [], \\\n '工商管理系': [], '外国语学院': [], '图书馆': [], '国际传媒教育学院': [], '播音主持艺术学院': [], \\\n '山东大学、广告学院': [], '北京大学、文法学部': [], \\\n '新闻学院': [], '北京大学、艺术学部': [], '吉林大学等\\n跨校共建、马克思主义学院': []}\nfor rs in result_info:\n f2t[rs.Cfaculty].append((rs.CTeacher, rs.CTeacher))\n\nclass TeacherForm1(FlaskForm):\n # my_choices = [('1', 'Choice1'), ('2', 'Choice2'), ('3', 'Choice3')]\n select0 = SelectMultipleField('新闻传播学部',choices=f2t['电视学院']+f2t['传播研究院']+f2t['新闻学院']+f2t['新闻传播学部'])#default=['1', '3']\n select1 = SelectMultipleField('艺术学部',choices=f2t['动画与数字艺术学院']+f2t['音乐与录音艺术学院']+f2t['艺术学部']+f2t['戏剧影视学院']+f2t['艺术研究院'])\n select2 = SelectMultipleField('理工学部',choices=f2t['理工学部']+f2t['理学院']+f2t['信息工程学院'])\n select3 = SelectMultipleField('文法学部',choices=f2t['文法学部']+f2t['传播研究院']+f2t['新闻学院'])\n select4 = SelectMultipleField('经管学部',choices=f2t['经济与管理学院']+f2t['文化发展研究院']+f2t['工商管理系'])\n select5 = SelectMultipleField('体育部',choices=f2t['体育部'])\n select6 = SelectMultipleField('播音主持艺术学院',choices=f2t['播音主持艺术学院'])\n\n submit = SubmitField('Submit')\n\nclass TeacherForm2(FlaskForm):\n select7 = SelectMultipleField('国际传媒教育学院',choices=f2t['国际传媒教育学院'])\n select8 = SelectMultipleField('外国语学院',choices=f2t['外国语学院'])\n select9 = SelectMultipleField('马克思主义学院',choices=f2t['马克思主义学院'])\n select10 = SelectMultipleField('协同创新中心',choices=f2t['协同创新中心'])\n select11 = SelectMultipleField('广告学院',choices=f2t['广告学院'])\n select12 = SelectMultipleField('学校机构',choices=f2t['教育体卫艺司、教务处']+f2t['图书馆'])\n select13 = SelectMultipleField('其它学校',choices=f2t['山东大学、广告学院']+f2t['北京大学、文法学部']+f2t['北京大学、艺术学部']+f2t['华中科技大学、理工学部']+f2t['吉林大学等\\n跨校共建、马克思主义学院']+f2t['新闻学院']+f2t['新闻学院'])\n\n submit = SubmitField('Submit')\n\nclass ClearForm(FlaskForm):\n submit = SubmitField('Clear')\n\n@app.route('/teacher', methods = ['GET', 'POST'])\ndef teacher():\n form1 = TeacherForm1()\n form2 = TeacherForm2()\n form3 = ClearForm()\n links = []\n info = []\n if form3.validate_on_submit():\n session['teachers'] = []\n return redirect(url_for('teacher'))\n if form1.validate_on_submit() or form2.validate_on_submit():\n session['teachers'] = session['teachers']+ form1.select0.data + form1.select1.data + form1.select2.data \\\n + form1.select3.data + form1.select4.data + form1.select5.data + form1.select6.data \\\n + form1.select1.data+ form2.select7.data + form2.select8.data + form2.select9.data \\\n + form2.select10.data + form2.select11.data + form2.select12.data + form2.select13.data\n return redirect(url_for('teacher'))\n # result_info = Course_info.query.filter().all()\n teachers = session.get('teachers',None)\n if(teachers):\n result_info=Course_info.query.filter(Course_info.CTeacher.in_(teachers)).all()\n result_tag = Course_tags.query.filter().all()\n # 英文序列号变成中文的课程类型\n E2C = {'NS': '科技类网络程', 'P0': '健康与体育类课程', 'H0': '人文社科类课程', 'A0': '艺术类课程', 'NE': '经管类网络课程', 'L0': '外语类课程', \\\n 'J0': '新闻传播类课程', 'NA': '艺术类网络课程', 'S0': '科技类课程', 'NH': '人文社科类网络课程', 'E0': '经管类课程'}\n if(result_info):\n for rs in result_info :\n # teacher->faculty\n links.append({'source':rs.CTeacher,'target':rs.Cfaculty,'type':'faculty','rela':'属于'})\n # teacher->coursetype\n links.append({'source':rs.CTeacher,'target':E2C[rs.Cno[2:4]],'type':'course','rela':'授课'})\n # info:teacher\n info.append({rs.CTeacher:'

    教授课程
    '+rs.Cname+ '

    课程标签

    '+rs.CTags+'

    教师简介
    '+rs.Ctinfo+'

    '})\n\n if(result_tag):\n for rs in result_tag:\n if (rs.Tteachers != None):\n teacherlist = rs.Tteachers.split()\n for teacher in teacherlist:\n if teacher in teachers:\n # teacher->tag\n links.append({'source': teacher, 'target': rs.Tname, 'type': \"tag\", 'rela': \"标签\"})\n\n return render_template(\"teacher.html\",links=Markup(links),info=Markup(info),form1=form1,form2=form2,form3=form3)\n\nclass SearchForm(FlaskForm):\n search = StringField('想上什么课?', validators = [Required()])\n submit = SubmitField('Submit')\n select = BooleanField('Available')\n\n@app.route('/search', methods = ['GET', 'POST'])\ndef search():\n form = SearchForm()\n # session['known'] = False\n # session['result'] = None\n if form.validate_on_submit():\n courselist = Course_info.query.filter(Course_info.Cname.like(\"%\"+form.search.data+\"%\")).all()\n if courselist == []:\n session['known'] = False\n session['result'] = None\n else:\n session['known'] = True\n session['result'] = []\n for course in courselist:\n session['result'] .append(course.Cname)\n return redirect(url_for('search'))\n\n return render_template(\"search.html\", form=form, result=session.get('result'),\n known=session.get('known', False))\n\nif __name__ == '__main__':\n app.run(debug=True)\n # app.run(host='10.194.72.68')\n","repo_name":"luyihong/VIS","sub_path":"public_course/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":12738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33207924672","text":"class Solution:\n def maxHeight(self, root) :\n if root == None :\n return 0\n return max(self.maxHeight(root.left) + 1, self.maxHeight(root.right) + 1)\n \n def solve(self, root, start, end, depth) :\n if root == None or self.height <= depth:\n return\n \n mid = int((start + end) / 2)\n self.result[depth][mid] = str(root.val)\n \n self.solve(root.left, start, mid - 1, depth + 1)\n self.solve(root.right, mid + 1, end, depth + 1)\n \n def printTree(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[List[str]]\n \"\"\"\n self.height = self.maxHeight(root)\n \n self.result = [[\"\" for i in range(2 ** self.height - 1)] for j in range(self.height)]\n\n self.solve(root, 0, 2 ** self.height - 1, 0)\n \n return self.result\n\n","repo_name":"dskym/Algorithm","sub_path":"LeetCode/655/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35887377174","text":"import unittest\nfrom itertools import islice\n\nfrom PIL import Image\n\nfrom pysstv import color\nfrom pysstv.tests.common import get_asset_filename, load_pickled_asset\n\n\nclass TestMartinM1(unittest.TestCase):\n\n def setUp(self):\n self.image = Image.new('RGB', (320, 256))\n self.s = color.MartinM1(self.image, 48000, 16)\n lena = Image.open(get_asset_filename('320x256.png'))\n self.lena = color.MartinM1(lena, 48000, 16)\n\n def test_gen_freq_bits(self):\n expected = load_pickled_asset(\"MartinM1_freq_bits\")\n actual = list(islice(self.s.gen_freq_bits(), 0, 1000))\n self.assertEqual(expected, actual)\n\n def test_gen_freq_bits_lena(self):\n expected = load_pickled_asset(\"MartinM1_freq_bits_lena\")\n actual = list(islice(self.lena.gen_freq_bits(), 0, 1000))\n self.assertEqual(expected, actual)\n\n def test_encode_line(self):\n zeroth = list(self.s.encode_line(0))\n first = list(self.s.encode_line(1))\n tenth = list(self.s.encode_line(10))\n eleventh = list(self.s.encode_line(11))\n\n self.assertEqual(zeroth, first)\n self.assertEqual(tenth, eleventh)\n self.assertEqual(zeroth, eleventh)\n\n def test_encode_line_lena(self):\n self.maxDiff = None\n line_numbers = [1, 10, 100]\n for line in line_numbers:\n expected = load_pickled_asset(\"MartinM1_encode_line_lena{0}\".format(line))\n actual = list(self.lena.encode_line(line))\n self.assertEqual(expected, actual)\n","repo_name":"dnet/pySSTV","sub_path":"pysstv/tests/test_color.py","file_name":"test_color.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","stars":112,"dataset":"github-code","pt":"48"} +{"seq_id":"18857396203","text":"from transformers import Trainer\nfrom transformers import AutoModelForSequenceClassification,TrainingArguments\nfrom transformers.trainer_utils import get_last_checkpoint\nfrom setting import setting\nfrom utils.data import MELDDataSet\nfrom utils.bert import create_tokenized_dataset,config,tokenizer,data_collator,compute_metrics,evaluate_model\nimport torch\nimport random\nimport numpy as np\nimport pathlib\nimport wandb\nfrom utils.common import prepare_logger,remove_directories,compute_weighted_f1\nimport re\nimport os\nimport pickle\nimport shutil\n\n\"\"\"\n本文件为过时文件,在研究text模态时用的huggingface trainer所做\n\"\"\"\n\n\n\n\n### 一些设置\nSEED = 42\nrandom.seed(SEED)\nnp.random.seed(SEED)\ntorch.manual_seed(SEED)\ntorch.backends.cudnn.deterministic = True\nuse_checkpoint = False\nuse_hpo_search = False #是否进行超参数搜索\n\n\n\n\n\nmodel = AutoModelForSequenceClassification.from_pretrained(setting.model_path)\ndataset = MELDDataSet()\ntokenized_datasets = create_tokenized_dataset(dataset)\n\n\n##log part\n\nsettings = [ \"classfication=%s\" % setting.mode,\n \"model=%s\" % setting.model_name,\n ]\nlog_path = pathlib.Path(\"logs/\")\nif not log_path.exists(): log_path.mkdir()\nlogger = prepare_logger(filename=\"%s/logfile@%s.log\" % (log_path, \"_\".join(settings)), name=\"t\")\nlogger.info(\"\\n\".join(settings))\n\n\n\ndef hp_space_optuna(trial): #超参数搜索空间\n return {\n \"learning_rate\": trial.suggest_categorical(\"learning_rate\", [1e-6, 5e-6, 1e-5]),\n \"num_train_epochs\": trial.suggest_categorical(\"num_train_epochs\", [3, 5]),\n \"per_device_train_batch_size\": trial.suggest_categorical(\"per_device_train_batch_size\", [2]),\n }\ndef hpo(tokonized_datasets): # 超参数搜索函数,搜到最好的超参数\n hpo_path = pathlib.Path(\"hpo\")\n if not hpo_path.exists(): hpo_path.mkdir()\n hpo_path = hpo_path / pathlib.Path(\"hpo.pkl\")\n\n if not pathlib.Path(hpo_path).exists():\n logger.info(\"HYPERPARAMETER SEARCH\")\n model_init = lambda: AutoModelForSequenceClassification.from_pretrained(setting.model_path)\n trainer = Trainer(args=TrainingArguments(output_dir=\"output/hpo\", evaluation_strategy=\"epoch\", eval_steps=500,\n report_to=\"none\", disable_tqdm=True),\n tokenizer=tokenizer,\n train_dataset=tokenized_datasets[\"train\"],\n eval_dataset=tokenized_datasets[\"dev\"],\n data_collator=data_collator,\n model_init=model_init,\n compute_metrics=compute_metrics,)\n\n best_trail = trainer.hyperparameter_search(hp_space=hp_space_optuna,\n # A function that defines the hyperparameter search space. Will default to default_hp_space_optuna() or default_hp_space_ray() or default_hp_space_sigopt() depending on your backend.\n direction=\"maximize\",\n backend=\"optuna\",\n n_trials=6)\n\n logger.info(\"CLEANUP\")\n remove_directories([\"runs/\", \"output/\"])\n\n hp_dict = dict()\n\n hp_dict[\"lr\"] = best_trail.hyperparameters[\"learning_rate\"]\n hp_dict[\"batch_size\"] = best_trail.hyperparameters[\"per_device_train_batch_size\"]\n hp_dict[\"n_epoch\"] = best_trail.hyperparameters[\"num_train_epochs\"]\n\n\n with open(hpo_path, \"wb\") as fp:\n pickle.dump(hp_dict, fp)\n else:\n logger.info(\"READING ALREADY SEARCHED HYPERPARAMETERS\")\n with open(hpo_path, \"rb\") as fp:\n hp_dict = pickle.load(fp)\n\n return hp_dict\ndef train_model(trainer):\n # load checkpoint and train\n last_checkpoint = None\n if os.path.isdir(training_args.output_dir) and use_checkpoint:\n last_checkpoint = get_last_checkpoint(training_args.output_dir)\n if last_checkpoint is not None:\n logger.info(f\"checkpoint detected, resuming training at {last_checkpoint}\")\n\n # if use_checkpoint == False, then checkpoint == None, no checkpoints will be loaded\n if last_checkpoint is not None:\n checkpoint = last_checkpoint\n else:\n checkpoint = None\n\n trainer.train(resume_from_checkpoint=checkpoint)\n\ndef get_checkpoint(folder,tokonized_datasets,mode=\"best\"):\n \"\"\"\n :param folder: 从存储checkpoint的文件夹里找\n :param tokonized_datasets:\n :param mode:\n :return:\n \"\"\"\n assert mode in [\"best\", \"median\", \"mean\", \"worst\"] #只支持这几种模式\n checkpoint_name_pattern = re.compile(r\"^\" + \"checkpoint\" + r\"\\-(\\d+)$\")\n checkpoints = [os.path.join(folder, path) for path in os.listdir(folder) if (checkpoint_name_pattern.search(path) is not None) and\n os.path.isdir(os.path.join(folder, path))]\n\n checkpoint_dict = dict()\n\n for checkpoint in checkpoints:\n logger.info(\"evaluating checkpoint: %s...\" % checkpoint)\n model = AutoModelForSequenceClassification.from_pretrained(checkpoint)\n trainer = Trainer(model=model,\n args=training_args,\n tokenizer=tokenizer,\n train_dataset=tokenized_datasets[\"train\"],\n eval_dataset=tokenized_datasets[\"dev\"],\n data_collator=data_collator,\n compute_metrics=compute_metrics)\n metric, metric_str = evaluate_model(trainer, tokenized_datasets, name=\"dev\")\n weighted_f1 = compute_weighted_f1(metric, target_names=setting.Sentiment_list)\n checkpoint_dict[checkpoint] = weighted_f1\n perf_str = \"\\n\".join(\"\\t%s: %.4f\" % (key, val)\n for key, val in sorted(checkpoint_dict.items(), key=lambda x: x[1], reverse=True))\n logger.info(perf_str)\n\n\n # select checkpoints based on different criterion\n if mode == \"best\":\n checkpoint = max(checkpoint_dict, key=checkpoint_dict.get)\n else:\n weighted_f1_arr = np.fromiter(checkpoint_dict.values(), dtype=float, count=len(checkpoint_dict))\n if mode == \"mean\":\n mean = np.mean(weighted_f1_arr)\n checkpoint_dict = {key: abs(val - mean) for key, val in checkpoint_dict.items()}\n if mode == \"median\":\n median = np.median(weighted_f1_arr)\n checkpoint_dict = {key: abs(val - median) for key, val in checkpoint_dict.items()}\n # if mode == \"worst\", no need to modify the checkpoint_dict\n checkpoint = min(checkpoint_dict, key=checkpoint_dict.get)\n\n return checkpoint\n\n\n\n\ndef save_best_checkpoint(checkpoint, save=True):\n # checkpoint: the filename of best checkpoint during evaluation\n if not save:\n logger.info(\"NOT SAVING TRAINING CHECKPOINT\")\n return\n\n logger.info(\"SAVING THE BEST CHECKPOINT DURING TRAINING\")\n save_checkpoint_path = setting.checkpoint_path\n if not save_checkpoint_path.exists(): save_checkpoint_path.mkdir()\n\n\n for filename in os.listdir(checkpoint):\n shutil.move(os.path.join(checkpoint, filename), save_checkpoint_path)\n\n\n\n\n# search for best main checkpoint and hyperparameters\nif use_hpo_search:\n hp_dict = hpo(tokenized_datasets) #返回一个最好的记录超参数的字典\nelse:\n hp_dict = None\nlr = hp_dict[\"lr\"] if hp_dict is not None else 1e-5\nbatch_size = hp_dict[\"batch_size\"] if hp_dict is not None else 32\nn_epoch = hp_dict[\"n_epoch\"] if hp_dict is not None else 3\n\n##wandb\n\nparam = {\"lr\": lr,\n \"n_epoch\": n_epoch,\n 'batch_size':batch_size,\n \"seed\": SEED,\n }\nlogger.info(\"\\n\".join(param))\nwandb.init(project=\"sentiment-analysis\",\n name=\"run\",\n config=param)\n\ntraining_args = TrainingArguments(\n \"bert-sentiment-text-finetune\",\n learning_rate=lr,\n num_train_epochs=n_epoch,\n per_device_train_batch_size=batch_size,\n per_device_eval_batch_size=batch_size,\n weight_decay=0.01,\n fp16 = True,\n do_train=True,\n do_eval=True,\n #checkpoint setting\n save_strategy=\"steps\",\n save_steps=100,\n # evaluation\n evaluation_strategy=\"steps\",\n eval_steps=100,\n disable_tqdm=True, #不要进度条了\n report_to=\"wandb\",\n)\n\n\n\ntrainer = Trainer(\n model,\n training_args,\n\n train_dataset=tokenized_datasets[\"train\"],\n eval_dataset=tokenized_datasets[\"dev\"],\n data_collator=data_collator,\n tokenizer=tokenizer,\n compute_metrics=compute_metrics\n)\n\n\n\n\n\n### Train##########################################\nlogger.info(\"Start Training\")\ntrain_model(trainer)\n\n### validation ##################################\nlogger.info(\"VALIDATION: validate checkponints\")\nbest_checkpoint = get_checkpoint(training_args.output_dir,\n tokenized_datasets,\n mode=\"best\",\n )\nlogger.info(\"BEST CHECKPOINT: %s\" % best_checkpoint)\n\n\n\n###TEST################################################\nmodel = AutoModelForSequenceClassification.from_pretrained(best_checkpoint)\ntrainer = Trainer(\n model,\n training_args,\n # logging_strategy=\"epoch\",\n train_dataset=tokenized_datasets[\"train\"],\n eval_dataset=tokenized_datasets[\"dev\"],\n data_collator=data_collator,\n tokenizer=tokenizer,\n compute_metrics=compute_metrics\n)\n\n\nmetric, metric_str = evaluate_model(trainer, tokenized_datasets, name=\"test\")\nweighted_f1 = compute_weighted_f1(metric, target_names=setting.Sentiment_list)\nlogger.info(metric_str)\nlogger.info(\"METRIC: weighted F1=%.4f\" % weighted_f1)\n\nsave_best_checkpoint(best_checkpoint, save=True)\n\n\n\n\n\n\n\n\n","repo_name":"MiloQ/MELD-Sentiment-Analysis","sub_path":"finetuning/text_trainer.py","file_name":"text_trainer.py","file_ext":"py","file_size_in_byte":9744,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"48"} +{"seq_id":"41224364141","text":"s=input()\n\nt=0\nprev=ord('a')\nfor i in s:\n diff=abs(ord(i)-prev)\n if diff>13:\n t+=26-diff\n else:\n t+=diff\n prev=ord(i)\nprint(t)","repo_name":"NvsYashwanth/Codeforces","sub_path":"CodeForces python/Night at the Museum.py","file_name":"Night at the Museum.py","file_ext":"py","file_size_in_byte":152,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"15204104513","text":"\"\"\"Test suite for Alpha Diversity diplay module.\"\"\"\n\nfrom app.display_modules.display_module_base_test import BaseDisplayModuleTest\nfrom app.display_modules.alpha_div import (\n AlphaDivDisplayModule,\n AlphaDiversityResult,\n MODULE_NAME,\n)\nfrom app.samples.sample_models import Sample\nfrom app.tool_results.alpha_diversity.tests.factory import (\n create_alpha_diversity,\n)\n\nfrom .factory import AlphaDivFactory, create_categories, create_tools, create_by_tool\n\n\nclass TestAlphaDivModule(BaseDisplayModuleTest):\n \"\"\"Test suite for Alpha Diversity diplay module.\"\"\"\n\n def test_add_alpha_div(self):\n \"\"\"Ensure Alpha Diversity model is created correctly.\"\"\"\n packed_data = {\n 'categories': create_categories(),\n 'tool_names': create_tools(),\n }\n packed_data['by_tool'] = create_by_tool(packed_data)\n alpha_div_result = AlphaDiversityResult(**packed_data)\n self.generic_adder_test(alpha_div_result, MODULE_NAME)\n\n def test_get_alpha_div(self):\n \"\"\"Ensure getting a single Alpha Diversity behaves correctly.\"\"\"\n alpha_diversity = AlphaDivFactory()\n fields = ('categories', 'tool_names', 'by_tool')\n self.generic_getter_test(alpha_diversity, MODULE_NAME, verify_fields=fields)\n\n def test_run_alpha_div_sample_group(self): # pylint: disable=invalid-name\n \"\"\"Ensure Alpha Diversity run_sample_group produces correct results.\"\"\"\n\n def create_sample(i):\n \"\"\"Create unique sample for index i.\"\"\"\n data = create_alpha_diversity()\n return Sample(name=f'Sample{i}',\n metadata={'foobar': f'baz{i}'},\n alpha_diversity_stats=data).save()\n\n self.generic_run_group_test(create_sample,\n AlphaDivDisplayModule)\n","repo_name":"MetaGenScope/metagenscope-server","sub_path":"app/display_modules/alpha_div/tests/test_module.py","file_name":"test_module.py","file_ext":"py","file_size_in_byte":1844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7419265956","text":"import rospy\nimport time\nimport datetime\n\nfrom std_msgs.msg import String\nfrom mavros_msgs.msg import State\nfrom sensor_msgs.msg import NavSatFix\nfrom geometry_msgs.msg import TwistStamped\nfrom sensor_msgs.msg import BatteryState\nfrom geometry_msgs.msg import PoseStamped\nfrom sensor_msgs.msg import Imu\nfrom std_msgs.msg import Float64\nfrom mavros_msgs.msg import *\n\n\nimport redis\n\n\nclass MavrosComm():\n def __init__(self):\n\n self.rate = rospy.Rate(5)\n self.redis_pub = redis.Redis()\n\n self.state = ''\n self.gps = ''\n self.battery = ''\n self.altitude = ''\n self.velocity = ''\n self.data = ''\n self.heading = ''\n self.wind_vel = ''\n self.circle_gps = ''\n\n rospy.Subscriber(\"/mavros/state\", State, self.callback_mavros_state)\n rospy.Subscriber(\"/mavros/global_position/raw/fix\",\n NavSatFix, self.callback_mavros_gps)\n rospy.Subscriber(\"/mavros/local_position/velocity_body\",\n TwistStamped, self.callback_mavros_vel)\n rospy.Subscriber(\"/mavros/battery\", BatteryState, self.callback_mavros_battery)\n rospy.Subscriber(\"/mavros/local_position/pose\",\n PoseStamped, self.callback_mavros_altitude)\n\n rospy.Subscriber(\"/mavros/imu/data\", Imu, self.callback_mavros_data)\n\n rospy.Subscriber(\"/mavros/global_position/compass_hdg\", Float64, self.callback_mavros_heading)\n\n rospy.Subscriber(\"/mavros/vfr_hud\", VFR_HUD, self.callback_wind)\n\n\n\n def callback_circle_gps(self, msg):\n self.circle_gps = 'circle_lat: ' + str(msg.latitude) + ' circle_lon: ' + str(msg.longitude)\n \n def callback_wind(self, msg):\n self.wind_vel = 'wind_vel: ' + str(msg.airspeed)\n\n def callback_mavros_heading(self, msg):\n self.heading = 'heading: ' + str(msg.data)\n \n def callback_mavros_data(self, msg):\n self.data = 'roll: '+ str(msg.angular_velocity.x) + ' pitch: ' + str(msg.angular_velocity.y) + ' yaw: ' + str(msg.angular_velocity.z)\n\n def callback_mavros_state(self, msg):\n self.state = 'connected:' + str(msg.connected)[0] + ' armed:' + str(\n msg.armed)[0] + ' guided:' + str(msg.guided)[0] + ' mode:' + str(msg.mode) \n \n def callback_mavros_gps(self, msg):\n self.gps = 'lat: ' + str(msg.latitude) + ' lon: ' + str(msg.longitude)\n \n def callback_mavros_vel(self, msg):\n if msg.twist.linear.x and msg.twist.linear.y and msg.twist.linear.z is not None:\n self.velocity = 'x: ' + str(round(msg.twist.linear.x, 2)) + ' y: ' + str(\n\t\t round(msg.twist.linear.y, 2)) + ' z: ' + str(round(msg.twist.linear.z, 2))\n else:\n self.velocity = 'x: ' + \"0.0\" + ' y: ' + \"0.0\" + ' z: ' + \"0.0\"\n \n def callback_mavros_battery(self, msg):\n if msg.percentage is not None:\n self.battery = \"{0:.2f}\".format(msg.percentage)\n else:\n self.battery = \"0.0\"\n \n def callback_mavros_altitude(self, msg):\n if msg.pose.position.z is not None:\n self.altitude = \"{0:.2f}\".format(msg.pose.position.z)\n else:\n self.altitude = \"0.0\"\n \n def send_status(self): \n while not rospy.is_shutdown():\n msg_status = self.state + ';' + self.gps + ';' + self.velocity + ';' + self.altitude + ';' + self.battery + ';' + self.data + ';' + self.heading + ';' + self.wind_vel + ';' + self.circle_gps\n ts = time.time()\n time_curr= datetime.datetime.fromtimestamp(ts).strftime('%H:%M:%S')\n self.redis_pub.rpush('incoming_messages', time_curr +\" \" + msg_status + \"\\n\")\n print('incoming_messages', time_curr +\" \" + msg_status + \"\\n\")\n self.rate.sleep()\n time.sleep(0.1)\n\n\nif __name__ == '__main__':\n rospy.init_node('mavroscomm', anonymous=True)\n mavroscomm = MavrosComm()\n mavroscomm.send_status()\n","repo_name":"FieldRoboticsLab/FixedWing_UAV_for_Aerial_Mapping","sub_path":"GroundStation/communication/mavroscomm.py","file_name":"mavroscomm.py","file_ext":"py","file_size_in_byte":3943,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42127082351","text":"from logging import getLogger, INFO, Formatter, StreamHandler, WARNING\nfrom sys import stderr\n\n\ndef setup_logging(verbosity: int):\n logger = getLogger(\"aoc21\")\n logger.setLevel(INFO if verbosity > 0 else WARNING)\n\n inner_logger = getLogger(\"aoc21.days\")\n inner_logger.setLevel(INFO if verbosity > 1 else WARNING)\n\n handler = StreamHandler(stderr)\n formatter = Formatter(\"%(message)s\")\n handler.setFormatter(formatter)\n\n logger.addHandler(handler)\n","repo_name":"macph/aoc21","sub_path":"src/aoc21/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23199648001","text":"import barcode\nfrom barcode.writer import ImageWriter\nfrom PIL import Image, ImageDraw\n\ndef INCH_TO_PX(inches):\n return int(inches * PPI)\n\nPPI = 300\nROWS = 10\nCOLS = 5\nX_MARGIN = INCH_TO_PX(0.0625)\nY_MARGIN = INCH_TO_PX(0.0625)\nX_SPACING = INCH_TO_PX(0.05)\nY_SPACING = INCH_TO_PX(-0.05)\n\nTAG_WIDTH = INCH_TO_PX(2.0)\nTAG_HEIGHT = INCH_TO_PX(0.75)\n\nPAGE_WIDTH = INCH_TO_PX(11.0)\nPAGE_HEIGHT = INCH_TO_PX(8.5)\n\ndef center(size1, size2):\n return (size1-size2)//2\n\ndef generate_barcode(number):\n barcode_image = barcode.get(\"code128\", str(number), writer=ImageWriter())\n opts = dict(\n write_text=True,\n module_width=.4,\n module_height=5,\n text_distance=1.5,\n font_size=12,\n quiet_zone=2)\n return barcode_image.render(opts)\n\ndef generate_single_tag(number, template):\n barcode_image = generate_barcode(number)\n template.paste(barcode_image, (center(template.width, barcode_image.width), 120))\n return template\n\ndef generate_tag_outline(image):\n draw = ImageDraw.Draw(image)\n start = (center(image.width, TAG_WIDTH), center(image.height, TAG_HEIGHT))\n draw.rectangle([start, (start[0] + TAG_WIDTH, start[1] + TAG_HEIGHT)], outline=\"grey\")\n del draw\n return image\n\nnumbers = range(25600001, 25600001+ROWS*COLS)\n\ntemplate = Image.open(\"template.png\")\n\ntag_sheet = Image.new('RGB', (PAGE_WIDTH, PAGE_HEIGHT), color=\"white\")\nfor row in range(ROWS):\n for col in range(COLS):\n tag = generate_single_tag(numbers[row*COLS+col], template)\n tag = generate_tag_outline(tag)\n x = X_MARGIN + col * (tag.width + X_SPACING)\n y = Y_MARGIN + row * (tag.height + Y_SPACING)\n tag_sheet.paste(tag, (x, y))\n\ntag_sheet.show()\ntag_sheet.save(\"sheet.png\")\n\n\n\n","repo_name":"tylercrumpton/ml-asset-tag","sub_path":"ml-asset-tag/testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37381758319","text":"import math\n\ndef calculate_solar_elevation(latitude, day_of_year, hour_of_day):\n \"\"\"\n Calculate solar elevation angle in degrees.\n\n Parameters:\n latitude (float): Latitude in degrees (positive for Northern Hemisphere, negative for Southern Hemisphere).\n day_of_year (int): Day of the year (1-365).\n hour_of_day (float): Hour of the day in decimal form (0-24).\n\n Returns:\n float: Solar elevation angle in degrees.\n \"\"\"\n # Convert latitude to radians\n lat_rad = math.radians(latitude)\n\n # Calculate the declination angle (δ) in radians\n declination = 23.45 * math.radians(math.sin(math.radians(360 / 365 * (day_of_year - 81))))\n\n # Calculate the solar hour angle (H) in radians\n solar_hour_angle = math.radians(15 * (hour_of_day - 12))\n\n # Calculate the argument for asin\n sin_arg = math.sin(lat_rad) * math.sin(declination) + math.cos(lat_rad) * math.cos(declination) * math.cos(solar_hour_angle)\n\n # Ensure that sin_arg stays within the valid range [-1, 1]\n sin_arg = max(min(sin_arg, 1), -1)\n\n # Calculate solar elevation angle (h) in radians\n solar_elevation_rad = math.asin(sin_arg)\n\n # Convert solar elevation angle to degrees\n solar_elevation_deg = math.degrees(solar_elevation_rad)\n\n return solar_elevation_deg\n\n# Example usage:\nlatitude = 37.7749 # San Francisco's approximate latitude\nday_of_year = 180 # Example: July 1st\nhour_of_day = 12.0 # Example: Noon\nelevation_angle = calculate_solar_elevation(latitude, day_of_year, hour_of_day)\nprint(f\"Solar Elevation Angle: {elevation_angle} degrees\")\n\n\n\n\ndef calculate_day_length(latitude, day_of_year):\n\n # Calculate the solar declination angle (δ) in radians\n declination = math.radians(23.45) * math.sin(math.radians(360 / 365 * (day_of_year - 81)))\n\n # Calculate the hour angles at sunrise and sunset (H0) in radians\n lat_rad = math.radians(latitude)\n \n # Calculate the value inside acos\n acos_arg = -math.tan(lat_rad) * math.tan(declination)\n \n # Ensure that acos_arg stays within the valid range [-1, 1]\n acos_arg = max(min(acos_arg, 1), -1)\n \n # Calculate the length of the day (in hours) as 2 times the hour angle at sunset\n H0 = math.acos(acos_arg)\n\n # Calculate day length in hours\n day_length_hours = 2 * math.degrees(H0) / 15.0\n\n # Handle cases where day length is 24 hours (continuous daylight)\n if day_length_hours >= 24:\n day_length_hours = 24\n\n return day_length_hours\n\n\ndef continuous_precipitation(latitude, day_of_year):\n \"\"\"\n Approximate continuous precipitation based on latitude and day of the year.\n\n Parameters:\n latitude (float): Latitude in degrees (positive for Northern Hemisphere, negative for Southern Hemisphere).\n day_of_year (int): Day of the year (1-365).\n\n Returns:\n float: Approximated precipitation value (in mm) for the given location and date.\n \"\"\"\n # Define functions to model precipitation variation throughout the year.\n # You can adjust the parameters to fit your desired patterns.\n seasonal_precipitation_amplitude = 15 # Amplitude of the seasonal variation\n annual_precipitation_average = 20 # Average annual precipitation\n\n # Calculate the angular frequency for the annual cycle\n omega = 2 * math.pi / 365\n\n # Calculate the latitude factor to model higher precipitation near the equator\n latitude_factor = math.cos(math.radians(latitude))\n\n # Calculate the precipitation value based on latitude, day of the year, and functions\n precipitation = (\n annual_precipitation_average\n + seasonal_precipitation_amplitude * latitude_factor * math.sin(omega * day_of_year)\n )\n\n # Ensure that precipitation values are non-negative\n precipitation = max(precipitation, 0)\n\n return precipitation\n\n\n# Check if the script is being run as the main program\nif __name__ == \"__main__\":\n latitude = 80 \n day_of_year = 120 \n hour_of_day = 12.0 \n\n elevation_angle = calculate_solar_elevation(latitude, day_of_year, hour_of_day)\n print(f\"Solar Elevation Angle: {elevation_angle} degrees\")\n\n day_length = calculate_day_length(latitude, day_of_year)\n print(f\"Day Length: {day_length} hours\")\n \n precip = continuous_precipitation(latitude, day_of_year)\n print(f\"Precipitation: {precip} mm\")\n \n ","repo_name":"byrdsl1999/Berinigia2","sub_path":"Beringia3/climate.py","file_name":"climate.py","file_ext":"py","file_size_in_byte":4324,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"36525813769","text":"# This program counts the number of lines, words, and chars in a file.\r\n\r\ndef main():\r\n\r\n # Starting number of:\r\n lines = 0\r\n words = 0\r\n chars = 0\r\n \r\n inputFile = input(\"What is file name: \") # Get file name\r\n\r\n # Open file and use for loop to go over each line,word,char\r\n infile = open(inputFile, \"r\")\r\n for line in infile:\r\n lines = lines + 1\r\n words = words + len(line.split())\r\n chars = chars + len(line)\r\n\r\n # Print result\r\n print(\"Total lines: \", lines)\r\n print(\"Total words: \", words)\r\n print(\"Total chars: \", chars)\r\n\r\n# Start program\r\nmain()\r\n","repo_name":"jodo993/Python-Beginner-","sub_path":"Extra Credit 2 - Files and Exceptions.py","file_name":"Extra Credit 2 - Files and Exceptions.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9600745594","text":"import numpy as np\r\nimport csv\r\n\r\nwith open(\"C:\\\\Users\\\\Sahil\\\\Downloads\\\\terrorismData.csv\" ,'r', encoding ='UTF-8') as file_obj:\r\n csv_obj=csv.DictReader(file_obj)\r\n # day_list=list()\r\n # count=0\r\n # for row in data:\r\n # if int(row['Day'])>=10 and int(row['Day'])<=20:\r\n # day_list.append(row['Day'])\r\n # count +=1\r\n # print(count)\r\n day_list=list()\r\n for row in csv_obj:\r\n day_list.append(int(row['Day']))\r\n\r\n np_day=np.array(day_list)\r\n\r\n # print(len(np_day))\r\n # bool=(np_day[np_day>=10]<=20)\r\n np_day=np_day[np.logical_and((np_day>=10),(np_day<=20))]\r\n\r\n\r\n print(np_day.size)\r\n # print(bool)\r\n\r\n","repo_name":"malhotrasahil/coding_ninjas","sub_path":"pycharm/numpy/terror_day.py","file_name":"terror_day.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21007472776","text":"import time\nimport random\nimport seaborn as sns\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\ndef quicksort(data):\n \"\"\"\n https://github.com/sidb70/CSE-331/blob/main/Projects/Project%204%20Sorting%20algorithms/solution.py\n Sorts a list in place using quicksort\n :param data: Data to sort\n \"\"\"\n\n def quicksort_inner(first, last):\n \"\"\"\n Sorts portion of list at indices in interval [first, last] using quicksort\n :param first: first index of portion of data to sort\n :param last: last index of portion of data to sort\n \"\"\"\n # List must already be sorted in this case\n if first >= last:\n return\n\n left = first\n right = last\n\n # Need to start by getting median of 3 to use for pivot\n # We can do this by sorting the first, middle, and last elements\n midpoint = (right - left) // 2 + left\n if data[left] > data[right]:\n data[left], data[right] = data[right], data[left]\n if data[left] > data[midpoint]:\n data[left], data[midpoint] = data[midpoint], data[left]\n if data[midpoint] > data[right]:\n data[midpoint], data[right] = data[right], data[midpoint]\n # data[midpoint] now contains the median of first, last, and middle elements\n pivot = data[midpoint]\n # First and last elements are already on right side of pivot since they are sorted\n left += 1\n right -= 1\n\n # Move pointers until they cross\n while left <= right:\n # Move left and right pointers until they cross or reach values which could be swapped\n # Anything < pivot must move to left side, anything > pivot must move to right side\n #\n # Not allowing one pointer to stop moving when it reached the pivot (data[left/right] == pivot)\n # could cause one pointer to move all the way to one side in the pathological case of the pivot being\n # the min or max element, leading to infinitely calling the inner function on the same indices without\n # ever swapping\n while left <= right and data[left] < pivot:\n left += 1\n while left <= right and data[right] > pivot:\n right -= 1\n # Swap, but only if pointers haven't crossed\n if left <= right:\n data[left], data[right] = data[right], data[left]\n left += 1\n right -= 1\n quicksort_inner(first, left - 1)\n quicksort_inner(left, last)\n\n # Perform sort in the inner function\n quicksort_inner(0, len(data) - 1)\n\ndef insertion_sort(arr):\n \"\"\"\n In place implementation of insertion sort\n :param arr: List of integers\n :return: Sorted list of integers\n \"\"\"\n for i in range(len(arr)):\n curr = arr[i]\n j = i\n while j > 0 and arr[j - 1] > curr:\n arr[j] = arr[j - 1]\n j -= 1\n arr[j] = curr \ndef measure_times(function,sizes):\n \"\"\"\n Measures the run time of a function for different sizes of input\n :param function: Function to measure\n :param sizes: Dictionary mapping size of input to list of run times\n \"\"\"\n # \n random.seed(0)\n for size in sizes.keys():\n arr = [random.randint(0, 1000) for _ in range(size)]\n start = time.time()\n function(arr)\n end = time.time()\n sizes[size].append((end - start)/size)\nif __name__ == '__main__':\n # Create a dictionary mapping n to a list of run times for each algorithm\n quicksort_runtimes = {5: [],10:[],15:[],20:[],30:[], 40:[], 50: [],100:[],200:[]}\n insertion_sort_runtimes ={5: [],10:[],15:[],20:[],30:[],40:[], 50: [],100:[],200:[]}\n \n # Populate each algorithm's dictionary with 20 run time tests for each n value\n for i in range(20):\n measure_times(quicksort,quicksort_runtimes)\n measure_times(insertion_sort,insertion_sort_runtimes)\n \n # Master list of data to plot\n data = []\n # Loop over the n values and run times for quicksort\n for n, times in quicksort_runtimes.items():\n for time in times:\n data.append({'Algorithm': 'Quick Sort', 'n': n, 'Time per element': time})\n # Loop over the n values and run times for insertion sort\n for n, times in insertion_sort_runtimes.items():\n for time in times:\n data.append({'Algorithm': 'Insertion Sort', 'n': n, 'Time per element': time})\n\n # Create a pandas DataFrame from the list of data\n df = pd.DataFrame(data)\n # Create a seaborn swarmplot\n sns.swarmplot(x='n', y='Time per element', hue='Algorithm', data=df,size=1)\n plt.legend(title='Algorithm', loc='upper left')\n plt.xlabel('input size, n')\n plt.ylabel('Run Time per element (microseconds)')\n plt.title('Comparison of Insertion Sort and Quick Sort Run Times')\n plt.savefig('insertion_vs_quick.png')\n plt.show()","repo_name":"sidb70/Algorithm-Engineering-Course-Project","sub_path":"Insertion Sort vs Quick Sort/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4928,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15734542781","text":"from django.urls import path\n\nfrom subscription.views import InvoiceCreate, InvoiceRetrieveView, InvoiceView, PackageCreateView, PackageRetrieveUpdateView, PackageView, SubscriptionCreate, UserSubscriptionRetrieveView, SubscriptionView\n\n\nurlpatterns = [\n path('subscription/', SubscriptionView.as_view()),\n path('subscription/create/', SubscriptionCreate.as_view()),\n path('subscription/view/', UserSubscriptionRetrieveView.as_view()),\n # path('packages/all/', PackageView.as_view()),\n # path('package/create/', PackageCreateView.as_view()),\n # path(\"package/detail//\", PackageRetrieveUpdateView.as_view()),\n path(\"invoices/\", InvoiceView.as_view()),\n path(\"invoices/create/\", InvoiceCreate.as_view()),\n path(\"invoice/view/\", InvoiceRetrieveView.as_view()),\n]","repo_name":"paisoncodes/expert-spork","sub_path":"subscription/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42083781484","text":"import os\nimport time\nfrom termcolor import colored\nimport subprocess as sp\n\n\nimport python.cxo_pipe_preproc as prepro\nimport python.cxo_pipe_spec as spec\nimport python.cxo_pipe_icm as icm\nimport python.cxo_pipe_plot as plt\nimport python.concentration as conc\nimport python.centroid as cent\nimport python.image as image\n\nfrom param import *\n\nti = time.time()\n\n\nprint(\"------------------------------------------------------------\")\nprint(colored(\"Pre-processing\", \"cyan\", None, [\"bold\"]))\nprint(\"------------------------------------------------------------\")\nres_dir = os.environ[\"CXO_RES_DIR\"] + source_name + \"/\"\n# Import data\nprepro.import_data(obsids, res_dir)\n# Reprocess data\nprepro.reprocess_data(obsids, res_dir)\n# Apply energy cuts\nprepro.energy_cut(obsids, res_dir)\n# Remove flares\nprepro.remove_flares(obsids, res_dir)\n# Compute maps of the observations\nif multiobs:\n prepro.reproj_obsids(obsids, res_dir)\nelse:\n prepro.make_images(obsids, res_dir)\n prepro.make_psf_map(res_dir)\n# Find point sources\nis_sources = prepro.find_sources(res_dir, multiobs)\n# Check point source regions\nprepro.check_sources(res_dir, is_sources)\n# Compute a background region for each point source\nprepro.bkg_point_sources(res_dir, is_sources)\n# Subtract point sources\nprepro.subtract_point_sources(res_dir, is_sources, multiobs, obsids)\n# Find X-ray peak and centroid locations\nXdepro, Ydepro = prepro.find_peak_cent(res_dir, z, R500, use_peak, fixed_coord)\n# Define background region for X-ray surface brightness and spectra\nbkg_area = prepro.bkg_region(res_dir, z, R500, Xdepro, Ydepro, multiobs, obsids)\n# Define annuli for the surface brightness profile\nprepro.find_SB_annuli(res_dir, Xdepro, Ydepro, bkg_area, z, R500, fast_annuli, obsids)\n# Compute weights to take vignetting into account\nprepro.vignetting_prof(res_dir, obsids)\n# Compute vignetting-corrected surface brightness profile\nprepro.X_ray_SB_profile(res_dir, obsids, z)\n\nprint(\"------------------------------------------------------------\")\nprint(colored(\"Spectral analysis\", \"cyan\", None, [\"bold\"]))\nprint(\"------------------------------------------------------------\")\n## Extract background spectra\n#spec.bkg_spectrum(res_dir, multiobs, obsids)\n# Define the annuli to be used for cluster spectrum extraction\nN_ann = spec.find_spec_annuli(\n res_dir, Xdepro, Ydepro, bkg_area, z, R500, single_ann_spec, obsids\n)\n# Extract a spectrum in each annulus for each obsid\nspec.extract_cl_spectra(res_dir, multiobs, obsids)\n# Compute the ARF and RMF in each annulis of the SB profile\nspec.arf_per_bin(res_dir, multiobs, obsids)\n# Compute the hydrogen column density in the cluster direction\nspec.hydrogen_column(res_dir)\n","repo_name":"laurelvwhite/xray-analysis","sub_path":"cxo-pipe/cxo_pipe_launch_1.py","file_name":"cxo_pipe_launch_1.py","file_ext":"py","file_size_in_byte":2679,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71322858385","text":"from typing import List\n\n\nclass Solution:\n # https://leetcode.com/problems/container-with-most-water/\n # two pointer\n #\n # 算法筆記 p374\n # https://labuladong.github.io/algo/4/33/128/\n def maxArea(self, height: List[int]) -> int:\n n = len(height)\n lo = 0\n hi = n - 1\n ans = 0\n\n while lo <= hi:\n lo_h = height[lo]\n hi_h = height[hi]\n size = min(lo_h, hi_h) * (hi - lo)\n ans = max(size, ans)\n # print(f'lo=>{lo}:{lo_h}, hi=>{hi}:{hi_h}')\n\n if lo_h > hi_h:\n hi -= 1\n else:\n lo += 1\n\n return ans\n\n\nif __name__ == '__main__':\n print(f'{Solution().maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7])}')\n","repo_name":"KScaesar/DSA-python","sub_path":"Blind Curated 75/0011. Container With Most Water.py","file_name":"0011. Container With Most Water.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35488372313","text":"from sklearn.preprocessing import MinMaxScaler\nfrom sklearn.model_selection import train_test_split\nfrom saveResults import SaveResults\nfrom datetime import datetime\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestRegressor\nimport winsound\nimport os\n\n\nclass FeatureImportance():\n def __init__(self):\n # Sets configuration\n self.cf = {}\n self.cf['sheet'] = 'Sheet1'\n # self.cf['selected_Xs'] = ['DIC', 'pH', 'Phosphate']\n self.cf['selected_Xs'] = ['Depth (µm)', 'Concentration', 'DIC', 'pH', 'Phosphate']\n self.cf['distance'] = 'Depth (µm)'\n self.cf['removal_targets'] = ['DIC', 'pH', 'Phosphate']\n # Concentration\n self.ml = RandomForestRegressor(n_estimators=100)\n\n # self.size_experiments = 2\n self.size_experiments = 5\n\n # Define excel data for storing all data to Excel\n self.excel = {}\n self.excel['Data'] = []\n self.excel['Target'] = []\n self.excel['Train Size'] = []\n self.excel['Test Size'] = []\n\n for x in self.cf['selected_Xs']:\n self.excel[x] = []\n\n self.excel['X Variables'] = []\n\n # set model info\n for v in self.cf['selected_Xs']:\n self.excel['X Variables'].append(v)\n\n def append_excel_column(self):\n self.excel['Data'].append('Data')\n self.excel['Target'].append('Target')\n\n self.excel['Train Size'].append('Train Size')\n self.excel['Test Size'].append('Test Size')\n self.excel['X Variables'].append('X Variables')\n\n for x in self.cf['selected_Xs']:\n self.excel[x].append(x)\n\n\n def save_excel_file(self):\n experiment_time = datetime.now().strftime(\"%m_%d_%Y-%H_%M_%S\")\n # excel_file = f\"../data_result/[Result]{self.cf['base_name']}\"\n excel_file = f\"../data_sensitivity_analysis/[Importance_Feature_Result]{experiment_time}.xlsx\"\n excel_experiment = SaveResults(excel_file)\n for k, l in self.excel.items():\n excel_experiment.insert(k, l)\n excel_experiment.save()\n\n def run(self, f):\n base_name = os.path.basename(f)\n print(base_name)\n\n self.cf['input_file'] = f\n self.cf['base_name'] = base_name\n\n if 'pH' in base_name:\n self.cf['targets'] = ['pH_output']\n else:\n self.cf['targets'] = ['Cs', 'J', 'K']\n\n for target in self.cf['targets']:\n self.cf['target'] = target\n\n # 1. Loads data from xlsx\n excel_data = pd.read_excel(self.cf['input_file'], self.cf['sheet'])\n\n selected_Xs = self.cf['selected_Xs'].copy()\n\n # 2. Selects variables\n excel_data = excel_data[selected_Xs + [self.cf['target']]]\n\n # 3. Removes all duplicated\n excel_data = excel_data.drop_duplicates()\n\n # 5. Normalization is performed\n scaled_df = MinMaxScaler(feature_range=(0, 1)).fit_transform(excel_data)\n excel_data = pd.DataFrame(scaled_df, index=excel_data.index, columns=excel_data.columns)\n\n # 6. Separate Xs and y\n df_X, df_y = excel_data[selected_Xs], excel_data[self.cf['target']]\n\n\n # 9. Split into training and test part\n X_train, X_test, y_train, y_test = train_test_split(df_X, df_y, test_size=.2)\n\n # Train model\n model = self.ml.fit(X_train, y_train)\n\n # Calculate feature importances\n importance = self.ml.feature_importances_\n importance = pd.DataFrame(importance, index=selected_Xs, columns=[\"Importance\"])\n\n print(importance)\n\n # 15. Set all results for the excel output\n for x in self.cf['selected_Xs']:\n self.excel[x].append(round(importance.iloc[:, x][0], 4))\n\n self.excel['Data'].append(self.cf['base_name'])\n self.excel['Train Size'].append(len(X_train))\n self.excel['Test Size'].append(len(X_test))\n self.excel['Target'].append(target)\n\n\nfiles = ['../data_jkCs/data_free_chlorine_jkCs_[DO-Copper].xlsx',\n '../data_jkCs/data_free_chlorine_jkCs_[DO-Ductile].xlsx',\n '../data_jkCs/data_free_chlorine_jkCs_[Free Chlorine-Copper].xlsx',\n '../data_jkCs/data_free_chlorine_jkCs_[Free Chlorine-Ductile].xlsx',\n '../data_jkCs/data_free_chlorine_jkCs_[pH-Copper].xlsx',\n '../data_jkCs/data_free_chlorine_jkCs_[pH-Ductile].xlsx',\n '../data_jkCs/data_monochloramine_jkCs_[DO-Copper].xlsx',\n '../data_jkCs/data_monochloramine_jkCs_[DO-Ductile].xlsx',\n '../data_jkCs/data_monochloramine_jkCs_[Monochloramine-Copper].xlsx',\n '../data_jkCs/data_monochloramine_jkCs_[Monochloramine-Ductile].xlsx',\n '../data_jkCs/data_monochloramine_jkCs_[pH-Copper].xlsx',\n '../data_jkCs/data_monochloramine_jkCs_[pH-Ductile].xlsx',\n ]\n\nex = FeatureImportance()\n\nfor f in files:\n ex.run(f)\n ex.append_excel_column()\n\nex.save_excel_file()\n\nwinsound.Beep(1000, 440)\n\n","repo_name":"woohyounglee/UCF_Corrosion","sub_path":"code/run5_sensitivity_analysis.py","file_name":"run5_sensitivity_analysis.py","file_ext":"py","file_size_in_byte":5028,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4778708090","text":"#encoding=utf-8\nfrom torch.utils import data\nimport torch\nimport os\nfrom PIL import Image\n\n\nclass EvalDataset(data.Dataset):\n def __init__(self, pre_img_root, label_root):\n print(\"pre_img_root is {}\".format(pre_img_root))\n print(\"label_gt_root is {}\".format(label_root))\n # 这个排序有时候会有bug 不要乱改图片名称\n self.image_path = list(map(lambda x: os.path.join(pre_img_root, x), sorted(os.listdir(pre_img_root))))\n self.label_path = list(map(lambda x: os.path.join(label_root, x), sorted(f for f in os.listdir(label_root) if f.endswith('.png') and (f.find(\"edge\") == -1))))\n if len(self.image_path) <= 0 :\n print(\"please check datasource path setting ! No image can be readed in \".format(pre_img_root))\n exit()\n if len(self.label_path) <= 0:\n print(\"please check datasource path setting ! No image can be readed in \".format(label_root))\n exit()\n\n def filter_files(self):\n print(\"images num is \", len(self.image_path))\n print(\"gts num is \", len(self.label_path))\n assert len(self.image_path) == len(self.label_path)\n\n def __getitem__(self, item):\n pred = Image.open(self.image_path[item]).convert('L')\n gt = Image.open(self.label_path[item]).convert('L')\n # print(\"get image path is {}\".format(self.image_path[item]))\n # print(\"get gt path is {}\".format(self.label_path[item]))\n # print(self.image_path[item], self.label_path[item])\n # 返回Image 图片名称以便于出现问题数据方便定位图片\n name = (self.image_path[item].split('/')[-1]).split(\".\")[0]\n if pred.size != gt.size:\n pred = pred.resize(gt.size, Image.BILINEAR)\n return pred, gt ,name\n\n def __len__(self):\n return len(self.image_path)\n\n\nclass validate_dataset():\n def __init__(self, image_root, gt_root, testsize):\n self.testsize = testsize\n self.images = [image_root + f for f in os.listdir(image_root) if f.endswith('.jpg')]\n self.gts = [gt_root + f for f in os.listdir(gt_root) if f.endswith('.png') and (f.find(\"edge\") == -1)]\n self.images = sorted(self.images)\n self.gts = sorted(self.gts)\n self.transform = transforms.Compose([\n transforms.Resize((self.testsize, self.testsize)),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])\n self.gt_transform = transforms.ToTensor()\n self.size = len(self.images)\n self.index = 0\n\n def load_data(self):\n image = self.rgb_loader(self.images[self.index])\n image = self.transform(image).unsqueeze(0)\n gt = self.binary_loader(self.gts[self.index])\n name = self.images[self.index].split('/')[-1]\n if name.endswith('.jpg'):\n name = name.split('.jpg')[0] + '.png'\n self.index += 1\n return image, gt, name\n\n def rgb_loader(self, path):\n with open(path, 'rb') as f:\n img = Image.open(f)\n return img.convert('RGB')\n\n def binary_loader(self, path):\n with open(path, 'rb') as f:\n img = Image.open(f)\n return img.convert('L')","repo_name":"binbincz/deep-learning-utils","sub_path":"evaluate/dataloader.py","file_name":"dataloader.py","file_ext":"py","file_size_in_byte":3231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6509693566","text":"from data_importers.management.commands import BaseXpressDemocracyClubCsvImporter\nfrom django.contrib.gis.geos import Point\n\n\nclass Command(BaseXpressDemocracyClubCsvImporter):\n council_id = \"STR\"\n addresses_name = (\n \"2023-05-04/2023-03-07T09:03:03.694104/Democracy_Club__04May2023.tsv\"\n )\n stations_name = (\n \"2023-05-04/2023-03-07T09:03:03.694104/Democracy_Club__04May2023.tsv\"\n )\n elections = [\"2023-05-04\"]\n csv_delimiter = \"\\t\"\n\n def address_record_to_dict(self, record):\n uprn = record.property_urn.strip().lstrip(\"0\")\n\n if uprn in [\n \"10024063650\", # THE STUDIO, CUTLERS FARM, EDSTONE, WOOTTON WAWEN, HENLEY-IN-ARDEN\n \"100071249390\", # KINGSTON HOLT FARM, BANBURY ROAD, LIGHTHORNE, WARWICK\n \"100071512710\", # DARLINGSCOTT HILL, DARLINGSCOTE ROAD, SHIPSTON-ON-STOUR\n \"100071244138\", # WIL HAVEN, DARLINGSCOTE ROAD, SHIPSTON-ON-STOUR\n \"10023584621\", # DITCHFORD FRIARY MANOR, TIDMINGTON, SHIPSTON-ON-STOUR\n \"10023584622\", # GARDEN COTTAGE DITCHFORD FRIARY DITCHFORD ROAD, TIDMINGTON\n \"10023584685\", # LITTLE KIRBY, KIRBY FARM, WHATCOTE, SHIPSTON-ON-STOUR\n \"100071241496\", # GLENDALE, CAMP LANE, WARMINGTON, BANBURY\n \"100071241501\", # RIDGE HOUSE, CAMP LANE, WARMINGTON, BANBURY\n \"10023582389\", # EGGE COTTAGE, EDGEHILL, BANBURY\n \"10023387192\", # BARN VIEW, KYTE GREEN, HENLEY-IN-ARDEN\n \"10094564878\", # FLAT 1 RIVERSIDE LODGE, CLIFFORD MILL, CLIFFORD ROAD, STRATFORD-UPON-AVON\n \"10094564879\", # FLAT 2 RIVERSIDE LODGE, CLIFFORD MILL, CLIFFORD ROAD, STRATFORD-UPON-AVON\n \"10094564880\", # FLAT 3 RIVERSIDE LODGE, CLIFFORD MILL, CLIFFORD ROAD, STRATFORD-UPON-AVON\n \"10094564881\", # FLAT 4 RIVERSIDE LODGE, CLIFFORD MILL, CLIFFORD ROAD, STRATFORD-UPON-AVON\n \"10094564882\", # FLAT 5 RIVERSIDE LODGE, CLIFFORD MILL, CLIFFORD ROAD, STRATFORD-UPON-AVON\n \"10094564883\", # FLAT 6 RIVERSIDE LODGE, CLIFFORD MILL, CLIFFORD ROAD, STRATFORD-UPON-AVON\n \"10023382223\", # RADBROOK EDGE, PRESTON ON STOUR, STRATFORD-UPON-AVON\n \"100071244137\", # WHADDON FARM, DARLINGSCOTE ROAD, SHIPSTON-ON-STOUR\n \"100071249075\", # GREENFIELDS FARM, HARDWICK LANE, OUTHILL, STUDLEY\n \"10023580629\", # OX HOUSE FARM, COMBROOK, WARWICK\n \"100071241494\", # BATTLE LODGE, CAMP LANE, WARMINGTON, BANBURY\n \"100071241504\", # YENTON, CAMP LANE, WARMINGTON, BANBURY\n ]:\n return None\n\n if record.addressline6 in [\n \"CV36 4DY\", # HIGH SCHOOL BUNGALOW & LOW FURLONG, DARLINGSCOTE ROAD, SHIPSTON-ON-STOUR\n ]:\n return None\n\n return super().address_record_to_dict(record)\n\n def station_record_to_dict(self, record):\n # Chaser Suite, Stratford-upon-Avon Racecourse, Luddington Road\n if record.polling_place_id == \"10305\":\n record = record._replace(\n polling_place_easting=\"0\", polling_place_northing=\"0\"\n )\n\n rec = super().station_record_to_dict(record)\n\n # Alcester Methodist Church, Priory Road, Alcester\n if rec[\"internal_council_id\"] == \"10403\":\n rec[\"location\"] = Point(-1.871973, 52.214217, srid=4326)\n\n # Alcester Guide and Scout Centre, 28 Moorfield Road, Alcester\n if rec[\"internal_council_id\"] == \"10410\":\n rec[\"location\"] = Point(-1.871852, 52.216259, srid=4326)\n\n # Station change from Council\n if rec[\"internal_council_id\"] == \"10556\":\n rec[\"postcode\"] = \"CV35 9RU\"\n rec[\"address\"] = (\n \"Wellesbourne Sports and Community Centre\\n\"\n \"Loxley Close\\n\"\n \"Wellesbourne\"\n )\n rec[\"location\"] = None\n\n return rec\n","repo_name":"DemocracyClub/UK-Polling-Stations","sub_path":"polling_stations/apps/data_importers/management/commands/import_stratford-on-avon.py","file_name":"import_stratford-on-avon.py","file_ext":"py","file_size_in_byte":3883,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"48"} +{"seq_id":"9031899435","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nimport json\nimport r2pipe\nimport hashlib\nimport sqlite3 as sql\nimport multiprocessing\nimport time\nimport sys, os\n\n\ndef extract_func(file):\n uniq_hashes = []\n r2 = r2pipe.open(path+file)\n r2.cmd(\"aaaa\")\n function_list = r2.cmdj(\"aflj\")\n while function_list is None:\n time.sleep(0.7)\n function_list = r2.cmdj(\"aflj\")\n\n for function in function_list:\n try:\n op_string = r2.cmd(\"p8f\" + str(function[\"size\"])+ \" @ \" + function[\"name\"]) \n op = op_string[:-1]\n\n op = op.encode('utf-8')\n op_hash = hashlib.sha256(op).hexdigest()\n if op_hash not in uniq_hashes:\n cr.execute(\"\"\"INSERT INTO Functions \n VALUES (?, ?)\"\"\", (file, op_hash))\n db.commit()\n uniq_hashes.append(op_hash)\n except:\n cr.execute(\"\"\"INSERT INTO error_func \n VALUES (?, ?)\"\"\", (file, str(function[\"name\"])))\n db.commit()\n r2.quit()\n\n\ndef extract_bblock(file):\n r2 = r2pipe.open(path+file)\n r2.cmd(\"aaaa\")\n uniq_hashes = []\n blocks_data = r2.cmd('pdbj @@ *')\n while blocks_data == '':\n time.sleep(0.7)\n blocks_data = r2.cmd('pdbj @@ *')\n\n blocks_data = blocks_data.split('\\n')\n blocks_data.remove('')\n\n blocks = set()\n for bb in blocks_data:\n blocks.add(bb)\n blocks = list(blocks)\n for block in blocks:\n try:\n block = json.loads(block)\n code = b''\n for b in block:\n if b['type'] != 'invalid':\n code += bytes.fromhex(b['bytes'])\n code_hash = hashlib.sha256(code).hexdigest()\n\n if code_hash not in uniq_hashes:\n cr.execute(\"\"\"INSERT INTO Blocks \n VALUES (?, ?)\"\"\", (file, code_hash)) \n db.commit()\n uniq_hashes.append(code_hash)\n except:\n cr.execute(\"\"\"INSERT INTO error_block \n VALUES (?, ?)\"\"\", (file, str(block)))\n db.commit()\n\n r2.quit()\n\n\ndef main():\n\n FILES = os.listdir(path)\n\n for file in FILES:\n p = multiprocessing.Process(target=extract_func, args=(file,))\n p.start()\n p.join(30)\n if p.is_alive():\n p.kill()\n cr.execute(\"\"\"INSERT INTO error_func_timeout \n VALUES (?)\"\"\", (file,))\n db.commit()\n p.join()\n\n\n p2 = multiprocessing.Process(target=extract_bblock, args=(file,))\n p2.start()\n p2.join(40)\n if p2.is_alive():\n p2.kill()\n cr.execute(\"\"\"INSERT INTO error_block_timeout \n VALUES (?)\"\"\", (file,))\n db.commit()\n p2.join()\n \n\n \n\nif __name__ == '__main__':\n path = sys.argv[1]\n db = sql.connect('dataset.db')\n cr = db.cursor()\n cr.execute(\"CREATE TABLE Functions (File, Func_SHA256)\")\n cr.execute(\"CREATE TABLE Blocks (File, Block_SHA256)\")\n cr.execute(\"CREATE TABLE error_block (File, Block)\")\n cr.execute(\"CREATE TABLE error_block_timeout (File)\")\n cr.execute(\"CREATE TABLE error_func (File, Func_name)\")\n cr.execute(\"CREATE TABLE error_func_timeout (File)\")\n db.commit()\n\n main()\n \n db.close()","repo_name":"mucoze/Umay","sub_path":"create_dataset.py","file_name":"create_dataset.py","file_ext":"py","file_size_in_byte":3313,"program_lang":"python","lang":"en","doc_type":"code","stars":42,"dataset":"github-code","pt":"48"} +{"seq_id":"12000212292","text":"import json\nimport os\nimport random\n\nimport bottle\nfrom bottle import HTTPResponse\ntry:\n from game import *\nexcept:\n from app.game import *\n\n\n@bottle.route(\"/\")\ndef index():\n return \"Your Battlesnake is alive!\"\n\n\n@bottle.post(\"/ping\")\ndef ping():\n \"\"\"\n Used by the Battlesnake Engine to make sure your snake is still working.\n \"\"\"\n return HTTPResponse(status=200)\n\n\n@bottle.post(\"/start\")\ndef start():\n \"\"\"\n Called every time a new Battlesnake game starts and your snake is in it.\n Your response will control how your snake is displayed on the board.\n \"\"\"\n data = bottle.request.json\n print(\"START:\", json.dumps(data))\n\n response = {\"color\": \"#a1223f\", \"headType\": \"bendr\", \"tailType\": \"curled\"}\n return HTTPResponse(\n status=200,\n headers={\"Content-Type\": \"application/json\"},\n body=json.dumps(response),\n )\n\n\n@bottle.post(\"/move\")\ndef move():\n \"\"\"\n Called when the Battlesnake Engine needs to know your next move.\n The data parameter will contain information about the board.\n Your response must include your move of up, down, left, or right.\n \"\"\"\n data = bottle.request.json\n print(\"MOVE:\", json.dumps(data))\n \n def HasFood(location):\n if location in board.food:\n return True\n return False\n\n directions = [\"up\", \"down\", \"left\", \"right\"]\n board = Board(data['board']['height'], data['board']['width'], data['board']['food'], data['board']['snakes'])\n player = Player(data['you']['id'], data['you']['name'], data['you']['health'], data['you']['body'])\n\n #wall locations\n xWalls = [-1, board.width]\n yWalls = [-1, board.height]\n\n snakeSpots = board.getSnakeSpots(data)\n\n #choosing a move that doesn't kill us\n moves = player.getSafeMoves(player.head, directions, xWalls, yWalls, snakeSpots)\n mostDirectionsOpen = 0 #we want to choose the move that gives us the most options from there so we don't corner ourself\n goodMoves = []\n for option in moves:\n #this loop looks one move into the future and chooses the moves that leave the most spaces open to move into next\n directionsOpen = len(player.getSafeMoves(player.getNewLocations(player.head, directions)[option], directions, xWalls, yWalls, snakeSpots))\n # print(\"\\n directions open for \", option, \" at \", GetNewLocations(currentLocation)[option], \" is \", directionsOpen)\n if directionsOpen == mostDirectionsOpen:\n goodMoves.append(option)\n elif directionsOpen > mostDirectionsOpen:\n goodMoves = [option]\n mostDirectionsOpen = directionsOpen\n \n if player.health < 40:\n #prioritize finding food if all else is equal\n foodMoves = []\n for option in moves:\n if HasFood(player.getNewLocations(player.head, directions)[option]):\n foodMoves.append(option)\n if len(foodMoves) > 0:\n goodMoves = foodMoves\n # print(\"\\n good moves: \", goodMoves)\n # for key in directions:\n if len(moves) == 0:\n move = random.choice(directions)\n else:\n move = random.choice(goodMoves)\n\n # Shouts are messages sent to all the other snakes in the game.\n # Shouts are not displayed on the game board.\n shout = \"I am a python snake!\"\n\n response = {\"move\": move, \"shout\": shout}\n return HTTPResponse(\n status=200,\n headers={\"Content-Type\": \"application/json\"},\n body=json.dumps(response),\n )\n\n\n@bottle.post(\"/end\")\ndef end():\n \"\"\"\n Called every time a game with your snake in it ends.\n \"\"\"\n data = bottle.request.json\n print(\"END:\", json.dumps(data))\n return HTTPResponse(status=200)\n\n\ndef main():\n bottle.run(\n application,\n host=os.getenv(\"IP\", \"0.0.0.0\"),\n port=os.getenv(\"PORT\", \"8080\"),\n debug=os.getenv(\"DEBUG\", True),\n )\n\n\n# Expose WSGI app (so gunicorn can find it)\napplication = bottle.default_app()\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"atol/battlesnake-2020","sub_path":"app/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33527480530","text":"import sys\nimport json\nimport gevent\nfrom gevent import monkey\nmonkey.patch_all()\n\nimport unittest\nfrom flexmock import flexmock\n\nfrom opserver.stats import StatQuerier\nfrom opserver.opserver_util import OpServerUtils\n\ntest_num = 0\nquery_dict = {}\ngot_expected_log_str = False\nresult_1 =\\\n'{\"value\": [\\n{\"T=\":1442446560000000,\"SUM(cpu_info.cpu_share)\":0}, {\"T=\":1442446620000000,\"SUM(cpu_info.cpu_share)\":4.16222}, {\"T=\":1442446680000000,\"SUM(cpu_info.cpu_share)\":4.10806}, {\"T=\":1442446740000000,\"SUM(cpu_info.cpu_share)\":1.71222}, {\"T=\":1442446800000000,\"SUM(cpu_info.cpu_share)\":1.68722}, {\"T=\":1442446860000000,\"SUM(cpu_info.cpu_share)\":1.64973}, {\"T=\":1442446920000000,\"SUM(cpu_info.cpu_share)\":1.67889}, {\"T=\":1442446980000000,\"SUM(cpu_info.cpu_share)\":1.65}, {\"T=\":1442447040000000,\"SUM(cpu_info.cpu_share)\":1.66639}, {\"T=\":1442447100000000,\"SUM(cpu_info.cpu_share)\":1.70805}, {\"T=\":1442447160000000,\"SUM(cpu_info.cpu_share)\":1.65806}\\n]}'\n\nclass StatQuerierTest(unittest.TestCase):\n\n @staticmethod\n def custom_post_url_http(url, params, sync = True):\n global query_dict\n query_dict = json.loads(params)\n if (test_num == 1):\n return result_1\n\n return []\n\n def custom_display(self, result):\n if (test_num == 1):\n expect_result = json.loads(result_1)\n expect_result = expect_result['value']\n self.assertTrue(result == expect_result)\n\n def setUp(self):\n self._querier = StatQuerier()\n\n flexmock(OpServerUtils).should_receive('post_url_http').once().replace_with(lambda x, y, w, z, **kwargs: self.custom_post_url_http(x, y, kwargs))\n flexmock(self._querier).should_receive('display').replace_with(lambda x: self.custom_display(x))\n\n\n #@unittest.skip(\"skip test_1_analytics_cpu_query\")\n def test_1_analytics_cpu_query(self):\n global test_num\n global query_dict\n test_num = 1\n\n argv = sys.argv\n sys.argv = \"contrail-stats --table NodeStatus.process_mem_cpu_usage --select T=60 SUM(process_mem_cpu_usage.cpu_share) --where name=*\".split()\n self._querier.run()\n sys.argv = argv\n\n expected_result_str = '{\"select_fields\": [\"T=60\", \"SUM(process_mem_cpu_usage.cpu_share)\"], \"table\": \"StatTable.NodeStatus.process_mem_cpu_usage\", \"where\": [[{\"suffix\": null, \"value2\": null, \"name\": \"name\", \"value\": \"\", \"op\": 7}]]}'\n expected_result_dict = json.loads(expected_result_str)\n self.assertEqual(int(query_dict['end_time']) - int(query_dict['start_time']), 10*60*pow(10,6))\n del query_dict['start_time']\n del query_dict['end_time']\n for key in expected_result_dict:\n self.assertTrue(key in query_dict)\n self.assertTrue(expected_result_dict[key] == query_dict[key])\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"tungstenfabric/tf-analytics","sub_path":"contrail-opserver/test/test_stats.py","file_name":"test_stats.py","file_ext":"py","file_size_in_byte":2833,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"36773202390","text":"from flask import Flask, render_template, Response, send_from_directory, url_for\n# import numpy as np\n# import cv2\n# Raspberry Pi camera module (requires picamera package, developed by Miguel Grinberg)\nfrom camera_pi import Camera\nfrom gpiozero import LEDBoard\n\n# cap = cv2.VideoCapture(-1)\n\nleds = LEDBoard(0, 1, 2, 3, 4, pwm=False, active_high=False, initial_value=False, pin_factory=None)# LEDBoard(17, 18, 15, 27)\n#my_message = \"Started\";\n\napp = Flask(__name__, static_url_path='/static')\n\n# def get_frame():\n# while(cap.isOpened()):\n# ret, frame = cap.read()\n# if ret==True:\n# #frame = cv2.flip(frame,0)\n# return frame\n\n@app.route('/')\ndef index():\n \"\"\"Video streaming home page.\"\"\"\n return render_template('index.html')\n\n# @app.route('/static/assets/')\n# def send_js(path):\n# return send_from_directory('static/assets/', path)\n\n@app.route(\"/switchlight/\")\ndef switchlight():\n #Moving forward code\n #my_message = \"Green!\"\n print('Green!')\n leds[0].toggle()\n return \"Nothing\"\n\n@app.route(\"/press/\")\ndef press(nr):\n print('press!')\n # leds[int(nr)].on()\n if int(nr) == 0:\n leds[0].on()\n leds[1].on()\n leds[2].off()\n leds[3].on()\n leds[4].off()\n if int(nr) == 1:\n leds[0].on()\n leds[1].on()\n leds[2].off()\n leds[3].off()\n leds[4].on()\n if int(nr) == 2:\n leds[0].on()\n leds[1].off()\n leds[2].on()\n leds[3].on()\n leds[4].off()\n if int(nr) == 3:\n leds[0].on()\n leds[1].off()\n leds[2].on()\n leds[3].off()\n leds[4].on()\n return \"Nothing\"\n\n@app.route(\"/release\")\ndef release():\n print('release!')\n # leds[int(nr)].off()\n leds[0].off()\n leds[1].off()\n leds[2].off()\n leds[3].off()\n leds[4].off()\n return \"Nothing\"\n\ndef gen(camera):\n \"\"\"Video streaming generator function.\"\"\"\n while True:\n frame = camera.get_frame()\n yield (b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n')\n\n@app.route('/video_feed')\ndef video_feed():\n \"\"\"Video streaming route. Put this in the src attribute of an img tag.\"\"\"\n return Response(gen(Camera()),\n mimetype='multipart/x-mixed-replace; boundary=frame')\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=80, debug=True, threaded=True)","repo_name":"NikolasDN/Mechi","sub_path":"RobotV3/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6831643600","text":"# -*- coding: utf-8 -*-\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport numpy as np\nimport plotly.graph_objs as go\nimport pandas as pd\nimport sqlite3\nimport plotly.figure_factory as ff\nimport json\nimport h5py\nimport time\nimport dash_table_experiments as dt\nimport os\n\nfrom app import app\nfrom dash.dependencies import Input, Output, State,Event\nfrom scipy.stats import norm,bernoulli,beta,binom\nfrom tasks.rl_basic_tasks import k_arm_bandit\n\n\nlayout_posterior = go.Layout(\n\n xaxis={'title': 'X'},\n yaxis={'title': 'Reward dist', 'range': [-1, 1]},\n\n)\n\nfig = dict(data=[],layout=layout_posterior)\n\nlayout = html.Div([\n\n html.Div([\n\n html.Div([\n\n html.Form([\n\n html.Div([\n\n html.Label('Lever number'),\n dcc.Slider(\n id='lever-number',\n min=1,\n max=10,\n step=1,\n marks={i: str(i) for i in range(1, 11)},\n value=5,\n ),\n\n ],className=\"form-group\"),\n\n\n html.Div([\n\n html.Label('Init Q'),\n dcc.Slider(\n id='init-q-value',\n min=0,\n max=5,\n step=1,\n marks={i: str(i) for i in range(1, 6)},\n value=0,\n ),\n\n ],className=\"form-group\"),\n\n html.Div([\n\n html.Label('Epsilon'),\n dcc.Slider(\n id='epsilon-value',\n min=0,\n max=1,\n step=0.1,\n marks={i/10.0: str(i/10.0) for i in range(1, 11)},\n value=0,\n ),\n\n ],className=\"form-group\"),\n\n html.Div([\n\n dcc.Dropdown(\n options=[\n {'label': 'e-greedy', 'value': 'greedy'},\n {'label': 'UCB', 'value': 'UCB'},\n {'label': 'e-greedy dynamic', 'value': 'greedy-2'}\n ],\n value='greedy',\n id='algorithm-select'\n )\n ],style={\"margin-top\":\"25px\"})\n\n\n ],id='model-parameter-form',style={\"margin-bottom\":\"25px\"}),\n\n\n html.Div([\n html.Button(id='submit-button', n_clicks=0, type=\"button\",children='Sample', className=\"btn btn-primary\"),\n html.Button(id='run-model', n_clicks=0, type=\"button\", children='Run', className=\"btn btn-primary\"),\n html.Button(id='toggle-model', n_clicks=0, type=\"button\", children='Toggle', className=\"btn btn-primary\")\n\n ],style={\"margin-top\":\"25px\"})\n\n\n ],className=\"col-sm-12\"),\n\n\n\n ],className=\"row\"),\n\n html.Div([\n\n html.Div([\n\n html.H3(children=\"Reward distribution\",className='text-center'),\n\n dcc.Graph(id='reward-distribution', figure=fig)\n\n ],className=\"col-sm-12\")\n\n ],className=\"row\",style={\"margin-top\":\"10px\"}),\n\n html.Div([\n\n html.Div([\n\n html.H3(children=\"Reward Graph\",className='text-center'),\n\n dcc.Graph(id='reward-graph')\n\n ],className=\"col-sm-12\")\n\n ],className=\"row\",style={\"margin-top\":\"10px\"}),\n\n html.Div([\n\n html.Div([\n\n html.H3('Lever Counts')\n\n ],className=\"col-sm-12\",id=\"datatable-lever-holder\")\n\n ],className=\"row\",style={\"margin-top\":\"10px\"}),\n\n html.Div([\n html.Div([\n html.H4('Completed tests DataTable'),\n dt.DataTable(\n rows=[],\n # optional - sets the order of columns\n columns=['files'],\n row_selectable=True,\n filterable=True,\n sortable=True,\n selected_row_indices=[],\n id='datatable-file'\n )\n\n ],id='file-datatable-container',className=\"col-sm-12\"),\n\n html.Button(id='fetch-files', n_clicks=0, type=\"button\", children='GetFiles', className=\"btn btn-primary\"),\n html.Button(id='delete-files', n_clicks=0, type=\"button\", children='DeleteFiles', className=\"btn btn-danger\")\n\n ],className=\"row\"),\n\n html.Div(id='interval-container'),\n\n # Hidden div inside the app that stores the intermediate value\n html.Div(id='model-state',children='stop'),\n\n html.Div(id='run-model-hidden', style={'display': 'none'}),\n html.Div(id='place-holder-div', style={'display': 'none'}),\n\n\n],style = {\"margin-top\":\"50px\",\"margin-left\":\"0px\",\"margin-right\":\"0px\"},className=\"container\",id='main-container')\n\n\n\n#################\n# Lever Graph\n#################\n@app.callback(\n dash.dependencies.Output('reward-distribution','figure'),\n [dash.dependencies.Input('submit-button','n_clicks')],\n [dash.dependencies.State('lever-number','value')]\n)\ndef update_current_sample(n_clicks,input1):\n\n traces = []\n for i in range(input1):\n\n # get random mean\n rand_mean = np.random.uniform(0,5)\n\n y_norm = norm.rvs(loc=rand_mean,size=1000)\n\n name = 'lever' + str(i) + ' mean: ' + str(rand_mean)\n\n tracei = {\n \"type\":\"violin\",\n \"y\":y_norm,\n \"box\": {\n \"visible\": True\n },\n \"name\":name,\n \"mean\":rand_mean,\n \"std\":1\n }\n\n traces.append(tracei)\n\n\n layout_posterior = go.Layout(\n\n xaxis={'title': 'lever number'},\n yaxis={'title': 'Reward dist', 'range': [-1, 1]},\n\n )\n\n fig = dict(data=traces)\n\n return fig\n\n'''\n@app.callback(\n dash.dependencies.Output('reward-graph','figure'),\n [dash.dependencies.Input('interval-component','n_intervals')],\n [dash.dependencies.State('model-state','children'),\n dash.dependencies.State('epsilon-value', 'value'),\n dash.dependencies.State('lever-number', 'value')]\n)\ndef display_loss(n_clicks,model_state,epsilon_value,lever_number):\n\n if model_state == 'stop':\n\n return {'data':[]}\n\n print(\"Inverval\")\n\n time.sleep(2)\n\n path_name = 'kbandit_{num_levers}_{epsilon}.h5'.format(num_levers=lever_number, epsilon=epsilon_value)\n\n hdf_file_path = '/Users/befeltingu/RLResearch/Data/' + path_name\n\n f = h5py.File(hdf_file_path, 'r', libver='latest',\n swmr=True)\n\n dset = f[\"avg_reward\"][:] # fetch all the datas\n\n figure = {\n 'data': [\n go.Scatter(\n x=[x for x in range(len(dset))],\n y=dset,\n\n )\n ],\n 'layout': go.Layout(\n xaxis={'title': 'iteration'},\n yaxis={'title': 'loss'},\n margin={'l': 40, 'b': 40, 't': 10, 'r': 10},\n legend={'x': 0, 'y': 1},\n )\n }\n\n f.close()\n\n return figure\n'''\n\n\n#################\n# Reward Graph\n#################\n\n@app.callback(\n Output('reward-graph', 'figure'),\n [Input('datatable-file', 'selected_row_indices')],\n [State('datatable-file', 'rows')])\ndef update_figure(selected_row_indices,rows):\n\n dff = pd.DataFrame(rows)\n\n traces = []\n\n for i in (selected_row_indices or []):\n\n file_name = str(rows[i]['files'])\n\n file_path = '/Users/befeltingu/RLResearch/Data/k_arm_bandit/' + file_name\n\n f = h5py.File(file_path, 'r', libver='latest',\n swmr=True)\n\n dset = f[\"avg_reward\"][:] # fetch all the datas\n\n init_q = f[\"init_q\"].value\n\n num_bandits = file_name.split('_')[1]\n\n epsilon = f['epsilon'].value\n\n label_name = \"Levers={levers} epsilon={epsilon} q0={init_q}\".format(levers=num_bandits,epsilon=epsilon,init_q=init_q)\n\n trace = go.Scatter(\n x=[x for x in range(len(dset))],\n y=dset,\n name=label_name\n\n )\n\n traces.append(trace)\n\n f.close()\n\n figure = {\n 'data': traces,\n 'layout': go.Layout(\n xaxis={'title': 'iteration'},\n yaxis={'title': 'loss'},\n margin={'l': 40, 'b': 40, 't': 10, 'r': 10},\n #legend={'x': 0, 'y': 1},\n )\n }\n\n return figure\n\n\n@app.callback(\n Output('datatable-lever-holder', 'children'),\n [Input('datatable-file', 'selected_row_indices')],\n [State('datatable-file', 'rows')])\ndef update_figure(selected_row_indices,rows):\n\n df = pd.DataFrame(rows)\n\n q_values = []\n\n for i in (selected_row_indices or []):\n\n file_name = str(rows[i]['files'])\n\n file_path = '/Users/befeltingu/RLResearch/Data/k_arm_bandit/' + file_name\n\n f = h5py.File(file_path, 'r', libver='latest',\n swmr=True)\n\n count_vaues = f['lever_count'][:]\n\n q_values.append([file_name] + list(count_vaues))\n\n\n f.close()\n\n if len(q_values) == 0:\n\n table = dt.DataTable(\n rows=[],\n # optional - sets the order of columns\n columns=[],\n row_selectable=True,\n filterable=True,\n sortable=True,\n selected_row_indices=[],\n id='datatable-lever-counts'\n )\n\n return table\n\n\n columns = [\"lever_name\"] + [\"lever_\" + str(i) for i in range(len(q_values[0]) - 1)]\n\n q_df = pd.DataFrame(q_values,columns=columns)\n\n table = dt.DataTable(\n rows=q_df.to_dict('records'),\n # optional - sets the order of columns\n columns=columns,\n row_selectable=True,\n filterable=True,\n sortable=True,\n selected_row_indices=[],\n id='datatable-lever-counts'\n )\n\n return table\n\n\n#################\n# Run Model\n#################\n@app.callback(\n dash.dependencies.Output('run-model-hidden','children'),\n [],\n [dash.dependencies.State('reward-distribution','figure'),\n dash.dependencies.State('epsilon-value', 'value'),\n dash.dependencies.State('init-q-value', 'value'),\n dash.dependencies.State('algorithm-select', 'value')],\n [Event('run-model', 'click')]\n)\ndef run_model(reward_figure,epsilon_value,init_q_value,algo_type):\n\n print(\"Running run_model task\")\n\n path_name = '{algotype}_{num_levers}_{epsilon}_{initq}.h5'.format(num_levers=len(reward_figure['data']),epsilon=epsilon_value,initq=init_q_value,algotype=algo_type)\n\n hdf_file_path = '/Users/befeltingu/RLResearch/Data/k_arm_bandit/' + path_name\n\n epochs = 1000\n\n result = k_arm_bandit.delay(hdf_file_path, reward_figure, epochs, epsilon_value,init_q_value,algo_type)\n\n dset, avg_reward, q_values, count_values = result.get()\n\n print(\"Done running model\")\n print(\"avg reward: \" + str(avg_reward))\n\n#################\n# File DataTable\n#################\n@app.callback(\n dash.dependencies.Output('datatable-file','rows'),\n [],\n [],\n [Event('fetch-files','click')]\n)\ndef populate_file_container():\n\n\n file_list = []\n for file in os.listdir('/Users/befeltingu/RLResearch/Data/k_arm_bandit/'):\n file_list.append(file)\n\n file_df = pd.DataFrame({'files':file_list})\n\n\n return file_df.to_dict('records')\n\n@app.callback(\n dash.dependencies.Output('place-holder-div','children'),\n [],\n [],\n [Event('delete-files','click')]\n)\ndef populate_file_container():\n\n for file in os.listdir('/Users/befeltingu/RLResearch/Data/k_arm_bandit/'):\n\n os.remove('/Users/befeltingu/RLResearch/Data/k_arm_bandit/' + file)\n\n return ''\n\n\n\n'''\n@app.callback(\n dash.dependencies.Output('interval-container','children'),\n [],\n [],\n [Event('run-model', 'click')]\n)\ndef run_model():\n\n return dcc.Interval(\n id='interval-component',\n interval=2 * 1000, # in milliseconds\n n_intervals=0\n )'''\n\n\n@app.callback(\n dash.dependencies.Output('model-state','children'),\n [],\n [dash.dependencies.State('model-state','children')],\n [Event('toggle-model', 'click')]\n)\ndef toggle_model(model_state):\n\n if model_state == 'stop':\n return \"start\"\n\n else:\n return \"stop\"\n\n\n\n","repo_name":"DavidRSeWell/RLDashApp","sub_path":"Dash/apps/k_arm_bandit.py","file_name":"k_arm_bandit.py","file_ext":"py","file_size_in_byte":12223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20289538607","text":"from machine import Pin, PWM\n\n\nclass HBridge:\n \"\"\" klasse H-Bridge voor het aansturen van 1 gelijkstroom motor.\n Laat de motor voorwaarts of achterwaarts draaien.\n Gebruikt PWM om de snelheid van de motor te varieren van 0 tot 100%.\n Als geen PWM gebruikt wordt is de maximale snelheid steeds 100% \"\"\"\n\n # default pwm frequentie en duty cycle\n PWM_FREQ = 60 # in Hz\n PWM_DUTY = 0 # in %\n\n # status motor\n (ONBEKEND, STOPPEN, VOORUIT, ACHTERUIT) = (-1, 0, 1, 2)\n \n \n # initialisatie H-Bridge\n def __init__(self, input_pins, pwm_pin=None):\n \"\"\":param input_pins: tuple met de 2 stuurpinnen\n :param pwm_pin: PWM pin voor de snelheid (None = geen PWM)\"\"\"\n self.snelheid = 0\n self.status = HBridge.ONBEKEND\n # Initialisatie HBridge stuurpinnen\n self.in1 = Pin(input_pins[0], Pin.OUT)\n self.in2 = Pin(input_pins[1], Pin.OUT)\n # Initialisatie PWM Enable pin voor snelheidscontrole\n # zonder PWM moet de Enable pin van de L293D hoog staan\n self.met_pwm = (pwm_pin is not None)\n if self.met_pwm:\n self.ena = PWM(Pin(pwm_pin, Pin.OUT))\n self.ena.freq(self.PWM_FREQ)\n self.ena.duty(self.pwm_waarde(self.PWM_DUTY))\n # Alles stoppen\n self.stoppen()\n\n def pwm_waarde(self, snelheid):\n # omzetten snelheid in % naar PWM waarde (0-1023)\n return int(snelheid / 100.0 * 1023.0)\n \n def zet_snelheid(self, snelheid):\n if not(0 <= snelheid <= 100):\n raise ValueError('Ongeldige snelheid')\n if self.met_pwm: # snelheid met PWM\n self.ena.duty(self.pwm_waarde(snelheid))\n self.snelheid = snelheid\n else: # zonder PWM\n if snelheid == 0:\n self.snelheid = 0\n else:\n self.snelheid = 100\n if self.snelheid == 0 and self.status != HBridge.STOPPEN:\n self.stoppen() # motor stoppen\n\n def stoppen(self):\n self.in1.low() # in1 laag\n self.in2.low() # in2 laag\n self.status = HBridge.STOPPEN # Deze 2 lijnen ...\n self.zet_snelheid(0) # niet omkeren\n\n def vooruit(self, snelheid=100):\n # HBridge herinstellen\n if self.status != HBridge.VOORUIT:\n self.stoppen()\n self.in1.low() # in1 laag\n self.in2.high() # in2 hoog\n self.status = HBridge.VOORUIT\n # snelheid instellen\n self.zet_snelheid(snelheid)\n\n def achteruit(self, snelheid=100):\n # HBridge herinstellen\n if self.status != HBridge.ACHTERUIT:\n self.stoppen()\n self.in1.high() # in1 hoog\n self.in2.low() # in2 laag\n self.status = HBridge.ACHTERUIT\n # snelheid instellen\n self.zet_snelheid(snelheid)\n\n\nclass DualHBridge():\n \"\"\" klasse Dual H-Bridge voor het aansturen van 2 gelijkstroom motoren.\n Laat de motoren voorwaarts of achterwaarts draaien.\n Gebruikt PWM om de snelheid van de motoren te varieren van 0 tot 100%.\n Als geen PWM gebruikt wordt is de maximale snelheid steeds 100% \"\"\"\n\n def __init__(self, mot1_pins, mot1_pwm, mot2_pins, mot2_pwm, afwijking=0):\n \"\"\":param mot1_pins: tuple met de 2 stuurpinnen voor motor 1\n :param mot1_pwm: PWM pin voor snelheid van motor 1 (None=geen PWM)\n :param mot2_pins: tuple met de 2 stuurpinnen voor motor 2\n :param mot2_pwm: PWM pin voor snelheid van motor 2 (None=geen PWM)\n :param afwijking: +3 om motor 1 te versnellen bij vooruit rijden\n -3 om motor 1 te vertragen bij vooruit rijden\"\"\"\n if (afwijking != 0) and ((mot1_pwm is None) or (mot2_pwm is None)):\n raise ValueError('Afwijking instelling werkt alleen met PWM')\n self.motor1 = HBridge(mot1_pins, mot1_pwm)\n self.motor2 = HBridge(mot2_pins, mot2_pwm)\n self.afwijking = afwijking\n\n def vooruit(self, snelheid=100, snelheid_2=None):\n if snelheid_2 is None: # snelheid motor 2\n snelheid_2 = snelheid # zelfde snelheid als motor 1\n # aanpassen snelheid motor1 met afwijking\n if self.afwijking > 0: # afwijking positief\n snelheid = snelheid - self.afwijking\n if snelheid < 0: # snelheid niet negatief !\n snelheid = 0\n elif self.afwijking < 0: # afwijking negatief\n snelheid_2 = snelheid_2 - abs(self.afwijking)\n if snelheid_2 < 0:\n snelheid_2 = 0 # snelheid niet negatief\n # motoren aansturen\n self.motor1.vooruit(snelheid)\n self.motor2.vooruit(snelheid_2)\n\n def achteruit(self, snelheid=100, snelheid_2=None):\n if speed_2 is None: # snelheid motor 2\n speed_2 = speed # zelfde snelheid als motor 1\n # aanpassen snelheid motor1 met afwijking\n if self.afwijking > 0: # afwijking positief\n snelheid = snelheid - self.afwijking\n if snelheid < 0: # snelheid niet negatief !\n snelheid = 0\n elif self.afwijking < 0: # afwijking negatief\n snelheid_2 = snelheid_2 - abs(self.afwijking)\n if snelheid_2 < 0:\n snelheid_2 = 0 # snelheid niet negatief\n # motoren aansturen\n self.motor1.achteruit(snelheid)\n self.motor2.achteruit(snelheid_2)\n\n def stoppen(self):\n self.motor1.stoppen()\n self.motor2.stoppen()\n","repo_name":"effevee/MicroPython_ESP8266_Projects","sub_path":"projecten/project08/dcmotor.py","file_name":"dcmotor.py","file_ext":"py","file_size_in_byte":5707,"program_lang":"python","lang":"nl","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41984189548","text":"class Solution:\n def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:\n \n ROWS, COLS = len(image), len(image[0])\n oldColor = image[sr][sc]\n if oldColor == color: return image\n def dfs(r, c):\n if image[r][c] == oldColor: \n image[r][c] = color\n if r > 0: dfs(r - 1, c)\n if r < ROWS - 1: dfs(r + 1, c)\n if c > 0: dfs(r, c - 1)\n if c < COLS - 1: dfs(r, c + 1)\n \n dfs(sr, sc)\n return image\n","repo_name":"prav10194/Python-Examples","sub_path":"733. Flood Fill/dfs_colution.py","file_name":"dfs_colution.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"42065161241","text":"import numpy as np\nimport modules as m\nfrom data_loaders import mnist\n\n\n\"\"\"\nThis file is used to test gradient descent capabilities\n\"\"\"\n\n\ndef sgd(x, dx, lr, weight_decay = 0):\n # standard sgd\n if type(x) is list:\n assert len(x) == len(dx), 'Should be the same'\n for _x, _dx in zip(x, dx):\n sgd(_x, _dx, lr)\n else:\n x -= lr * (dx + 2 * weight_decay * x)\n\n\ndef sgdm(x, dx, lr, alpha = 0.8 , state = None, weight_decay = 0):\n # sgd with momentum, standard update\n if not state:\n if type(x) is list:\n state = [None] * len(x)\n else:\n state = {}\n state['v'] = np.zeros(x.shape)\n if type(x) is list:\n for _x, _dx, _state in zip(x, dx, state):\n sgdm(_x, _dx, lr, alpha, _state)\n else:\n state['v'] *= alpha\n state['v'] += lr * (dx + 2 * weight_decay * x)\n x -= state['v']\n\n\ndef sgdmom(x, dx, lr, alpha = 0, state = None, weight_decay = 0):\n # sgd momentum, uses nesterov update (reference: http://cs231n.github.io/neural-networks-3/#sgd)\n if not state:\n if type(x) is list:\n state = [None] * len(x)\n else:\n state = {}\n state['m'] = np.zeros(x.shape)\n state['tmp'] = np.zeros(x.shape)\n if type(x) is list:\n for _x, _dx, _state in zip(x, dx, state):\n sgdmom(_x, _dx, lr, alpha, _state)\n else:\n state['tmp'] = state['m'].copy()\n state['m'] *= alpha\n state['m'] -= lr * (dx + 2 * weight_decay * x)\n\n x -= alpha * state['tmp']\n x += (1 + alpha) * state['m']\n\n\nclass TestCriterion(object):\n def __init__(self):\n return\n\n def forward(self, _input, _target):\n return np.mean(np.sum(np.abs(_input), 1))\n\n def backward(self, _input, _target):\n self._gradInput = np.sign(_input) / len(_input)\n return self._gradInput\n\n\n# the loss should decrease continuously over time\ndef test_grad_descent(model, crit, trainX, test_learning_rate):\n #params, gradParams = model.params()\n it = 0\n state = None\n while True:\n params, gradParams = model.params()\n output = model.forward(trainX)\n loss = crit.forward(output, None)\n if it % 1000 == 0:\n print(loss)\n doutput = crit.backward(output, None)\n model.backward(trainX, doutput)\n #sgdm(params, gradParams, test_learning_rate, 0.8, state)\n sgdmom(params, gradParams, lr=test_learning_rate, alpha=0, state=state)\n if it > 10000:\n break\n it += 1\n\n\ndef main():\n trainX = np.random.random((10, 5))\n crit = TestCriterion()\n test_learning_rate = 1e-4\n model = m.Sequential(\n m.Linear(5, 3),\n m.ReLU(),\n m.Dropout(),\n m.Linear(3, 1)\n )\n\n print(\"testing gradient descent of two layer model\")\n test_grad_descent(model, crit, trainX, test_learning_rate)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"j93hahn/neural-networks","sub_path":"test_framework/gradient_descent.py","file_name":"gradient_descent.py","file_ext":"py","file_size_in_byte":2951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7132528176","text":"import sqlite3\n\nconnection = sqlite3.connect('data.db')\ncursor = connection.cursor()\n\ncreate_table = \"CREATE TABLE IF NOT EXISTS articles (id INTEGER PRIMARY KEY, feed text, date text, url text, title text, description text)\"\ncursor.execute(create_table)\n\nconnection.commit()\nconnection.close()\n","repo_name":"zarak/fractionserver","sub_path":"create_tables.py","file_name":"create_tables.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37723073596","text":"\"\"\" Reinvents the OLS classifier wheel for illustrative purposes.\"\"\"\n\nimport numpy as np\nfrom typing import List\nfrom .esl_classifier import EslClassifier\n\n\nclass OLSClassifier(EslClassifier):\n \"\"\" Classifier based on OLS of one-hot class encodings.\"\"\"\n\n def __init__(self):\n\n super(OLSClassifier, self).__init__()\n\n self.__betas = None # type: List[np.ndarray]\n\n def beta(self, i_lab: int) -> np.ndarray:\n \"\"\" Returns the 2D array of OLS coefficients, shape ``(1 + n_features, n_levels)``, for one of the labels.\"\"\"\n\n return self.__betas[i_lab]\n\n def _fit(self, X: np.ndarray, G_one_hots: List[np.ndarray]) -> None:\n \"\"\" Trains the classifier.\n\n Args:\n X: numpy matrix of input features, dimensions ``(N, n_features)``.\n G_one_hots: list (one element per label) of 2d arrays of one-hot-encoded categorical values,\n dimensions ``(N, n_levels)``.\n \"\"\"\n\n # including the constant in the regression\n Xo = np.ones((self._n_fit_points, self._n_features + 1))\n Xo[:, 1:] = X\n\n # performing the regression\n cov = np.dot(Xo.T, Xo) / self._n_fit_points\n inv_cov = np.linalg.inv(cov)\n\n self.__betas = [np.dot(inv_cov, np.dot(Xo.T, G_one_hot)) for G_one_hot in G_one_hots]\n\n def _predict_level_indices(self, X: np.ndarray, i_lab: int) -> np.ndarray:\n \"\"\" Predicts the most likely levels, returning an array of level indices, for one of the labels.\"\"\"\n\n Xo = np.ones((X.shape[0], self._n_features + 1))\n Xo[:, 1:] = X\n\n Y_hat = np.dot(Xo, self.__betas[i_lab])\n return np.argmax(Y_hat, axis=1)\n","repo_name":"battarra/ESLEx","sub_path":"pyesl/ch2/ols_classifier.py","file_name":"ols_classifier.py","file_ext":"py","file_size_in_byte":1668,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"4827862462","text":"from flask import Flask,redirect,render_template,request\n\nfrom users import User\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n users = User.get_all()\n print(users)\n return render_template(\"users.html\",users=users)\n\n@app.route('/new_user/')\ndef new_user():\n return render_template(\"new_user.html\")\n\n\n@app.route('/add_user',methods=['POST'])\ndef add_user():\n print(request.form)\n data = {\n \"fname\" : request.form[\"fname\"],\n \"lname\": request.form[\"lname\"],\n \"email\": request.form[\"email\"]\n }\n\n User.save(data)\n\n return redirect('/')\n\nif __name__ == \"__main__\":\n app.run(debug=True,host='0.0.0.0',port=5500)","repo_name":"jdg24g/202306_mysql","sub_path":"OPTIONAL/usuario_cr/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74388949905","text":"from ttkbootstrap import *\nfrom ttkbootstrap.constants import *\nimport customtkinter\nfrom threading import Thread\nimport os\n\ndef run_text():\n\tos.system(\"python3 office_apps/text_docx.py\")\n\ndef run_db():\n\tos.system(\"python3 office_apps/datbase_docx.py\")\n\ndef run_table():\n\tos.system(\"python3 office_apps/table_docx.py\")\n\ndef run_press():\n\tos.system(\"python3 office_apps/press_docx.py\")\n\n\nclass App(Window):\n\n\tdef __init__(self):\n\t\tsuper().__init__(title=\"Ruffice hub\", themename=\"darkly\")\n\t\tThread(target=self.user_interface).start()\n\t\tself.themename=\"darkly\" \n\t\tself.title=\"Ruffice hub\"\n\n\tdef user_interface(self):\n\t\tself.w, self.h = self.winfo_screenwidth(), self.winfo_screenheight()\n\t\tself.geometry(\"%dx%d\" % (self.w, self.h)) \n\n\t\tself.docx = ttk.Button(master=self, text=\"Текстовый редактор\", command=lambda : self.app_run(\"text_docx\"))\n\t\tself.docx.place(x=10, y=20)\n\n\t\tself.tables = ttk.Button(master=self, text=\"Таблицы\", command=lambda : self.app_run(\"table_docx\"))\n\t\tself.tables.place(x=10, y=60)\n\n\t\tself.press = ttk.Button(master=self, text=\"Презентации\", command=lambda : self.app_run(\"press_docx\"))\n\t\tself.press.place(x=10, y=100)\n\n\t\tself.database = ttk.Button(master=self, text=\"Базы данных\", command=lambda : self.app_run(\"db_docx\"))\n\t\tself.database.place(x=10, y=140)\n\n\t\tself.exit_app = ttk.Button(master=self, text=\"Выход из офиса\", command=self.destroy)\n\t\tself.exit_app.place(x=10, y=180)\n\n\tdef app_run(self, docs_type):\n\t\tfrom functions import sub_title\n\t\t\n\t\tif docs_type == \"table_docx\":\n\t\t\tsub_title(\"Таблицы\")\n\t\t\tThread(target=run_table).start()\n\n\t\telif docs_type == \"text_docx\":\n\t\t\tsub_title(\"Текстовый редактор\")\n\t\t\tThread(target=run_text).start()\n\n\t\telif docs_type == \"press_docx\":\n\t\t\tsub_title(\"Презентации\")\n\t\t\n\t\telif docs_type == \"db_docx\":\n\t\t\tsub_title(\"Базы данных\")\n\nif __name__==\"__main__\":\n\tapp = App()\n\tapp.mainloop()","repo_name":"okolelov/okolelov","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14032469553","text":"#!/usr/bin/env python\n# coding: utf-8\n\n\n\n## CycleGAN\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim \nimport torchvision \nimport torchvision.datasets as datasets\nimport torchvision.transforms as T \nfrom torch.utils import data\n\nimport matplotlib.pyplot as plt\nimport os\nos.environ['KMP_DUPLICATE_LIB_OK']='True'\n\n\niters = 50000 \n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n\n## Data Loader\n# cycleGAN의 경우 두 가지 서로 다른 도메인의 데이터(MNIST, SVHN)가 필요\n# 모델이 학습 된 이후에는 MNIST -> SVHN��, 또는 SVHN -> MNIST로 바꿀 수 있음\ndef MNIST_DATA(root='./data/', download=True, batch_size=32):\n \n transform = T.Compose([T.Resize(32), \n T.ToTensor(),\n T.Normalize([0.5],[0.5])])\n \n mnist_train = datasets.MNIST(root = root, \n train = True, \n transform = transform,\n download = True) \n mnist_test = datasets.MNIST(root = root,\n train = False, \n transform = transform,\n download = True)\n\n trainDataLoader = data.DataLoader(dataset = mnist_train, \n batch_size = batch_size, \n shuffle =True) \n\n testDataLoader = data.DataLoader(dataset = mnist_test, \n batch_size = batch_size,\n shuffle = False) \n\n return mnist_train, mnist_test, trainDataLoader, testDataLoader\n\n\ndef SVHN_DATA(root='./data/', download =True, batch_size=32):\n\n transform = T.Compose([T.Resize(32), \n T.ToTensor(),\n T.Normalize([0.5,0.5,0.5],[0.5,0.5,0.5])])\n \n svhn_train = datasets.SVHN(root = root, \n split = 'train', # SVHN 데이터의 경우 'split' argument로 train/test를 지정\n transform = transform, \n download = True) \n\n svhn_test = datasets.SVHN(root = root,\n split = 'test', # SVHN 데이터의 경우 'split' argument로 train/test를 지정\n transform = transform,\n download = True)\n \n trainDataLoader = data.DataLoader(dataset = svhn_train, \n batch_size = batch_size, \n shuffle =True)\n\n testDataLoader = data.DataLoader(dataset = svhn_test, \n batch_size = batch_size, \n shuffle = False)\n \n return svhn_train, svhn_test, trainDataLoader, testDataLoader\n\n\nmnist_trainset, mnist_testset, mnist_trainloader, mnist_testloader = MNIST_DATA(batch_size = 4) \nsvhn_trainset, svhn_testset, svhn_trainloader, svhn_testloader = SVHN_DATA(batch_size = 4) \n\n\n## MNIST, SVHN 데이터 확인\ndef show_images_by_class(dataset, cmap=None):\n \n per_class_index = []\n try:\n labels = dataset.targets # dataset의 레이블 정보\n except:\n labels = dataset.labels \n \n for idx in range(10):\n try:\n per_class_index += [(labels == idx).nonzero()[1].item()]\n except:\n per_class_index += [(labels == idx).nonzero()[0][1].item()]\n\n images = dataset.data[torch.Tensor(per_class_index).long()]\n \n plt.figure(figsize=(16,160)) # 세로 사이즈 20, 가로 사이즈 20*10 \n \n for a in range(1, 11): \n plt.subplot(1, 10, a)\n try:\n plt.imshow(images[a-1], cmap)\n except:\n plt.imshow(images[a-1].transpose(1,2,0), cmap)\n plt.xticks([])\n plt.yticks([]) \n plt.show() \n\n\nshow_images_by_class(mnist_testset, plt.cm.gray)\n\n\nshow_images_by_class(svhn_testset)\n\n\n## Generator, Discriminator\n\n'''\n코드 단순화를 위한 함수들을 정의\n'''\n\ndef conv(c_in, c_out, k_size, stride=2, pad=1, bn=True, activation='lrelu'):\n \"\"\" \n 코드 단순화를 위한 convolution block 생성을 위한 함수\n Conv -> Batchnorm -> Activation function 으로 이어지는 일련의 레이어를 생성\n \"\"\"\n layers = []\n \n # Conv.\n layers.append(nn.Conv2d(c_in, c_out, k_size, stride, pad, bias=False))\n \n # Batchnorm\n if bn:\n layers.append(nn.BatchNorm2d(c_out))\n \n # Activation\n if activation == 'lrelu':\n layers.append(nn.LeakyReLU(0.2))\n elif activation == 'relu':\n layers.append(nn.ReLU())\n elif activation == 'tanh':\n layers.append(nn.Tanh())\n elif activation == 'none':\n pass\n \n return nn.Sequential(*layers)\n \ndef deconv(c_in, c_out, k_size, stride=2, pad=1, bn=True, activation='lrelu'):\n \"\"\" \n 코드 단순화를 위한 deconvolution block 생성을 위한 함수\n Deconv -> Batchnorm -> Activation function 으로 이어지는 일련의 레이어를 생성\n \"\"\"\n \n layers = []\n \n # Deconv.\n layers.append(nn.ConvTranspose2d(c_in, c_out, k_size, stride, pad, bias=False))\n \n # Batchnorm\n if bn:\n layers.append(nn.BatchNorm2d(c_out))\n \n # Activation\n if activation == 'lrelu':\n layers.append(nn.LeakyReLU(0.2))\n elif activation == 'relu':\n layers.append(nn.ReLU())\n elif activation == 'tanh':\n layers.append(nn.Tanh())\n elif activation == 'none':\n pass\n \n return nn.Sequential(*layers)\n\n\n'''\nGenerator와 Discriminator를 선언\nMNIST는 흑백 이미지이므로 채널이 1이고, SVHN은 컬러 이미지이므로 채널이 3이다\n'''\n\nclass Generator(nn.Module):\n \"\"\" Generator. \"\"\"\n def __init__(self, in_dim=1, out_dim=3):\n super(Generator, self).__init__()\n # encoding blocks\n self.conv1 = conv(in_dim, 64, 4)\n self.conv2 = conv(64, 64*2, 4)\n \n # intermediate blocks\n self.conv3 = conv(64*2, 64*2, 3, 1, 1)\n self.conv4 = conv(64*2, 64*2, 3, 1, 1)\n \n # decoding blocks\n self.deconv1 = deconv(64*2, 64, 4)\n self.deconv2 = deconv(64, out_dim, 4, bn=False, activation='tanh')\n \n def forward(self, x):\n out = self.conv1(x) # (B, 64, 16, 16)\n out = self.conv2(out) # (B, 128, 8, 8)\n \n out = self.conv3(out) # (B, 128, 8, 8)\n out = self.conv4(out) # (B, 128, 8, 8)\n \n out = self.deconv1(out) # (B, 64, 16, 16)\n out = self.deconv2(out) # (B, out_dim, 32, 32)\n return out\n\n\nclass Discriminator(nn.Module):\n \"\"\" Discriminator. \"\"\"\n def __init__(self, in_dim=1):\n super(Discriminator, self).__init__()\n self.conv1 = conv(in_dim, 64, 4, bn=False)\n self.conv2 = conv(64, 64*2, 4)\n self.conv3 = conv(64*2, 64*4, 4)\n self.fc = conv(64*4, 1, 4, 1, 0, bn=False, activation='none')\n \n def forward(self, x):\n out = self.conv1(x) # (B, 64, 16, 16)\n out = self.conv2(out) # (B, 128, 8, 8)\n out = self.conv3(out) # (B, 256, 4, 4)\n out = self.fc(out).squeeze()\n out = torch.sigmoid(out)\n return out\n\n\n\nG_ms = Generator(in_dim=1, out_dim=3).train().to(device)\nG_sm = Generator(in_dim=3, out_dim=1).train().to(device)\nD_m = Discriminator(in_dim=1).train().to(device)\nD_s = Discriminator(in_dim=3).train().to(device)\n\n\ng_optimizer = optim.Adam(list(G_ms.parameters()) + list(G_sm.parameters()), lr=0.0002, betas=(0.5, 0.99))\nd_optimizer = optim.Adam(list(D_m.parameters()) + list(D_s.parameters()), lr=0.0002, betas=(0.5, 0.99))\n\n\n# Fixed된 이미지를 프린팅하는 함수\ndef plot_images(images):\n print_list = []\n for i in range(2):\n print_list += [images[0][i], images[1][i], images[2][i]]\n \n for i in range(2):\n print_list += [images[3][i], images[4][i], images[5][i]] \n plt.figure(figsize=(8,14)) # 세로 사이즈 40, 가로 사이즈 20*3\n \n for a in range(1, 7):\n target_img = print_list[a-1]\n if target_img.shape[0] == 3:\n target_img = target_img.transpose(1, 2, 0)\n cmap = None\n else:\n target_img = target_img.transpose(1, 2, 0).squeeze()\n cmap = plt.cm.gray\n plt.subplot(4, 3, a)\n plt.imshow(target_img, cmap)\n plt.xticks([])\n plt.yticks([])\n for a in range(7, 13):\n target_img = print_list[a-1]\n if target_img.shape[0] == 3:\n target_img = target_img.transpose(1, 2, 0)\n cmap = None\n else:\n target_img = target_img.transpose(1, 2, 0).squeeze()\n cmap = plt.cm.gray\n plt.subplot(4, 3, a)\n plt.imshow(target_img, cmap)\n plt.xticks([])\n plt.yticks([]) \n plt.show() \n\n\n## Training CycleGAN \n''' \nloss는 크게 4가지로 나누어 짐\n- D: Real images들을 1로 분류하기 위한 loss (d_loss_real)\n- D: Fake images들을 0로 분류하기 위한 loss (d_loss_fake)\n- G: D를 속이는 Fake images들을 만들기 위한 loss (D에서 1로 분류함)(g_loss (1))\n- G: 다시 돌아 갔을 때 reconstruction을 위한 cycle loss (g_loss (2))\n'''\n\n# trainig 과정에서 생성되는 이미지가 어떻게 변화하는지 볼 수 있도록 \n# 데이터를 고정시킴\nmnist_test_iter = iter(mnist_testloader)\nsvhn_test_iter = iter(svhn_testloader)\n\n# 각 도메인별로 2개만 생성\nfixed_mnist = next(mnist_test_iter)[0][:2].to(device)\nfixed_svhn = next(svhn_test_iter)[0][:2].to(device)\n\n\nfor i in range(iters):\n \n mnist, m_labels = next(iter(mnist_trainloader)) \n svhn, s_labels = next(iter(svhn_trainloader))\n mnist = mnist.to(device)\n m_labels = m_labels.to(device)\n svhn = svhn.to(device)\n s_labels = s_labels.to(device)\n \n \n #============= Train the discriminator =============#\n\n # Real images를 통해 D를 트레이닝\n out = D_m(mnist)\n d_loss_mnist = torch.mean((out-1)**2)\n\n out = D_s(svhn)\n d_loss_svhn = torch.mean((out-1)**2)\n\n d_real_loss = d_loss_mnist + d_loss_svhn\n \n d_optimizer.zero_grad()\n d_real_loss.backward()\n d_optimizer.step()\n\n # Fake images = generated images를 통해 D를 트레이닝\n fake_svhn = G_ms(mnist)\n out = D_s(fake_svhn)\n d_loss_mnist = torch.mean(out**2)\n\n fake_mnist = G_sm(svhn)\n out = D_m(fake_mnist)\n d_loss_svhn = torch.mean(out**2)\n\n d_fake_loss = d_loss_mnist + d_loss_svhn\n \n d_optimizer.zero_grad()\n d_fake_loss.backward()\n d_optimizer.step()\n\n #=============== Train the generator ===============#\n # mnist-svhn-mnist cycle loss를 발생 시킴\n fake_svhn = G_ms(mnist)\n out = D_s(fake_svhn)\n recon_mnist = G_sm(fake_svhn)\n \n g_loss = torch.mean((out-1)**2) \n g_loss += torch.mean((mnist - recon_mnist)**2) \n \n g_optimizer.zero_grad()\n g_loss.backward()\n g_optimizer.step()\n\n # svhn-mnist-svhn loss를 발생 시킴\n fake_mnist = G_sm(svhn)\n out = D_m(fake_mnist)\n recon_svhn = G_ms(fake_mnist)\n\n g_loss = torch.mean((out-1)**2) \n g_loss += torch.mean((svhn - recon_svhn)**2) \n\n g_optimizer.zero_grad()\n g_loss.backward()\n g_optimizer.step()\n\n # print the log info\n if i % 200 == 0: \n # fixed image 로 이미지 생성\n mnist_to_svhn = G_ms(fixed_mnist)\n mnist_recon = G_sm(mnist_to_svhn) \n\n svhn_to_mnist = G_sm(fixed_svhn)\n svhn_recon = G_ms(svhn_to_mnist)\n\n print('Step[%d/%d], d_real_loss: %.4f, d_fake_loss: %.4f, g_loss: %.4f' \n %(i, iters, d_real_loss.item(), d_fake_loss.item(), g_loss.item()))\n plot_images([fixed_mnist.detach().cpu().numpy()*0.5+0.5, mnist_to_svhn.detach().cpu().numpy()*0.5+0.5, mnist_recon.detach().cpu().numpy()*0.5+0.5\n ,fixed_svhn.detach().cpu().numpy()*0.5+0.5, svhn_to_mnist.detach().cpu().numpy()*0.5+0.5, svhn_recon.detach().cpu().numpy()*0.5+0.5])\n\n\n \n","repo_name":"Hee0305/DL","sub_path":"main_CycleGAN.py","file_name":"main_CycleGAN.py","file_ext":"py","file_size_in_byte":12050,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72959912147","text":"import imghdr\nimport os\nimport tensorflow as tf\n\n# Read tfrecords and convert it into image files\nclass TFRecordExtractor:\n\tdef __init__(self, tfrecord_dir, batch_size, epochs, image_height, image_width, shuffle_size):\n\t\t(_, _, filenames) = next(os.walk(tfrecord_dir))\n\t\tfilenames = [tfrecord_dir + name for name in filenames]\n\t\tself.record_names = filenames\n\t\tself.batch_size = batch_size\n\t\tself.epochs = epochs\n\t\tself.image_height = image_height\n\t\tself.image_width = image_width\n\t\tself.shuffle_size = shuffle_size\n\n\tdef _extract_fn(self, tfrecord):\n\t\tfeatures = {\n\t\t\t# 'filename': tf.FixedLenFeature([], tf.string),\n\t\t\t'image': tf.FixedLenFeature([], tf.string),\n\t\t}\n\n\t\t# Extract the data record\n\t\tsample = tf.parse_single_example(tfrecord, features)\n\t\timage = tf.image.decode_jpeg(sample['image'], channels=3)\n\t\timage = tf.image.convert_image_dtype(image, tf.float32)\n\t\timage = tf.image.resize_images(image, [self.image_height, self.image_width])\n\n\t\treturn image\n\n\tdef extract_image(self):\n\t\t# Create folder to store extracted images\n\t\t# os.makedirs(img_out_dir, exist_ok=True)\n\n\t\t# Pipeline of dataset and iterator\n\t\tdataset = tf.data.TFRecordDataset(self.record_names)\n\t\tdataset = dataset.shuffle(self.shuffle_size, reshuffle_each_iteration=True)\n\t\tdataset = dataset.map(self._extract_fn)\n\t\tdataset = dataset.batch(self.batch_size)\n\t\tdataset = dataset.repeat(self.epochs)\n\n\t\t# create one shot iterator\n\t\titerator = tf.compat.v1.data.make_one_shot_iterator(dataset)\n\t\tnext_image_data = iterator.get_next()\n\n\t\treturn next_image_data, \"\"\n\nclass old_input:\n\tdef is_image_valid(filepath):\n\t\treturn imghdr.what(filepath) is not None\n\n\tdef get_image_paths(image_dir):\n\t\timage_paths = []\n\t\tfor root, directories, filenames in os.walk(image_dir):\n\t\t\tprint(\"filenames: \" + str(filenames[:100]))\n\t\t\timage_paths += [os.path.join(root, filename) for filename in filenames]\n\t\timage_paths = [filepath for filepath in image_paths if self.is_image_valid(filepath)]\n\n\t\treturn image_paths\n\n\n\tdef inputs(image_dir, batch_size, min_queue_examples, input_height, input_width):\n\t\tdef read_images(image_paths):\n\t\t\tfilename_queue = tf.train.string_input_producer(image_paths)\n\t\t\treader = tf.WholeFileReader()\n\t\t\tkey, value = reader.read(filename_queue)\n\t\t\timage = tf.image.decode_image(value)\n\t\t\timage = tf.image.convert_image_dtype(image, dtype=tf.float32)\n\t\t\t# understand this line\n\t\t\timage.set_shape([None, None, 3])\n\n\t\t\treturn image\n\n\t\timage_paths = self.get_image_paths(image_dir)\n\t\timages = read_images(image_paths)\n\t\timages = tf.image.crop_to_bounding_box(images, 30, 0, 178, 178)\n\t\t# images = tf.image.random_flip_left_right(images)\n\t\timages = tf.image.resize_images(images, [input_height, input_width])\n\n\t\ttotal_image_count = len(image_paths)\n\t\tinput_batch = tf.train.shuffle_batch([images],\n\t\t\t\t\t\t\t\t\t\t\t batch_size=batch_size,\n\t\t\t\t\t\t\t\t\t\t\t num_threads=16,\n\t\t\t\t\t\t\t\t\t\t\t capacity=min_queue_examples + 3 * batch_size,\n\t\t\t\t\t\t\t\t\t\t\t min_after_dequeue=min_queue_examples)\n\n\t\treturn input_batch, total_image_count\n\n\ndef inputs(file_dir, batch_size, min_queue_examples, input_height, input_width, tfrecord=False, epochs=10, shuffle_size=1000):\n\tif(tfrecord):\n\t\tt = TFRecordExtractor(file_dir, batch_size, epochs, input_height, input_width, shuffle_size)\n\t\treturn t.extract_image()\n\telse:\n\t\treturn old_input.inputs(file_dir, batch_size, min_queue_examples, input_height, input_width)\n\nif __name__ == '__main__':\n\tpass\n","repo_name":"DarkByt31/sketch-to-face","sub_path":"input.py","file_name":"input.py","file_ext":"py","file_size_in_byte":3395,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"16840108717","text":"import re\n\nPREFIX_TENSOR_NAME = 'input_'\nPREFIX_META_TENSOR_NAME = 'meta_'\n\n\nclass BaseAPI(object):\n def __init__(self, api_item_yaml):\n self.api = self.get_api_name(api_item_yaml)\n\n # inputs:\n # names : [], list of input names\n # input_info : {input_name : type}\n # attrs:\n # names : [], list of attribute names\n # attr_info : { attr_name : (type, default_values)}\n # outputs:\n # names : [], list of output names\n # types : [], list of output types\n # out_size_expr : [], expression for getting size of vector\n # return_type : Tensor, vector, ..., the return type of api\n # args_str:\n # args_declare : \"str\" // str of function params with default value. Example: (..., bool flag=false)\n # args_define : \"str\" // str of function params without default value. Example: (..., bool flag)\n self.inputs, self.attrs, self.outputs, self.args_str, self.optional_vars = self.parse_args(\n self.api, api_item_yaml)\n\n self.is_base_api = True\n if 'invoke' in api_item_yaml:\n self.is_base_api = False\n self.invoke = api_item_yaml['invoke']\n else:\n if 'infer_meta' in api_item_yaml:\n self.infer_meta = self.parse_infer_meta(api_item_yaml[\n 'infer_meta'])\n self.kernel = self.parse_kernel(api_item_yaml['kernel'])\n self.support_selected_rows_kernel = False if len(self.kernel[\n 'func']) == 1 else True\n self.data_transform = self.parse_data_transform(api_item_yaml)\n self.inplace_map, self.view_map = self.parse_inplace_and_view(\n api_item_yaml)\n\n def get_api_name(self, api_item_yaml):\n return api_item_yaml['api']\n\n def get_api_func_name(self):\n return self.api\n\n def parse_args(self, api_name, api_item_yaml):\n optional_vars = []\n if 'optional' in api_item_yaml:\n optional_vars = [\n item.strip() for item in api_item_yaml['optional'].split(',')\n ]\n inputs, attrs, args_str = self.parse_input_and_attr(\n api_name, api_item_yaml['args'], optional_vars)\n output_type_list, output_names, out_size_expr, return_type = self.parse_output(\n api_name, api_item_yaml['output'])\n return inputs, attrs, {\n 'names': output_names,\n 'types': output_type_list,\n 'out_size_expr': out_size_expr,\n 'return_type': return_type\n }, args_str, optional_vars\n\n def parse_input_and_attr(self, api_name, args_config, optional_vars=[]):\n inputs = {'names': [], 'input_info': {}}\n attrs = {'names': [], 'attr_info': {}}\n args_str = args_config.strip()\n assert args_str.startswith('(') and args_str.endswith(')'), \\\n f\"Args declaration should start with '(' and end with ')', please check the args of {api_name} in yaml.\"\n args_str = args_str[1:-1]\n args_list = args_str.split(',')\n input_types_map = {\n 'Tensor': 'const Tensor&',\n 'Tensor[]': 'const std::vector&'\n }\n attr_types_map = {\n 'IntArray': 'const IntArray&',\n 'Scalar': 'const Scalar&',\n 'Scalar(int)': 'const Scalar&',\n 'Scalar(int64_t)': 'const Scalar&',\n 'Scalar(float)': 'const Scalar&',\n 'Scalar(dobule)': 'const Scalar&',\n 'int': 'int',\n 'int32_t': 'int32_t',\n 'int64_t': 'int64_t',\n 'long': 'long',\n 'size_t': 'size_t',\n 'float': 'float',\n 'double': 'double',\n 'bool': 'bool',\n 'str': 'const std::string&',\n 'Place': 'const Place&',\n 'DataLayout': 'DataLayout',\n 'DataType': 'DataType',\n 'int64_t[]': 'const std::vector&',\n 'int[]': 'const std::vector&'\n }\n optional_types_trans = {\n 'Tensor': 'paddle::optional',\n 'Tensor[]': 'const paddle::optional>&',\n 'int': 'paddle::optional',\n 'int32_t': 'paddle::optional',\n 'int64_t': 'paddle::optional',\n 'float': 'paddle::optional',\n 'double': 'paddle::optional',\n 'bool': 'paddle::optional',\n 'Place': 'paddle::optional',\n 'DataLayout': 'paddle::optional',\n 'DataType': 'paddle::optional'\n }\n\n args_declare_str = \"\"\n args_define_str = \"\"\n\n for item in args_list:\n item = item.strip()\n type_and_name = item.split(' ')\n # match the input tensor\n has_input = False\n for in_type_symbol, in_type in input_types_map.items():\n if type_and_name[0] == in_type_symbol:\n input_name = type_and_name[1].strip()\n assert len(input_name) > 0, \\\n f\"The input tensor name should not be empty. Please check the args of {api_name} in yaml.\"\n assert len(attrs['names']) == 0, \\\n f\"The input Tensor should appear before attributes. please check the position of {api_name}:input({input_name}) in yaml\"\n\n if input_name in optional_vars:\n in_type = optional_types_trans[in_type_symbol]\n\n inputs['names'].append(input_name)\n inputs['input_info'][input_name] = in_type\n args_declare_str = args_declare_str + in_type + ' ' + input_name + ', '\n args_define_str = args_define_str + in_type + ' ' + input_name + ', '\n has_input = True\n break\n if has_input:\n continue\n\n # match the attribute\n for attr_type_symbol, attr_type in attr_types_map.items():\n if type_and_name[0] == attr_type_symbol:\n attr_name = item[len(attr_type_symbol):].strip()\n assert len(attr_name) > 0, \\\n f\"The attribute name should not be empty. Please check the args of {api_name} in yaml.\"\n default_value = None\n if '=' in attr_name:\n attr_infos = attr_name.split('=')\n attr_name = attr_infos[0].strip()\n default_value = attr_infos[1].strip()\n\n if attr_name in optional_vars:\n attr_type = optional_types_trans[attr_type_symbol]\n\n default_value_str = \"\" if default_value is None else '=' + default_value\n args_declare_str = args_declare_str + attr_type + ' ' + attr_name + default_value_str + ', '\n args_define_str = args_define_str + attr_type + ' ' + attr_name + ', '\n attrs['names'].append(attr_name)\n attrs['attr_info'][attr_name] = (attr_type, default_value)\n break\n\n return inputs, attrs, {\n 'args_declare': args_declare_str[:-2],\n 'args_define': args_define_str[:-2]\n }\n\n def parse_output(self, api_name, output_config):\n def parse_output_item(output_item):\n output_type_map = {\n 'Tensor': 'Tensor',\n 'Tensor[]': 'std::vector'\n }\n result = re.search(\n r\"(?P[a-zA-Z0-9_[\\]]+)\\s*(?P\\([a-zA-Z0-9_@]+\\))?\\s*(?P\\{[^\\}]+\\})?\",\n output_item)\n assert result is not None, f\"{api_name} : the output config parse error.\"\n out_type = result.group('out_type')\n assert out_type in output_type_map, \\\n f\"{api_name} : Output type error: the output type only support Tensor and Tensor[], \\\n but now is {out_type}.\"\n\n out_name = 'out' if result.group('name') is None else result.group(\n 'name')[1:-1]\n out_size_expr = None if result.group(\n 'expr') is None else result.group('expr')[1:-1]\n return output_type_map[out_type], out_name, out_size_expr\n\n temp_list = output_config.split(',')\n\n if len(temp_list) == 1:\n out_type, out_name, size_expr = parse_output_item(temp_list[0])\n return [out_type], [out_name], [size_expr], self.get_return_type(\n [out_type])\n else:\n out_type_list = []\n out_name_list = []\n out_size_expr_list = []\n for output_item in temp_list:\n out_type, out_name, size_expr = parse_output_item(output_item)\n out_type_list.append(out_type)\n out_name_list.append(out_name)\n out_size_expr_list.append(size_expr)\n\n return out_type_list, out_name_list, out_size_expr_list, self.get_return_type(\n out_type_list)\n\n def parse_infer_meta(self, infer_meta_config):\n infer_meta = infer_meta_config\n if 'param' not in infer_meta_config:\n infer_meta['param'] = None\n\n return infer_meta\n\n def parse_kernel(self, kernel_config):\n # kernel :\n # func : [], Kernel functions (example: scale, scale_sr)\n # param : [], Input params of kernel\n # backend : str, the names of param to choose the kernel backend, default is None\n # layout : str, the names of param to choose the kernel layout, default is None\n # data_type : str, the names of param to choose the kernel data_type, default is None\n kernel = {\n 'func': [],\n 'param': None,\n 'backend': None,\n 'layout': None,\n 'data_type': None,\n 'use_cudnn': 'false'\n }\n if 'backend' in kernel_config and len(kernel_config['backend']) > 0:\n kernel['backend'] = kernel_config['backend']\n if 'layout' in kernel_config and len(kernel_config['layout']) > 0:\n kernel['layout'] = kernel_config['layout']\n if 'data_type' in kernel_config and len(kernel_config['data_type']) > 0:\n kernel['data_type'] = kernel_config['data_type']\n if 'param' in kernel_config:\n kernel['param'] = kernel_config['param']\n if 'use_cudnn' in kernel_config:\n kernel['use_cudnn'] = kernel_config['use_cudnn']\n if isinstance(kernel['use_cudnn'], bool):\n kernel['use_cudnn'] = str(kernel['use_cudnn']).lower()\n kernel['func'] = [\n kernel_fn.strip() for kernel_fn in kernel_config['func'].split(',')\n ]\n\n if len(kernel['func']) == 2:\n assert kernel['func'][0] == self.api, \\\n f\"{self.api} : Kernel func error: If kernel has two func config, the name of first func should be same with api name({self.api}), \\\n but now is {kernel['func'][0]}.\"\n assert kernel['func'][1].endswith('_sr'), \\\n f\"{self.api} : Kernel func error: If kernel has two func config, the name of second func should be a selected_rows kernel (the func name endwith '_sr'), \\\n but now is {kernel['func'][1]}.\"\n\n return kernel\n\n def parse_data_transform(self, api_item_yaml):\n data_transform = {'skip_transform': [], 'support_trans_dtype': []}\n if 'data_transform' in api_item_yaml:\n if 'skip_transform' in api_item_yaml['data_transform']:\n data_transform['skip_transform'] = api_item_yaml[\n 'data_transform']['skip_transform']\n if 'support_trans_dtype' in api_item_yaml['data_transform']:\n data_transform['support_trans_dtype'] = api_item_yaml[\n 'data_transform']['support_trans_dtype']\n\n return data_transform\n\n def parse_inplace_and_view(self, api_item_yaml):\n inplace_map, view_map = None, None\n for mode in ['inplace', 'view']:\n if mode in api_item_yaml:\n if mode == 'inplace':\n inplace_map = {}\n else:\n view_map = {}\n in_out_mapping_list = api_item_yaml[mode].split(',')\n for item in in_out_mapping_list:\n result = re.search(r\"(?P\\w+)\\s*->\\s(?P\\w+)\", item)\n in_val = result.group('in')\n out_val = result.group('out')\n assert in_val in self.inputs['names'], \\\n f\"{self.api} : {mode} input error: the input var name('{in_val}') is not found in the input args of {self.api}.\"\n assert out_val in self.outputs['names'], \\\n f\"{self.api} : {mode} output error: the output var name('{out_val}') is not found in the output args of {self.api}.\"\n\n if mode == 'inplace':\n inplace_map[out_val] = in_val\n else:\n view_map[out_val] = in_val\n\n return inplace_map, view_map\n\n # Override by child class\n def get_return_type(self, out_type_list):\n return None\n\n def gene_api_declaration(self):\n api_declaration = f\"\"\"\nPADDLE_API {self.gene_return_type_code()} {self.get_api_func_name()}({self.args_str['args_declare']});\n\"\"\"\n\n if self.is_base_api and self.inplace_map is not None:\n api_declaration = api_declaration + f\"\"\"\nPADDLE_API {self.gene_return_type_code()} {self.get_api_func_name() + '_'}({self.args_str['args_declare']});\n\"\"\"\n\n return api_declaration\n\n # Backward API Override this method\n def gene_kernel_backend_select(self):\n backend_select_code = \"\"\n if self.kernel['backend'] is not None:\n if '>' in self.kernel['backend']:\n vars_list = self.kernel['backend'].split('>')\n assert len(\n vars_list\n ) == 2, f\"{self.api} api: The number of params to set backend with '>' only allows 2, but received {len(vars_list)}.\"\n assert (vars_list[0].strip() in self.attrs['names']) and (self.attrs['attr_info'][vars_list[0].strip()][0] == 'const Place&'), \\\n f\"{self.api} api: When use '>' to set kernel backend, the first param should be a attribute with Place type.\"\n backend_select_code = f\"\"\"\n kernel_backend = ParseBackendWithInputOrder({vars_list[0].strip()}, {vars_list[1].strip()});\n\"\"\"\n\n else:\n backend_args = [\n ele.strip() for ele in self.kernel['backend'].split(',')\n ]\n backend_select_code = f\"\"\"\n kernel_backend = ParseBackend({\", \".join(backend_args)});\n\"\"\"\n\n return backend_select_code\n\n def gene_kernel_select(self) -> str:\n api = self.api\n input_names = self.inputs['names']\n attrs = self.attrs\n kernel = self.kernel\n\n kernel_key_item_init = \"\"\"\n Backend kernel_backend = Backend::UNDEFINED;\n DataLayout kernel_layout = DataLayout::UNDEFINED;\n DataType kernel_data_type = DataType::UNDEFINED;\n\"\"\"\n # Check the tensor options\n attr_backend_count = 0\n attr_layout_count = 0\n attr_data_type_count = 0\n for attr_name in attrs['names']:\n if attrs['attr_info'][attr_name][0] == 'const Place&':\n assert kernel['backend'] is not None, \\\n f\"{api} api: When there is a parameter with 'Place' type in attributes, you must set backend of kernel manually.\"\n attr_backend_count = attr_backend_count + 1\n if attrs['attr_info'][attr_name][0] == 'DataLayout':\n assert kernel['layout'] is not None, \\\n f\"{api} api: When there is a parameter with 'DataLayout' type in attributes, you must set layout of kernel manually.\"\n attr_layout_count = attr_layout_count + 1\n if attrs['attr_info'][attr_name][0] == 'DataType':\n assert kernel['data_type'] is not None, \\\n f\"{api} api: When there is a parameter with 'DataType' type in attributes, you must set data_type of kernel manually.\"\n attr_data_type_count = attr_data_type_count + 1\n\n # preprocess kernel configures\n kernel_select_code = self.gene_kernel_backend_select()\n\n if kernel['layout'] is not None:\n if '>' in kernel['layout']:\n vars_list = kernel['layout'].split('>')\n assert len(\n vars_list\n ) == 2, f\"{api} api: The number of params to set layout with '>' only allows 2, but received {len(vars_list)}.\"\n assert vars_list[0].strip() in attrs['names'] and attrs['attr_info'][vars_list[0].strip()][0] == 'DataLayout', \\\n f\"{api} api: When use '>' to set kernel layout, the first param should be a attribute with DataLayout type.\"\n kernel_select_code = kernel_select_code + f\"\"\"\n kernel_layout = ParseLayoutWithInputOrder({vars_list[0].strip()}, {vars_list[1].strip()});\n\"\"\"\n\n else:\n vars_list = kernel['layout'].split(',')\n assert len(\n vars_list\n ) == 1, f\"{api} api: The number of params to set layout must be 1, but received {len(vars_list)}.\"\n kernel_select_code = kernel_select_code + f\"\"\"\n kernel_layout = ParseLayout({vars_list[0].strip()});\n\"\"\"\n\n if kernel['data_type'] is not None:\n if '>' in kernel['data_type']:\n vars_list = kernel['data_type'].split('>')\n assert len(\n vars_list\n ) == 2, f\"{api} api: The number of params to set data_type with '>' only allows 2, but received {len(vars_list)}.\"\n assert vars_list[0].strip() in attrs['names'] and attrs['attr_info'][vars_list[0].strip()][0] == 'DataType', \\\n f\"{api} api: When use '>' to set kernel data_type, the first param should be a attribute with DataType type.\"\n kernel_select_code = kernel_select_code + f\"\"\"\n kernel_data_type = ParseDataTypeWithInputOrder({vars_list[0].strip()}, {vars_list[1].strip()});\n\"\"\"\n\n else:\n vars_list = kernel['data_type'].split(',')\n assert len(\n vars_list\n ) == 1, f\"{api} api: The number of params to set data_type only allows 2, but received {len(vars_list)}.\"\n kernel_select_code = kernel_select_code + f\"\"\"\n kernel_data_type = ParseDataType({vars_list[0].strip()});\n\"\"\"\n\n if len(input_names) == 0:\n assert attr_backend_count > 0 and attr_data_type_count > 0, \\\n f\"{api} api: When there is no input tensor, the args must have 'Place' and 'DataType'.\"\n\n kernel_select_args = \"\"\n for input_name in input_names:\n kernel_select_args = kernel_select_args + input_name + \", \"\n\n if len(kernel_select_args) > 2:\n kernel_select_args = kernel_select_args[:-2]\n\n kernel_select_code = kernel_key_item_init + kernel_select_code\n\n if len(input_names) > 0:\n if self.support_selected_rows_kernel:\n kernel_select_code = kernel_select_code + f\"\"\"\n KernelType kernel_type = ParseKernelTypeByInputArgs({\", \".join(input_names)});\n\"\"\"\n\n kernel_select_code = kernel_select_code + f\"\"\"\n if (kernel_backend == Backend::UNDEFINED\n || kernel_layout == DataLayout::UNDEFINED\n || kernel_data_type == DataType::UNDEFINED ) {{\n auto kernel_key_set = ParseKernelKeyByInputArgs({kernel_select_args});\n auto kernel_key = kernel_key_set.GetHighestPriorityKernelKey();\n if (kernel_backend == Backend::UNDEFINED) {{\n kernel_backend = kernel_key.backend();\n }}\n if (kernel_layout == DataLayout::UNDEFINED) {{\n kernel_layout = kernel_key.layout();\n }}\n if (kernel_data_type == DataType::UNDEFINED) {{\n kernel_data_type = kernel_key.dtype();\n }}\n }}\"\"\"\n\n return kernel_select_code\n\n def gene_infer_meta(self, kernel_output_names, code_indent) -> str:\n input_names = self.inputs['names']\n attr_names = self.attrs['names']\n infer_meta = self.infer_meta\n\n infer_meta_params = infer_meta['param'] if infer_meta[\n 'param'] is not None else input_names + attr_names\n # generate meta tensors\n meta_tensor_code = \"\"\n param_code = \"\"\n for param in infer_meta_params:\n if param in input_names:\n if self.inputs['input_info'][param] == \"const Tensor&\":\n param_code = param_code + \"MakeMetaTensor(*\" + PREFIX_TENSOR_NAME + param + \"), \"\n elif self.inputs['input_info'][\n param] == \"const std::vector&\":\n meta_tensor_code = meta_tensor_code + f\"\"\"\n{code_indent} auto {param}_meta_vec = MakeMetaTensor({PREFIX_TENSOR_NAME}{param});\n{code_indent} std::vector {param}_metas({param}_meta_vec.size());\n{code_indent} for (size_t i = 0; i < {param}_meta_vec.size(); ++i) {{\n{code_indent} {param}_metas[i] = &{param}_meta_vec[i];\n{code_indent} }}\n\"\"\"\n\n param_code = param_code + param + \"_metas, \"\n elif param in self.optional_vars:\n meta_tensor_code = meta_tensor_code + f\"\"\"\n{code_indent} paddle::optional {PREFIX_TENSOR_NAME}meta_ref_{param} = paddle::none;\n{code_indent} phi::DenseTensor {param}_dt;\n{code_indent} phi::MetaTensor {PREFIX_TENSOR_NAME}meta_tmp_{param}({param}_dt);\n{code_indent} if ({PREFIX_TENSOR_NAME}{param}_ptr) {{\n{code_indent} {PREFIX_TENSOR_NAME}meta_tmp_{param}.set_dtype( {PREFIX_TENSOR_NAME}{param}_ptr->dtype() );\n{code_indent} {PREFIX_TENSOR_NAME}meta_tmp_{param}.set_dims( {PREFIX_TENSOR_NAME}{param}_ptr->dims() );\n{code_indent} {PREFIX_TENSOR_NAME}meta_tmp_{param}.set_layout( {PREFIX_TENSOR_NAME}{param}_ptr->layout() );\n{code_indent} {PREFIX_TENSOR_NAME}meta_ref_{param} = {PREFIX_TENSOR_NAME}meta_tmp_{param};\n{code_indent} }}\\n\"\"\"\n\n param_code = param_code + f\"{PREFIX_TENSOR_NAME}meta_ref_{param}, \"\n else:\n raise ValueError(\n f\"{self.api} : Param of infer_meta error : {self.inputs['input_info'][param]} type is not supported.\"\n )\n elif param in attr_names:\n param_code = param_code + param + \", \"\n elif isinstance(param, str):\n param_code = param_code + \"\\\"\" + param + \"\\\", \"\n elif isinstance(param, bool):\n param_code = param_code + str(param).lower() + \", \"\n else:\n param_code = param_code + str(param) + \", \"\n\n for i, out_name in enumerate(kernel_output_names):\n if self.outputs['types'][i] == 'std::vector':\n meta_tensor_code = meta_tensor_code + f\"\"\"\n{code_indent} auto {out_name}_{PREFIX_META_TENSOR_NAME}vec = MakeMetaTensor({out_name});\n{code_indent} std::vector {out_name}_metas({out_name}_{PREFIX_META_TENSOR_NAME}vec.size());\n{code_indent} for (size_t i = 0; i < {out_name}_{PREFIX_META_TENSOR_NAME}vec.size(); ++i) {{\n{code_indent} {out_name}_metas[i] = &{out_name}_{PREFIX_META_TENSOR_NAME}vec[i];\n{code_indent} }}\"\"\"\n\n param_code = param_code + out_name + '_metas, '\n else:\n meta_tensor_code = meta_tensor_code + code_indent + \" phi::MetaTensor \" + out_name.replace(\n 'kernel_',\n PREFIX_META_TENSOR_NAME) + \"(\" + out_name + \");\\n\"\n param_code = param_code + \"&\" + out_name.replace(\n 'kernel_', PREFIX_META_TENSOR_NAME) + \", \"\n\n param_code = param_code[:-2]\n return f\"\"\"{meta_tensor_code}\n{code_indent} phi::{infer_meta['func']}({param_code});\n\"\"\"\n\n def get_kernel_args(self, code_indent):\n input_trans_map = {\n 'const Tensor&': 'const phi::DenseTensor&',\n 'const std::vector&':\n 'const std::vector&',\n 'const paddle::optional':\n 'paddle::optional',\n 'paddle::optional':\n 'paddle::optional',\n 'const paddle::optional>&':\n 'paddle::optional&>'\n }\n out_trans_map = {\n 'Tensor': 'phi::DenseTensor*',\n 'std::vector': 'std::vector&'\n }\n input_names = self.inputs['names']\n input_infos = self.inputs['input_info']\n kernel_args_type_list = ['const platform::DeviceContext&']\n\n attr_names = self.attrs['names']\n kernel_param = self.kernel['param']\n if kernel_param is None:\n kernel_param = input_names + attr_names\n\n input_tensor_code = \"\"\n kernel_idx = -1\n for i, input_name in enumerate(input_names):\n # set input code\n if input_name in kernel_param:\n kernel_idx = kernel_idx + 1\n trans_flag = \"{}\"\n if input_name in self.data_transform['skip_transform']:\n trans_flag = \"{true}\"\n elif input_name in self.data_transform['support_trans_dtype']:\n trans_flag = \"{false, true}\"\n if input_name in self.optional_vars:\n input_tensor_code = input_tensor_code + f\"\"\"\n{code_indent} {input_trans_map[input_infos[input_name]]} {PREFIX_TENSOR_NAME}{input_name}(paddle::none);\n{code_indent} auto {PREFIX_TENSOR_NAME}{input_name}_ptr = PrepareData({input_name}, kernel.InputAt({kernel_idx}), {trans_flag});\n{code_indent} if ({PREFIX_TENSOR_NAME}{input_name}_ptr) {{\n{code_indent} {PREFIX_TENSOR_NAME}{input_name} = paddle::make_optional(*{PREFIX_TENSOR_NAME}{input_name}_ptr);\n{code_indent} }}\"\"\"\n\n else:\n if self.inputs['input_info'][input_name] == \"const Tensor&\":\n input_tensor_code = input_tensor_code + f\"\"\"\n{code_indent} auto {PREFIX_TENSOR_NAME}{input_name} = PrepareData({input_name}, kernel.InputAt({kernel_idx}), {trans_flag});\"\"\"\n\n elif self.inputs['input_info'][\n input_name] == \"const std::vector&\":\n input_tensor_code = input_tensor_code + f\"\"\"\n{code_indent} auto {PREFIX_TENSOR_NAME}{input_name}_vec = PrepareData({input_name}, kernel.InputAt({kernel_idx}), {trans_flag});\n{code_indent} std::vector {PREFIX_TENSOR_NAME}{input_name}({PREFIX_TENSOR_NAME}{input_name}_vec->size());\n{code_indent} for (size_t i = 0; i < {PREFIX_TENSOR_NAME}{input_name}.size(); ++i) {{\n{code_indent} {PREFIX_TENSOR_NAME}{input_name}[i] = &{PREFIX_TENSOR_NAME}{input_name}_vec->at(i);\n{code_indent} }}\"\"\"\n\n else:\n # do nothing\n pass\n elif self.infer_meta[\n 'param'] is None or input_name in self.infer_meta['param']:\n if input_name in self.optional_vars:\n input_tensor_code = input_tensor_code + f\"\"\"\n{code_indent} {input_trans_map[input_infos[input_name]]} {PREFIX_TENSOR_NAME}{input_name}(paddle::none);\n{code_indent} auto {PREFIX_TENSOR_NAME}{input_name}_ptr = TensorToDenseTensor({input_name});\n{code_indent} if ({PREFIX_TENSOR_NAME}{input_name}_ptr) {{\n{code_indent} {PREFIX_TENSOR_NAME}{input_name} = paddle::make_optional(*{PREFIX_TENSOR_NAME}{input_name}_ptr);\n{code_indent} }}\"\"\"\n\n else:\n input_tensor_code = input_tensor_code + f\"\"\"\n{code_indent} auto {PREFIX_TENSOR_NAME}{input_name} = TensorToDenseTensor({input_name});\"\"\"\n\n kernel_args = \"*dev_ctx, \"\n for param in kernel_param:\n if param in input_names:\n if param in self.optional_vars:\n kernel_args = kernel_args + PREFIX_TENSOR_NAME + param + \", \"\n else:\n if self.inputs['input_info'][param] == \"const Tensor&\":\n kernel_args = kernel_args + \"*\" + PREFIX_TENSOR_NAME + param + \", \"\n elif self.inputs['input_info'][\n param] == \"const std::vector&\":\n kernel_args = kernel_args + PREFIX_TENSOR_NAME + param + \", \"\n else:\n # do nothing\n pass\n kernel_in_type = input_trans_map[input_infos[param]]\n kernel_args_type_list.append(kernel_in_type)\n elif param in attr_names:\n # set attr for kernel_context\n if 'IntArray' in self.attrs['attr_info'][param][0]:\n kernel_args_type_list.append('const phi::IntArray&')\n param = 'phi::IntArray(' + param + ')'\n elif 'Scalar' in self.attrs['attr_info'][param][0]:\n kernel_args_type_list.append('const phi::Scalar&')\n param = 'phi::Scalar(' + param + ')'\n else:\n kernel_args_type_list.append(self.attrs['attr_info'][param][\n 0])\n kernel_args = kernel_args + param + \", \"\n elif isinstance(param, bool):\n kernel_args = kernel_args + str(param).lower() + \", \"\n else:\n kernel_args = kernel_args + str(param) + \", \"\n\n for out_type in self.outputs['types']:\n kernel_args_type_list.append(out_trans_map[out_type])\n\n kernel_signature = \"void(*)(\" + \", \".join(kernel_args_type_list) + \")\"\n\n return input_tensor_code, kernel_args[:-2], kernel_signature\n\n def get_selected_rows_kernel_args(self, code_indent):\n input_trans_map = {\n 'const Tensor&': 'const phi::SelectedRows&',\n 'const paddle::optional&':\n 'paddle::optional'\n }\n out_trans_map = {'Tensor': 'phi::SelectedRows*'}\n input_names = self.inputs['names']\n input_infos = self.inputs['input_info']\n kernel_args_type_list = ['const platform::DeviceContext&']\n\n attr_names = self.attrs['names']\n kernel_param = self.kernel['param']\n if kernel_param is None:\n kernel_param = input_names + attr_names\n\n input_tensor_code = \"\"\n for i, input_name in enumerate(input_names):\n # set input code\n if input_name in self.optional_vars:\n input_tensor_code = input_tensor_code + f\"\"\"\n\n{code_indent} {input_trans_map[input_infos[input_name]]} {PREFIX_TENSOR_NAME}{input_name}(paddle::none);\n{code_indent} auto {PREFIX_TENSOR_NAME}{input_name}_ptr = TensorToSelectedRows({input_name});\n{code_indent} if ({PREFIX_TENSOR_NAME}{input_name}_ptr) {{\n{code_indent} {PREFIX_TENSOR_NAME}{input_name} = paddle::make_optional(*{PREFIX_TENSOR_NAME}{input_name}_ptr);\n{code_indent} }}\"\"\"\n\n else:\n input_tensor_code = input_tensor_code + f\"\"\"\n{code_indent} auto {PREFIX_TENSOR_NAME}{input_name} = TensorToSelectedRows({input_name});\"\"\"\n\n kernel_args = \"*dev_ctx, \"\n for param in kernel_param:\n if param in input_names:\n if param in self.optional_vars:\n kernel_args = kernel_args + PREFIX_TENSOR_NAME + param + \", \"\n else:\n kernel_args = kernel_args + \"*\" + PREFIX_TENSOR_NAME + param + \", \"\n kernel_in_type = input_trans_map[input_infos[param]]\n kernel_args_type_list.append(kernel_in_type)\n elif param in attr_names:\n # set attr for kernel_context\n if 'IntArray' in self.attrs['attr_info'][param][0]:\n kernel_args_type_list.append('const phi::IntArray&')\n param = 'phi::IntArray(' + param + ')'\n elif 'Scalar' in self.attrs['attr_info'][param][0]:\n kernel_args_type_list.append('const phi::Scalar&')\n param = 'phi::Scalar(' + param + ')'\n else:\n kernel_args_type_list.append(self.attrs['attr_info'][param][\n 0])\n kernel_args = kernel_args + param + \", \"\n elif isinstance(param, bool):\n kernel_args = kernel_args + str(param).lower() + \", \"\n else:\n kernel_args = kernel_args + str(param) + \", \"\n\n for out_type in self.outputs['types']:\n kernel_args_type_list.append(out_trans_map[out_type])\n\n kernel_signature = \"void(*)(\" + \", \".join(kernel_args_type_list) + \")\"\n\n return input_tensor_code, kernel_args[:-2], kernel_signature\n\n # Override by child class\n def gene_return_type_code(self):\n return self.outputs['return_type']\n\n # Override by child class\n def gene_return_code(self):\n return \"api_output\"\n\n # Override by child class\n def gene_output(self,\n output_type_list,\n set_out_func,\n code_indent,\n inplace_flag=False):\n return None, None, None\n\n def gen_dense_tensor_kernel_code(self, code_indent, inplace_flag=False):\n input_tensors, kernel_args, kernel_signature = self.get_kernel_args(\n code_indent)\n outputs_args, kernel_output_names, output_create = self.gene_output(\n self.outputs['types'], 'SetKernelOutput', code_indent, inplace_flag)\n api_func_name = self.get_api_func_name() + ('_' if inplace_flag else '')\n cudnn_args = '' if self.kernel[\n 'use_cudnn'] == 'false' else ', ' + self.kernel['use_cudnn']\n return f\"\"\"\n{code_indent} VLOG(6) << \"{self.api} API kernel key: [\" << kernel_backend << \", \" << kernel_layout << \", \"<< kernel_data_type << \"]\";\n{code_indent} const auto& kernel = phi::KernelFactory::Instance().SelectKernelOrThrowError(\n{code_indent} \"{self.kernel['func'][0]}\", {{kernel_backend, kernel_layout, kernel_data_type}}{cudnn_args});\n{code_indent} VLOG(6) << \"{self.api} API kernel: \" << kernel;\n\n{code_indent} auto* dev_ctx = GetDeviceContextByBackend(kernel_backend);\n{input_tensors}\n{output_create}\n{self.gene_infer_meta(kernel_output_names, code_indent)}\n\n{code_indent} using kernel_signature = {kernel_signature};\n{code_indent} auto* kernel_fn = kernel.GetVariadicKernelFn();\n{code_indent} {{\n{code_indent} paddle::platform::RecordEvent kernel_record_event(\\\"{api_func_name} compute\\\", paddle::platform::TracerEventType::OperatorInner, 1);\n{code_indent} (*kernel_fn)({kernel_args}, {outputs_args});\n{code_indent} }}\n\n{code_indent} return {self.gene_return_code()};\"\"\"\n\n def gen_selected_rows_kernel_code(self, code_indent, inplace_flag=False):\n input_tensors, kernel_args, kernel_signature = self.get_selected_rows_kernel_args(\n code_indent)\n outputs_args, kernel_output_names, output_create = self.gene_output(\n self.outputs['types'], 'SetSelectedRowsKernelOutput', code_indent,\n inplace_flag)\n api_func_name = self.get_api_func_name() + ('_' if inplace_flag else '')\n return f\"\"\"\n{code_indent} auto kernel = phi::KernelFactory::Instance().SelectKernelOrThrowError(\n{code_indent} \"{self.kernel['func'][1]}\", {{kernel_backend, kernel_layout, kernel_data_type}});\n{code_indent} VLOG(6) << \"{self.api} API SelectedRows kernel key: [\" << kernel_backend << \", \" << kernel_layout << \", \"<< kernel_data_type << \"]\";\n{code_indent} VLOG(6) << \"{self.api} API SelectedRows kernel: \" << kernel;\n\n{code_indent} auto* dev_ctx = GetDeviceContextByBackend(kernel_backend);\n{input_tensors}\n{output_create}\n{self.gene_infer_meta(kernel_output_names, code_indent)}\n\n{code_indent} using kernel_signature = {kernel_signature};\n{code_indent} auto* kernel_fn = kernel.GetVariadicKernelFn();\n{code_indent} {{\n{code_indent} paddle::platform::RecordEvent kernel_record_event(\\\"{api_func_name} compute\\\", paddle::platform::TracerEventType::OperatorInner, 1);\n{code_indent} (*kernel_fn)({kernel_args}, {outputs_args});\n{code_indent} }}\n\n{code_indent} return {self.gene_return_code()};\"\"\"\n\n def gene_base_api_code(self, inplace_flag=False):\n api_func_name = self.get_api_func_name() + ('_' if inplace_flag else '')\n api_code = f\"\"\"\nPADDLE_API {self.gene_return_type_code()} {api_func_name}({self.args_str[\"args_define\"]}) {{\n{self.gene_kernel_select()}\n\"\"\"\n\n if self.support_selected_rows_kernel:\n code_indent = ' '\n return api_code + f\"\"\"\n if(kernel_type == KernelType::DENSE_TENSOR_KENREL){{\n{self.gen_dense_tensor_kernel_code(code_indent, inplace_flag)}\n }} else {{\n{self.gen_selected_rows_kernel_code(code_indent, inplace_flag)}\n }}\n}}\n\"\"\"\n\n else:\n code_indent = ''\n return api_code + self.gen_dense_tensor_kernel_code(\n code_indent, inplace_flag) + \"\"\"\n}\n\"\"\"\n\n def gene_api_code(self):\n if self.is_base_api:\n api_code = self.gene_base_api_code()\n if self.inplace_map is not None:\n api_code = api_code + self.gene_base_api_code(inplace_flag=True)\n return api_code\n\n else:\n inveke_func_name = self.invoke.split('(')[0].strip()\n if inveke_func_name in self.attrs['names']:\n # Adjust the param whose name is same with api invoked.\n pattern = r'\\W' + inveke_func_name + '[^A-Za-z0-9_(]'\n\n def adjust_name(matched):\n matched_str = matched.group()\n return matched_str[0:-1] + '_val' + matched_str[-1]\n\n invoke_code = re.sub(pattern, adjust_name, self.invoke)\n params_code = re.sub(pattern, adjust_name,\n self.args_str[\"args_define\"])\n else:\n invoke_code = self.invoke\n params_code = self.args_str[\"args_define\"]\n return f\"\"\"\n{self.outputs['return_type']} {self.api}({params_code}) {{\n return {invoke_code};\n}}\n\"\"\"\n","repo_name":"EnnSou/ooss-paddle2.3","sub_path":"python/paddle/utils/code_gen/api_base.py","file_name":"api_base.py","file_ext":"py","file_size_in_byte":38653,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"17130066361","text":"import time\r\nimport csv\r\nfrom selenium import webdriver\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\n\r\nurl = 'https://en.wikipedia.org/wiki/List_of_brown_dwarfs'\r\nbrowser = webdriver.Chrome('chromedriver.exe')\r\nbrowser.get(url)\r\ntime.sleep(10)\r\n\r\nheaders = ['star' , 'constellation' , 'right ascension' , 'Declination' , 'app. mag.' , 'distance' , 'spectral_type' , 'brown dwarf' , 'mass' , 'radius' , 'orbital period' , 'smimajor axis', 'eccentricity' , 'discovery year' , 'luminosity' , 'surface gravity' , 'temperature' , 'metallicity' , 'rotation' , 'age']\r\nstarData = []\r\nnewStarData = []\r\n\r\ndef scrape():\r\n\r\n for i in range(1 , 201):\r\n while True: \r\n time.sleep(2)\r\n \r\n soup = BeautifulSoup(browser.page_source , 'html.parser')\r\n\r\n currentPageNumber = int(soup.find_all('input' , attrs = {'class' , 'page_num'})[0].get('value'))\r\n\r\n if currentPageNumber > i:\r\n browser.find_element_by_xpath('//*[@id=\"primary_column\"]/footer/div/div/div/nav/span[2]/a').click()\r\n \r\n elif currentPageNumber < i:\r\n browser.find_element_by_xpath('//*[@id=\"primary_column\"]/footer/div/div/div/nav/span[1]/a').click()\r\n\r\n else:\r\n break\r\n\r\n for ulTag in soup.find_all('ul' , attrs = {'class' , 'dwarf star'}):\r\n liTag = ulTag.find_all('li')\r\n tempList = []\r\n \r\n for index , li in enumerate(liTag):\r\n if index == 0:\r\n tempList.append(li.find_all('a')[0].contents[0])\r\n else:\r\n try:\r\n tempList.appned(li.contents[0])\r\n except:\r\n tempList.append(\"\")\r\n \r\n hyperlinkLiTag = liTag[0]\r\n tempList.append(\"https://en.wikipedia.org/wiki/List_of_brown_dwarfs\" + hyperlinkLiTag.find_all('a' , href = True)[0]['href'])\r\n\r\n starData.append(tempList)\r\n\r\n browser.find_element_by_xpath('//*[@id=\"primary_column\"]/footer/div/div/div/nav/span[2]/a').click()\r\n\r\ndef scrapeMoreData(hyperlink):\r\n\r\n try:\r\n page = requests.get(hyperlink)\r\n soup = BeautifulSoup(page.content , 'html.parser')\r\n tempList = []\r\n\r\n for tr in soup.find_all('tr' , attrs = {'class' , 'details'}):\r\n td = tr.find_all('td')\r\n\r\n for tdTag in td:\r\n try:\r\n tempList.append(tdTag.find_all('div' , attrs = {'class' , 'value'})[0].contents[0])\r\n except:\r\n tempList.append('')\r\n \r\n newStarData.append(tempList)\r\n\r\n except:\r\n time.sleep(1)\r\n scrapeMoreData(hyperlink)\r\n \r\nscrape()\r\n\r\nfor index , i in enumerate(planetData):\r\n scrapeMoreData(i[5])\r\n\r\nfinalStarData = []\r\n\r\nfor index , j in enumerate(planetData):\r\n newData = newPlanetData[index]\r\n newData = [new.replace('\\n' , '') for new in newData ]\r\n newData = newData[:7]\r\n\r\n finalStarData.append(j + newData)\r\n\r\nwith open('final.csv' , 'w') as f:\r\n csvWriter = csv.writer(f)\r\n csvWriter.writeRow(headers)\r\n csvWriter.writeRows(finalStarData)\r\n\r\n\r\n","repo_name":"Shubham09876/Project-128","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3083,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7705952701","text":"#!/usr/bin/env python\nimport rospy\nimport numpy as np\nimport time\nimport math as m\n\nfrom geometry_msgs.msg import Point\nfrom path_planning.msg import PathCoordinates\nfrom nav_msgs.msg import Odometry\n\nclass SetpointPublisher:\n def __init__(self, name):\n rospy.init_node(name)\n\n self.setpointVectorX = []\n self.setpointVectorY = []\n\n self.current_position = [0, 0]\n\n self.setpoint_distance = 15\n\n # PUBLISHER:\n self.pub_setPoint= rospy.Publisher(\"pathPlanning/setpoints2goal\", Point, queue_size=1)\n\n # SUBSCRIBER:\n rospy.Subscriber(\"path/coordinates\", PathCoordinates, self.path_callback, queue_size=1)\n rospy.Subscriber(\"/ground_truth/state\", Odometry, self.ground_truth_callback, queue_size=1)\n\n def ground_truth_callback(self, msg):\n self.current_position = np.array([msg.pose.pose.position.x, msg.pose.pose.position.y])*100\n\n def path_callback(self, msg):\n self.setpointVectorX = msg.x_array\n self.setpointVectorY = msg.y_array\n\n def calculate_setpoint(self):\n if len(self.setpointVectorX) == len(self.setpointVectorY):\n for i in reversed(range(len(self.setpointVectorX))):\n if self.setpoint_distance >= np.linalg.norm(np.array(self.current_position[0:2]) - np.array([self.setpointVectorX[i], self.setpointVectorY[i]])):\n setPoint = Point()\n setPoint.x = self.setpointVectorX[i]/100\n setPoint.y = self.setpointVectorY[i]/100 \n self.pub_setPoint.publish(setPoint)\n # print(\"setPoint : \")\n # print(setPoint)\n break\n\n def run(self):\n rate = rospy.Rate(20.0)\n while not rospy.is_shutdown():\n self.calculate_setpoint()\n rate.sleep()\n\n\nif __name__ == \"__main__\":\n node = SetpointPublisher(\"SetpointPublisher\")\n node.run()\n","repo_name":"adamanov/TUHH_FaV","sub_path":"src/path_planning/nodes/setpoint_publisher.py","file_name":"setpoint_publisher.py","file_ext":"py","file_size_in_byte":1952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17283468989","text":"# app/user/user_routes.py\r\n# app/user/user_routes.py\r\nimport os\r\nimport streamlit as st\r\nfrom db.database import create_connection, save_assignment\r\nfrom datetime import datetime\r\nfrom analyzer.utility import utility\r\n\r\nimport PyPDF2\r\nfrom io import BytesIO\r\ntimestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\r\n\r\nUPLOADS_PATH = \"uploads\"\r\n# app/user/user_routes.py\r\n\r\n# ... (previous imports)\r\ndef user_home():\r\n st.title(\"Student's Submission page \")\r\n st.write(\"Welcome to the Submission Home !\")\r\n # Add a form for users to input their name, enrollment number, topic, and submit their assignment\r\n\r\n name = st.text_input(\"Enter your name:\")\r\n enrollment_number = st.text_input(\"Enter your enrollment number:\")\r\n topic = st.text_input(\"Enter the topic of your assignment:\")\r\n \r\n uploaded_file = st.file_uploader(\"Upload your assignment file\", type=[\"pdf\", \"docx\"])\r\n destination=None\r\n\r\n if st.button(\"Submit Assignment\"):\r\n if name and enrollment_number and topic and uploaded_file:\r\n # Save the assignment to the file system\r\n folder_name = f\"{name}_{enrollment_number}\"\r\n save_path = os.path.join(UPLOADS_PATH, folder_name)\r\n # Create the directory if it doesn't exist\r\n os.makedirs(save_path, exist_ok=True)\r\n file_path = os.path.join(save_path, uploaded_file.name)\r\n with open(file_path, \"wb\") as f:\r\n f.write(uploaded_file.read())\r\n destination = file_path\r\n # Save assignment details to the database\r\n conn = create_connection()\r\n if conn:\r\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\r\n save_assignment(conn, name, enrollment_number, topic, file_path, timestamp)\r\n conn.close()\r\n st.success(f\"Assignment submitted successfully, {name}! Enrollment Number: {enrollment_number}, Topic: {topic}\")\r\n st.balloons()\r\n else:\r\n st.warning(\"Please fill in all the details and upload your assignment.\")\r\n \r\n if(destination is not None):\r\n ss = utility()\r\n result = ss.analyze_sentiment(destination,name,enrollment_number,name)\r\n \r\n ","repo_name":"shadowfaxx1/Assignment-Evaluator","sub_path":"user/user_routes.py","file_name":"user_routes.py","file_ext":"py","file_size_in_byte":2242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28992121841","text":"import mitsuba\nimport pytest\nimport enoki as ek\nfrom enoki.dynamic import Float32 as Float\n\nfrom mitsuba.python.test.util import fresolver_append_path\nfrom mitsuba.python.util import traverse\n\n\ndef test01_create_mesh(variant_scalar_rgb):\n from mitsuba.core import Struct, float_dtype\n from mitsuba.render import Mesh\n\n m = Mesh(\"MyMesh\", 3, 2)\n m.vertex_positions_buffer()[:] = [0.0, 0.0, 0.0, 1.0, 0.2, 0.0, 0.2, 1.0, 0.0]\n m.faces_buffer()[:] = [0, 1, 2, 1, 2, 0]\n m.parameters_changed()\n\n assert str(m) == \"\"\"Mesh[\n name = \"MyMesh\",\n bbox = BoundingBox3f[\n min = [0, 0, 0],\n max = [1, 1, 0]\n ],\n vertex_count = 3,\n vertices = [36 B of vertex data],\n face_count = 2,\n faces = [24 B of face data],\n disable_vertex_normals = 0,\n surface_area = 0.96\n]\"\"\"\n\n\n@fresolver_append_path\ndef test02_ply_triangle(variant_scalar_rgb):\n from mitsuba.core import UInt32, Vector3f\n from mitsuba.core.xml import load_string\n\n m = load_string(\"\"\"\n \n \n \n \n \"\"\")\n\n positions = m.vertex_positions_buffer()\n faces = m.faces_buffer()\n\n assert not m.has_vertex_normals()\n assert ek.slices(positions) == 9\n assert ek.allclose(positions[0:3], [0, 0, 0])\n assert ek.allclose(positions[3:6], [0, 0, 1])\n assert ek.allclose(positions[6:9], [0, 1, 0])\n assert ek.slices(faces) == 3\n assert faces[0] == UInt32(0)\n assert faces[1] == UInt32(1)\n assert faces[2] == UInt32(2)\n\n\n@fresolver_append_path\ndef test03_ply_computed_normals(variant_scalar_rgb):\n from mitsuba.core import Vector3f\n from mitsuba.core.xml import load_string\n\n \"\"\"Checks(automatic) vertex normal computation for a PLY file that\n doesn't have them.\"\"\"\n shape = load_string(\"\"\"\n \n \n \n \"\"\")\n normals = shape.vertex_normals_buffer()\n assert shape.has_vertex_normals()\n # Normals are stored in half precision\n assert ek.allclose(normals[0:3], [-1, 0, 0])\n assert ek.allclose(normals[3:6], [-1, 0, 0])\n assert ek.allclose(normals[6:9], [-1, 0, 0])\n\n\ndef test04_normal_weighting_scheme(variant_scalar_rgb):\n from mitsuba.core import Struct, float_dtype, Vector3f\n from mitsuba.render import Mesh\n import numpy as np\n\n \"\"\"Tests the weighting scheme that is used to compute surface normals.\"\"\"\n m = Mesh(\"MyMesh\", 5, 2, has_vertex_normals=True)\n\n vertices = m.vertex_positions_buffer()\n normals = m.vertex_normals_buffer()\n\n a, b = 1.0, 0.5\n vertices[:] = [0, 0, 0, -a, 1, 0, a, 1, 0, -b, 0, 1, b, 0, 1]\n\n n0 = Vector3f(0.0, 0.0, -1.0)\n n1 = Vector3f(0.0, 1.0, 0.0)\n angle_0 = ek.pi / 2.0\n angle_1 = ek.acos(3.0 / 5.0)\n n2 = n0 * angle_0 + n1 * angle_1\n n2 /= ek.norm(n2)\n n = np.vstack([n2, n0, n0, n1, n1]).transpose()\n\n m.faces_buffer()[:] = [0, 1, 2, 0, 3, 4]\n\n m.recompute_vertex_normals()\n for i in range(5):\n assert ek.allclose(normals[i*3:(i+1)*3], n[:, i], 5e-4)\n\n\n@fresolver_append_path\ndef test05_load_simple_mesh(variant_scalar_rgb):\n from mitsuba.core.xml import load_string\n\n \"\"\"Tests the OBJ and PLY loaders on a simple example.\"\"\"\n for mesh_format in [\"obj\", \"ply\"]:\n shape = load_string(\"\"\"\n \n \n \n \"\"\".format(mesh_format))\n\n positions = shape.vertex_positions_buffer()\n faces = shape.faces_buffer()\n\n assert shape.has_vertex_normals()\n assert ek.slices(positions) == 72\n assert ek.slices(faces) == 36\n assert ek.allclose(faces[6:9], [4, 5, 6])\n assert ek.allclose(positions[:5], [130, 165, 65, 82, 165])\n\n\n@pytest.mark.parametrize('mesh_format', ['obj', 'ply', 'serialized'])\n@pytest.mark.parametrize('features', ['normals', 'uv', 'normals_uv'])\n@pytest.mark.parametrize('face_normals', [True, False])\ndef test06_load_various_features(variant_scalar_rgb, mesh_format, features, face_normals):\n \"\"\"Tests the OBJ & PLY loaders with combinations of vertex / face normals,\n presence and absence of UVs, etc.\n \"\"\"\n from mitsuba.core.xml import load_string\n\n def test():\n shape = load_string(\"\"\"\n \n \n \n \n \"\"\".format(mesh_format, features, str(face_normals).lower()))\n assert shape.has_vertex_normals() == (not face_normals)\n\n positions = shape.vertex_positions_buffer()\n normals = shape.vertex_normals_buffer()\n texcoords = shape.vertex_texcoords_buffer()\n faces = shape.faces_buffer()\n\n (v0, v2, v3) = [positions[i*3:(i+1)*3] for i in [0, 2, 3]]\n\n assert ek.allclose(v0, [-2.85, 0.0, -7.600000], atol=1e-3)\n assert ek.allclose(v2, [ 2.85, 0.0, 0.599999], atol=1e-3)\n assert ek.allclose(v3, [ 2.85, 0.0, -7.600000], atol=1e-3)\n\n if 'uv' in features:\n assert shape.has_vertex_texcoords()\n (uv0, uv2, uv3) = [texcoords[i*2:(i+1)*2] for i in [0, 2, 3]]\n # For OBJs (and .serialized generated from OBJ), UV.y is flipped.\n if mesh_format in ['obj', 'serialized']:\n assert ek.allclose(uv0, [0.950589, 1-0.988416], atol=1e-3)\n assert ek.allclose(uv2, [0.025105, 1-0.689127], atol=1e-3)\n assert ek.allclose(uv3, [0.950589, 1-0.689127], atol=1e-3)\n else:\n assert ek.allclose(uv0, [0.950589, 0.988416], atol=1e-3)\n assert ek.allclose(uv2, [0.025105, 0.689127], atol=1e-3)\n assert ek.allclose(uv3, [0.950589, 0.689127], atol=1e-3)\n\n if shape.has_vertex_normals():\n for n in [normals[i*3:(i+1)*3] for i in [0, 2, 3]]:\n assert ek.allclose(n, [0.0, 1.0, 0.0])\n\n return fresolver_append_path(test)()\n\n\n@fresolver_append_path\ndef test07_ply_stored_attribute(variant_scalar_rgb):\n from mitsuba.core import Vector3f\n from mitsuba.core.xml import load_string\n\n m = load_string(\"\"\"\n \n \n \n \"\"\")\n\n assert str(m) == \"\"\"PLYMesh[\n name = \"triangle_face_colors.ply\",\n bbox = BoundingBox3f[\n min = [0, 0, 0],\n max = [0, 1, 1]\n ],\n vertex_count = 3,\n vertices = [72 B of vertex data],\n face_count = 1,\n faces = [24 B of face data],\n disable_vertex_normals = 0,\n surface_area = 0,\n mesh attributes = [\n face_color: 3 floats\n ]\n]\"\"\"\n\n\ndef test08_mesh_add_attribute(variant_scalar_rgb):\n from mitsuba.core import Struct, float_dtype\n from mitsuba.render import Mesh\n\n m = Mesh(\"MyMesh\", 3, 2)\n m.vertex_positions_buffer()[:] = [0.0, 0.0, 0.0, 1.0, 0.2, 0.0, 0.2, 1.0, 0.0]\n m.faces_buffer()[:] = [0, 1, 2, 1, 2, 0]\n m.parameters_changed()\n\n m.add_attribute(\"vertex_color\", 3)[:] = [0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0]\n\n assert str(m) == \"\"\"Mesh[\n name = \"MyMesh\",\n bbox = BoundingBox3f[\n min = [0, 0, 0],\n max = [1, 1, 0]\n ],\n vertex_count = 3,\n vertices = [72 B of vertex data],\n face_count = 2,\n faces = [24 B of face data],\n disable_vertex_normals = 0,\n surface_area = 0.96,\n mesh attributes = [\n vertex_color: 3 floats\n ]\n]\"\"\"","repo_name":"tizian/specular-manifold-sampling","sub_path":"src/librender/tests/test_mesh.py","file_name":"test_mesh.py","file_ext":"py","file_size_in_byte":7652,"program_lang":"python","lang":"en","doc_type":"code","stars":204,"dataset":"github-code","pt":"48"} +{"seq_id":"25872219351","text":"import sys\nsys.setrecursionlimit(10000)\ndef input():\n return sys.stdin.readline().rstrip()\n\ndef cycle_check(node,parent):\n if visited[node]:\n return node\n else:\n visited[node] = True\n for next_node in graph[node]:\n if next_node == parent:continue\n return_node = cycle_check(next_node,node)\n if return_node > 0:\n cycle_check_node[node] = True\n distance[node] = 0\n if return_node == node:\n return 0\n else:\n return return_node\n cycle_check_node[node] = False\n return 0\ndef dfs(start,parent):\n if distance[start] != INF:\n return distance[start]\n for next_node in graph[start]:\n if next_node == parent:continue\n distance[start] = min(dfs(next_node,start)+1,distance[start])\n\n return distance[start]\n\n \n\n\n\nN = int(input())\n\ngraph = [[] for _ in range(N+1)]\n\nfor _ in range(N):\n x,y = map(int,input().split())\n graph[x].append(y)\n graph[y].append(x)\n\n\nvisited = [False for _ in range(N+1)]\ncycle_check_node = [False for _ in range(N+1)]\nINF = float('inf')\ndistance = [INF for _ in range(N+1)]\n\ncycle_check(1,0)\n\nfor k in range(1,N+1):\n if not cycle_check_node[k] and distance[k] == INF:\n dfs(k,0)\n\nprint(*distance[1:])","repo_name":"gkgg123/TIL_new","sub_path":"알고리즘/백준/16947_서울_지하철_2호선_version2.py","file_name":"16947_서울_지하철_2호선_version2.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8428540500","text":"\"\"\"\n\t\\command tele\n\t\\description Transports you directly to the targetted location.\n\"\"\"\n\nimport wolfpack\nfrom wolfpack.consts import *\n\ndef onLoad():\n\twolfpack.registercommand( \"tele\", commandTele )\n\treturn\n\ndef commandTele( socket, cmd, args ):\n\tsocket.sysmessage( 'Select your teleport destination.' )\n\tsocket.attachtarget( \"commands.tele.teleport\", [] )\n\treturn True\n\ndef teleport( char, args, target ):\n\tsource = char.pos\n\t# Keeps you from teleporting to weird places.\n\tif target.item and target.item.container:\n\t\ttarget = char.pos\n\telse:\n\t\ttarget = target.pos\n\n\tchar.removefromview()\n\tchar.moveto( target )\n\tchar.update()\n\tif char.socket:\n\t\tchar.socket.resendworld()\n\twolfpack.effect(0x3728, source, 10, 15)\n\twolfpack.effect(0x3728, target, 10, 15)\n\tchar.soundeffect(0x1fe)\n\treturn True\n","repo_name":"BackupTheBerlios/wolfpack-svn","sub_path":"tags/Release_12_9_9/server/release/scripts/commands/tele.py","file_name":"tele.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"31926422266","text":"\"\"\"Some formatting tools.\"\"\"\n\ndef int_or_float(x):\n d = float(x)\n return int(d) if int(d) == d else d \n\ndef deploy_schedule(s, start=2010, ind=8):\n \"\"\"Creates a formatted deployment schedule from a string.\"\"\"\n ind = ind * ' '\n dep = list(map(int_or_float, s.split()))\n rtn = ''\n for i in range(0, len(dep), 10):\n data = dep[i:i+10]\n rtn += ind + ', '.join(map(str, data)) + ','\n beg = start + i\n end = beg + len(data) - 1\n rtn += ' # {0} - {1}\\n'.format(beg, end)\n return rtn\n","repo_name":"scopatz/fco-ta","sub_path":"tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"44669592400","text":"from . exceptions import SnipsError, SnipsClarificationError\nfrom . i18n import get_translations\nfrom . intent import IntentPayload\nfrom . log import LoggingMixin\nfrom . snips import SnipsClient, on_intent\nfrom basecmd import BaseCmd\nfrom configparser import ConfigParser\nfrom functools import wraps\nimport logging, os\n\n\n__all__ = ('Skill', 'intent', 'min_confidence', 'PARDON', 'require_slot' )\n_, ngettext = get_translations(__file__, 'snips_skill')\n\n\nPARDON = _('Pardon?')\n\n\nclass Skill(LoggingMixin, BaseCmd, SnipsClient):\n 'Base class for Snips actions.'\n \n CONFIGURATION_FILE = 'config.ini'\n \n STANDARD_SECTIONS = ('DEFAULT', 'global', 'secret')\n \n \n def __init__(self, client_id=None, clean_session=True, userdata=None):\n # Work around a Paho cleanup bug if called with -h or illegal args\n self._sock = self._sockpairR = self._sockpairW = None\n \n super(Skill, self).__init__(\n client_id=client_id,\n clean_session=clean_session,\n userdata=userdata)\n \n self.configuration = ConfigParser()\n\n if os.path.isfile(self.options.config):\n self.log.debug('Reading configuration: %s', self.options.config)\n self.configuration.read(self.options.config, encoding='UTF-8')\n self.process_config()\n else:\n self.log.warning('Configuration %s not found', self.options.config)\n\n \n def process_config(self):\n 'May be overridden'\n pass\n\n\n def get_config(self, section='DEFAULT'):\n 'Get a configuration section, or DEFAULT values'\n if section in self.configuration:\n return self.configuration[section]\n return self.configuration['DEFAULT']\n\n\n def add_arguments(self):\n super().add_arguments()\n self.parser.add_argument('-c', '--config',\n default=self.CONFIGURATION_FILE,\n help='Configuration file (%s)' % self.CONFIGURATION_FILE)\n \n \ndef intent(intent, qos=1, log_level=logging.NOTSET, silent=False):\n ''' Decorator for intent handlers.\n :param intent: Intent name.\n :param qos: MQTT quality of service.\n :param log_level: Log intents at this level, if set.\n :param silent: Set to `True` for intents that should return `None` \n The wrapped function gets a parsed `IntentPayload` object\n instead of a JSON `msg.payload`.\n If a `SnipsClarificationError` is raised, the session continues with a question.\n Otherwise, the session is ended.\n '''\n\n def wrapper(method):\n @on_intent(intent, qos=qos)\n @wraps(method)\n def wrapped(client, userdata, msg):\n msg.payload = IntentPayload(msg.payload)\n if log_level: client.log_intent(msg.payload, level=log_level)\n try:\n result = method(client, userdata, msg)\n if log_level and result:\n client.log_response(result, level=log_level)\n if result is None and silent:\n client.end_session(msg.payload.session_id, qos=qos)\n return\n raise SnipsError(result)\n except SnipsClarificationError as sce:\n if log_level: client.log_response(sce, level=log_level)\n client.continue_session(msg.payload.session_id, str(sce),\n [sce.intent ] if sce.intent else None,\n slot=sce.slot, custom_data=sce.custom_data)\n except SnipsError as e:\n client.end_session(msg.payload.session_id, str(e), qos=qos)\n return wrapped\n return wrapper\n\n\ndef min_confidence(threshold, prompt=PARDON):\n ''' Decorator that requires a minimum intent confidence, or else asks the user.\n :param threshold: Minimum confidence (0.0 - 1.0)\n :param prompt: Question for the user\n '''\n\n def wrapper(method):\n @wraps(method)\n def wrapped(client, userdata, msg):\n if msg.payload.intent.confidence_score >= threshold:\n return method(client, userdata, msg)\n raise SnipsClarificationError(prompt)\n return wrapped\n return wrapper\n\n\ndef require_slot(slot, prompt, kind=None):\n ''' Decorator that checks whether a slot is present, or else asks the user.\n :param slot: Slot name\n :param prompt: Question for the user\n :param kind: Optionally, the slot is expected to be of the given kind.\n '''\n\n def wrapper(method):\n @wraps(method)\n def wrapped(client, userdata, msg):\n if slot in msg.payload.slots and (kind is None\n or msg.payload.slot_values[slot].kind == kind):\n return method(client, userdata, msg)\n raise SnipsClarificationError(prompt,\n msg.payload.intent.intent_name, slot)\n return wrapped\n return wrapper\n","repo_name":"dnknth/snips-skill","sub_path":"snips_skill/skill.py","file_name":"skill.py","file_ext":"py","file_size_in_byte":4895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14572048665","text":"import torch\nfrom torchvision import datasets\nfrom torchvision import transforms\nfrom torch import nn\nimport matplotlib.pyplot as plt\nimport pdb\n\n\nclass net(torch.nn.Module):\n def __init__(self):\n super().__init__()\n\n self.weights = [64, 32, 16, 8]\n self.w = [];\n self.a = [];\n\n for i in range(len(self.weights[:-1])):\n self.w.append(nn.Linear(self.weights[i], self.weights[i+1]))\n nn.init.xavier_uniform_(self.w[i].weight, gain=nn.init.calculate_gain('relu'))\n\n self.a.append(nn.ReLU())\n\n def forward(self, x):\n\n for i in range(len(self.weights[:-1])):\n x = self.w[i](x)\n x = self.a[i](x)\n\n return x\n\n\nx = torch.rand((1, 64))\n\npdb.set_trace()\n\nmynet = net()\ntemp = mynet(x)\n\npdb.set_trace()","repo_name":"alexanderpei/sindy","sub_path":"test_build.py","file_name":"test_build.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15381663341","text":"#\t \n# ___ ___ ___ ___ ___ \n# / /\\ ___ / /\\ / /\\ / /\\ / /\\ \n# / /::\\ / /\\ / /:/ / /::\\ / /::\\ / /:/ \n# /__/:/\\:\\ / /::\\ / /:/ / /:/\\:\\ /__/:/\\:\\ / /:/ \n# _\\_ \\:\\ \\:\\ / /:/\\:\\ / /:/ / /::\\ \\:\\ _\\_ \\:\\ \\:\\ / /::\\ ___ \n# /__/\\ \\:\\ \\:\\ / /::\\ \\:\\ /__/:/ /__/:/\\:\\_\\:\\ /__/\\ \\:\\ \\:\\ /__/:/\\:\\ /\\\n# \\ \\:\\ \\:\\_\\/ /__/:/\\:\\_\\:\\ \\ \\:\\ \\__\\/ \\:\\/:/ \\ \\:\\ \\:\\_\\/ \\__\\/ \\:\\/:/\n# \\ \\:\\_\\:\\ \\__\\/ \\:\\/:/ \\ \\:\\ \\__\\::/ \\ \\:\\_\\:\\ \\__\\::/ \n# \\ \\:\\/:/ \\ \\::/ \\ \\:\\ / /:/ \\ \\:\\/:/ / /:/ \n# \\ \\::/ \\__\\/ \\ \\:\\ /__/:/ \\ \\::/ /__/:/ \n# \\__\\/ \\__\\/ \\__\\/ \\__\\/ \\__\\/ \n# Update 15/04/2020\n#=================================================================================================================================\n\n# Please go to here : https://support.microsoft.com/en-gb/help/4026757/windows-10-find-out-how-many-cores-your-processor-has\n# to check how many cores your cpu has before you run\nnumber_of_processes=4\n#\n\n# For layer 1 2 3 4 5 6 7 8 9 10\nsimilr_max=[1,0.8,0.7,0.6,0.6,0.6,0.6,0.6,0.6,0.6] #<- make sure you input 10 values\nC_diff_min=[0,0,0,0,0,0,0,0,0,0]\nC_diff_max=[7,7,7,7,7,7,7,7,7,7]\nR_diff_min=[0,0,0,0,0,0,0,0,0,0]# to make the condition about ring fail,\n\ndef count_C(smiles):\n\tp=smiles\n\tpc=p.count('C')+p.count('c')-p.count('Cl')-p.count('Cs')-p.count('Cd')-p.count('Cu')-p.count('Co')\n\treturn pc\n\ndef compare(smiles_A,smiles_B):\n\ttry:\n\t\tmol1 = Chem.MolFromSmiles(smiles_A)\n\t\tmol2 = Chem.MolFromSmiles(smiles_B)\n\t\tfp1 = AllChem.GetMorganFingerprintAsBitVect(mol1,1)\n\t\tfp2 = AllChem.GetMorganFingerprintAsBitVect(mol2,1)\n\t\treturn DataStructs.TanimotoSimilarity(fp1,fp2)\n\texcept:\n\t\treturn 0\n\t\t#Smiles wrong -> remove this result\ndef Draw_mol(smiles,filename):\n\ttry:\n\t\tm1 = AllChem.MolFromSmiles(smiles)\n\t\tmc = rdMolDraw2D.PrepareMolForDrawing(m1)\n\t\tdrawer = Draw.MolDraw2DCairo(300, 300)\n\t\tdrawer.DrawMolecule(mc)\n\t\tdrawer.FinishDrawing()\n\t\toutput = drawer.GetDrawingText()\n\t\twith open(filename,'wb') as pngf:\n\t\t\tpngf.write(output)\n\texcept:\n\t\tprint('cannot draw from smiles ',smiles)\ndef Draw_temp(smarts,filename):\n\ttry:\n\t\trxn = AllChem.ReactionFromSmarts(smarts)\n\t\trimage = Draw.ReactionToImage(rxn)\n\t\trimage.save(filename)\n\texcept:\n\t\tprint('cannot draw from smarts',smarts)\n\t\tpass\n\n\ndef apply(temp,target,condition_list,layer):\n\tsimilr_max=condition_list[0][layer]\n\tC_diff_min=condition_list[1][layer] \n\tC_diff_max=condition_list[2][layer] \n\tR_diff_min=condition_list[3][layer] \n\tR_diff_max=condition_list[4][layer]\n\t#print('condition parameter',similr_max,C_diff_min,C_diff_max,R_diff_min,R_diff_max)\n\tsmarts_input=temp\n\tnBits=2048\n\tC_diff_max=7\n\n\trxn = AllChem.ReactionFromSmarts(smarts_input)\n\tps = rxn.RunReactants((Chem.MolFromSmiles(target),))\n\ttarget_NC=count_C(target)\n\ttarget_NR=count_ring(target)\n\tif ps:\n\n\t\tif len(ps[0])==3:\n\t\t\tp1=(Chem.MolToSmiles(ps[0][0]))\n\t\t\tp2=(Chem.MolToSmiles(ps[0][1]))\n\t\t\tp3=(Chem.MolToSmiles(ps[0][2]))\n\t\t\toutput_NC=count_C(p1)+count_C(p2)+count_C(p3)\n\t\t\toutput_NR=count_ring(p1)+count_ring(p2)+count_ring(p3)\n\t\t\tif compare(target,p1+'.'+p2+'.'+p3) > similr_max:\n\t\t\t\treturn False\n\t\t\tif not(C_diff_min similr_max:\n\t\t\t\treturn False\n\t\t\tif not(C_diff_min similr_max:\n\t\t\t\treturn False\n\t\t\tif not(C_diff_min<=np.abs(target_NC - output_NC) >'+reactants[1])\n\tif reactants[0]==2:\n\t\tpath_mol_1=path+'/'+str(1000000000+Mol_ID)+'_a_temp_'+str(1000000000+Temp_ID)+'.png'\n\t\tpath_mol_list.append(path_mol_1[:-string_cut])\n\t\tpath_mol_2=path+'/'+str(1000000000+Mol_ID)+'_b_temp_'+str(1000000000+Temp_ID)+'.png'\n\t\tpath_mol_list.append(path_mol_2[:-string_cut])\n\t\tpath_temp=path+'/'+'temp_'+str(1000000000+Temp_ID)+'.png'\n\t\tif outputimage:\n\t\t\tDraw_mol(reactants[1],path_mol_1)\n\t\t\tDraw_mol(reactants[2] ,path_mol_2)\n\t\t\tDraw_temp(smarts[Temp_ID],path_temp)\n\t\t\tpredicted_reaction_list.append('Tree:'+'\\t'+path+'-'+str(Mol_ID)+'\\t'+'temp_ID'+'\\t'+str(Temp_ID)+'\\t'+previous_reactant+'>>'+reactants[1]+'.'+reactants[2])\n\tif reactants[0]==3:\n\t\tpath_mol_1=path+'/'+str(1000000000+Mol_ID)+'_a_temp_'+str(1000000000+Temp_ID)+'.png'\n\t\tpath_mol_list.append(path_mol_1[:-string_cut])\n\t\tpath_mol_2=path+'/'+str(1000000000+Mol_ID)+'_b_temp_'+str(1000000000+Temp_ID)+'.png'\n\t\tpath_mol_list.append(path_mol_2[:-string_cut])\n\t\tpath_mol_3=path+'/'+str(1000000000+Mol_ID)+'_c_temp_'+str(1000000000+Temp_ID)+'.png'\n\t\tpath_mol_list.append(path_mol_3[:-string_cut])\n\t\tpath_temp=path+'/'+'temp_'+str(1000000000+Temp_ID)+'.png'\n\t\tif outputimage:\n\t\t\tDraw_mol(reactants[1],path_mol_1)\n\t\t\tDraw_mol(reactants[2] ,path_mol_2)\n\t\t\tDraw_mol(reactants[3] ,path_mol_3)\n\t\t\tDraw_temp(smarts[Temp_ID],path_temp)\n\t\t\tpredicted_reaction_list.append('Tree:'+'\\t'+path+'-'+str(Mol_ID)+'\\t'+'temp_ID'+'\\t'+str(Temp_ID)+'\\t'+previous_reactant+'>>'+reactants[1]+'.'+reactants[2]+'.'+reactants[3])\n\tfor item in path_mol_list:\n\t\tcurrent_gen_path_list.append(item)\ndef node_expansion(tasks_to_accomplish,\n\t\t\t\t\tinputs_q,\n\t\t\t\t\tprevious_gen_reactants,\n\t\t\t\t\tprevious_path_list,\n\t\t\t\t\tcurrent_gen_reactants,\n\t\t\t\t\tcurrent_gen_path_list,\n\t\t\t\t\tpredicted_reaction_list,\n\t\t\t\t\tsmarts,\n\t\t\t\t\tnumber_of_processes,\n\t\t\t\t\tcondition_list,\n\t\t\t\t\tlayer,\n\t\t\t\t\tfirst_layer):\n\tloop_limit=condition_list[5][layer]\n\t#print('start node expansion')\n\twhile True:\n\t\ttry:\n\t\t\ttask = tasks_to_accomplish.get_nowait() #<- task_to_accomplish is queue\n\t\t\tID=inputs_q.get()\n\t\t\tif len(previous_gen_reactants) > number_of_processes:\n\t\t\t\tnew_ID=ID+number_of_processes\n\t\t\t\tinputs_q.put(new_ID)\n\t\t\t\ttasks_to_accomplish.put(\"Layer \"+str(layer+1)+\": Task with queque ID \" + str(new_ID) +\"over total \"+str(len(previous_gen_reactants)))\n\t\t\ttarget=previous_gen_reactants[ID]\n\t\t\t##print('debug 3 previous_path_list',previous_path_list)\n\t\t\tpath=previous_path_list[ID]\n\t\t\t#print(target)\n\t\t\t # <- for later when we need ID for each predicted reactants:\n\t\t\tDraw_mol(target,path+'/000000000.png')\n\t\t\tbranch_reactants_no=0\n\t\t\tloop_limit=condition_list[5][layer]\n\t\t\tlen_smarts=len(smarts) #<-get number of template\n\t\t\tfor Temp_ID in range(0,len_smarts): #<-need template ID for the file name\n\t\t\t\tif Temp_ID%10000==0 and first_layer:\n\t\t\t\t\tos.system('cls' if os.name == 'nt' else 'clear')\n\t\t\t\t\tprint('first layer will take a while, please wait, especially if the condition you put is too strict or unreasonable')\n\t\t\t\t\tprint('apply temp ID',Temp_ID,'/',len_smarts)\n\t\t\t\ttemp=smarts[Temp_ID]\n\t\t\t\tp,r=temp.split('>>')\n\t\t\t\tif '.' in p: continue\n\t\t\t\tif branch_reactants_no>=loop_limit:\n\t\t\t\t\tbreak\n\t\t\t\tout_list=apply(temp,target,condition_list,layer)\n\t\t\t\tif out_list: #<- check if this molecule appear on the current list\n\t\t\t\t\t#print('debug outlist',out_list)\n\t\t\t\t\tfor item in out_list:\n\t\t\t\t\t\tif item in current_gen_reactants: continue \n\t\t\t\t\tcurrent_gen_reactants.extend(out_list[1:])\n\t\t\t\t\tbranch_reactants_no+=1\n\t\t\t\t\t##print('debug 2 path',path)\n\t\t\t\t\tMol_ID=random.randint(0,999999999)\n\t\t\t\t\tplot_n_make_folder(target,\n\t\t\t\t\t\t\t\t\t\tout_list,\n\t\t\t\t\t\t\t\t\t\tTemp_ID,\n\t\t\t\t\t\t\t\t\t\tMol_ID,\n\t\t\t\t\t\t\t\t\t\tpath,\n\t\t\t\t\t\t\t\t\t\tsmarts,\n\t\t\t\t\t\t\t\t\t\tcurrent_gen_path_list,\n\t\t\t\t\t\t\t\t\t\tpredicted_reaction_list,\n\t\t\t\t\t\t\t\t\t\t)\n\n\t\texcept queue.Empty:\n\t\t\tbreak\n\t\telse:\n\t\t\tprint(task,'are done') # In splash, will print which task for which \n\t\t\ttime.sleep(1)\n\treturn True\n\n\ndef layer_expansion(previous_gen_reactants,previous_path_list,condition_list,number_of_processes,layer,first_layer=False):\n\tloop_limit=condition_list[5][layer]\n\tif loop_limit==0:\n\t\tsys.exit(\"No more layer\")\n\t#print('debug 4 previous_path_list:',previous_path_list)\n\twith open(\"SMARTS_template_no_chirality.txt\", \"r\") as f:\n\t\tsmarts=f.readlines()\n\ttasks_to_accomplish = Queue() #<- this to show which current are running\n\tinputs_q= Queue()\n\tprocesses = []\n\tmanager=Manager()\n\tcurrent_gen_reactants = manager.list() #<- Make this so that the list can be shared\n\tcurrent_gen_path_list = manager.list() #<- Make this so that the list can be shared\n\tpredicted_reaction_list = manager.list() #<- Make this so that the list can be shared\n\n\t# Append ID for process\n\tif len(previous_gen_reactants) < number_of_processes:\n\t\tfor i in range(0,len(previous_gen_reactants)):\n\t\t\t#print('debug 5 previous_gen_reactants',previous_gen_reactants)\n\t\t\ttasks_to_accomplish.put(\"Layer \"+str(layer+1)+\": Task with queque ID \" + str(i))\n\t\t\tinputs_q.put(i)\n\telse:\n\t\tfor i in range(0,number_of_processes):\n\t\t\t# If the lenght of queue is too big, the script will get error\n\t\t\t##print('debug 5 previous_gen_reactants',previous_gen_reactants)\n\t\t\ttasks_to_accomplish.put(\"Layer \"+str(layer+1)+\": Task with queque ID \" + str(i) +\"over total \"+str(len(previous_gen_reactants)))\n\t\t\tinputs_q.put(i)\n\t\t# creating processes\n\n\tfor w in range(number_of_processes):\n\t\tp = Process(target=node_expansion, args=(tasks_to_accomplish,\n\t\t\t\t\t\t\t\t\t\t\t\t\tinputs_q,\n\t\t\t\t\t\t\t\t\t\t\t\t\tprevious_gen_reactants,\n\t\t\t\t\t\t\t\t\t\t\t\t\tprevious_path_list,\n\t\t\t\t\t\t\t\t\t\t\t\t\tcurrent_gen_reactants,\n\t\t\t\t\t\t\t\t\t\t\t\t\tcurrent_gen_path_list,\n\t\t\t\t\t\t\t\t\t\t\t\t\tpredicted_reaction_list,\n\t\t\t\t\t\t\t\t\t\t\t\t\tsmarts,\n\t\t\t\t\t\t\t\t\t\t\t\t\tnumber_of_processes,\n\t\t\t\t\t\t\t\t\t\t\t\t\tcondition_list,\n\t\t\t\t\t\t\t\t\t\t\t\t\tlayer,\n\t\t\t\t\t\t\t\t\t\t\t\t\tfirst_layer))\n\t\tprocesses.append(p)\n\t\tp.start()\n\t# completing process\n\tfor p in processes:\n\t\tp.join()\n\t# print the output\n\tprint('current_gen_reactants', current_gen_reactants)\n\t#print('current_path_list', current_gen_path_list)\n\t# make folder for next expansion\n\tfor item in current_gen_path_list:\n\t\tos.mkdir(item)\n\t# write reaction path list\n\twith open(folder_name+'/0_reaction_for_layer'+str(layer+1)+'.txt', 'w') as f:\n\t\tfor item in predicted_reaction_list:\n\t\t\tf.write(\"%s\\n\" % item)\n\tprint('-----------------------------------------------------------------')\n\tprint('-----------------------------END LAYER '+str(layer+1)+'-------------------------')\n\tprint('-----------------------------------------------------------------')\n\treturn current_gen_reactants,current_gen_path_list,layer+1\nif __name__ == '__main__':\n\n\t# Get those similarity limit:\n\tcondition_list=[]\n\tcondition_list.extend([similr_max,C_diff_min,C_diff_max,R_diff_min,R_diff_max,expand_max])\n\n\n\n\tlayer=0\n\ttry:\n\t\tos.mkdir(folder_name)\n\texcept:\n\t\tsys.exit('a Folder with the same name already exist')\n\treactants_list,path_list,layer=layer_expansion(input_target,[folder_name],condition_list,number_of_processes,layer,first_layer=True)\n\treactants_list,path_list,layer=layer_expansion(reactants_list,path_list,condition_list,number_of_processes,layer)\n\treactants_list,path_list,layer=layer_expansion(reactants_list,path_list,condition_list,number_of_processes,layer)\n\treactants_list,path_list,layer=layer_expansion(reactants_list,path_list,condition_list,number_of_processes,layer)\n\treactants_list,path_list,layer=layer_expansion(reactants_list,path_list,condition_list,number_of_processes,layer)\n\treactants_list,path_list,layer=layer_expansion(reactants_list,path_list,condition_list,number_of_processes,layer)\n\treactants_list,path_list,layer=layer_expansion(reactants_list,path_list,condition_list,number_of_processes,layer)\n\treactants_list,path_list,layer=layer_expansion(reactants_list,path_list,condition_list,number_of_processes,layer)\n\treactants_list,path_list,layer=layer_expansion(reactants_list,path_list,condition_list,number_of_processes,layer)\n\treactants_list,path_list,layer=layer_expansion(reactants_list,path_list,condition_list,number_of_processes,layer)\n","repo_name":"longthanhta/Chem_Coupling-Reaction_DA","sub_path":"1_retrosynthesis_w_NN/without_NN/SPLASH.py","file_name":"SPLASH.py","file_ext":"py","file_size_in_byte":15448,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"26751801074","text":"\"\"\"摄像头人脸检测\"\"\"\r\nimport cv2\r\n\r\nface_cascade = cv2.CascadeClassifier(r'./cascades/haarcascade_frontalface_default.xml')\r\neye_cascade = cv2.CascadeClassifier(r'./cascades/haarcascade_eye.xml')\r\n\r\n\"\"\"构建过程\"\"\"\r\ncameraCapture = cv2.VideoCapture(0) #传入设备索引号构建\r\ncv2.namedWindow('My Window')\r\n\r\n\"\"\"一帧一帧判断显示\"\"\"\r\nsuccess, frame = cameraCapture.read()\r\nwhile success:\r\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n \"\"\"绘制人脸\"\"\"\r\n faces = face_cascade.detectMultiScale(gray, 1.3, 5)\r\n # print('faces', faces)\r\n for (x, y, w, h) in faces:\r\n img = cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2) #绘制蓝色框\r\n \"\"\"绘制眼睛\"\"\"\r\n eye_gray = gray[y:y+h, x:x+w] #缩小眼睛搜索范围\r\n eyes = eye_cascade.detectMultiScale(eye_gray, 1.03, 5, 0, (50, 50))\r\n # print('eyes', eyes)\r\n for (ex, ey, ew, eh) in eyes:\r\n # pass\r\n cv2.rectangle(img, (ex+x, ey+y), (ex+ew, ey+eh), (0, 255, 0), 2) #绘制两个红色框\r\n cv2.imshow('My Window', frame)\r\n success, frame = cameraCapture.read()\r\n\r\ncv2.destroyWindow('My Window')\r\ncameraCapture.release()\r\n\r\n","repo_name":"birdtianyu/Object-Detection","sub_path":"FaceDetection.py","file_name":"FaceDetection.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"31189413297","text":"import sqlite3\nfrom django.shortcuts import render\nfrom django.shortcuts import redirect\nfrom django.urls import reverse\nfrom django.contrib.auth.decorators import login_required\nfrom hrapp.models import Computer\nfrom hrapp.models import employee\nfrom ..connection import Connection\n\n\ndef get_employees():\n with sqlite3.connect(Connection.db_path) as conn:\n conn.row_factory = sqlite3.Row\n db_cursor = conn.cursor()\n\n db_cursor.execute(\"\"\"\n select\n e.id,\n e.first_name,\n e.last_name,\n d.name\n from hrapp_employee e\n join hrapp_department d on e.department_id = d.id;\n \"\"\")\n\n return db_cursor.fetchall()\n\n\n@login_required\ndef computer_form(request):\n if request.method == \"GET\":\n employees = get_employees()\n template = 'computers/form.html'\n context = {\n 'employees': employees\n }\n return render(request, template, context)\n","repo_name":"nss-day-cohort-33/bangazon-workforce-management-kingdom-of-glyweth","sub_path":"hrapp/views/computers/form.py","file_name":"form.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42041852453","text":"from playsound import playsound\nfrom time import sleep\nimport logging\nlogging.basicConfig(filename='user_log.log', filemode='w', level=logging.INFO)\n\ndef beginning_of_game():\n global name\n name = input(\"Who are you? \")\n logging.info(\"User input name\")\n start = input(f'Hello {name} would you like to play the game? (yes / no) ')\n if start == \"yes\":\n logging.info('User chose to play the game')\n print(\"You're walking down a stright road\")\n sleep(1)\n path()\n elif start == \"no\":\n print(\"That's to bad\")\n sleep(1)\n logging.info(\"Game has ended\")\n exit()\n else:\n print(\"I didn't catch you, can you repeat that?\")\n sleep(1)\n beginning_of_game()\n\n\ndef path():\n direction = input(\"Would you like to go left or right? \")\n if direction == \"left\":\n print(\"You went on your merry way down the road on the left and tripped on a twig! Game Over.\")\n sleep(1)\n play_again()\n elif direction == \"right\":\n print('Great choice {name} you survived!')\n sleep(1)\n second_path()\n elif direction == \"up\":\n print(\"You feel the need to defy the laws of the universe and will not be limited to such foolish things. You choose your own your own path so you call for no your trusty steed Buttstallion. The a ray of sunshine beams next to you, as you see your trusted companion decend from the heavens. You hop and ride off into the distance never to be seen again. All the evil in the world suddenly vanished as if it never existed. You win the game.\")\n sleep(5)\n play_again()\n else:\n print(\"You wanna do what now?\")\n sleep(1)\n path()\n\n\ndef second_path():\n sleep(1)\n direction = input(\"Now would you like to go up or down? \")\n if direction == \"up\":\n print(f'Quick {name}! Your absurd decision some how got us in Cloud City and that bounty hunter is headed toward you? You can either hide in this closet next you that says \"occupied\" or fight him head on! What are you gonna do?')\n hide_or_fight()\n elif direction == \"down\":\n print('')\n else:\n print(\"You wanna do what now?\")\n sleep(1)\n second_path()\n\n\ndef hide_or_fight():\n sleep(1)\n choice = input(\n 'Hide in closet that says \"occupied\" / Fight the Bounty Hunter (hide / fight) ')\n if choice == \"hide\":\n hide()\n elif choice == \"fight\":\n fight()\n else:\n print(\"You wanna do what now?\")\n sleep(1)\n hide_or_fight()\n\n\ndef hide():\n print(\"Of course! The Bounty Hunter obviously hasn't spotted you yet. Hurry up and get in that closet. You frantically rush into the closet and immediately run into something. This something can speak as it yelled 'Hey give me some room here!' You freak out and feel the walls for a light switch. You find the light and turn it on and you will not believe what you see before your very eyes. It's Solo Han and Chewbacco both half dressed in stormtrooper armor that they stole off of a couple of unconscious guys in the corner. You can't help but fangirl over them and exposed your new hiding spot. The Bounty Hunter opens the door and catches all three of you. Now thanks to you there never was a new triology featuring Adam Driver as Kylo Ren aka Ben Solo. I hope you can sleep at night I'm done with you!\")\n sleep(5)\n check_point()\n\n\ndef fight():\n print(\"You really wanna fight him? This guy is a fan favorite among a lot of Star Wars fans AND he's capable of defeating Jedi, so you will not be much a challenge for him! You really wanna fight him huh? Alrighty then your funeral I gonna be smart and get on outa here. Morgan Freeman ain't gonna support my family.\")\n sleep(20)\n print(\"(Que Morgan Freeman voice over) You were left alone to fight against Boba Fett, and obviously you aren't gonna beat him alone if fact you died immediately, but hey you died in combat which means you have earned yourself a spot in Valhalla. I would say your a lucky man. Game Over.\")\n playsound(\"./sound.mp3\")\n sleep(1)\n check_point()\n\n\ndef play_again():\n restart = input(\"Would you like play to again? (yes / no)\")\n if restart == \"yes\":\n beginning_of_game()\n elif restart == \"no\":\n print(\"That's too bad\")\n logging.info(\"Game has ended\")\n exit()\n else:\n print(\"You wanna do what now?\")\n sleep(1)\n play_again()\n\n\ndef check_point():\n restart = input('Would you like to play again? (yes / no) ')\n if restart == 'yes':\n check_point_spawn()\n\n elif restart == \"no\":\n print(\"That's too bad\")\n logging.info(\"Game has ended\")\n exit()\n\n else:\n print(\"You wanna do what now?\")\n sleep(1)\n check_point()\n\n\ndef check_point_spawn():\n spawn = input(\n 'Where would you like to start at? (up / down) (hide / fight) ')\n if spawn == \"up\" or spawn == \"down\":\n second_path()\n \n elif spawn == \"hide\" or spawn == \"fight\":\n hide_or_fight()\n \n else:\n print(\"You wanna do what now?\")\n sleep(1)\n check_point_spawn()\n\n\nbeginning_of_game()\nlogging.info(\"Game has ended\")","repo_name":"gwalker4760/python-text-rpg","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":5198,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31152202601","text":"\"\"\"myHouse URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom .import views\n\nfrom rest_framework.routers import DefaultRouter\nfrom .apiviews import CategorieViewSet, HouseViewSet, ArticleViewSet, LocationViewSet, Info_houseViewSet\n\nrouter = DefaultRouter()\nrouter.register('apicategorie', CategorieViewSet, base_name='categorie')\nrouter.register('apihouse', HouseViewSet, base_name='house')\nrouter.register('apiarticle', ArticleViewSet, base_name='article')\nrouter.register('apilocation', LocationViewSet, base_name='location')\nrouter.register('apiinfo', Info_houseViewSet, base_name='info')\n\nurlpatterns = [\n path('house', views.home, name='home'),\n path('about', views.about, name='about'),\n path('news', views.news, name='news'),\n path('developpement', views.developpement, name='developpement'),\n path('propriete', views.propriete, name='propriete'),\n path('contact', views.contact, name='contact'),\n path('views', views.views, name='views'),\n path('/detail', views.detail, name='detail'),\n \n]\n\nurlpatterns += router.urls","repo_name":"Dagoserge-martial/HOUSES","sub_path":"myHouse/house/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1705,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2333721360","text":"from datetime import datetime\nfrom typing import Optional, Union\n\nfrom asyncz.triggers.base import BaseCombinationTrigger\n\n\nclass AndTrigger(BaseCombinationTrigger):\n \"\"\"\n Always returns the earliest next trigger time that all the passed triggers agree on.\n The trigger is consideres to be finished when any of the given triggers finished its schedule.\n\n Args:\n triggers: List of triggers to combine.\n jitter: Delay the task execution by the jitter seconds at most.\n \"\"\"\n\n alias: str = \"and\"\n\n def get_next_trigger_time(\n self, previous_time: datetime, now: Optional[datetime] = None\n ) -> Union[datetime, None]:\n while True:\n trigger_times = [\n trigger.get_next_trigger_time(previous_time, now) for trigger in self.triggers\n ]\n\n if None in trigger_times:\n return None\n elif min(trigger_times) == max(trigger_times):\n return self.apply_jitter(trigger_times[0], self.jitter, now)\n else:\n now = max(trigger_times)\n\n\nclass OrTrigger(BaseCombinationTrigger):\n \"\"\"\n Always returns the earliest next trigger time produced by any of the given triggers.\n The trigger is considered finished when all the given triggers have finished their schedules.\n\n Args:\n triggers: List of triggers to combine.\n jitter: Delay the task execution by the jitter seconds at most.\n \"\"\"\n\n alias: str = \"or\"\n\n def get_next_trigger_time(\n self, previous_time: datetime, now: Optional[datetime] = None\n ) -> Union[datetime, None]:\n trigger_times = [\n trigger.get_next_trigger_time(previous_time, now) for trigger in self.triggers\n ]\n trigger_times = [\n trigger_time for trigger_time in trigger_times if trigger_time is not None\n ]\n\n if trigger_times:\n return self.apply_jitter(min(trigger_times), self.jitter, now)\n else:\n return None\n","repo_name":"tarsil/asyncz","sub_path":"asyncz/triggers/combination.py","file_name":"combination.py","file_ext":"py","file_size_in_byte":2002,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"48"} +{"seq_id":"73001596627","text":"# WAP to check whether a string is symmetrical (A string is said to be symmetrical if both the halves of the string are the same ) and palindrome\n\ndef palindrome(str):\n mid = (len(str) - 1) //2\n start = 0\n last = len(str) - 1\n flag = 0\n\n while start < mid:\n if str[start] == str[last]:\n start += 1\n last -= 1\n else:\n flag = 1\n break\n\n if flag == 0:\n print('String is palindrome')\n else:\n print('String is not palindrome')\n\n\ndef symmetrical(str):\n flag = 0\n if len(str) % 2:\n mid = len(str) // 2 + 1\n else:\n mid = len(str) // 2\n\n start1 = 0\n start2 = mid\n\n while (start1 < mid) and (start2 < len(str)):\n if str[start1] == str[start2]:\n start1 = start1 + 1\n start2 = start2 + 1\n else:\n flag = 1\n break\n\n if flag == 0:\n print(\"String is symmetrical\")\n else:\n print(\"String is not symmetrical\")\n\n\n#st = 'amaama'\nst = 'khokho'\npalindrome(st)\nsymmetrical(st)\n","repo_name":"BeighIrtiqa/Hands-On-to-Python","sub_path":"Python_Programs/SymmetricalPalindromeString.py","file_name":"SymmetricalPalindromeString.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"5794290831","text":"\"\"\"Realizar un programa que le solicite a 3 usuarios ingresar por teclado información personal,\nla información de cada usuario se debe guardar en una estructura de colección inmutable,\nluego mostrar por pantalla la información de los usuarios agrupada en una estructura de colección mutable.\n\nLa información para solicitar es:\na.Nombres y apellidos.\nb.Ocupación.\nc.Edad.\nd.Ciudad.\ne.Número de contacto.\nf.Correo electrónico.\n\"\"\"\n\nnames_and_surnames_1 = input('Ingrese sus nombres y apellidos: ')\noccupation_1 = input('Ingrese su ocupación: ')\nage_1 = input('Ingrase su edad: ')\ncity_1 = input('Ingrese su ciudad: ')\ncontact_number_1 = input('Ingrese su número de contacto: ')\nemail_1 = input('Ingrese su correo electrónico: ')\n\nuser_info_1 = ('Nombres y apellidos 1: ' + names_and_surnames_1, 'Ocupación 1: ' + occupation_1,\n 'Edad 1: ' + age_1, 'Ciudad 1: ' + city_1, 'Número de contacto 1: ' + contact_number_1,\n 'Correo electrónico 1: ' + email_1)\n\nnames_and_surnames_2 = input('Ingrese sus nombres y apellidos: ')\noccupation_2 = input('Ingrese su ocupación: ')\nage_2 = input('Ingrase su edad: ')\ncity_2 = input('Ingrese su ciudad: ')\ncontact_number_2 = input('Ingrese su número de contacto: ')\nemail_2 = input('Ingrese su correo electrónico: ')\n\nuser_info_2 = ('Nombres y apellidos 2: ' + names_and_surnames_2, 'Ocupación 2: ' + occupation_2,\n 'Edad 2: ' + age_2, 'Ciudad 2: ' + city_2, 'Número de contacto 2: ' + contact_number_2,\n 'Correo electrónico 2: ' + email_2)\n\nnames_and_surnames_3 = input('Ingrese sus nombres y apellidos: ')\noccupation_3 = input('Ingrese su ocupación: ')\nage_3 = input('Ingrase su edad: ')\ncity_3 = input('Ingrese su ciudad: ')\ncontact_number_3 = input('Ingrese su número de contacto: ')\nemail_3 = input('Ingrese su correo electrónico: ')\n\nuser_info_3 = ('Nombres y apellidos 3: ' + names_and_surnames_3, 'Ocupación 3: ' + occupation_3,\n 'Edad 3: ' + age_3, 'Ciudad 3: ' + city_3, 'Número de contacto 3: ' + contact_number_3,\n 'Correo electrónico 3: ' + email_3)\n\n# Concatenate the tuples and convert the result to a list:\nlist_users_info = list(user_info_1 + user_info_2 + user_info_3)\n\nprint(list_users_info)\n","repo_name":"JulianaCarvajal/iniciando_el_viaje","sub_path":"punto_2.py","file_name":"punto_2.py","file_ext":"py","file_size_in_byte":2248,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16038534445","text":"\"\"\"\nProgram that gives the day of the week for any given date\nAgustina Varas\n01/23/2022\n\n\"\"\"\nfrom datetime import date\n\n\n\n#Adds up number of days from the year given by user\n#leap years are every four years except if they are divisble by 100 they must \n#also be divisible by 400 to be a leap year\ndef year_days(year):\n total_days = 0\n while year > 1:\n if year % 100 == 0:\n if year % 400 == 0:\n total_days += 1\n elif year % 4 == 0:\n total_days += 1\n total_days += 365\n year -= 1\n return total_days\n \n\n# add up the number of days in that year up to the month that is given\n# example: if the given month is februrary the function returns 31\ndef month_days (month):\n days_from_month = 0\n days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n i = 0\n while (i < month - 1):\n days_from_month += days_in_month[i]\n i += 1\n return days_from_month\n\n\n# adds up the total days at the given date\ndef total_days(day, month, year):\n total_days = day\n total_days += year_days(year)\n total_days += month_days(month)\n return total_days\n\n\n#returns a string corresponding to the day of the week\ndef day_of_week(day, month, year):\n days_of_week = [ \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"]\n total = total_days(day, month, year)\n day_of_week = total % 7\n return days_of_week[day_of_week]\n\n\ndef days_difference(day, month, year):\n today = date.today()\n today_total = total_days(today.day, today.month, today.year)\n other_date_total = total_days(day, month, year)\n return today_total - other_date_total\n \n\ndef calculate_date():\n print(\"Enter the date in mm/dd/yyyy format: \")\n date = input()\n date_seperated = date.split(\"/\")\n day = int(date_seperated[1])\n month = int(date_seperated[0])\n year = int(date_seperated[2])\n print(date + \" is a \" + day_of_week(day, month, year) + \". \")\n difference = days_difference(day, month, year)\n if difference < 0:\n \n print(str(abs(difference)) + \" days until \" + date)\n elif difference > 0:\n print(date + \" was \" + str(difference) + \" days ago.\" )\n else:\n print(date + \" is today!\")\n \ncalculate_date()\n\n","repo_name":"aguvarasc/day-of-week-app","sub_path":"date_calculater.py","file_name":"date_calculater.py","file_ext":"py","file_size_in_byte":2276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18955677966","text":"import argparse\nimport os\nimport re\n\nDEBUG_ON = False\n\nDEFAULT_ROOT_DIR = \"root\"\nDEFAULT_TEMPLATE_FILE = \"Models/sms_fullExampleModel.txt\"\nDEFAULT_TAB_SIZE = 4\n\n\n# Count number of tabs on a line\ndef count_tabs(line):\n cnt = 0\n for char in line:\n if char == \" \":\n cnt += 1\n else:\n break\n if cnt % 4 != 0:\n raise Exception(\"Irregular tab length\")\n else:\n return cnt // 4\n\n\n# Move up x number of directories\ndef move_up_dirs(cnt):\n for i in range(0, cnt):\n os.chdir('..')\n return\n\n\n# Generate directories from template file starting at root\ndef generate_dirs(root_path, template_file):\n details = \"Generated directories:\\n\"\n cwd = os.getcwd()\n os.chdir(root_path)\n\n current_level, prev_level = 0, 0\n with open(template_file, 'r') as template:\n for line in template:\n # Skip over whitespace\n if line.isspace():\n continue\n\n dir_name = line.lstrip().rstrip() # Strip white space before and after\n prev_level = current_level\n current_level = count_tabs(line) + 1\n\n # Move up directories if needed\n if prev_level >= current_level:\n move_up_dirs(prev_level - current_level + 1)\n\n if DEBUG_ON:\n print(f\"Current path: {os.getcwd()}\")\n print(f\"Cur Level={current_level}, Prev Level={prev_level}, {dir_name}\")\n\n # Create directory and enter it\n os.mkdir(dir_name)\n dir_path = os.path.join(os.getcwd(), dir_name)\n details += current_level * \"\\\\\" + f\"{dir_name}\\n\"\n os.chdir(dir_path)\n\n os.chdir(cwd)\n return details\n\n\n# Generates a root directory based off a naming convention string (Ex. E### -> E001)\ndef generate_root(root_of_root, number_template):\n start_i, end_i = re.search(\"#+\", number_template).regs[0]\n start_str = number_template[:start_i]\n num_length = end_i - start_i\n\n model_cnt = get_models_in_dir_count(root_of_root, start_str)\n num_str = str(model_cnt + 1).zfill(num_length)\n\n path = os.path.join(root_of_root, start_str + num_str)\n os.mkdir(path)\n return path\n\n\n# Counts number of files in root whose start of name matches the string\ndef get_models_in_dir_count(root, start_str):\n i = 0\n files = os.listdir(root)\n for f in files:\n if re.match(f\"^({start_str}\\B)\", f):\n i += 1\n return i\n\n\nif __name__ == \"__main__\":\n description = \"Create directory structure based off template file.\"\n parser = argparse.ArgumentParser(description=description)\n parser.add_argument(\"--root_dir\", help=f\"Root directory. Default is '{DEFAULT_ROOT_DIR}'\", default=DEFAULT_ROOT_DIR)\n parser.add_argument(\"--template\", help=f\"Template file. Default is '{DEFAULT_TEMPLATE_FILE}'\",\n default=DEFAULT_TEMPLATE_FILE)\n parser.add_argument(\"--tab_size\", help=f\"Tab size in spaces. Default is '{DEFAULT_TAB_SIZE}'\",\n default=DEFAULT_TAB_SIZE)\n args = parser.parse_args()\n\n starting_path = os.getcwd()\n root_path = os.path.join(starting_path, args.root_dir)\n\n if not os.path.isdir(root_path):\n os.mkdir(root_path)\n\n generate_dirs(root_path, args.template, \"Project Medicine\")\n","repo_name":"mmelkumyan/PipelineStructureTool","sub_path":"PipelineScript/folderStructureGenerator.py","file_name":"folderStructureGenerator.py","file_ext":"py","file_size_in_byte":3292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6922167335","text":"import heapq\nfrom collections import deque\nimport sys\ninput = sys.stdin.readline\n'''\n-다익스트라 최단 경로 알고리즘을 수행합니다\n-다익스트라 최단 경로에 포함되는 모든 간선을 추적해야합니다\n-초기 최단 경로에 포함된 간선을 제외한 뒤에 다시 최단 경로를 탐색합니다 \n\nBFS를 이용하여 최단 경로에 포함되어 있는 모든 간선을 역으로 추적할 수 있습니다\n\n'''\ndef dijikstra():\n distance[start] = 0 # 자기 자신의 거리 = 0\n data = []\n heapq.heappush(data,(0,start))\n while data:\n dist, now = heapq.heappop(data)\n if dist > distance[now]:\n continue\n for node in graph[now]:\n cost = node[1]+dist # cost = 현재노드에서 node까지의 거리\n if cost < distance[node[0]] and not dropped[now][node[0]]: # 만약 이미 저장된 거리 정보가 더 작다면 pass\n distance[node[0]] = cost\n heapq.heappush(data,(cost,node[0])) # 노드와 거리정보를 힙에 담아줌\n\ndef bfs():\n q = deque([end])\n while q:\n now = q.popleft()\n if now==start:\n continue\n for node,c in bfsGraph[now]:\n if distance[node]+c==distance[now]:\n dropped[node][now] = True\n q.append(node)\n\nwhile True: # n,m 이 모두 0일때 종료\n INF = float('inf')\n n,m = map(int,input().split()) # 장소의 수, 도로의 수\n if n==0:\n break\n start,end = map(int,input().split()) # 시작점, 도착점\n graph = [[] for _ in range(n)] # 0~n-1 까지의 도로 정보\n bfsGraph = [[] for _ in range(n)]\n for _ in range(m):\n u,v,p = map(int,input().split())\n graph[u].append((v,p)) # u에서 v까지의 거리 P\n bfsGraph[v].append((u,p))\n # u 에서 v까지 가는 도로는 최대 한개이다 이를 이용하여 거의 거리를 계산하자\n dropped = [[False]*(n+1) for _ in range(n+1)]\n distance = [INF]*(n)\n dijikstra()\n bfs()\n distance = [INF]*(n)\n dijikstra()\n print((distance[end] if distance[end] != INF else -1))\n\n\n\n","repo_name":"wjddn3711/algorithm","sub_path":"basic/5719.py","file_name":"5719.py","file_ext":"py","file_size_in_byte":2149,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39736697379","text":"# A file contating my implementations of all the ml algortihms\nimport numpy as np\nfrom helperFunctions import *\n\n\nclass LinearRegression:\n def __init__(self):\n self.trained = False\n self.parameters = None\n self.costsOverTime = None\n \n\n def train(self, x, y, learn_rate = 0.01, n_itter = 1000, Lambda = 0):\n\n X = addBiases(x)\n m, n = np.shape(X)\n self.costsOverTime = []\n self.parameters = np.random.random_sample(n)\n\n # Gradient Descent\n for i in range(n_itter):\n y_hat = np.dot(X, self.parameters)\n grad = (1 / m) * np.dot((y_hat - y), X) + (Lambda / m) * np.hstack((0, self.parameters[1:]))\n\n self.parameters = self.parameters - learn_rate * grad\n self.costsOverTime.append(self.cost(y, y_hat, m, Lambda))\n\n self.trained = True\n\n\n def cost(self, y, y_hat, m, Lambda):\n return (1 / (2 * m)) * sum(np.square((y_hat - y))) + (Lambda / m) * sum(self.parameters[1:] ** 2)\n\n\n def predict(self, x):\n if self.trained:\n X = np.hstack((np.ones((np.shape(x)[0], 1)), x))\n return np.dot(X, self.parameters)\n else: \n print(\"Please train the model first\")\n\n\n\nclass LogisticRegression:\n def __init__(self):\n self.trained = False\n self.parameters = None\n self.costsOverTime = None\n \n\n def train(self, x, y, learn_rate = 0.1, n_itter = 1000, Lambda = 0):\n \n X = addBiases(x)\n m, n = np.shape(X)\n self.costsOverTime = []\n self.parameters = np.random.random_sample(n)\n\n # Gradient Descent\n for i in range(n_itter):\n y_hat = sigmoid(np.matmul(X, self.parameters))\n grad = (1 / m) * np.matmul((y_hat - y), X) + (Lambda / m) * np.hstack((0, self.parameters[1:]))\n\n self.parameters = self.parameters - learn_rate * grad\n self.costsOverTime.append(self.cost(y, y_hat, m, Lambda))\n\n self.trained = True\n\n\n def cost(self, y, y_hat, m, Lambda):\n return (1 / m) * sum(-y * np.log(y_hat) - (1 - y) * np.log(1 - y_hat)) + (Lambda / (2*m)) * sum(self.parameters[1:] ** 2)\n\n\n def predict(self, x, response = True):\n if self.trained:\n X = addBiases(x)\n p = sigmoid(np.matmul(X, self.parameters))\n\n return np.round(p) if response else p\n\n else:\n print(\"Please train the model first\")\n\n\n\nclass KNNClassifier:\n def __init__(self):\n self.X = None\n self.labels = None\n self.trained = False\n\n \n def train(self, x, y):\n self.X = x\n self.labels = y\n self.trained = True\n \n\n def predict(self, x, k = 7):\n if self.trained:\n dist = distance(x, self.X)\n\n knn_to_x = np.argpartition(dist, k)[:, 0:k] # Indecies of the knn to x in the train set\n y_hat = mode(self.labels[knn_to_x]) # Predict the knn's modal class\n return np.array(y_hat)\n \n else:\n print(\"Please first train the model\")\n\n\n\nclass KMeansClustering:\n def __init__(self):\n self.trained = False\n self.centroids = None\n self.costsOverTime = None\n\n\n def train(self, x, k, n_itter = 20):\n m, n = np.shape(x)\n self.costsOverTime = []\n\n # Initilise centroids as random elements of x\n self.centroids = x[np.random.choice(m, k, replace = False), :]\n \n for i in range(n_itter):\n closest_centroids = self.closestCentroids(x)\n\n # Assign the new centroids as the mean positon of x's assigned to it\n for j in range(k):\n self.centroids[j] = np.mean(x[np.where(closest_centroids == j), :], 1)\n\n # Record the new centroid choice's cost\n self.costsOverTime.append(self.cost(x))\n\n self.trained = True\n\n\n def cost(self, x):\n closest_centroids = self.closestCentroids(x)\n\n # Find square distance from x and its corresponding centroid\n sq_dist_xs_centriods = np.sum(np.square(x - self.centroids[[int(i) for i in closest_centroids.tolist()], :]), 1)\n\n return (1 / len(sq_dist_xs_centriods)) * np.sum(sq_dist_xs_centriods)\n\n\n def closestCentroids(self, x):\n closest_centroids = np.array([])\n\n for entry in x:\n closest_centriod = np.argmin(np.sum(np.square(entry - self.centroids), 1))\n closest_centroids = np.append(closest_centroids, closest_centriod)\n \n return closest_centroids\n\n\n\ndef PCA(x, var_to_retain = 0.99):\n Sigma = (1 / np.shape(x)[0]) * np.matmul(np.transpose(x), x)\n\n # Singular value decomposition of sigma\n results = np.linalg.svd(Sigma)\n U, S = results[0:2]\n\n # Find min number of principal components to preserve (var_to_retain) varience\n n_pc = np.where((np.cumsum(S) / np.sum(S)) > var_to_retain)[0][0]\n\n # Return data mapped to a lower dimention\n return np.matmul(x, U[:, 0:n_pc])\n","repo_name":"mlglegobloxer/machine-learning-algorthms","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4978,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71370601425","text":"import logging\n\nfrom waveapi import robot\nfrom waveapi import element\nfrom waveapi import blip\nimport credentials\n\ndef logSomething(str):\n logging.info(str)\n\ndef addLine(wavelet_ser, num):\n # Construct robot\n myrobot = robot.Robot('Scrolly')\n\n # Construct wavelet\n wavelet = myrobot.blind_wavelet(wavelet_ser)\n\n # Setup Oauth\n myrobot.setup_oauth(credentials.CONSUMER_KEY, credentials.CONSUMER_SECRET,\n server_rpc_base=credentials.RPC_BASE[wavelet.domain])\n\n pattern = '>>>'\n line = ''\n for x in range(num):\n line += pattern\n line += '\\n'\n\n wavelet.root_blip.append(line)\n myrobot.submit(wavelet)\n","repo_name":"JackDanger/google-wave-samples","sub_path":"extensions/robots/python/deferry/actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"31568638812","text":"from flask import Flask, render_template, request\nimport RPi.GPIO as GPIO\nimport time\nimport os\n\n# STATUSLED = 40\nSTATUSLED = 7 #rood\nSTATUSDRUP1 = 22 #bruin\nSTATUSDRUP2 = 18 #zwart\nSTATUSCAM = 16 #lichtgrijs\nSWITCHDRUP = 15 #grijs\nSWITCHCAM = 13 #paars\nINPUTSW1 = 11 #blauw\nINPUTSW2 = 12 #groen\n\n# timing_druppel1 = 0.0400 # druppel 1 tijd dat het klepje open staat\n# timing_druppel2 = 0.0400 # druppel 2 tijd dat het klepje open staat\n\n# timing_tussen1 = 0.0600 # tijd tussen druppel 1 en druppel 2\n# timing_tussen2 = 0.2000 # tijd tot de camera een signaal krijgt (samen 0.24 / 0.26\n\n# timing_flash = 0.0200 # Duur van het signaal om de camera een foto te laten maken.\n# timing_pauze = 7.0000 # Pause tijd waarop het water weer rustig is en de volgende druppels kunnen komen\nontluchten = 0.5000 # opstarten en laat 1/2 seconde water stromen\n\ndef cls():\n os.system('clear')\n\ndef init():\n cls()\n GPIO.setmode(GPIO.BOARD)\n GPIO.setwarnings(False)\n\n GPIO.setup(STATUSLED, GPIO.OUT)\n GPIO.setup(STATUSDRUP1, GPIO.OUT)\n GPIO.setup(STATUSDRUP2, GPIO.OUT)\n GPIO.setup(STATUSCAM, GPIO.OUT)\n GPIO.setup(SWITCHDRUP, GPIO.OUT)\n GPIO.setup(SWITCHCAM, GPIO.OUT)\n # GPIO.setup(INPUTSW1, GPIO.IN, pull_up_down = GPIO.PUD_UP)\n # GPIO.setup(INPUTSW2, GPIO.IN, pull_up_down = GPIO.PUD_UP)\n\n GPIO.output(STATUSLED, GPIO.LOW) # LED opstelling actief\n GPIO.output(STATUSDRUP1, GPIO.LOW) # LED druppel 1\n GPIO.output(STATUSDRUP2, GPIO.LOW) # LED druppel 2\n GPIO.output(STATUSCAM, GPIO.LOW) # LED Camera\n GPIO.output(STATUSDRUP1, GPIO.HIGH) # Trigger Camera\n\n GPIO.output(SWITCHDRUP, GPIO.LOW) # Trigger Magneetklep\n print(\"Ontluchten waterklep\")\n time.sleep(ontluchten)\n GPIO.output(SWITCHDRUP, GPIO.HIGH) # Trigger Magneetklep\n\ndef druppel1(timing):\n print(\"Druppel 1 aan voor %.4f seconden\" % timing)\n GPIO.output(STATUSDRUP1, GPIO.HIGH)\n GPIO.output(SWITCHDRUP, GPIO.LOW)\n time.sleep(timing)\n GPIO.output(SWITCHDRUP, GPIO.HIGH)\n GPIO.output(STATUSDRUP1, GPIO.LOW)\n print(\"Druppel 1 uit\")\n\ndef druppel2(timing):\n print(\"Druppel 2 aan voor %.4f seconden\" % timing)\n GPIO.output(STATUSDRUP2, GPIO.HIGH)\n GPIO.output(SWITCHDRUP, GPIO.LOW)\n time.sleep(timing)\n GPIO.output(SWITCHDRUP, GPIO.HIGH)\n GPIO.output(STATUSDRUP2, GPIO.LOW)\n print(\"Druppel 2 uit\")\n\ndef flash(timing):\n print(\"Camera in \")\n GPIO.output(STATUSCAM, GPIO.HIGH)\n GPIO.output(SWITCHCAM, GPIO.LOW)\n time.sleep(timing)\n GPIO.output(SWITCHCAM, GPIO.HIGH)\n GPIO.output(STATUSCAM, GPIO.LOW)\n print(\"Camera uit\")\n\napp = Flask(__name__)\n\ninit()\n\n@app.route(\"/\", methods=['POST','GET'])\ndef index():\n if request.method == 'GET':\n return render_template('index.html')\n else:\n cls()\n try:\n # value = float(request.form['amount'])\n timing_druppel1 = float(request.form['timing_druppel1']) # druppel 1 tijd dat het klepje open staat\n timing_druppel2 = float(request.form['timing_druppel2']) # druppel 2 tijd dat het klepje open staat\n timing_tussen1 = float(request.form['timing_tussen1']) # tijd tussen druppel 1 en druppel 2\n timing_tussen2 = float(request.form['timing_tussen2']) # tijd tot de camera een signaal krijgt (samen 0.24 / 0.26\n timing_flash = float(request.form['timing_flash']) # Duur van het signaal om de camera een foto te laten maken.\n timing_pauze = float(request.form['timing_pauze']) # Pause tijd waarop het water weer rustig is en de volgende\n exacutetimes = int(request.form['exacutetimes'])\n\n print(\"Timing drup1: {}\\n Timing drup2: {}\\n Timing tussen1: {}\\n Timing tussen2: {}\\n Timing flash: {}\\n Timing pauze: {}\\n Aantal loops: {}\".format(timing_druppel1,\n timing_druppel2,\n timing_tussen1,\n timing_tussen2,\n timing_flash,\n timing_pauze,\n exacutetimes))\n try:\n for i in range(0, exacutetimes):\n GPIO.output(STATUSLED, GPIO.HIGH)\n print(\"Druppelaar nieuwe loop\")\n druppel1(timing_druppel1)\n time.sleep(timing_tussen1)\n print(\"Druppelaar nieuwe loop\")\n druppel2(timing_druppel2)\n time.sleep(timing_tussen2)\n flash(timing_flash)\n print(\"Sleeping\")\n GPIO.output(STATUSLED, GPIO.LOW)\n time.sleep(timing_pauze)\n except:\n print(\"except\")\n pass\n # GPIO.output(STATUSLED, GPIO.LOW)\n except:\n print('Exception')\n pass\n return render_template('index.html', \n timing_druppel1=timing_druppel1, \n timing_druppel2=timing_druppel2,\n timing_tussen=timing_tussen1,\n timing_tussen2=timing_tussen2,\n timing_flash=timing_flash,\n timing_pauze=timing_pauze)\n\n\nif __name__ == '__main__':\n app.run(debug=True, host='0.0.0.0')","repo_name":"MaxNijholt/RBPI","sub_path":"WebFlask.py","file_name":"WebFlask.py","file_ext":"py","file_size_in_byte":5240,"program_lang":"python","lang":"nl","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37705607418","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport math\ndef fx(x):\n return (x-3)**2\n\ndef grad_f(x):\n return 2*(x-3)\n\ndef sgd(iter=300,eta=0.1,x=0):\n err = 1.0\n it = 0\n ys = [fx(x)]\n while err > 1e-4 and it < iter:\n x = x - grad_f(x) * eta\n # print(x)\n new_y = fx(x)\n err = math.fabs(new_y - ys[it])\n ys.append(new_y)\n it += 1\n return ys\n\ndef back_tracking(iter=300,gamma=0.25,c=0.8,x=0):\n err = 1.0\n it = 0\n ys = [fx(x)]\n while err > 1e-4 and it < iter:\n g = grad_f(x) \n step = 1.0\n newf = fx(x - step*g)\n df = c*g*g\n # print(x-t*g)\n while newf > ys[it] - step*df:\n step *= gamma\n newf = fx(x - step*g)\n \n \n x = x-step*g\n print(x)\n new_y = fx(x)\n err = math.fabs(new_y - ys[it])\n ys.append(new_y)\n it += 1\n return ys\n\n\nplt.figure(figsize=(12,8))\nys = back_tracking()\nys2 = sgd()\nprint(ys)\n\n# print(np.arange(len(ys)))\nplt.plot(np.arange(len(ys)),ys,label='ys1')\nplt.plot(np.arange(len(ys2)),ys2,label='ys2',marker='o' )\nplt.legend()\n# plt.plot([1,2],[2,3])\nplt.show()\n\n\n ","repo_name":"tinymindxx/time-series-predict","sub_path":"line_search.py","file_name":"line_search.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"43744025273","text":"from NetworkTrainer import NetworkTrainer\n\nimport time\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.ensemble import AdaBoostClassifier\n\n\nclass SuSyTruthChecker(NetworkTrainer):\n \"\"\"\n This class should read in a .csv file containing training data, train a\n model based on 19 free parameters to identify if a simulated signal should\n be true or not.\n \"\"\"\n\n def __init__(self, train_file: str, test_file: str, target: str = '',\n standardised: bool = False, normalised: bool = False):\n super().__init__(train_file, test_file, target,\n standardised, normalised)\n self.method = 'none'\n\n def train(self, method: str):\n \"\"\"\n Method for selecting a preconfigured training method applied to the\n dataset.\n :param method: ['knn', 'dt', 'gnb'].\n :return:\n \"\"\"\n if method == 'knn':\n # 'Best' result came from had an accuracy of ~0.59, which is just a\n # bit better than guessing.\n self.method = 'k nearest neighbours'\n model = KNeighborsClassifier(n_neighbors=5)\n return self._train_model(model)\n elif method == 'dt':\n # Best result came from doing nothing with the data, and resulted\n # in an accuracy of ~0.89.\n self.method = 'decision tree'\n model = DecisionTreeClassifier(\n min_samples_leaf=4,\n min_samples_split=10\n )\n return self._train_model(model)\n elif method == 'gnb':\n # This method is based on the Bayesian probability that a point in\n # the data set is a certain class, e.g. p(x = 1), given all the\n # parameters for this point, y_i, so e.g. p(x = 1 | y_i). The naive\n # part of the method is that it considers that all these parameters\n # y_i are independent of each other.\n # This method was just implemented to see the documentation from\n # scikit-learn, no real experimenting has been done. This delivered\n # an accuracy of ~0.78.\n self.method = 'naive bayes (gaussian)'\n model = GaussianNB()\n return self._train_model(model)\n elif method == 'adaboost':\n self.method = method\n model = AdaBoostClassifier(n_estimators=2)\n return self._train_ensemble(model)\n else:\n raise Exception(\"No proper training method provided.\")\n return 0\n\n def _train_model(self, training_model):\n start = time.time()\n training_model.fit(self.train_data[self.attributes],\n self.train_data[self.target])\n\n prediction = training_model.predict(self.val_data[self.attributes])\n accuracy = accuracy_score(self.val_data[self.target], prediction)\n\n print(\"Training time: %d seconds\" % (time.time() - start))\n print(\"Accuracy of model:\", accuracy)\n\n return training_model\n\n def _train_ensemble(self, training_model):\n start = time.time()\n scores = cross_val_score(training_model,\n self.full_train_data[self.attributes],\n self.full_train_data[self.target],\n cv=5)\n\n print(\"Training time: %d seconds\" % (time.time() - start))\n print(\"Accuracy of model:\", scores.mean())\n return training_model\n","repo_name":"GroenteLepel/ML_ParticleAndAstrophysics","sub_path":"SuSyTruthChecker.py","file_name":"SuSyTruthChecker.py","file_ext":"py","file_size_in_byte":3622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13364131065","text":"'''\nWrite a short recursive Python function that determines if a string s is a\npalindrome, that is, it is equal to its reverse. For example, \"racecar\" and\n\"gohangasalamiimalasagnahog\" are palindromes.\n'''\ndef is_palindrome(s):\n if s == \"\":\n return True\n else:\n if s[0] == s[-1]:\n return is_palindrome(s[1:-1])\n else:\n return False\n \n \n \nprint(is_palindrome(\"racecar\"))\nprint(is_palindrome(\"gohangasalamiimalasagnahog\"))\n\n ","repo_name":"FuratMAlsmadi/AlgoNinga","sub_path":"Chapter_4/Creativity/C_4.17.py","file_name":"C_4.17.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30378324427","text":"import sys\n\nn = int(sys.stdin.readline())\narray = []\nfor i in range(n) :\n\tarray.append(list(map(int,sys.stdin.readline().split())))\n\ncheck = 0\ndef dfs(x,y) :\n\n\tglobal check\n\tif array[x][y] == -1 :\n\t\tcheck +=1\n\tdx = [0,array[x][y]*1]\n\tdy = [array[x][y]*1,0]\n\tfor j in range(array[x][y]) :\n\t\tfor i in range(len(dx)) :\n\t\t\tnx = x + dx[i]\n\t\t\tny = y + dy[i]\n\t\t\tif (0<=nx<=n-1) and (0<=ny<=n-1) :\n\t\t\t\tdfs(nx,ny)\n\ndfs(0,0)\nif check!=0 :\n\tprint('HaruHaru')\nelse :\n\tprint('Hing')\n\n\n","repo_name":"mostar39/coding_study","sub_path":"baekjoon/dfs/16173_점프왕 쩰리(Small).py","file_name":"16173_점프왕 쩰리(Small).py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10793585896","text":"import logging\nimport warnings\nfrom copy import deepcopy\n\nfrom great_expectations.datasource.batch_kwargs_generator.batch_kwargs_generator import (\n BatchKwargsGenerator,\n)\nfrom great_expectations.exceptions import BatchKwargsError, InvalidBatchKwargsError\n\nlogger = logging.getLogger(__name__)\n\n\nclass ManualBatchKwargsGenerator(BatchKwargsGenerator):\n \"\"\"ManualBatchKwargsGenerator returns manually-configured batch_kwargs for named data assets. It provides a\n convenient way to capture complete batch requests without requiring the configuration of a more\n fully-featured batch kwargs generator.\n\n A fully configured ManualBatchKwargsGenerator in yml might look like the following::\n\n my_datasource:\n class_name: PandasDatasource\n batch_kwargs_generators:\n my_generator:\n class_name: ManualBatchKwargsGenerator\n assets:\n asset1:\n - partition_id: 1\n path: /data/file_1.csv\n reader_options:\n sep: ;\n - partition_id: 2\n path: /data/file_2.csv\n reader_options:\n header: 0\n logs:\n path: data/log.csv\n \"\"\"\n\n recognized_batch_parameters = {\"data_asset_name\", \"partition_id\"}\n\n def __init__(self, name=\"default\", datasource=None, assets=None) -> None:\n logger.debug(f\"Constructing ManualBatchKwargsGenerator {name!r}\")\n super().__init__(name, datasource=datasource)\n\n if assets is None:\n assets = {}\n\n self._assets = assets\n\n @property\n def assets(self):\n return self._assets\n\n def get_available_data_asset_names(self):\n return {\"names\": [(key, \"manual\") for key in self.assets.keys()]}\n\n def _get_data_asset_config(self, data_asset_name):\n if data_asset_name is None:\n return\n\n elif data_asset_name in self.assets:\n return self.assets[data_asset_name]\n\n raise InvalidBatchKwargsError(\n f\"No asset definition for requested asset {data_asset_name}\"\n )\n\n def _get_iterator(self, data_asset_name, **kwargs):\n datasource_batch_kwargs = self._datasource.process_batch_parameters(**kwargs)\n asset_definition = deepcopy(self._get_data_asset_config(data_asset_name))\n if isinstance(asset_definition, list):\n for batch_request in asset_definition:\n batch_request.update(datasource_batch_kwargs)\n return iter(asset_definition)\n else:\n asset_definition.update(datasource_batch_kwargs)\n return iter([asset_definition])\n\n # TODO: deprecate generator_asset argument\n def get_available_partition_ids(self, generator_asset=None, data_asset_name=None):\n assert (generator_asset and not data_asset_name) or (\n not generator_asset and data_asset_name\n ), \"Please provide either generator_asset or data_asset_name.\"\n if generator_asset:\n # deprecated-v0.11.0\n warnings.warn(\n \"The 'generator_asset' argument is deprecated as of v0.11.0 and will be removed in v0.16. \"\n \"Please use 'data_asset_name' instead.\",\n DeprecationWarning,\n )\n data_asset_name = generator_asset\n\n partition_ids = []\n asset_definition = self._get_data_asset_config(data_asset_name=data_asset_name)\n if isinstance(asset_definition, list):\n for batch_request in asset_definition:\n try:\n partition_ids.append(batch_request[\"partition_id\"])\n except KeyError:\n pass\n elif isinstance(asset_definition, dict):\n try:\n partition_ids.append(asset_definition[\"partition_id\"])\n except KeyError:\n pass\n return partition_ids\n\n def _build_batch_kwargs(self, batch_parameters):\n \"\"\"Build batch kwargs from a partition id.\"\"\"\n partition_id = batch_parameters.pop(\"partition_id\", None)\n batch_kwargs = self._datasource.process_batch_parameters(batch_parameters)\n if partition_id:\n asset_definition = self._get_data_asset_config(\n data_asset_name=batch_parameters.get(\"data_asset_name\")\n )\n if isinstance(asset_definition, list):\n for batch_request in asset_definition:\n try:\n if batch_request[\"partition_id\"] == partition_id:\n batch_kwargs = deepcopy(batch_request)\n batch_kwargs.pop(\"partition_id\")\n except KeyError:\n pass\n elif isinstance(asset_definition, dict):\n try:\n if asset_definition[\"partition_id\"] == partition_id:\n batch_kwargs = deepcopy(asset_definition)\n batch_kwargs.pop(\"partition_id\")\n except KeyError:\n pass\n else:\n batch_kwargs = next(\n self._get_iterator(\n data_asset_name=batch_parameters.get(\"data_asset_name\")\n )\n )\n\n if batch_kwargs is not None:\n return batch_kwargs\n else:\n raise BatchKwargsError(\n \"Unable to find batch_kwargs for given batch_parameters\",\n batch_parameters,\n )\n","repo_name":"franciscojavierarceo/Python","sub_path":"demos/great-expectations/venv/lib/python3.8/site-packages/great_expectations/datasource/batch_kwargs_generator/manual_batch_kwargs_generator.py","file_name":"manual_batch_kwargs_generator.py","file_ext":"py","file_size_in_byte":5541,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"} +{"seq_id":"19176959990","text":"import threading\nimport time\nimport random\n\n\ndef execute_thread(thread_num):\n print(\"Thread {} sleeps at {}.\".format(thread_num, time.strftime(\"%H:%M:%S\", time.gmtime())))\n\n sleep_time = random.randint(1, 5)\n\n time.sleep(sleep_time)\n\n print(\"Thread {} stops sleeping at {}.\".format(thread_num, time.strftime(\"%H:%M:%S\", time.gmtime())))\n\n\ndef main():\n for i in range(10):\n thread = threading.Thread(target=execute_thread, args=(i, ))\n # thread.daemon = True\n thread.start()\n # thread.join()\n\n print(\"Active threads: \", threading.active_count())\n print(\"thread objects: \", threading.enumerate())\n\nif __name__ == '__main__':\n main()\n","repo_name":"jwasham/practice-python","sub_path":"experiments/threads.py","file_name":"threads.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","stars":1548,"dataset":"github-code","pt":"48"} +{"seq_id":"19084451035","text":"# https://programmers.co.kr/learn/courses/30/lessons/42576\n\ndef solution(participant, completion):\n hash = {}\n \n for someone in participant:\n if(someone in hash):\n hash[someone] += 1\n else:\n hash[someone] = 1\n \n for someone in completion:\n if(someone in hash):\n hash[someone] -= 1\n \n for key, value in hash.items():\n if(value > 0):\n return key\n \n return ''","repo_name":"scissorstail/study","sub_path":"programmers/code_test_practice/hash/42576.py","file_name":"42576.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39959811281","text":"import csv as csv\nfrom os import listdir\nfrom os.path import isfile, join\n\nonlyfiles = [f for f in listdir(\"./JointFiles/\") if isfile(join(\"./JointFiles/\", f))]\n\nnumberOfRowsPython = 0\nnumberOfRowsC = 0\n\nfor fileName in onlyfiles:\n file = open(\"./JointFiles/\" + fileName, mode = \"r\", encoding=\"utf8\")\n fReader = csv.reader(file, delimiter = \",\")\n yearReader = 0\n firstRow = True\n for row in fReader:\n if firstRow:\n firstRow = False\n continue\n if 'C' in fileName:\n numberOfRowsC += 1\n else:\n numberOfRowsPython += 1\n yearReader += 1\n if 'C' in fileName:\n print(\"In \" + fileName[10:14] + \" the C community has answered \" + str(yearReader) + \" questions.\")\n else:\n print(\"In \" + fileName[15:19] + \" the Python community has answered \" + str(yearReader) + \" times.\")\nprint(\"The C community has answered a total of \" + str(numberOfRowsC) + \" times.\")\nprint(\"The Python community has answered a total of \" + str(numberOfRowsPython) + \" times.\")\nprint(\"In total the dataset contains \" + str((numberOfRowsC+numberOfRowsPython))+ \" answers.\")","repo_name":"GilgusMaximus/PolarityMining-StackOverflow","sub_path":"DataProcessing/statreader.py","file_name":"statreader.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23955704782","text":"import os, logging\nfrom logging import FileHandler\n\nclass Logger:\n def __init__(self, **kwargs):\n self.info_format = '[%(asctime)s] [%(process)d] [%(levelname)s] %(message)s'\n self.timestamp_format = '%Y-%m-%d %H:%M:%S %z'\n self.message = kwargs['message']\n self.type = 'info'\n self.file = 'app'\n\n if 'type' in kwargs.keys():\n self.type = kwargs['type']\n\n if 'file' in kwargs.keys():\n self.file = kwargs['file']\n\n def log(self):\n log = self._log()\n log.handlers.clear()\n log.addHandler(self._file_handler())\n log.setLevel(getattr(logging, self.type.upper()))\n return getattr(log, self.type)(self.message)\n\n def _log(self):\n return logging.getLogger(self.file)\n\n def _file_handler(self):\n handler = FileHandler(self._pwd(), mode='a')\n handler.setFormatter(self._formatter())\n return handler\n\n def _formatter(self):\n return logging.Formatter(self.info_format, self.timestamp_format)\n\n def _pwd(self):\n if not os.path.exists('logs'):\n os.makedirs('logs')\n\n return \"logs/{file}.log\".format(file=self.file)\n","repo_name":"open-sourcepad/python-skeleton","sub_path":"app/libs/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22438587679","text":"# 변수의 세부 구현 사항\nx = 10\nid(x)\n\nx = 3\ny = x # 변수 y에 변수 x의 참조값이 복사된다.\nid(x)\nid(y) # 같은 주소를 가리킨다.\n\ny = 10 # 변수 y에 새로운 값이 할당되면 주소가 달라진다.\nid(y)\n","repo_name":"peterchokr/python","sub_path":"src/chap02/p58_id.py","file_name":"p58_id.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"ko","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"29508623279","text":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport sys\nimport os\nimport datetime\n\nfrom supervision import anatomy_consistency_loss, masked_l1_loss\nfrom utils.checkpoint import save_network_state\nfrom utils.checkpoint import count_parameters\nfrom utils.label_mixing import check_label_mix\nfrom utils.visualization import VisdomVisualizer\nfrom loaders.dataloader import get_training_data\nfrom options.base_options import parse_arguments\nfrom models import get_model\n\nif __name__ == \"__main__\":\n opt, uknown = parse_arguments(sys.argv)\n print('{} | Torch Version: {}'.format(datetime.datetime.now(), torch.__version__)) \n gpus = [int(id) for id in opt.gpu.split(',') if int(id) >= 0]\n device = torch.device('cuda:{}' .format(gpus[0]) if torch.cuda.is_available() and len(gpus) > 0 and gpus[0] >= 0 else 'cpu')\n print('Training {0} for {1} epochs using a batch size of {2} on {3}'.format(opt.name, opt.epochs, opt.batch_size, device))\n\n torch.manual_seed(667)\n if device.type == 'cuda':\n torch.cuda.manual_seed(667)\n visualizer = VisdomVisualizer(opt.name, count=1)\n\n #load DAA-GAN noise injection+generator, discriminator modules\n G, D = get_model(opt)\n model_dict = G.state_dict()\n if opt.load_sdnet_decoder_weights_path != '':\n pretrained_model = torch.load(opt.load_sdnet_decoder_weights_path, map_location=device)\n pretrained_dict = pretrained_model['model_state_dict']\n pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict}\n model_dict.update(pretrained_dict) \n G.load_state_dict(model_dict)\n G.to(device)\n num_paramsG = count_parameters(G)\n D.to(device)\n num_paramsD = count_parameters(D)\n num_params = num_paramsD + num_paramsG\n\n #load pretrained pathology classifier weights\n if opt.load_vgg_weights_path != '':\n opt.model_name = 'vgg'\n VGG = get_model(opt)\n pretrained = torch.load(opt.load_vgg_weights_path, map_location=device)\n VGG.load_state_dict(pretrained['model_state_dict'])\n VGG.to(device)\n else:\n print(\"Could not find VGG weights in the specified path ({})\".format(opt.load_vgg_weights_path), file=sys.stderr)\n sys.exit()\n print('Model Parameters: ', num_params)\n\n #load data\n all_images, labels, anatomy_factors, modality_factors = get_training_data(opt)\n\n #optimizer initialization\n optimizerG = optim.Adam(G.parameters(), betas=(0.0,0.999), lr=opt.learning_rate)\n optimizerD = optim.Adam(D.parameters(), betas=(0.0,0.999), lr=opt.learning_rate)\n\n #loss initialization\n nll_loss = nn.NLLLoss().to(device)\n\n #auxiliary tensors init\n b_images = torch.zeros(opt.batch_size, 1, opt.dim, opt.dim)\n b_labels = torch.zeros(opt.batch_size, 1)\n \n b_images2 = torch.zeros(opt.batch_size, 1, opt.dim, opt.dim)\n b_labels2 = torch.zeros(opt.batch_size, 1)\n \n a_out = torch.zeros(opt.batch_size, opt.anatomy_out_channels, opt.dim, opt.dim)\n mu_out = torch.zeros(opt.batch_size, 8)\n a_out_2 = torch.zeros(opt.batch_size, opt.anatomy_out_channels, opt.dim, opt.dim)\n \n mixed = torch.zeros(opt.batch_size, 1)\n mixed_real = torch.zeros(opt.batch_size, 1, opt.dim, opt.dim)\n mixed_labels = torch.zeros(opt.batch_size, 1)\n \n aggregated_noise_mask = torch.zeros(opt.batch_size, 1, opt.dim, opt.dim)\n aggregated_source_mask = torch.zeros(opt.batch_size, 1, opt.dim, opt.dim)\n zero_mask = torch.zeros(1, opt.dim, opt.dim)\n \n #create real/fake labels for Discriminator training\n real_labels = torch.ones(opt.batch_size).to(device)\n real_labels -= 0.1 # label smoothing\n fake_labels = torch.zeros(opt.batch_size).to(device)\n\n #train process\n total_batches = all_images.shape[0] // opt.batch_size\n global_iterations = 0\n for epoch in range(opt.epochs):\n idx = torch.randperm(all_images.shape[0])\n in_batch_iter = 0\n if opt.load_sdnet_decoder_weights_path != '':\n G.eval()\n else:\n G.train()\n D.train()\n VGG.eval()\n for iteration in range(all_images.shape[0]):\n idx2 = torch.randperm(all_images.shape[0])\n if (iteration + opt.batch_size) > all_images.shape[0]:\n break\n if in_batch_iter < opt.batch_size:\n #sample subject 1 and 2 images and the corresponding content and style factors\n b_images[in_batch_iter] = all_images[idx[iteration]]\n b_labels[in_batch_iter] = labels[idx[iteration]]\n b_images2[in_batch_iter] = all_images[idx2[iteration]]\n b_labels2[in_batch_iter] = labels[idx2[iteration]]\n a_out[in_batch_iter] = anatomy_factors[idx[iteration]]\n mu_out[in_batch_iter] = modality_factors[idx[iteration]]\n a_out_2[in_batch_iter] = anatomy_factors[idx2[iteration]]\n in_batch_iter += 1\n else:\n optimizerD.zero_grad()\n augmented_a_out = a_out.clone()\n #anatomy mixing based on pathology labels\n augmented_a_out, aggregated_noise_mask, aggregated_source_mask, mixed, _ = check_label_mix(2, 3, 4, \\\n augmented_a_out, a_out, a_out_2, aggregated_noise_mask, aggregated_source_mask, \\\n zero_mask, mixed, b_labels, b_labels2)\n for i in range(mixed.shape[0]):\n if mixed[i] > 0:\n mixed_real[i] = b_images2[i]\n mixed_labels[i] = b_labels2[i]\n else:\n mixed_real[i] = b_images[i]\n mixed_labels[i] = b_labels[i]\n real_input = aggregated_source_mask * mixed_real\n real_output = D(real_input.detach().to(device)).squeeze()\n\n #lsgan discriminator loss - real\n real_disc_loss = 0.5 * torch.mean((real_output-real_labels)**2)\n reco, noisy_a_out = G(augmented_a_out.to(device), mu_out.to(device), aggregated_noise_mask.to(device))\n consistency_loss = anatomy_consistency_loss(noisy_a_out, augmented_a_out.to(device), aggregated_noise_mask.to(device))\n fake_output = D(reco.detach()).squeeze()\n if opt.load_vgg_weights_path is not None:\n pathology_output, _ = VGG(reco.detach())\n pathology_loss = nll_loss(pathology_output, mixed_labels.squeeze(1).long().to(device))\n l1_masked_loss, l1_masked_loss_map = masked_l1_loss(reco, b_images.to(device), aggregated_source_mask.to(device))\n \n #lsgan discriminator loss - fake\n fake_disc_loss = 0.5 * torch.mean((fake_output-fake_labels)**2)\n batch_D_loss = real_disc_loss + fake_disc_loss\n batch_D_loss.backward() \n optimizerD.step()\n D_x = real_output.mean()\n optimizerG.zero_grad()\n fake_input = aggregated_source_mask.to(device) * reco\n fake_output = D(fake_input).squeeze()\n \n #lsgan generator loss\n batch_fake_gen_loss = 0.5 * torch.mean((fake_output-real_labels)**2)\n generator_loss = batch_fake_gen_loss + pathology_loss + 10*(l1_masked_loss + consistency_loss)\n losses = {\n 'train_ADV': batch_fake_gen_loss.item(),\n 'train_PATH': pathology_loss.item(),\n 'train_BG': l1_masked_loss.item(),\n 'train_CONS': consistency_loss.item(),\n 'train_DISC': batch_D_loss.item()\n }\n \n #backprop and optimizer update\n generator_loss.backward()\n optimizerG.step()\n\n #visualizations\n if (iteration + 1) % opt.visdom_iters == 0:\n visualizer.show_map(b_images.to(device), 'A_')\n visualizer.show_map(b_images2.to(device), 'B_')\n visualizer.show_map(reco, 'A_prime')\n if opt.print_factors:\n visualizer.show_anatomical_factors(augmented_a_out, 'Mixed')\n if opt.model_name == 'noise':\n visualizer.show_map(aggregated_noise_mask.to(device), 'Noise_patch_')\n visualizer.show_anatomical_factors(noisy_a_out, 'Noisy')\n if (iteration + 1) % opt.disp_iters <= opt.batch_size:\n visualizer.append_loss(epoch, global_iterations, generator_loss.item(), \"train_COMBINED\")\n visualizer.append_loss(epoch, global_iterations, batch_fake_gen_loss.item(), \"train_G_loss\")\n visualizer.append_loss(epoch, global_iterations, consistency_loss.item(), \"train_cons_loss\")\n visualizer.append_loss(epoch, global_iterations, l1_masked_loss.item(), \"train_bg_loss\")\n visualizer.append_loss(epoch, global_iterations, batch_D_loss.item(), \"train_D_loss\")\n visualizer.append_loss(epoch, global_iterations, pathology_loss.item(), \"train_path_loss\")\n visualizer.append_loss(epoch, global_iterations, D_x.item(), \"D(x)\")\n global_iterations += opt.batch_size\n in_batch_iter = 0\n\n print(\"Epoch {} checkpoint\".format(epoch))\n if epoch == opt.epochs - 1 :\n current_dir = os.getcwd()\n final_dir = os.path.join(current_dir, opt.save_path)\n save_network_state(G, D, opt.dim, opt.ndf, \\\n opt.anatomy_out_channels, \\\n opt.z_length, optimizerG, optimizerD, \\\n epoch, opt.name + \"_model_state_epoch_\" + str(epoch), \\\n final_dir)\n\n \n\n","repo_name":"spthermo/DAA-GAN","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":9971,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"13897576751","text":"from django.contrib import messages\nfrom django.shortcuts import redirect\nfrom django.utils import translation\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.views.generic import FormView\n\nfrom ...base.models import Item, ItemVariation, WaitingListEntry\nfrom ...multidomain.urlreverse import eventreverse\nfrom ..forms.waitinglist import WaitingListForm\n\n\nclass WaitingView(FormView):\n template_name = 'pretixpresale/event/waitinglist.html'\n form_class = WaitingListForm\n\n def get_form_kwargs(self):\n kwargs = super().get_form_kwargs()\n kwargs['event'] = self.request.event\n kwargs['instance'] = WaitingListEntry(\n item=self.item_and_variation[0], variation=self.item_and_variation[1],\n event=self.request.event, locale=translation.get_language()\n )\n return kwargs\n\n def get_context_data(self, **kwargs):\n ctx = super().get_context_data()\n ctx['event'] = self.request.event\n ctx['item'], ctx['variation'] = self.item_and_variation\n return ctx\n\n @cached_property\n def item_and_variation(self):\n try:\n item = self.request.event.items.get(pk=self.request.GET.get('item'))\n if 'var' in self.request.GET:\n var = item.variations.get(pk=self.request.GET['var'])\n elif item.has_variations:\n return None\n else:\n var = None\n return item, var\n except (Item.DoesNotExist, ItemVariation.DoesNotExist):\n return None\n\n def dispatch(self, request, *args, **kwargs):\n self.request = request\n\n if not self.request.event.settings.waiting_list_enabled:\n messages.error(request, _(\"Waiting lists are disabled for this event.\"))\n return redirect(eventreverse(self.request.event, 'presale:event.index'))\n\n if not self.item_and_variation:\n messages.error(request, _(\"We could not identify the product you selected.\"))\n return redirect(eventreverse(self.request.event, 'presale:event.index'))\n\n return super().dispatch(request, *args, **kwargs)\n\n def form_valid(self, form):\n availability = (\n self.item_and_variation[1].check_quotas(count_waitinglist=False)\n if self.item_and_variation[1]\n else self.item_and_variation[0].check_quotas(count_waitinglist=False)\n )\n if availability[0] == 100:\n messages.error(self.request, _(\"You cannot add yourself to the waiting list as this product is currently \"\n \"available.\"))\n return redirect(eventreverse(self.request.event, 'presale:event.index'))\n\n form.save()\n messages.success(self.request, _(\"We've added you to the waiting list. You will receive \"\n \"an email as soon as tickets get available again.\"))\n return super().form_valid(form)\n\n def get_success_url(self):\n return eventreverse(self.request.event, 'presale:event.index')\n","repo_name":"BenBE/pretix","sub_path":"src/pretix/presale/views/waiting.py","file_name":"waiting.py","file_ext":"py","file_size_in_byte":3117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"41267482089","text":"import io\nimport os\nimport time\nimport zipfile\nimport json\nimport base64\nimport zlib\nfrom io import BytesIO\n\nimport yaml\nimport boto3\nimport pandas as pd\nfrom smart_open import open as sm_open\nfrom flask import Flask, send_file, render_template\nfrom flask_cors import CORS\n\napp = Flask(__name__)\nCORS(app=app)\n\n\n@app.route('/create_yaml')\ndef create_yaml_file():\n data = {\n 'a': ['contains', 'something'],\n }\n memory_file = BytesIO()\n memory_file.write(bytes(yaml.dump(data=data, default_flow_style=False), 'utf-8'))\n memory_file.seek(0)\n return send_file(memory_file, as_attachment=True, attachment_filename='file.yaml')\n\n\ndef get_files_present(s3_client, prefix, bucket_name='cclp-bench-data-dev-01'):\n files_present = list()\n response = s3_client.list_objects_v2(Bucket=bucket_name, Prefix=prefix)\n files = response.get('Contents')\n for file_info in files:\n file_path = file_info.get('Key')\n file_name = os.path.basename(file_path)\n files_present.append(file_name)\n return files_present\n\n\ndef read_file_as_bytes(path, bucket_name='cclp-bench-data-dev-01'):\n file_path = os.path.join('s3://', bucket_name, path)\n with sm_open(file_path, mode='rb') as s3_file:\n file_data = s3_file.read()\n return file_data\n\n\ndef read_parquet_file(s3_client, path, bucket_name='cclp-bench-data-dev-01'):\n print(path)\n s3_object = s3_client.get_object(Bucket=bucket_name, Key=path)\n file_data = io.BytesIO(s3_object['Body'].read())\n dataframe = pd.read_parquet(file_data)\n data = dataframe.to_dict('records')\n return base64.b64encode(zlib.compress(str.encode(json.dumps(data), 'utf-8'), 6))\n\n\n@app.route('/download/files', methods=['POST'])\ndef download_files():\n s3_client = boto3.client('s3')\n files = ['ground_truth_kpi.parquet', 'rss_kpi.parquet', 'level0_level1_kpi.parquet']\n key = os.path.join('data',\n 'bench1',\n '1631098174959-61732184-bbb2-41de-ad57-9cb57dceddae',\n 'Reprocessed_Output',\n 'xosc_61732184-bbb2-41de-ad57-9cb57dceddae')\n files_present = get_files_present(s3_client=s3_client, prefix=key)\n memory_file = io.BytesIO()\n with zipfile.ZipFile(\n memory_file,\n mode='w'\n ) as z_file:\n for filename in files:\n if filename in files_present:\n path = os.path.join(key, filename)\n zip_info = zipfile.ZipInfo(os.path.join('gt_files', filename.replace('parquet', 'csv')))\n zip_info.date_time = time.localtime(time.time())[:6]\n zip_info.compress_type = zipfile.ZIP_DEFLATED\n file_data = read_parquet_file(s3_client=s3_client, path=path)\n z_file.writestr(zip_info, file_data)\n memory_file.seek(0)\n return send_file(memory_file, as_attachment=True,\n mimetype='application/zip', attachment_filename='gt.zip')\n\n\n@app.route('/index')\ndef index():\n return render_template('scratch_23.html')\n\n\nif __name__ == '__main__':\n app.run()\n","repo_name":"Nareshwill/playground","sub_path":"sample_app_to_download_yaml/scratch_22.py","file_name":"scratch_22.py","file_ext":"py","file_size_in_byte":3075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20959951231","text":"# \n########################################################################\n# Importação das Bibliotecas Necessárias\n########################################################################\n#\nimport cv2 as cv\n\n# \n########################################################################\n# Definições Gerais\n########################################################################\n#\nNomeJanela = \"Imagem Base\"\nNomeImagem = \"Girassol.png\"\nCaminhoBase = \"/home/asoares/OpenCV/\"\nCaminhoImagem = CaminhoBase + \"Imagens/\" \n\n# \n########################################################################\n# Funções de Uso Geral\n########################################################################\n#\ndef Controlador (tmpImagem, Brilho=255, Contraste=127):\n \n Brilho = int((Brilho - 0) * (255 - (-255)) / (510 - 0) + (-255))\n Contraste = int((Contraste - 0) * (127 - (-127)) / (254 - 0) + (-127))\n \n if Brilho != 0:\n if Brilho > 0:\n Sombra = Brilho\n Maximo = 255\n else:\n Sombra = 0\n Maximo = 255 + Brilho\n \n al_pha = (Maximo - Sombra) / 255\n ga_mma = Sombra\n ImagemResultado = cv.addWeighted(tmpImagem, al_pha, tmpImagem, 0, ga_mma)\n \n else:\n ImagemResultado = tmpImagem\n \n if Contraste != 0:\n Alpha = float(131 * (Contraste + 127)) / (127 * (131 - Contraste))\n Gamma = 127 * (1 - Alpha)\n ImagemResultado = cv.addWeighted(ImagemResultado, Alpha, ImagemResultado, 0, Gamma)\n \n return ImagemResultado\n\ndef EfeitoContrasteBrilho (Brilho=0):\n Brilho = cv.getTrackbarPos(\"Brilho\", \"Processamento de Imagem\")\n Contraste = cv.getTrackbarPos(\"Contraste\", \"Processamento de Imagem\")\n EfeitoResultado = Controlador (Imagem, Brilho, Contraste)\n cv.imshow(\"Efeito Resultante\", EfeitoResultado)\n return ()\n\n# \n########################################################################\n# Lendo a Imagem\n########################################################################\n#\nImagem = cv.imread ( CaminhoImagem + NomeImagem, cv.IMREAD_COLOR)\n\ncv.namedWindow(\"Processamento de Imagem\")\ncv.imshow(\"Processamento de Imagem\", Imagem)\n\ncv.createTrackbar(\"Brilho\", \"Processamento de Imagem\", 255, 2 * 255, EfeitoContrasteBrilho) \ncv.createTrackbar(\"Contraste\", \"Processamento de Imagem\", 127, 2 * 127, EfeitoContrasteBrilho) \n \nEfeitoContrasteBrilho (0)\ncv.waitKey(0)\n\n########################################################################\n# FIM DO PROGRAMA\n########################################################################\n","repo_name":"Alxsoa/OpenCV","sub_path":"1.0-Processamento de Imagem/0180.0-Contraste e Brilho/Contraste e Brilho - Versão 1.0.0.py","file_name":"Contraste e Brilho - Versão 1.0.0.py","file_ext":"py","file_size_in_byte":2563,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"24061392044","text":"import pandas as pd\r\nimport numpy as np\r\nimport os\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nimport FindingRegimeFilter\r\nimport scipy.integrate\r\nimport inflightcomponents as inflight\r\nimport matplotlib.ticker as mtick\r\nimport LinearRegression as lr\r\nimport FindingRegime2\r\nimport airdensity\r\nimport model_one\r\nfrom matplotlib.ticker import FormatStrFormatter\r\n\r\n\r\ndef rl(regime,interval,coeff):\r\n return [coeff.loc[regime,'b1']*interval[0] + coeff.loc[regime,'b0'],\r\n coeff.loc[regime,'b1']*interval[1] + coeff.loc[regime,'b0']]\r\n\r\ndef main():\r\n plt.rcParams.update({'figure.autolayout': True})\r\n plt.rcParams[\"font.family\"] = \"Helvetica\"\r\n plt.rc('font', **{'family': 'sans-serif', 'sans-serif': ['Helvetica']})\r\n plt.rcParams['legend.title_fontsize'] = 'large'\r\n\r\n mainpath = os.getcwd()\r\n #os.chdir(r'C:\\Users\\thiag\\Box\\Thiago DOE Research\\Delivery Robots\\Data\\Review\\data\\Kilthub')\r\n #data = pd.read_csv('flights.csv', low_memory=False)\r\n\r\n #data = data[((data.route == 'R1') | (data.route == 'R2') | (data.route == 'R3') | (data.route == 'R4') | (\r\n # data.route == 'R5')) & (\r\n # data.payload < 750)]\r\n\r\n #data['Power'] = data['battery_current'] * data['battery_voltage']\r\n\r\n os.chdir(mainpath)\r\n\r\n summary = pd.read_csv('energy_summary_model1.csv')\r\n pool = pd.read_csv('pool.csv')\r\n tk_b1 = []\r\n tk_b0 = []\r\n cr_b1 = []\r\n cr_b0 = []\r\n ld_b1 = []\r\n ld_b0 = []\r\n\r\n os.chdir(r'C:\\Users\\thiag\\Box\\Thiago DOE Research\\Delivery Robots\\Paper\\energy_model\\bootstrap')\r\n std = pd.DataFrame()\r\n n=2000\r\n fig, ax = plt.subplots()\r\n for i in range(n):\r\n print(\"iteration: %d\"%(i), end='\\r')\r\n subpool = np.random.choice(pool.flight, size=120, replace=True)\r\n summary.payload = summary.payload.astype(int)\r\n summary_pool = summary[summary.flight.isin(subpool)].copy()\r\n\r\n coeff = lr.linear_regression(summary_pool)\r\n tk_b1.append(coeff.loc['takeoff', 'b1'])\r\n tk_b0.append(coeff.loc['takeoff', 'b0'])\r\n cr_b1.append(coeff.loc['cruise', 'b1'])\r\n cr_b0.append(coeff.loc['cruise', 'b0'])\r\n ld_b1.append(coeff.loc['landing', 'b1'])\r\n ld_b0.append(coeff.loc['landing', 'b0'])\r\n\r\n local = pd.DataFrame({\"iteration\":i, \"tk_b1\":np.std(tk_b1), \"tk_b0\":np.std(tk_b0), \"cr_b1\":np.std(cr_b1),\r\n \"cr_b0\":np.std(cr_b0), \"ld_b1\":np.std(ld_b1), \"ld_b0\":np.std(ld_b0)}, index=[0])\r\n\r\n std = pd.concat([std,local], ignore_index=True)\r\n\r\n\r\n interval = [0, 0.5]\r\n ax.plot(interval, rl('takeoff', interval, coeff), linestyle='--', color='black', alpha=0.7)\r\n #ax.plot(interval, rl('cruise', df, coeff), linestyle='--', color='black', alpha=0.7)\r\n #ax.plot(interval, rl('landing', df, coeff), linestyle='--', color='black', alpha=0.7)\r\n\r\n #plt.legend(title='Flight regime', frameon=False, loc=\"lower center\", fontsize='large', ncol=3)\r\n #plt.ylim(500, 600)\r\n plt.xlim(interval)\r\n plt.xlabel(r\"$\\dfrac{mass^{1.5}}{\\sqrt{\\rho}}$ [$kg \\cdot m^{1.5}$]\", fontsize=20)\r\n plt.ylabel(\"Average Power [W]\", fontsize=20)\r\n plt.xticks(fontsize=16)\r\n ax.xaxis.set_major_formatter(FormatStrFormatter('%.1f'))\r\n plt.yticks(fontsize=16)\r\n sns.despine(top=True, right=True)\r\n plt.grid(b=True, which='major', axis='both', color='gray', linewidth=1.0, alpha=0.1)\r\n #plt.savefig('Power_regime_trendline.pdf')\r\n plt.show()\r\n\r\n\r\n\r\n bootstrap = pd.DataFrame({\"iteration\":range(n),\"tk_b1\":tk_b1, \"tk_b0\":tk_b0, \"cr_b1\":cr_b1, \"cr_b0\":cr_b0, \"ld_b1\":ld_b1, \"ld_b0\":ld_b0})\r\n\r\n\r\n cols_b1 = [\"tk_b1\", \"cr_b1\", \"ld_b1\"]\r\n cols_b0 = [\"tk_b0\", \"cr_b0\", \"ld_b0\"]\r\n print(bootstrap)\r\n print(std)\r\n for col in cols_b1:\r\n plt.plot(std.iteration,std[col], label=str(col))\r\n plt.legend()\r\n plt.title(\"b1\")\r\n plt.show()\r\n\r\n for col in cols_b0:\r\n plt.plot(std.iteration,std[col], label=str(col))\r\n plt.legend()\r\n plt.title(\"b0\")\r\n plt.show()\r\n bootstrap.to_csv(\"bootstrap_results.csv\", index=False)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"thiago-a-rod/energy_consumption","sub_path":"Boostrap.py","file_name":"Boostrap.py","file_ext":"py","file_size_in_byte":4161,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9985162883","text":"# Sort a string with alphabets followed by numbers\n\nstring = input()\nalphabets = []\nnumbers = []\n\nfor ch in string:\n if ch.isalpha():\n alphabets.append(ch)\n else:\n numbers.append(ch)\n\nfinal_array = sorted(alphabets)+sorted(numbers)\noutput = ''.join(final_array)\nprint(output)\n","repo_name":"Sandhra-gk/Python_Coding_Questions","sub_path":"Alpha_num_sorting.py","file_name":"Alpha_num_sorting.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"44291900196","text":"def checkSeatAvailability():\n print(\"Checking Availability\")\n\ndef verifyPayment():\n print(\"Verifing Payment\")\n\ntrain = input(\"Please choose a train enter the number coordinating with the destination:\\n\"\n \" 1) New York City, NY 2) Buffalo, NY 3) Jersey City, NJ \\n\")\n\ntrain = int(train)\n\ncost = 0\nif train == 1:\n cost = 3.25\nelif train == 2:\n cost = 5.25\nelif train == 3:\n cost = 7.50\n#system checks\ncheckSeatAvailability()\n\nprint(\"You have selected {} your cost is {} \\nThere is a seat available on that train,\\n\"\n \"Please insert payment\".format(train, cost))\n\n#system connects to card company to verify payment\nverifyPayment()\n\n#system prints receipt\nprint(\"Thank you please take receipt below\")\n","repo_name":"Galbraithjt/SE440Lab2","sub_path":"Lab2.py","file_name":"Lab2.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6075530255","text":"import torch\nimport shutil\nimport os\nfrom typing import List\nimport quiver.utils as quiver_util\n\n\n__all__ = [\"quiver_partition_feature\", \"load_quiver_feature_partition\"]\n\n\nQUIVER_MAGIC_NUMBER = 256\n\n\ndef partition_feature_without_replication(probs: List[torch.Tensor], chunk_size: int):\n \"\"\"Partition node with node access distribution. \n The result will cause no replication between each parititon.\n\n 这段代码实��了基于节点访问分布(node access distribution)的无重复特征分割方法,其输入参数为一个概率分布列表和一个chunk size,输出为一个ID列表,其中每个ID列表代表一个特征分割(feature partition)的结果,以及分割后每个节点的概率分布。具体流程如下:\n\n 将概率分布列表中的每个张量转移到当前设备(这里假定使用GPU)。\n 计算chunk_num,即将所有节点分成的块数。对于每个块,其包含从当前块的起始位置开始的 chunk_size 个节点。每个块对应一个包含节点ID的张量 chunk。\n 对于每个块,计算每个分区(partition)的节点访问概率之和 probs_sum_chunk。对于每个分区,假设当前分区为 src_rank,对于除了当前分区以外的所有分区,将其概率分布相加,然后将结果减去当前分区的概率分布。最后将得到一个包含当前块中所有节点的 probs_sum_chunk 张量列表。这里通过将除当前分区以外的所有分区的概率分布相加再减去当前分区的概率分布的方式,保证了分割后每个节点只被分配到一个分区中。\n 对于每个分区,找到其应该选择的节点,即在当前块中选择其概率分布最高的节点。将这些节点的ID存储在一个张量 pick_ids 中,并将其添加到结果列表 res 中。同时,将这些节点在所有分区的 probs_sum_chunk 张量列表中的值设置为 -1,以确保下一次选择不会再次选择到这些节点。\n 重复步骤4直到所有节点都被分配到一个分区为止。\n 将每个分区的ID列表拼接起来,返回结果。\n\n Args:\n probs (torch.Tensor): node access distribution\n chunk_size (int): chunk_size \n\n Returns:\n [torch.Tensor]: list of IDs for each partition\n\n \"\"\"\n\n device = torch.cuda.current_device()\n partitioned_num = len(probs)\n\n probs = [prob.to(device) for prob in probs]\n total_node_num = probs[0].size(0)\n\n res = [[] for _ in range(partitioned_num)]\n\n blob_size = chunk_size * partitioned_num\n chunk_num = (total_node_num + chunk_size - 1) // chunk_size\n\n current_chunk_start_pos = 0\n current_partition_idx = 0\n for _ in range(chunk_num):\n current_chunk_end_pos = min(\n total_node_num, current_chunk_start_pos + blob_size)\n current_chunk_size = current_chunk_end_pos - current_chunk_start_pos\n chunk = torch.arange(current_chunk_start_pos,\n current_chunk_end_pos, device=device)\n probs_sum_chunk = [\n torch.zeros(current_chunk_size, device=device) + 1e-6 for _ in range(partitioned_num)\n ]\n for src_rank in range(partitioned_num):\n for dst_rank in range(partitioned_num):\n if dst_rank == src_rank:\n probs_sum_chunk[src_rank] += probs[dst_rank][chunk] * \\\n partitioned_num\n else:\n probs_sum_chunk[src_rank] -= probs[dst_rank][chunk]\n assigned_node_size = 0\n per_partition_size = chunk_size\n for partition_idx in range(current_partition_idx, current_partition_idx + partitioned_num):\n partition_idx = partition_idx % partitioned_num\n actual_per_partition_size = min(\n per_partition_size, current_chunk_size - assigned_node_size)\n _, sorted_res_order = torch.sort(\n probs_sum_chunk[partition_idx], descending=True)\n pick_chunk_part = sorted_res_order[:actual_per_partition_size]\n pick_ids = chunk[pick_chunk_part]\n res[partition_idx].append(pick_ids)\n for idx in range(partitioned_num):\n probs_sum_chunk[idx][pick_chunk_part] = -1\n assigned_node_size += actual_per_partition_size\n current_partition_idx += 1\n current_chunk_start_pos += current_chunk_size\n\n for partition_idx in range(partitioned_num):\n res[partition_idx] = torch.cat(res[partition_idx])\n return res, probs\n\n\ndef quiver_partition_feature(probs: torch.Tensor, result_path: str, cache_memory_budget=0, per_feature_size=0, chunk_size=QUIVER_MAGIC_NUMBER):\n \"\"\"\n 它基于访问概率对图形特征张量进行分区,并生成一个结果文件夹,其中包含每个分区的分区特征张量和缓存特征张量。\n\n 以下是该函数的详细说明:\n\n 输入参数为:\n\n probs:图形中每个节点的访问概率张量。\n result_path:分区特征张量和缓存特征张量将保存的路径。\n cache_memory_budget:用户指定的缓存热点特征的内存预算。\n per_feature_size:用户特征的每个特征大小。\n chunk_size:一个常量值,用于确定分区特征张量的每个块的大小。\n 该函数首先检查结果文件夹是否已存在。如果存在,则会提示用户确认是否删除文件夹并继续或退出该函数。\n\n 分区数等于probs张量的长度。\n\n ��结果文件夹中的每个分区创建一个文件夹。\n\n 该函数根据用户指定的内存预算和每个特征大小计算可以缓存的特征数量。\n\n 然后,该函数使用partition_feature_without_replication函数对特征张量进行无重复分区。\n\n 如果启用了缓存,则根据访问概率计算要缓存哪些特征,并将它们缓存。\n\n 将每个分区的分区特征张量和缓存特征张量保存在它们各自的文件夹中。\n\n 该函数返回分区图书,它是一个张量,指示每个节点属于哪个分区,以及每个分区的分区特征张量和缓存特征张量。\n\n Partition graph feature based on access probability and generate result folder. The final result folder will be like:\n\n -result_path\n -partition_0\n -partition_res.pth\n -cache_res.pth\n -partition_1\n -partition_res.pth\n -cache_res.pth\n -partition_2\n -partition_res.pth\n -cache_res.pth\n ...\n\n Args:\n probs:\n result_path (str): path for partition result\n cache_memory_budget (Union[str, int, float]): user-specified memory budget for caching hot feature\n per_feature_size (Union[str, int, float]): per-feature size for user's feature\n\n Returns:\n partition_book (torch.Tensor): Indicates which partition_idx a node belongs to\n feature_partition_res (torch.Tensor): partitioned feature result\n feature_cache_res (torch.Tensor): cached feature result\n \"\"\"\n\n if os.path.exists(result_path):\n res = input(\n f\"{result_path} already exists, enter Y/N to continue, If continue, {result_path} will be deleted:\")\n res = res.upper()\n if res == \"Y\":\n shutil.rmtree(result_path)\n else:\n print(\"exiting ...\")\n exit()\n\n partition_num = len(probs)\n\n # create result folder\n for partition_idx in range(partition_num):\n os.makedirs(os.path.join(\n result_path, f\"feature_partition_{partition_idx}\"))\n\n # calculate cached feature count\n cache_memory_budget_bytes = quiver_util.parse_size(cache_memory_budget)\n per_feature_size_bytes = quiver_util.parse_size(per_feature_size)\n cache_count = int(cache_memory_budget_bytes /\n (per_feature_size_bytes + 1e-6))\n per_partition_cache_count = cache_count // partition_num\n\n partition_book = torch.zeros(\n probs[0].shape, dtype=torch.int64, device=torch.cuda.current_device())\n partition_res, changed_probs = partition_feature_without_replication(\n probs, chunk_size)\n\n cache_res = [None] * partition_num\n\n if cache_count > 0:\n for partition_idx in range(partition_num):\n _, prev_order = torch.sort(\n changed_probs[partition_idx], descending=True)\n cache_res[partition_idx] = prev_order[: per_partition_cache_count]\n\n for partition_idx in range(partition_num):\n partition_result_path = os.path.join(\n result_path, f\"feature_partition_{partition_idx}\", \"partition_res.pth\")\n cache_result_path = os.path.join(\n result_path, f\"feature_partition_{partition_idx}\", \"cache_res.pth\")\n partition_book[partition_res[partition_idx]] = partition_idx\n torch.save(partition_res[partition_idx], partition_result_path)\n torch.save(cache_res[partition_idx], cache_result_path)\n\n partition_book_path = os.path.join(\n result_path, f\"feature_partition_book.pth\")\n torch.save(partition_book, partition_book_path)\n\n return partition_book, partition_res, cache_res\n\n\ndef load_quiver_feature_partition(partition_idx: int, result_path: str):\n \"\"\"\n Load partition result for partition ${partition_idx}\n\n 它用于从保存的文件中加载分区结果。\n\n 函数的输入参数包括:\n\n partition_idx:分区的索引值\n result_path:保存分区结果的路径\n 函数返回三个张量,分别是:\n\n partition_book:指示每个节点属于哪个分区的张量\n partition_res:属于这个分区的节点的索引张量\n cache_res:属于这个分区且已被缓存的节点的索引张量\n 在函数内部,首先会检查result_path路径是否存在,如果不存在则会抛出异常。然后会根据partition_idx和result_path构造分区结果文件和缓存结果文件的路径。接着,函数会使用torch.load函数加载分区结果、缓存结果和分区标记的张量,然后返回这些张量。\n\n Args:\n partition_idx (int): Partition idx\n partition_result_path (str): partition result path\n\n Returns:\n partition_book (torch.Tensor): partition_book indicates which partition_idx a node belongs to\n partition_res (torch.Tensor): node indexes belong to this partition\n cache_res (torch.Tensor): cached node indexes belong to this partition\n\n \"\"\"\n\n if not os.path.exists(result_path):\n raise Exception(\"Result path not exists\")\n\n partition_result_path = os.path.join(\n result_path, f\"feature_partition_{partition_idx}\", \"partition_res.pth\")\n cache_result_path = os.path.join(\n result_path, f\"feature_partition_{partition_idx}\", \"cache_res.pth\")\n partition_book_path = os.path.join(\n result_path, f\"feature_partition_book.pth\")\n\n partition_book = torch.load(partition_book_path)\n partition_res = torch.load(partition_result_path)\n cache_res = torch.load(cache_result_path)\n\n return partition_book, partition_res, cache_res\n","repo_name":"Baizx98/BCGraph","sub_path":"srcs/python/quiver/partition.py","file_name":"partition.py","file_ext":"py","file_size_in_byte":11019,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71833833425","text":"#\n# @lc app=leetcode.cn id=110 lang=python3\n#\n# [110] 平衡二叉树\n#\n\n# @lc code=start\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def isBalanced(self, root: TreeNode) -> bool:\n # 自底向上递归 不平衡返回-1\n def height(r: TreeNode)->int:\n if r is None:\n return 0\n leftHeight = height(r.left)\n if leftHeight == -1:\n return -1\n rightHeight = height(r.right)\n if rightHeight == -1:\n return -1\n if abs(rightHeight - leftHeight)>1:\n return -1\n return max(leftHeight, rightHeight) +1\n return height(root)>=0\n\n \n \n \n\n# @lc code=end\n\n","repo_name":"zch0423/leetcode","sub_path":"110.平衡二叉树.py","file_name":"110.平衡二叉树.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42206050131","text":"# Your code here\n[A, B] = input().split()\n[A, B] = [int(A), int(B)]\nwinner = \"\"\nplace = 1\ncount = 1\nwhile True:\n if A == 0:\n winner = \"Joey\"\n break\n if B == 0:\n winner = \"Chandler\"\n break\n if place == 1:\n B -= count\n place = 0\n else:\n A -= count\n place = 1\n count += 1\nprint(winner)","repo_name":"rajdeep-biswas/multiplayer","sub_path":"Newton Jun 30/Problem 3/sol.py","file_name":"sol.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38611125980","text":"import socket\n#socket.AF_INET ip协议 有ipv4 ipv6 socket.SOCK_DGRAM SOCK_STREAM 基于数据流传输\nudpserver = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)\nudpserver.bind((\"127.0.0.1\",8090))\n\nwhile True:\n data,addr = udpserver.recvfrom(1024)\n #print(\"客户端:\"+data.decode(\"utf8\"))\n #print(data[0].decode(\"utf8\"))\n print(\"客户端:\"+data.decode(\"utf8\"))\n #info = input(\"请输入东西:\")\n #udpserver.sendto(str(info).encode(\"utf8\"),addr)","repo_name":"immortalChensm/python","sub_path":"socketcsm/udp_server.py","file_name":"udp_server.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20908685147","text":"# THE IMPORTANT APPROACH TO LOCK MACHINE IN ONE GO\r\n\r\n#import os\r\n\r\n#Hel = os.environ[\"windir\"]\r\n#os.system(winpath + r'\\system32\\rundll32 user32.dll, LockWorkStation')\r\n\r\n\r\nimport tkinter as tk\r\nimport subprocess as sub\r\nimport pyautogui as py\r\nimport time\r\nimport random\r\nimport os\r\nimport ctypes\r\n\r\n\r\n\r\npy.FAILSAFE = False\r\n\r\nroot = tk.Tk() \r\nlist1 = ['komodo', 'idea64', 'PHP Storm ', ' Visual Studio' , 'NetBeans' , 'eclipse_PHP', 'eclipse_Java' , 'Ruby' , 'pycharm64' ] \r\n\r\ncanvas1 = tk.Canvas (root, width=700, height=800)\r\n\r\n#canvas1.configure(background='black')\r\n\r\nfilename = tk.PhotoImage(file = \"C:\\\\Users\\\\karanaro\\\\Desktop\\\\image_logo.png\")\r\nbackground_label = tk.Label(image=filename)\r\nbackground_label.place(x=0, y=0, relwidth=1, relheight=1)\r\n\r\n\r\n\r\n\r\n\r\n############################################################################################################################################\r\n\r\n\r\nclass Paint:\r\n\tdef paint_mouse(self):\r\n\t\ttime.sleep(2)\r\n\t\tsub.call('start mspaint', shell = True)\r\n\t\ttime.sleep(2)\r\n\t\tscreenWidth, screenHeight = py.size()\r\n\t\tcurrentMouseX, currentMouseY = py.position()\r\n\t\tpy.moveTo(100, 150)\r\n\t\tpy.click()\r\n\t\tpy.moveRel(None, 10) # move mouse 10 pixels down\r\n\t\tpy.doubleClick()\r\n\t\tpy.moveTo(300,280, duration=.75, tween=py.easeInOutQuad) # use tweening/easing function to move mouse over 2 seconds.\r\n\t\tpy.typewrite('Hello world!', interval=0.25) # type with quarter-second pause in between each key\r\n\t\tpy.press('esc')\r\n\t\tpy.keyDown('shift')\r\n\t\tpy.press(['left', 'left', 'left', 'left', 'left', 'left'])\r\n\t\tpy.keyUp('shift')\r\n\t\tpy.hotkey('ctrl', 'c')\r\n\t\tdistance = 500\r\n\t\twhile distance > 0:\r\n\t\t\tpy.dragRel(distance, 0, duration=0.14) # move right\r\n\t\t\tdistance -= 10\r\n\t\t\tpy.dragRel(0, distance, duration=0.14) # move down\r\n\t\t\tpy.dragRel(-distance, 0, duration=0.14) # move left\r\n\t\t\tdistance -= 15\r\n\t\t\tpy.dragRel(0, -distance, duration=0.14) # move up\r\n\t\tpy.moveTo(1250,8, 3, py.easeInQuad)\r\n\t\tfor i in range(1):\r\n\t\t\tpy.click(1250,8)\r\n\t\tpy.PAUSE = 0.5\r\n\t\tpy.typewrite(['tab'])\r\n\t\tpy.PAUSE = 2\r\n\t\tpy.typewrite(['enter'])\r\n\t\ttime.sleep(2)\r\n#\t\tfor i in range(4):\r\n#\t\t\tpy.keyDown(['alt'])\r\n#\t\t\ttime.sleep(2)\r\n#\t\t\tpy.typewrite(['tab'])\r\n#\t\t\tpy.keyUp(['alt'])\r\n\t\r\n\r\n\r\nsecond = Paint()\r\n\r\n############################################################################################################################################\r\n\r\nclass _outlook:\r\n\tdef outlook(self):\r\n\t\tpy.typewrite(['win'])\r\n\t\tpy.PAUSE = 0.5\r\n\t\tpy.typewrite('outlook' , interval = 0.25 )\r\n\t\tpy.PAUSE = 0.25\r\n\t\tpy.typewrite(['enter'])\r\n\t\ttime.sleep(4)\r\n\t\tpy.click(23,75)\r\n\t\t_list = ['komal', 'karanaro', 'swati', 'prerna']\r\n\t\tfor i in range(4):\r\n\t\t\tpy.typewrite(_list[i])\r\n\t\t\tpy.PAUSE = 0.35\r\n\t\t\tpy.typewrite(['enter'])\r\n\t\tpy.PAUSE = 0.5\t\t\r\n\t\tpy.typewrite(['tab'])\r\n\t\tpy.typewrite('nilesh')\r\n\t\tpy.typewrite(['enter'])\r\n\t\tpy.PAUSE = 0.5\t\r\n\t\tpy.click(723,633)\r\n\t\tpy.typewrite('Demo Mail To Test The Automation Framework For EXCEL SHORE PLUS' , interval= 0.20)\r\n\t\tpy.click(723,633)\r\n\t\tpy.typewrite('\\n BLANK MESSAGE: PLEASE IGNORE THIS MESSAGE', interval=0.25)\r\n\t\tpy.moveTo(26,190, 2, py.easeInQuad)\r\n\t\tpy.click(26,190)\r\n\t\tpy.PAUSE = 0.5\r\n\t\tpy.typewrite(['tab'])\r\n\t\tpy.pause = 0.2\r\n\t\tpy.typewrite(['enter'])\r\n\t\ttime.sleep(3)\r\n\t\tsub.call('taskkill /F /IM outlook.exe' , shell = True)\r\n\t\tpy.PAUSE = 0.5\r\n\t\t\r\n\r\n\r\nthird = _outlook()\r\n\r\n\r\n\r\n############################################################################################################################################\r\n############################################################################################################################################\r\n\r\n\r\nclass _fileexp:\r\n\tdef explorer(self):\r\n\t\tpy.typewrite(['win'])\r\n\t\tpy.typewrite('explorer' , interval = 0.25)\r\n\t\tpy.PAUSE = 0.35\r\n\t\tpy.typewrite(['enter'])\r\n\t\tpy.PAUSE = 1\r\n\t\tfor i in range(2):\r\n\t\t\tpy.click(386,748)\r\n\t\ttime.sleep(2)\r\n\t\tpass\r\n\t\tfor i in range(0,2,1):\r\n\t\t\tpy.click(524,375)\r\n\t\ttime.sleep(2)\r\n\t\tpy.typewrite(['enter'])\r\n\t\ttime.sleep(1)\r\n\t\tpy.moveTo(1195,880, 3, py.easeInQuad)\r\n\t\tpy.click(button = 'right')\r\n\t\tpy.typewrite(['up'])\r\n\t\tpy.PAUSE = 0.15\r\n\t\tpy.typewrite(['up'])\r\n\t\tpy.PAUSE = 0.15\r\n\t\tpy.typewrite(['right'])\r\n\t\tpy.PAUSE = 0.15\r\n\t\tpy.typewrite(['up'])\r\n\t\tpy.PAUSE = 0.15\r\n\t\tpy.typewrite(['up'])\r\n\t\tpy.PAUSE = 0.15\r\n\t\tpy.typewrite(['up'])\r\n\t\tpy.PAUSE = 0.15\r\n\t\tpy.typewrite(['up'])\r\n\t\tpy.PAUSE = 0.15\r\n\t\tpy.typewrite(['enter'])\r\n\t\tpy.PAUSE = 0.15\r\n\t\trand = str(random.randint(1,200))\r\n\t\tpy.typewrite('random' , interval=0.25)\r\n\t\tpy.typewrite(rand)\r\n\t\tfor i in range(2):\r\n\t\t\tpy.typewrite(['enter'])\r\n\t\tpy.typewrite('test file \\n next we will save this test file with a random name \\n Then Next we will rename it and then delete it', interval= 0.15)\r\n\t\tpy.PAUSE = 1.5\r\n\t\t#py.typewrite('\\n \\n \\n \\n \\n After alt tabs we will now save this edited file' , interval= 0.15)\r\n\t\ttime.sleep(1)\r\n\t\tpy.keyDown('alt')\r\n\t\ttime.sleep(0.2)\r\n\t\tpy.press('tab')\r\n\t\ttime.sleep(0.2)\r\n\t\tpy.keyUp('alt')\r\n\t\tpy.hotkey('alt', 'f4')\r\n\t\tpy.pause = 2\r\n\t\tpy.typewrite(['tab'])\r\n\t\tpy.typewrite(['enter'])\r\n\t\tpy.typewrite(['space'])\r\n\t\tpy.pause = 0.50\r\n\t\tpy.typewrite(['f2'])\r\n\t\trand = str(random.randint(1,200))\r\n\t\tpy.typewrite('random' , interval=0.25)\r\n\t\tpy.typewrite(rand)\r\n\t\tpy.typewrite(['enter'])\r\n\t\tpy.pause = 0.50\r\n\t\tpy.typewrite(['space'])\r\n\t\tpy.pause = 0.50\r\n\t\tpy.typewrite(['delete'])\r\n\t\tpy.typewrite(['enter'])\r\n\t\t\r\n\t\tpy.moveTo(1279,0 , 3 , py.easeInQuad)\r\n\t\tfor i in range(2):\r\n\t\t\tpy.click(1279,0)\r\n\r\n\r\n\r\n\r\nexplore = _fileexp()\r\n\r\n\r\n\r\n############################################################################################################################################\r\n############################################################################################################################################\r\n\r\n\r\n\r\nclass browserTest:\r\n\r\n\tdef open_close(self):\r\n\t\tpass\r\n\r\n\r\n\tdef open_minimize(self):\r\n\t\tsub.call([r'y.bat'])\r\n\r\n\r\n\r\n\tdef stress_test(self):\r\n\t\tsub.call([r'100URL.bat'])\r\n\t\tpy.hotkey('win', 'r')\r\n\t\tpy.typewrite('notepad', interval= 0.2)\r\n\t\tpy.typewrite(['enter'])\r\n\t\tpy.typewrite('The test is complete' , interval = 0.25)\r\n\t\ttime.sleep(1)\r\n\t\tsub.call('taskkill /F /IM notepad.exe')\r\n\r\n\tdef close(self):\r\n\t\tsub.call('cmd /c \"taskkill /f /im explorer.exe && start explorer\"')\r\n\r\n\r\n\r\n\r\nfourth = browserTest()\r\n\r\n\r\n############################################################################################################################################\r\n\r\n\r\nclass generate_data:\r\n\r\n\tdef start_matrix(self): \r\n\t sub.call([r'C:\\Users\\Karanaro\\Desktop\\the_new-thng_loop.bat'])\r\n\t \t\r\n\t\r\n\r\n\tdef start_batch_manually(self):\r\n\t\t\tsub.call([r'C:\\Users\\Karanaro\\Desktop\\runthis.bat'])\t\r\n\t\r\n\t\r\n\t#class ApplyData:\r\n\tdef AutomateOpenAndAct(self):\r\n\t\ttime.sleep(8)\r\n\t\tpy.hotkey('ctrl', 'n')\r\n\t\t#py.typewrite(['enter'])\r\n\t\ttime.sleep(3)\r\n\t\tpy.typewrite('\\n \\n Random text `` Used For Testing --- Tool Detector Tools Automate Data Generation', interval=0.15)\r\n\t\ttime.sleep(2)\r\n\t\tpy.typewrite('\\n \\n This file will be stored in the default destination' , interval=0.15)\r\n\t\ttime.sleep(2)\r\n\t\tpy.typewrite('\\n \\n We will save it now and close this program and move on to the next in the list' , interval=0.15)\r\n\t\ttime.sleep(1)\r\n\t\tpy.typewrite('\\n \\n THANK-YOU ' , interval=0.15)\r\n\t\ttime.sleep(2)\r\n\t\tpy.hotkey('ctrl','s')\r\n\t\ttime.sleep(1)\r\n\t\trand = str(random.randint(1,200))\r\n\t\tpy.typewrite('random' , interval=0.35)\r\n\t\tpy.typewrite(rand)\r\n\t\ttime.sleep(5)\r\n\t\tpy.typewrite(['enter'])\t\r\n\t\r\n\t\r\n\t\r\n\r\n\tdef Notpresent(self):\r\n\t\ttime.sleep(3)\r\n\t\tpass\r\n\t\tpy.hotkey('win', 'r')\r\n\t\ttime.sleep(2)\r\n\t\tpy.typewrite('notepad' , interval=0.15)\r\n\t\tpy.typewrite(['enter'])\r\n\t\ttime.sleep(3)\r\n\t\tpy.typewrite('Sorry, This software is a paid software and key is not available to Users' , interval=0.3)\r\n\t\ttime.sleep(2)\r\n\t\tpy.typewrite('\\n \\n \\n Moving on to the next in the list' , interval=0.2)\r\n\t\ttime.sleep(3)\r\n\t\tsub.call(r'taskkill /F /IM notepad.exe' , shell = True)\t\r\n\t\r\n\r\n\tdef forIdea(self):\r\n\t\ttime.sleep(17)\r\n\t\tsub.call('echo this is idea test', shell = True)\r\n\t\tpy.moveTo(1195,880, 3, py.easeInQuad)\r\n\t\ttime.sleep(1)\r\n\t\tpy.click(1195, 800)\r\n\t\tpy.pause = 2\r\n\t\t\r\n\t\tpy.hotkey('alt', 'ctrl' , 'shift' , 'insert')\r\n\r\n\t\tpy.pause = 2\r\n\t\tpy.typewrite(['enter'])\r\n\t\ttime.sleep(2)\r\n\t\tpy.hotkey('ctrl','s')\r\n\t\ttime.sleep(1)\r\n\t\trand = str(random.randint(1,200))\r\n\t\tpy.typewrite('random' , interval=0.35)\r\n\t\tpy.typewrite(rand)\r\n\t\ttime.sleep(5)\r\n\t\tpy.typewrite(['enter'])\t\r\n\t\tpy.typewrite('\\n \\n Idea Editor, Random data to test the same for before that was done before' , interval=0.2)\r\n\t\ttime.sleep(5)\t\r\n\t\tpy.typewrite('\\n \\n This file will be stored in the default destination' , interval=0.2)\r\n\t\ttime.sleep(2)\r\n\t\tpy.typewrite('\\n \\n We will save it now and close this program and move on to the next in the list' , interval=0.2)\r\n\t\ttime.sleep(2)\r\n\t\tpy.typewrite('\\n \\n THANK-YOU ' , interval=0.2)\r\n\t\ttime.sleep(2)\r\n\t\tpy.hotkey('ctrl','s')\r\n\t\ttime.sleep(5)\r\n\t\tpy.typewrite(['enter'])\t\r\n\t\r\n\t\r\n\tdef toolDetector(self):\r\n\t\tsub.call([r'C:\\Users\\Karanaro\\Desktop\\test1.bat'])\r\n\t\tfirst.AutomateOpenAndAct()\r\n\t\ttime.sleep(1)\r\n\t\tsub.call('taskkill /F /IM komodo.exe', shell = True)\r\n\t\tpass\r\n\t\tsub.call([r'C:\\Users\\Karanaro\\Desktop\\test2.bat'])\r\n\t\tfirst.forIdea()\r\n\t\ttime.sleep(1)\r\n\t\tsub.call('taskkill /F /IM idea64.exe', shell = True)\r\n\t\tpy.typewrite(['enter'])\r\n\t\tsub.call([r'C:\\Users\\Karanaro\\Desktop\\test3.bat'])\r\n\t\ttime.sleep(5)\r\n\t\ttime.sleep(2)\r\n\t\tfirst.Notpresent()\r\n\t\ttime.sleep(2)\r\n\t\tsub.call('taskkill /F /IM phpstorm64.EXE', shell = True)\r\n\t\t#sub.call([r'C:\\Users\\Karanaro\\Desktop\\test4.bat'])\r\n\t\t#time.sleep(2)\r\n\t\t#first.Notpresent()\r\n\t\t#time.sleep(2)\r\n\t\t#sub.call('taskkill /F /IM webstorm64.exe', shell = True)\r\n\t\tsub.call([r'C:\\Users\\Karanaro\\Desktop\\test5.bat'])\r\n\t\tfirst.AutomateOpenAndAct()\r\n\t\ttime.sleep(2)\r\n\t\tsub.call('taskkill /F /IM devenv.exe', shell = True)\t\r\n\t\tpy.hotkey('win', 'r')\r\n\t\tpy.typewrite('notepad')\r\n\t\tpy.typewrite(['enter'])\r\n\t\ttime.sleep(1)\r\n\t\tpy.typewrite('The test for tool detector is complete', interval= 0.15)\r\n\t\tpy.pause = 1\r\n\t\tsub.call('taskkill /F /IM notepad.exe', shell = True)\r\n\r\n\r\nfirst = generate_data()\r\n\r\nclass _lock_Hibernate:\r\n\tdef _locksys(self):\r\n\t\twinpath = os.environ[\"windir\"]\r\n\t\tos.system(winpath + r'\\system32\\rundll32 user32.dll, LockWorkStation')\r\n\t\t\r\n\r\n\tdef _Hibernatesys(self):\r\n\t\tos.system(r'%windir%\\system32\\rundll32.exe powrprof.dll,SetSuspendState Hibernate') \r\n\r\n_lock = _lock_Hibernate()\r\n\r\n\r\n\r\n###########################################################################################################\r\n\r\n\r\nclass _incognito:\r\n\tdef Incognito(self):\r\n\t\tpy.moveTo(1112,1002, 3, py.easeInQuad)\r\n\t\tpy.click(button = 'left')\r\n\r\n\r\n\r\nincog = _incognito()\r\n\r\n\r\n\r\n###############################################################################################################\r\n\r\n\r\nclass runAll:\r\n\r\n\tdef openO(self):\r\n\t\t\r\n###########################################################################################################\r\n\r\n\t\r\n###############################################################################################################\r\n\t\t\r\n#\t\tpy.confirm('Do you want to continue with tool-detector test ?')\r\n\t\tfirst.toolDetector()\r\n\r\n\r\n#\t\tpy.confirm('Do you want to continue with explorer test ?')\r\n\t\t\r\n\t\texplore.explorer()\r\n\r\n\r\n#\t\tpy.confirm('Do you want to start with paint test ?.')\r\n\t\t#PUT AN IF BLOCK INSIDE IT\r\n\t\tsecond.paint_mouse()\r\n\r\n#\t\tpy.confirm('Open Outlook and send the messages to everyone in the team')\r\n\t\tthird.outlook()\r\n\r\n\r\n#\t\tpy.confirm('Do you want to continue with browser test ?')\r\n\t\tfourth.open_minimize()\r\n\t\tfourth.stress_test()\r\n\t\tfourth.close()\r\n\r\n\r\n\t\t\r\n\t\t\r\n\r\n\t\t#\r\n#\r\n\r\nmain = runAll()\r\n\r\n\r\n\r\nmain.openO()\r\n\r\n#############################################################################################################################################\r\n##############################################################################################################################################\r\n\r\n#button1 =tk.Button (root, text='Run The Matrix ',command= first.start_matrix)\r\n#canvas1.create_window(100,50, window=button1)#\r\n#\r\n\r\n#button2 = tk.Button(root, text = 'Run the TOOLS manually' , command = first.start_batch_manually)\r\n#canvas1.create_window(350, 453, window= button2)#\r\n#\r\n#\r\n\r\n#button3 = tk.Button (root, text='Run the Framework automatically ', command= main.openO)\r\n#canvas1.create_window(350,493, window=button3)\r\n###\r\n#\r\n\r\n#button4 = tk.Button (root, text='Lock The MACHINE ', command= _lock._locksys)\r\n#canvas1.create_window(100,100, window=button4)#\r\n#\r\n#\r\n\r\n#button5 = tk.Button (root, text='Hibernate The MACHINE ', command= _lock._Hibernatesys)\r\n#canvas1.create_window(100,150, window=button5)#\r\n#\r\n#\r\n\r\n#button6 = tk.Button (root, text='Start Incognito Mode', command= incog.Incognito)\r\n#canvas1.create_window(350,593, window=button6)#\r\n#\r\n\r\n##button4 = tk.Button(root , text = 'Test01', command = __init__)\r\n##canvas1.create_window(340, 393, window = button4)\r\n#canvas1.pack()\r\n#root.mainloop()\r\n\r\n\r\ntry:\r\n\tpass\r\n\r\n\r\n\r\nexcept:\r\n\tpass\r\n\tpass","repo_name":"Karan36k/Machine_Automation","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":13020,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"48"} +{"seq_id":"18049053815","text":"import pygame\nimport time\nimport sys\nfrom pygame.locals import *\n\nkey_black = 1\nkey_white = 2\nkey_block = 0\nwhite = (255, 255, 255)\nblack = (0, 0, 0)\ncolor_restart = (230, 67, 64) # restart按钮颜色\ncolor_regret = (26, 173, 25) # regret按钮颜色\ngrey = (200, 200, 200) # 点击后按钮的颜色\n\n\nclass Element:\n def __init__(self, pointX, pointY, value):\n self.x = pointX\n self.y = pointY\n self.value = value\n\n\nclass Map:\n def __init__(self):\n self.len = 15\n self.ChessBoard = []\n self.start_x = 27\n self.start_y = 27\n self.winner = 0\n self.Laststep = []\n\n def init_board(self):\n for i in range(self.len):\n rowlist = []\n for j in range(self.len):\n pointX = self.start_x + 40 * j\n pointY = self.start_y + 40 * i\n rowlist.append(Element(pointX, pointY, key_block))\n self.ChessBoard.append(rowlist)\n\n def judge(self, row, col, key):\n for x in range(col - 4, col + 5): # 目标点的左4个右4个\n if x >= 0 and x + 4 < 15:\n if self.ChessBoard[row][x].value == key and \\\n self.ChessBoard[row][x + 1].value == key and \\\n self.ChessBoard[row][x + 2].value == key and \\\n self.ChessBoard[row][x + 3].value == key and \\\n self.ChessBoard[row][x + 4].value == key:\n self.winner = key\n return True\n\n for y in range(row - 4, row + 5):\n if y >= 0 and y + 4 < 15:\n if self.ChessBoard[y][col].value == key and \\\n self.ChessBoard[y + 1][col].value == key and \\\n self.ChessBoard[y + 2][col].value == key and \\\n self.ChessBoard[y + 3][col].value == key and \\\n self.ChessBoard[y + 4][col].value == key:\n self.winner = key\n return True\n\n for x in range(row - 4, row + 5):\n for y in range(col - 4, col + 5):\n if x - y == row - col:\n if x >= 0 and x + 4 < 15 and y >= 0 and y + 4 < 15:\n if self.ChessBoard[x][y].value == key and \\\n self.ChessBoard[x + 1][y + 1].value == key and \\\n self.ChessBoard[x + 2][y + 2].value == key and \\\n self.ChessBoard[x + 3][y + 3].value == key and \\\n self.ChessBoard[x + 4][y + 4].value == key:\n self.winner = key\n return True\n\n if x + y == row + col:\n if x >= 0 and x + 4 < 15 and y < 15 and y - 4 >= 0:\n if self.ChessBoard[x][y].value == key and \\\n self.ChessBoard[x + 1][y - 1].value == key and \\\n self.ChessBoard[x + 2][y - 2].value == key and \\\n self.ChessBoard[x + 3][y - 3].value == key and \\\n self.ChessBoard[x + 4][y - 4].value == key:\n self.winner = key\n return True\n return False\n\n def regret(self, steps, Role):\n cnt = 0\n while True:\n if len(self.Laststep) == 0:\n break\n else:\n temp = self.Laststep.pop()\n self.ChessBoard[temp.x][temp.y].value = key_block\n Role = temp.value\n cnt = cnt + 1\n if cnt >= steps:\n break\n\n def clear(self):\n self.ChessBoard.clear()\n self.winner = 0\n\n\nclass Graph:\n def __init__(self, screen_width, screen_height, console_x, console_y, title):\n self.title = title\n self.screen_width = screen_width\n self.screen_height = screen_height\n self.console_x = console_x\n self.console_y = console_y\n\n self.button_width = 0\n self.button_height = 0\n self.button_x = 0\n self.button_y = 0\n\n def calc(self):\n self.button_width = (self.screen_width - self.console_x) - 50 # 按钮宽度\n self.button_height = 50 # 按钮长度\n self.button_x = (self.screen_width + self.console_x) / 2 - self.button_width / 2 # 按钮位置\n self.button_y = self.screen_height / 3 - self.button_height / 2\n\n def init_screen(self):\n pygame.init()\n self.screen = pygame.display.set_mode((self.screen_width, self.screen_height))\n pygame.display.set_caption(self.title)\n\n def load_pic(self):\n self.background = pygame.image.load(\"images/background.png\")\n self.white = pygame.image.load(\"images/white.png\")\n self.black = pygame.image.load(\"images/black.png\")\n self.result = pygame.image.load(\"images/result.jpg\")\n\n def load_text(self):\n font = pygame.font.Font(None, 30)\n self.text1 = font.render('restart', True, white)\n tw1, th1 = self.text1.get_size()\n self.posx_1 = self.button_x + self.button_width / 2 - tw1 / 2\n self.posy_1 = self.button_y + self.button_height / 2 - th1 / 2\n self.text2 = font.render('regret', True, white)\n tw2, th2 = self.text2.get_size()\n self.posx_2 = self.button_x + self.button_width / 2 - tw2 / 2\n self.posy_2 = 2 * self.button_y + self.button_height / 2 - th2 / 2\n\n def draw_button(self, clicked):\n pygame.draw.rect(self.screen, white,\n (self.console_x, self.console_y, self.screen_width - self.console_x, self.screen_height - 5))\n if clicked == 0:\n color1 = color_restart\n color2 = color_regret\n elif clicked == 1:\n color1 = grey\n color2 = color_regret\n else:\n color1 = color_restart\n color2 = grey\n pygame.draw.rect(self.screen, color1, (self.button_x, self.button_y, self.button_width, self.button_height))\n pygame.draw.rect(self.screen, color2, (self.button_x, 2 * self.button_y, self.button_width, self.button_height))\n pygame.display.update()\n\n def draw_text(self):\n self.screen.blit(self.text1, (self.posx_1, self.posy_1))\n self.screen.blit(self.text2, (self.posx_2, self.posy_2))\n pygame.display.update()\n\n def draw_board(self, map):\n self.screen.blit(self.background, (0, 0))\n for temp in map.ChessBoard:\n for point in temp:\n if point.value == 1:\n self.screen.blit(self.black, (point.x - 18, point.y - 18))\n if point.value == 2:\n self.screen.blit(self.white, (point.x - 18, point.y - 18))\n pygame.display.update()\n\n def print_winner(self, delay):\n self.screen.blit(self.result, (200, 200))\n pygame.display.update()\n time.sleep(delay)\n\n def click_restart(self, x, y):\n if x >= self.button_x and x <= self.button_x + self.button_width and \\\n y >= self.button_y and y <= self.button_y + self.button_height:\n return True\n else:\n return False\n\n def click_regret(self, x, y):\n if x >= self.button_x and x <= self.button_x + self.button_width and \\\n y >= 2 * self.button_y and y <= 2 * self.button_y + self.button_height:\n return True\n else:\n return False\n","repo_name":"Jelly-Roger/gomoku","sub_path":"五子棋_test/gomoku_graph.py","file_name":"gomoku_graph.py","file_ext":"py","file_size_in_byte":7480,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"22692222543","text":"import json\nfrom glob import glob\nimport os\n\ndef wikiart_filter(folder_in='wikiart-saved', folder_out='wikiart-filtered', field='genre', target_value='abstract'):\n\t\"\"\"\n\tthis function does the trick of filtering all wikiart entries (artists and their paintings) for a wanted category (e.g. 'genre' or 'style') in the wikiarts annnotations.\n\n\tit builds on the 'wikiart' repository by lucasdavid (https://github.com/lucasdavid/wikiart)\n\n\thow to use it:\n\t- download all metainfo from wikiart using lucasdavid's code (takes forever) \n\tpython3 wikiart.py --datadir ./wikiart-saved/ fetch --only paintings\n\t- build custom subsets using my function\n\t- use lucasdavid's code again to download the wanted jpegs\n\tpython3 wikiart.py --datadir wikiart-filtered/field/target-value/ fetch\n\n\tauthor: Dominik Welke, dominik.welke@web.de, https://github.com/dominikwelke\n\n\t\"\"\"\n\n\t# check if artsits.json file exists\n\tif not os.path.isfile(os.path.join(folder_in, 'meta', 'artists.json')):\n\t\traise FileNotFoundError('artists.json file not in %s. stop execution' % folder_in)\n\n\t# create necessary folders\n\ttry:\n\t\tos.makedirs(os.path.join(folder_out, 'meta'))\n\texcept FileExistsError:\n\t\tpass\n\ttry:\n\t\tos.makedirs(os.path.join(folder_out, 'images'))\n\texcept FileExistsError:\n\t\tpass \n\n\t\n\t# get list of all artist json files\n\tolddir = os.getcwd()\n\tos.chdir(folder_in)\n\tjson_list = glob(os.path.join('meta', '*.json'))\n\tjson_list = [i for i in json_list if i != os.path.join(folder_in, 'meta', 'artists.json')]\n\tjson_list.sort()\n\tos.chdir(olddir)\n\n\n\t# loop through artists\n\tn_artists = len(json_list) # total number of artists\n\tc_artists = 0 # counter\n\tc_artwork = 0 # counter\n\tkeep_artists = []\n\tfor i_artist in range(n_artists):\n\t\t# load json\n\t\twith open(os.path.join(folder_in, json_list[i_artist])) as f:\n\t\t\td_artist = json.load(f)\n\n\t\t# subselect the wanted pics\n\t\tpics = []\n\t\tfor pic in d_artist:\n\t\t\tif field in pic:\n\t\t\t\tif pic[field] == target_value:\n\t\t\t\t\tpics.append(pic)\n\n\n\t\t# save subsetted json to disc\n\t\tif pics != []:\n\t\t\twith open(os.path.join(folder_out, json_list[i_artist]), 'w+') as f:\n\t\t\t\tjson.dump(pics,f,indent=True)\n\t\t\t# compile relevant metainfo\n\t\t\tc_artists += 1\n\t\t\tc_artwork += len(pics)\n\t\t\tkeep_artists.append(json_list[i_artist])\n\t\t\t\n\n\n\n\t# clean out and save updated artists.json (important for only downloading the wanted pictures)\n\twith open(os.path.join(folder_in, 'meta', 'artists.json')) as f:\n\t\tartists_json = json.load(f)\n\t\n\tartists_json_keep = [art for art in artists_json if any([(art['url'] in arti) for arti in keep_artists])]\n\t\n\twith open(os.path.join(folder_out, 'meta', 'artists.json'),'w+') as f:\n\t\tjson.dump(artists_json_keep, f, indent=True)\n\n\n\n\t# print a summary\n\tprint('SUMMARY:')\n\tprint('%s - %s' % (field, target_value))\n\tprint('artists - %i out of %i ' % (c_artists, n_artists))\n\tprint('artworks - %i in total' % c_artwork)\n\n\t# clean up\n\tos.chdir(olddir)\n\n","repo_name":"dominikwelke/wikiart-collector","sub_path":"wikiart_filter/wikiart_filter.py","file_name":"wikiart_filter.py","file_ext":"py","file_size_in_byte":2879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36144092014","text":"import getpass\nimport os\nimport re\nfrom urllib.parse import unquote\n\nimport pdfkit\nimport requests\nfrom bs4 import BeautifulSoup\n\n\ndef get(session, url, attempts=5, timeout=30, raise_exception=0):\n for attempt in range(attempts):\n try:\n return session.get(url, timeout=timeout, headers={'User-Agent': user_agent, 'Referer': url})\n except requests.exceptions.RequestException as e:\n print(f'Failed to connect (URL: {url})')\n if attempt == attempts - 1:\n print()\n if raise_exception:\n raise e\n return 0\n\n\ndef valid_name(name):\n return re.sub(r'[\\\\/:\"*?<>|]', '-', name)\n\n\ndef parse_videos(lessons, filename='webinars.txt'):\n with open(filename, 'w') as f:\n for lesson in lessons:\n r = get(s, lesson)\n if r == 0:\n print(f'Failed to get the page (URL: {lesson})\\n')\n continue\n page = r.text.replace('
    ', '\\n')\n page = page.replace('
    ', '\\n')\n lesson_soup = BeautifulSoup(page, 'html.parser')\n lesson_name = lesson_soup.find('h1').get_text()\n lesson_date = lesson_soup.find('span', class_='val').get_text()\n yt = 'https://youtu.be/' + re.search(r'https://www\\.youtube\\.com/embed/.{11}', page).group(1)\n print(f'{lesson_name} ({lesson_date}): {yt}', file=f)\n description = lesson_soup.find('div', class_='fr-view')\n if description:\n lines = description.find_all('p')\n if lines:\n print('\\n', file=f)\n for line in lines:\n print(line.get_text(), file=f)\n print('\\n', file=f)\n save_materials(page, valid_name(lesson_name))\n\n\ndef save_materials(lesson_page, lesson_name):\n files = re.findall(r'/media/[^\"]+\\.(?:pdf|docx|doc|jpg|jpeg|png|rar|zip)', lesson_page, re.I)\n if files:\n if not os.path.isdir('extra_materials'):\n os.mkdir('extra_materials')\n os.chdir('extra_materials')\n if not os.path.isdir(lesson_name):\n os.mkdir(lesson_name)\n os.chdir(lesson_name)\n for file in files:\n link = 'https://umschool.net' + unquote(file)\n filename = re.search(r'/[^/\"]+\\.(?:pdf|docx|doc|jpg|jpeg|png|rar|zip)', unquote(file), re.I).group(0)\n data = get(s, link)\n if data == 0:\n print(f'Failed to download the file (URL: {link})\\n')\n continue\n with open(valid_name(filename[1:]), 'wb') as doc:\n doc.write(data.content)\n os.chdir('..')\n os.chdir('..')\n\n\ndef save_homework(homework):\n for assignment in homework:\n r = get(s, assignment)\n if r == 0:\n print(f'Failed to get the page (URL: {assignment})\\n')\n continue\n assignment_soup = BeautifulSoup(r.text, 'html.parser')\n try:\n title = assignment_soup.find('span', class_='val').get_text()\n except:\n title = assignment_soup.find('h1').get_text()\n assignment_name = f'{title}.pdf'\n k = 1\n while os.path.isfile(assignment_name):\n assignment_name = f'{title} ({k}).pdf'\n k += 1\n cookies = s.cookies.items()\n options = {'custom-header': [('User-Agent', user_agent)], 'cookie': cookies}\n pdfkit.from_url(assignment, valid_name(assignment_name), options=options)\n\n\nlogin_page = 'https://umschool.net/accounts/login/'\nuser_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 ' \\\n 'Safari/537.36'\ns = requests.Session()\n\nget(s, login_page, raise_exception=1)\ncsrftoken = s.cookies['csrftoken']\nlogin = input('Login: ')\npassword = getpass.getpass()\nlogin_data = dict(login=login, password=password, csrfmiddlewaretoken=csrftoken)\nr = s.post(login_page, data=login_data, headers={'User-Agent': user_agent, 'Referer': login_page})\nif 'Имя пользователя и/или пароль не верны.' in r.text:\n raise Exception('Имя пользователя и/или пароль не верны.')\n\ncourse_page = input('Enter course page URL: ')\ncourse = get(s, course_page, raise_exception=1)\nif course.status_code == 404:\n raise Exception('Invalid URL or no access to the course.')\n\nlessons = ['https://umschool.net' + lesson for lesson in re.findall(r'/\\w+/lessons/\\d+/', course.text)]\nlessons = sorted(set(lessons))\n\npattern = r'/\\w+/lessons/\\d+/homework/|/homework/go/\\d+/'\nhomework = ['https://umschool.net' + assignment for assignment in re.findall(pattern, course.text)]\nhomework = sorted(set(homework))\n\nsoup = BeautifulSoup(course.text, 'html.parser')\nname = valid_name(soup.find('h1').get_text())\nif not os.path.isdir(name):\n os.mkdir(name)\nos.chdir(name)\n\nif lessons:\n parse_videos(lessons)\n\nif homework:\n if not os.path.isdir('homework'):\n os.mkdir('homework')\n os.chdir('homework')\n save_homework(homework)\n os.chdir('..')\n\nos.chdir('..')\n","repo_name":"emiilkaa/umschool-parser","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5110,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19161957925","text":"import rospy\nimport numpy as np\nimport geometry_msgs.msg\nimport nav_msgs.msg\nfrom collections import deque\n\n\ndef reshape_map(data, height, width):\n return np.reshape(data, (height, width))\n\n\ndef pose_to_map_point(pose, resolution):\n return int(pose.position.x / resolution), int(pose.position.y / resolution)\n\n\ndef pose_to_relative_map_point(pose, origin, resolution):\n return int((pose.position.y - origin.position.y) / resolution), int((pose.position.x - origin.position.x) / resolution)\n\n\ndef map_point_to_relative_pose(point, origin, resolution):\n pose = geometry_msgs.msg.Pose()\n pose.position.x = origin.position.x + point[1] * resolution\n pose.position.y = origin.position.y + point[0] * resolution\n pose.orientation.w = 1\n return pose\n\n\ndef map_point_to_relative_pose_with_euclidean_distance(point, origin, resolution):\n pose = map_point_to_relative_pose(point, origin, resolution)\n a = pose.position.x - origin.position.x\n b = pose.position.y - origin.position.y\n distance = np.sqrt(a*a+b*b)\n return pose, distance\n\n\ndef find_frontier_points_in_map(start, grid_map):\n rospy.loginfo(\"Find frontier points in map, start with {} = {}\".format(start, grid_map[start]))\n processed = -2\n unknown = -1\n occupied_threshold = 50\n neighbours = [\n [1, 0],\n [0, 1],\n [-1, 0],\n [0, -1]\n ]\n frontiers = []\n if grid_map[start] == unknown or grid_map[start] >= occupied_threshold:\n rospy.loginfo(\"No frontier points found!\")\n return frontiers\n queue = deque()\n queue.append(start)\n grid_map[start] = processed\n while len(queue) > 0:\n curr = queue.popleft()\n for neighbour in neighbours:\n coord = (curr[0] + neighbour[0], curr[1] + neighbour[1])\n if 0 <= grid_map[coord] < occupied_threshold:\n grid_map[coord] = processed\n queue.append(coord)\n elif grid_map[coord] == unknown:\n frontiers.append(coord)\n rospy.loginfo(\"Found {} frontier points.\".format(len(frontiers)))\n return frontiers\n\n\ndef find_frontier_points_in_occupancy_grid(occupancy_grid):\n grid_map = np.reshape(occupancy_grid.data, (occupancy_grid.info.height, occupancy_grid.info.width))\n origin = occupancy_grid.info.origin\n resolution = occupancy_grid.info.resolution\n start = pose_to_map_point(origin, resolution)\n frontiers = find_frontier_points_in_map(start, grid_map)\n return [map_point_to_relative_pose(x, origin, resolution) for x in frontiers]\n\n\ndef find_closest_frontier_point_in_occupancy_grid(occupancy_grid, odometry, min_distance):\n \"\"\"\n :param occupancy_grid:\n :type occupancy_grid: nav_msgs.msg.OccupancyGrid\n :param min_distance: The min distance of the frontier point in m\n :type min_distance: float\n :return:\n :rtype: geometry_msgs.msg.Pose\n \"\"\"\n rospy.loginfo(\"Find closest frontier point in occupancy grid\")\n grid_map = np.reshape(occupancy_grid.data, (occupancy_grid.info.width, occupancy_grid.info.height))\n robot_pose = odometry.pose.pose\n origin = occupancy_grid.info.origin\n resolution = occupancy_grid.info.resolution\n start = pose_to_relative_map_point(robot_pose, origin, resolution)\n frontiers = find_frontier_points_in_map(start, grid_map)\n frontiers_with_distance = [map_point_to_relative_pose_with_euclidean_distance(x, origin, resolution) for x in frontiers]\n frontiers_with_distance.sort(cmp=lambda a, b: int(a[1] - b[1]))\n for pose_with_distance in frontiers_with_distance:\n if pose_with_distance[1] >= min_distance:\n rospy.loginfo(\"Closest frontier point: {}\".format(pose_with_distance[0]))\n return pose_with_distance[0]\n rospy.loginfo(\"No closest frontier point!\")\n return None\n\n\ndef find_random_frontier_point_in_occupancy_grid(occupancy_grid, odometry, min_distance):\n \"\"\"\n :param occupancy_grid:\n :type occupancy_grid: nav_msgs.msg.OccupancyGrid\n :param min_distance: The min distance of the frontier point in m\n :type min_distance: float\n :return:\n :rtype: geometry_msgs.msg.Pose\n \"\"\"\n rospy.loginfo(\"Find random frontier point in occupancy grid\")\n grid_map = np.reshape(occupancy_grid.data, (occupancy_grid.info.height, occupancy_grid.info.width))\n robot_pose = odometry.pose.pose\n origin = occupancy_grid.info.origin\n resolution = occupancy_grid.info.resolution\n start = pose_to_relative_map_point(robot_pose, origin, resolution)\n frontiers = find_frontier_points_in_map(start, grid_map)\n frontiers_with_distance = [map_point_to_relative_pose_with_euclidean_distance(x, origin, resolution) for x in frontiers]\n if len(frontiers_with_distance) > 0:\n frontier_pose_idx = np.random.choice(range(len(frontiers_with_distance)))\n frontier_pose = frontiers_with_distance[frontier_pose_idx]\n rospy.loginfo(\"Chosen frontier point: {}\".format(frontier_pose[0]))\n return frontier_pose[0]\n rospy.loginfo(\"No frontier point!\")\n return None\n","repo_name":"benikm91/IANA_IP6","sub_path":"iana_driver/scripts/common/frontier_detection.py","file_name":"frontier_detection.py","file_ext":"py","file_size_in_byte":5032,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13351264645","text":"from string import punctuation\nimport numpy as np\nfrom sklearn.datasets import fetch_20newsgroups\nfrom collections import Counter\nfrom sklearn.utils import shuffle\nfrom nltk.corpus import stopwords\nimport matplotlib as mplt\nmplt.use('agg') # Must be before importing matplotlib.pyplot or pylab!\nimport matplotlib.pyplot as plt\nimport nltk\nimport os\nnltk.download('stopwords')\n\n\"\"\"\nReferences \n[1] AROW - http://www.alexkulesza.com/pubs/arow_nips09.pdf\n[2] MOA - http://www.jmlr.org/papers/volume11/bifet10a/bifet10a.pdf\n\"\"\"\n\nseed = 42\nnp.random.seed(seed)\n\n\nclass AROW:\n\n def __init__(self, nb_class, d):\n self.w = np.zeros((nb_class, d))\n self.sigma = np.identity(d)\n self.r = 1\n self.nb_class = nb_class\n\n def fit(self, X, y):\n w = np.copy(self.w)\n sigma = np.copy(self.sigma)\n\n # y = ((y - y.min()) * (1/(y.max() - y.min()) * (nb_class-1))).astype('uint8')\n\n F_t = np.dot(self.w, X.T)\n\n # compute hinge loss and support vector\n F_s = np.copy(F_t)\n F_s[y] = -np.inf\n s_t = np.argmax(F_s)\n m_t = F_t[y] - F_t[s_t]\n v_t = np.dot(X, np.dot(sigma, X.T))\n l_t = np.maximum(0, 1 - m_t) # hinge loss\n\n # update weights\n if l_t > 0:\n beta_t = 1 / (v_t + self.r)\n alpha_t = l_t * beta_t\n self.w[y] = w[y] + (alpha_t * np.dot(sigma, X.T).T)\n self.w[s_t] = w[s_t] - (alpha_t * np.dot(sigma, X.T).T)\n self.sigma = sigma - beta_t * np.dot(np.dot(sigma, X.T), np.dot(X, sigma))\n\n def predict(self, X):\n return np.argmax(np.dot(self.w, X.T), axis=0)\n\ndef preProcess():\n direc = \"enron/emails/\"\n files = os.listdir(direc)\n emails = [direc + email for email in files]\n\n words = []\n\n for email in emails:\n f = open(email, encoding=\"utf8\", errors='ignore')\n blob = f.read()\n words += blob.split(\" \")\n\n for i in range(len(words)):\n if not words[i].isalpha():\n words[i] = \"\"\n\n dictionary = Counter(words)\n del dictionary[\"\"]\n dictionary.most_common(3000)\n\n direc = \"enron/emails/\"\n files = os.listdir(direc)\n emails = [direc + email for email in files]\n print(len(emails))\n\n feature_set = []\n labels = []\n\n for email in emails:\n data = []\n f = open(email, encoding=\"utf8\", errors='ignore')\n words = f.read().split(' ')\n\n for entry in dictionary:\n data.append(words.count(entry[0]))\n feature_set.append(data)\n if \"ham\" in email:\n labels.append(0)\n else:\n labels.append(1)\n\n return feature_set, labels\n\n\ndef plot(noOfWrongPred, dataPoints, name):\n font_size = 14\n fig = plt.figure(dpi=100,figsize=(10, 6))\n mplt.rcParams.update({'font.size': font_size})\n plt.title(\"Distribution of wrong predictions\", fontsize=font_size)\n plt.ylabel('Error rate', fontsize=font_size)\n plt.xlabel('Number of data points', fontsize=font_size)\n\n plt.plot(dataPoints, noOfWrongPred, label='Prediction', color='blue', linewidth=1.8)\n # plt.legend(loc='upper right', fontsize=14)\n\n plt.savefig(name+'.png')\n # plt.show()\n\nif __name__ == '__main__':\n\n features, labels = preProcess()\n\n features= np.asarray(features)\n labels=np.asarray(labels)\n\n print(type(features))\n print(type(labels))\n\n X_train, y_train = shuffle(features, labels, random_state=seed)\n\n n, d = X_train.shape\n\n nb_class = 20\n\n arow = AROW(nb_class, d)\n\n error = 0\n noOfWrongPreds = []\n dataPoints = []\n for i in range(n):\n X, y = X_train[i:i + 1], y_train[i:i + 1]\n print()\n p_y = arow.predict(X)\n arow.fit(X, y)\n\n if y-p_y != 0:\n error += 1\n\n if i % 50 == 0:\n print(error)\n print(i)\n print(i+1)\n noOfWrongPreds.append(error / (i+1))\n dataPoints.append(i+1)\n\n print(error)\n print(np.divide(error, n, dtype=np.float))\n plot(noOfWrongPreds, dataPoints, \"distribution of wrong predictions Arrow\")\n\n\n","repo_name":"suleka96/RNN-and-ML-models","sub_path":"AROW_Enron.py","file_name":"AROW_Enron.py","file_ext":"py","file_size_in_byte":4070,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"26378757106","text":"# this project uses OCR from pytesseract, so will not run properly unless you have\r\n# installed pytesseract and put the file location of the tesseract.exe in the first variable\r\n\r\n# this project was mainly me trying to use OCR for practical purposes\r\n\r\n# this program hasn't been trained, so can only recognise certain texts (like pycharm's segoe UI)\r\n\r\nprint('please wait')\r\nfrom gtts import gTTS\r\nimport os\r\nimport pyautogui\r\nimport pytesseract\r\nimport mouse\r\nimport time\r\nimport keyboard\r\npytesseract.pytesseract.tesseract_cmd = 'C:/program files/Tesseract-OCR/tesseract.exe'\r\n\r\ntry:\r\n from PIL import Image\r\nexcept ImportError:\r\n import Image\r\n\r\n\r\nmylist = []\r\nclick_list = []\r\nj = 0\r\n\r\n\r\n# shift to mark\r\ndef mark():\r\n while True:\r\n if keyboard.is_pressed(\"shift\"):\r\n x, y = mouse.get_position()\r\n click_list.append(x)\r\n click_list.append(y)\r\n break\r\n\r\n\r\nprint('mark ready')\r\nfor i in range(2):\r\n mark()\r\n time.sleep(0.3)\r\n\r\nim = pyautogui.screenshot(region=(click_list[0], click_list[1], click_list[2] - click_list[0], click_list[3] - click_list[1]))\r\nprint('converting to string')\r\ntext = pytesseract.image_to_string(im)\r\nfor letter in text:\r\n if letter.isalnum():\r\n mylist.append(str(letter))\r\n else:\r\n mylist.append(str(letter))\r\n\r\n\r\nprint(mylist)\r\nprint(text)\r\n\r\nspeak = ''\r\nspeak += text\r\nlanguage = 'en'\r\nprint('preparing audio')\r\nmyobj = gTTS(text=speak, lang=language, slow=False)\r\nmyobj.save(\"TTS_MP3_FILE.mp3\")\r\nos.system(\"TTS_MP3_FILE.mp3\")\r\n","repo_name":"Bubchez/interesting-bits","sub_path":"TTS.py","file_name":"TTS.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20333765046","text":"# coding:utf-8\n\nimport os\nfrom setuptools import setup\n\n\ndef read(fname):\n return open(os.path.join(os.path.dirname(__file__), fname)).read().strip()\n\nVERSION = '0.1.0'\n\nsetup(name='nose-sigterm',\n version=VERSION,\n description='Raise KeyboardInterrupt on SIGTERM',\n url='https://github.com/scoutexchange/nose-sigterm',\n classifiers=['Intended Audience :: Developers',\n 'Topic :: Software Development :: Testing',\n 'Programming Language :: Python'],\n py_modules=['nose_sigterm'],\n zip_safe=False,\n entry_points={\n 'nose.plugins': ['nose_sigterm = nose_sigterm:NoseSigterm']\n },\n install_requires=['nose'])\n","repo_name":"scoutexchange/nose-sigterm","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35307068925","text":"from aiogram.types import CallbackQuery, Message\n\nfrom loader import dp, bot\nfrom utils.db_api.db import Db\nfrom utils.qiwi_api import qiwi\nfrom utils.stateMachine import StateMachine\nfrom keyboards.inline.inline_keyboard import check_status_pay\n\n\n# Депозит\n@dp.callback_query_handler(lambda c: c.data == 'deposit', state='*')\nasync def process_callback_buttonDeposit(callback_query: CallbackQuery):\n state = dp.current_state(user=callback_query.from_user.id)\n await state.set_state(StateMachine.all()[1])\n\n await bot.answer_callback_query(callback_query.id)\n await bot.send_message(callback_query.from_user.id, f'''💰 Мин. сумма депозита: 1 ₽.\n\n📥 Пополнение Вашего баланса проводится через платежную систему \"QIWI\".\n\n💬 Введите в чат сумму пополнения:''')\n\n await bot.delete_message(callback_query.message.chat.id, callback_query.message.message_id)\n\n\n@dp.message_handler(state=StateMachine.STATE_1)\nasync def getAmountFromUser(message: Message):\n amount = message.text\n db = Db()\n\n try:\n if amount.isdigit():\n amount = int(amount)\n\n if amount >= 1:\n invoice = qiwi.create_invoice(amount)\n pay_url = invoice.pay_url\n bill_id = invoice.bill_id\n \n db.updateBillId(bill_id, message.from_user.id)\n db.updateWaitingAmount(amount, message.from_user.id)\n\n await bot.send_message(message.from_user.id, f'🚀 Ссылка для оплаты счета: \\n\\n{pay_url}')\n\n await bot.send_message(message.from_user.id, '⚠️ Нажмите кнопку ниже, чтобы проверить статус платежа',\n reply_markup=check_status_pay)\n\n elif amount < 1:\n db.updateBillId(0, message.from_user.id)\n await bot.send_message(message.from_user.id, '''❗️ Мин. сумма пополнения равна 1 руб.''')\n \n else:\n db.updateBillId(0, message.from_user.id)\n await bot.send_message(message.from_user.id, '''❗️ Ошибка: неверный формат''')\n\n state = dp.current_state(user=message.from_user.id)\n await state.set_state(StateMachine.all()[0])\n \n except:\n pass\n ","repo_name":"pettroch/boot","sub_path":"callbacks/users/deposit.py","file_name":"deposit.py","file_ext":"py","file_size_in_byte":2467,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"70206820947","text":"'''sort a csv by selected field'''\nfrom misc import *\n\nif len(args) < 3:\n err('python3 csv_sort.py [input csv file name] [name of field to sort on (increasing)]')\n\nofn, fi = args[1] + '_sort.csv', -1\nfields, data = read_csv(args[1])\nlookup = {fields[i]: i for i in range(len(fields))}\n\ntry: fi = lookup[args[2]]\nexcept: err('field not found:', args[2])\n\nN = len(data[0])\nsortd = [ [data[fi][i], i] for i in range(N)] # intentional naming\nsortd.sort(reverse=False) # increasing order\n\nprint(\"+w\", ofn)\nM = range(len(fields))\nlines = [','.join(fields)]\nfor i in range(N):\n lines += [','.join([ ('\"' + data[j][sortd[i][1]] + '\"') for j in M])]\nopen(ofn, 'wb').write(('\\n'.join(lines)).encode())\n\n","repo_name":"bcgov/wps-research","sub_path":"py/csv_sort.py","file_name":"csv_sort.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"48"} +{"seq_id":"20478917445","text":"#!/usr/bin/env python3\nfrom concurrent.futures import ThreadPoolExecutor as Executor\nimport threading\n\n\ndef view_thread_worker():\n print('Executing Thread')\n print(f'Accessing thread: {threading.get_ident()}')\n print(f'Thread Executed {threading.current_thread()}')\n\n\ndef main():\n with Executor(max_workers=3) as exe:\n fut1 = exe.submit(view_thread_worker)\n fut2 = exe.submit(view_thread_worker)\n fut3 = exe.submit(view_thread_worker)\n\n\nif __name__ == '__main__':\n main()\n\n\"\"\"\nOutput order not guaranteed.\n\n$ p3 thread_pool_concurrency.py\nExecuting Thread\nAccessing thread: 123145323118592\nThread Executed \nExecuting Thread\nAccessing thread: 123145323118592\nThread Executed \nExecuting Thread\nAccessing thread: 123145323118592\nThread Executed \n\"\"\"\n","repo_name":"sashadev-sky/Python-for-Networking","sub_path":"chapter2/concurrency/thread_pool_concurrency.py","file_name":"thread_pool_concurrency.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16895571049","text":"import tensorflow as tf\r\nimport numpy as np\r\nimport gym\r\nimport random\r\nfrom collections import deque\r\n\r\n#env=gym.make('Pendulum-v0')\r\nenv=gym.make('MountainCarContinuous-v0')\r\n\r\nenv=env.unwrapped\r\n\r\ns_dim = env.observation_space.shape[0]\r\nprint(s_dim)\r\na_dim = env.action_space.shape[0]\r\nprint(a_dim)\r\na_bound = env.action_space.high[0]\r\nprint(a_bound)\r\nDUMMY_ACTION, DUMMY_VALUE = np.zeros((1,a_dim)), np.zeros((1, 1))\r\n\r\n\r\n################## policy ################\r\nE_inputs = tf.keras.Input(shape=(1,), name='E_samples')\r\ndq_da = tf.keras.Input(shape=(1,), name='dq1/danew')\r\n\r\nstate_inputs = tf.keras.Input(shape=(s_dim,), name='state')\r\nx = tf.keras.layers.Dense(100, activation='relu')(state_inputs)\r\nx1 = tf.keras.layers.Dense(100, activation='relu')(x)\r\nmu_0 = tf.keras.layers.Dense(a_dim, activation='tanh')(x1)\r\nx2 = tf.keras.layers.Dense(100, activation='relu')(x)\r\nsigma_0 = tf.keras.layers.Dense(a_dim, activation='softplus')(x2)\r\nmu = tf.keras.layers.Lambda(lambda x: x )(mu_0)\r\nsigma = tf.keras.layers.Lambda(lambda x: tf.clip_by_value(x,1e-22 , 1e+02))(sigma_0)# clamp bet e -22 , e +2\r\nmusig=tf.keras.layers.concatenate([mu,sigma])\r\n\r\ndef SAC_loss(E_inputs,dq_da):\r\n\talpha = 1.\r\n\tpi=3.1415926\r\n\tmu_mask = tf.convert_to_tensor(np.array([[1],[0]]), dtype = tf.float32)\r\n\tsig_mask = tf.convert_to_tensor(np.array([[0],[1]]), dtype = tf.float32)\r\n\t\t\r\n\tdef loss(y_true, y_pred):\r\n\t\tmu = tf.keras.backend.dot(y_pred,mu_mask)# masking incase above slicing fails\r\n\t\tsigma = tf.keras.backend.dot(y_pred,sig_mask)\r\n\t\t#mu=tf.keras.backend.expand_dims(y_pred[:,0],1)\r\n\t\t#sigma = tf.keras.backend.expand_dims(y_pred[:,1],1)\r\n\t\t#mu= tf.keras.backend.transpose(mu)\r\n\t\t#sigma =tf.keras.backend.transpose(sigma)\r\n\t\tsigma_sq=tf.keras.backend.square(sigma)\r\n\t\tnew_act = mu + tf.multiply(sigma,E_inputs) #Add tanh*a_bound\r\n\t\tnew_actions = tf.tanh(new_act)\r\n\t\tpdf = 1. / tf.keras.backend.sqrt(2. *pi* sigma_sq) * tf.keras.backend.exp(-tf.keras.backend.square(new_act- mu) / (2. * sigma_sq))\r\n\t\tlog_pdf = tf.keras.backend.log(pdf )- tf.keras.backend.log(1 - tf.keras.backend.square(new_actions) + tf.keras.backend.epsilon())\r\n\r\n\t\tloss =tf.keras.backend.mean( alpha*log_pdf - tf.multiply(dq_da,new_actions) )\r\n\t\treturn loss\r\n\treturn loss\t\r\npolicy= tf.keras.Model(inputs=(state_inputs,E_inputs,dq_da), outputs=(musig), name='p_actor_model')\r\npolicy.compile(loss=SAC_loss(E_inputs=E_inputs,dq_da=dq_da), optimizer=tf.keras.optimizers.Adam(lr=0.001))\r\npolicy.summary()\r\n\r\n###################### q functions #######################333\r\n\r\naction_inputs = tf.keras.Input(shape=(a_dim,), name='action')\r\nx=tf.keras.layers.Dense(100, activation='relu')(state_inputs)\r\nx=tf.keras.layers.concatenate([tf.keras.layers.Flatten()(x),action_inputs])\r\nx=tf.keras.layers.Dense(64, activation='relu')(x)\r\nQout=tf.keras.layers.Dense(1, activation=None)(x)\r\nq_1= tf.keras.Model(inputs=[state_inputs,action_inputs], outputs=Qout, name='p_critic_model')\r\nq_1.compile(loss=\"mse\",optimizer=tf.keras.optimizers.Adam(lr=0.001), metrics=['accuracy'])\r\nq_1.summary()\r\nq_2= tf.keras.Model(inputs=[state_inputs,action_inputs], outputs=Qout, name='t_critic_model')\r\nq_2.compile(loss=\"mse\",optimizer=tf.keras.optimizers.Adam(lr=0.001), metrics=['accuracy'])\r\nq_2.summary()\r\n# now we create a function to give dQ(s,a)/da\r\nget_q_1_grads= tf.keras.backend.function([q_1.input[0], q_1.input[1]], tf.keras.backend.gradients(q_1.output, [q_1.input[1]]))\r\n\r\n########################### val func #######################\r\n\r\n\r\nx = tf.keras.layers.Dense(100, activation='relu')(state_inputs)\r\nx = tf.keras.layers.Dense(64, activation='relu')(x)\r\nvalue_outputs = tf.keras.layers.Dense(1, activation=None)(x)\r\nvalue= tf.keras.Model(inputs=state_inputs, outputs=value_outputs, name='p_value_model')\r\nvalue.compile(loss=\"mse\", optimizer=tf.keras.optimizers.Adam(lr=0.001), metrics=['accuracy'])\r\nvalue.summary()\r\nt_value= tf.keras.Model(inputs=state_inputs, outputs=value_outputs, name='t_value_model')\r\n#t_value.compile(loss=\"mse\", optimizer=tf.keras.optimizers.Adam(lr=0.001), metrics=['accuracy'])\r\nt_value.trainable =False\r\nt_value.summary()\r\n\r\n\r\n\r\n\r\nmemory=deque(maxlen=20000)\r\n\r\nimport math\r\n\r\ndef get_log_pdf(x, mean, std):\r\n\tsigma_sq = (std)**2\r\n\tpdf= 1./(2*3.1415926*sigma_sq)**0.5 * math.exp(-(float(x)-float(mean))**2/(2.*sigma_sq))\r\n\tlog_pdf = np.log(pdf) \r\n\treturn log_pdf\r\n\r\ndef update_value_target(tau=0.1):\r\n\t# for soft weight updates\r\n\tvalue_weights= value.get_weights()\r\n\tvalue_target_weights=t_value.get_weights()\r\n\tfor i in range(len(value_target_weights)):\r\n\t\tvalue_target_weights[i]=(1-tau)*value_target_weights[i]+tau*value_weights[i]\r\n\tt_value.set_weights(value_target_weights)\r\ndef remember(s,a,r,ns,d):\r\n\ts=s.ravel()\r\n\tns=ns.ravel()\r\n\tmemory.append([s,a,r,ns,d])\r\ndef replay_and_train(size=128):\r\n\tgamma=0.95\r\n\tsample_size=size\r\n\tif len(memory) < sample_size:\r\n\t\treturn\r\n\tsamples=random.sample(memory,sample_size)\r\n\tyvs=[]\r\n\tyqs=[]\r\n\tEs=[]\r\n\tstates=[]\r\n\tnew_Actions=[]\r\n\tactions=[]\r\n\tnew_musigs=[]\r\n\tfor sample in samples:\r\n\t\ts,a,r,ns,d=sample\r\n\t\tyq = r + gamma*(1-d)*t_value.predict(np.array([ns]))[0]\r\n\t\tE =np.random.normal(0,1)\r\n\t\tnew_musig = policy.predict((np.array([s]),np.array([[0]]),np.array([[0]])))\r\n\t\tnew_mu,new_sig=new_musig[0][0],new_musig[0][1]\r\n\t\tnew_Action =np.tanh(new_mu + new_sig*E) \r\n\t\t# check dimensions for everything\r\n\t\t#log_prob = Normal(mean, std).log_prob(mean+ std*z.to(device)) - torch.log(1 - action.pow(2) + epsilon)\r\n\t\t#pre_sum = -0.5 * (((pi - mu) / (tf.exp(log_std) + EPS)) ** 2 + 2 * log_std + np.log(2 * np.pi))\r\n\t\t#logp_pi = tf.reduce_sum(pre_sum, axis=1)\r\n\r\n\t\tlog_pi_new_actions = get_log_pdf(new_mu + new_sig*E,new_mu,new_sig) - np.log((1- (new_Action)**2 )+ 1e-07) #additional regulizer with entropy\r\n\t\t#################################################################log prob is needed\r\n\t\tyv = min(q_1.predict([np.array([s]),np.array([new_Action])])[0],q_2.predict([np.array([s]),np.array([new_Action])])[0]) - 1.* log_pi_new_actions\r\n\t\tnew_Actions.append(np.array([new_Action]))\r\n\t\tactions.append(np.array([a]))\r\n\t\tEs.append(np.array([E]))\r\n\t\tyvs.append(yv)\r\n\t\tyqs.append(yq)\r\n\t\tstates.append(s)\t\r\n\t\tnew_musigs.append(new_musig)\r\n\r\n\r\n\ta = np.array(new_Actions) \r\n\tEs =np.array(Es)\r\n\tstates=np.array(states)\r\n\tq_1.fit([states,np.array(actions)],np.array(yqs),epochs=1,batch_size=512,verbose=0)\t\t\r\n\tq_2.fit([states,np.array(actions)],np.array(yqs),epochs=1,batch_size=512,verbose=0)\t\t\r\n\tvalue.fit(states,np.array(yvs),epochs=1,batch_size=512,verbose=0)\t\r\n\tdq_da=get_q_1_grads([states,a])[0]\r\n\tpolicy.fit((states,Es,dq_da),np.array(new_musigs),epochs=1,batch_size=512,verbose=0)\r\n\tupdate_value_target(0.01)\r\n\r\ndef save_actor_critic_weights():\r\n\tactorpath=r\"C:\\\\Users\\\\Dell\\\\Desktop\\\\holidASY\\\\softAC,DDPG\\\\ddpg_car_actor.h5\"\r\n\tcriticpath=r\"C:\\\\Users\\\\Dell\\\\Desktop\\\\holidASY\\\\softAC,DDPG\\\\ddpg_car_critic.h5\"\r\n\t#tf.keras.models.save_model(primary_actor,actorpath,overwrite=True,include_optimizer=True)\r\n\t#tf.keras.models.save_model(primary_critic,criticpath,overwrite=True,include_optimizer=True)\r\n\tprimary_actor.save_weights(actorpath)\r\n\tprimary_critic.save_weights(criticpath)\r\n\tprint(\"saved\")\r\ndef load_actor_critic_weights():\r\n\tactorpath=r\"C:\\\\Users\\\\Dell\\\\Desktop\\\\holidASY\\\\softAC,DDPG\\\\ddpg_car_actor.h5\"\r\n\tcriticpath=r\"C:\\\\Users\\\\Dell\\\\Desktop\\\\holidASY\\\\softAC,DDPG\\\\ddpg_car_critic.h5\"\r\n\tprimary_actor.load_weights(actorpath)\r\n\tprimary_critic.load_weights(criticpath)\r\n\tprint(\"loaded\")\r\n\r\n\r\n\r\nepisodes = 5000\r\nsteps = 3000 \r\nupdate_value_target(1)\r\nctr = 0\r\nrender =False\r\n#load_actor_critic_weights()\r\ns = env.reset()\r\nfor ep in range(episodes):\r\n\ts = env.reset()\r\n\tdone=False\r\n\tstp=0\r\n\trews=0\r\n\tif ep>20:\r\n\t\trender=1\r\n\twhile not done:\r\n\t\r\n\t\tif render:\r\n\t\t\tenv.render()\t\r\n\t\tmusig = policy.predict((np.array([s]),np.array([[0]]),np.array([[0]])))\r\n\t\tmu,sig=musig[0][0],musig[0][1]\r\n\t\tE =np.random.normal(0,1)\r\n\t\t#print(mu,sig,E,a_bound)\r\n\t\t#Action =np.clip(mu + sig*E,-2,2)\r\n\t\tAction =np.tanh(mu + sig*E)\r\n\t\t#print(Action)\r\n\t\tif ep < 10 :\r\n\t\t\tif E > 0.5:\r\n\t\t\t\tAction = np.clip(a_bound*E,-a_bound,a_bound)\r\n\r\n\t\ts_,r,done,_=env.step(np.array([Action*a_bound]))\r\n\t\t#if done == 1:\r\n\t\t#\tr =r +100\r\n\t\t#\tprint(\"M\")\r\n\t\tremember(s,Action,r,s_,done)\r\n\t\trews+=r\r\n\t\t#if ctr% ==0:##100\r\n\t\t#\treplay_and_train(32)#128\\\r\n\t\tif ep < 20:\r\n\t\t\treplay_and_train(16)\r\n\t\tstp+=1\r\n\t\tctr+=1\r\n\t\ts=s_\r\n\t\tif stp > 5000:\r\n\t\t\tdone =1\r\n\tprint(\"episode: \"+str(ep)+ \" rews: \"+str(rews))\r\n\treplay_and_train(2048)","repo_name":"rootAkash/reinforcement_learning","sub_path":"Soft AC/my_SAC.py","file_name":"my_SAC.py","file_ext":"py","file_size_in_byte":8407,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"42294534913","text":"script_var = \"This is a script or global level variable\"\n\n# Print the fibonacci number up to n\nn = 10\na, b = 0, 1\nwhile b < n:\n print(b)\n a, b = b, a + b\n\n# A dog class\nclass Dog:\n def __init__(self, name):\n self.name = name\n\n def speak(self):\n print(self.name + \" says woof.\")\n\nd = Dog(\"Fido\")\nd.speak()\n","repo_name":"JuliaDana/wags-magnetizer","sub_path":"spec/python3_complex/complex.py","file_name":"complex.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41921760173","text":"import inspect\nimport logging\nimport logging.handlers\nimport os\nimport time\nimport datetime\nimport sys\nimport getpass\n\n\nclass LogConfig:\n def __init__(self, log_level=logging.INFO):\n if __name__ != \"__main__\":\n self.logger = self.get_file_logger(log_level=log_level)\n pass\n\n def get_console_logger(self):\n def _gen_file_logger_handler():\n _handler = logging.StreamHandler()\n formatter = logging.Formatter(\n \"[%(asctime)s %(msecs)03d][%(process)d][tid=%(thread)d][%(name)s]\"\n \"[%(levelname)s] %(message)s [%(filename)s\"\n \" %(funcName)s %(lineno)s] \", datefmt=\"%Y-%m-%d %H:%M:%S\")\n _handler.setLevel(logging.INFO)\n _handler.setFormatter(formatter)\n return _handler\n\n def _gen_console_logger():\n _console_logger = logging.getLogger(\"console_logger\")\n _console_logger.addHandler(handler)\n return _console_logger\n\n handler = _gen_file_logger_handler()\n console_logger = _gen_console_logger()\n return console_logger\n\n # 允许同时存在不同的logger,即可以传入不同log_file_name实例化不同logger即可实现不同类型日志写入不同文件\n # logger自带了线程锁,是线程安全的,所以多线程不用自己实现日志文件锁\n def get_file_logger(self, logger_name=None, log_file_name=None, log_level=logging.INFO):\n def _get_log_file_name():\n # 如果已定义有日志文件则直接原样返回\n if log_file_name:\n return log_file_name\n # 如果是直接运行的,那取当前文件名\n if __name__ == \"__main__\":\n caller_file_name = __file__\n # 如果是被调用的,则取上层调用文件文件名\n else:\n frame = inspect.stack()[3]\n module = inspect.getmodule(frame[0])\n caller_file_name = module.__file__\n inner_log_file_name = f\"{os.path.basename(caller_file_name)[:-3]}.log\"\n return inner_log_file_name\n\n def _make_sure_log_dir_exist():\n if not os.path.isdir(log_file_dir):\n os.mkdir(log_file_dir)\n\n def _gen_file_logger_handler():\n # 操作系统本身不允许文件名包含:等特殊字符,所以这里也不要用,不然赋给filename时会报错\n # nowTime = datetime.datetime.now().strftime('%Y-%m-%d')\n file_path = f'{log_file_dir}/{log_file_name}'\n # formatter = logging.Formatter(\n # \"[%(asctime)s %(msecs)03d][%(process)d][tid=%(thread)d][%(name)s]\n # [%(levelname)s] %(message)s [%(filename)s\"\n # \" %(funcName)s %(lineno)s] \", datefmt=\"%Y-%m-%d %H:%M:%S\")\n formatter = logging.Formatter(\n \"%(asctime)s %(msecs)03d - %(name)s - %(levelname)s - %(message)s\", datefmt=\"%Y-%m-%d %H:%M:%S\")\n # filename----日志文件\n # when----更换日志文件的时间单位\n # interval----更换日志文件的时间单位个数;这里是7天换一个文件\n # backupCount----保存的旧日志文件个数;这里即只保留上一个日志文件\n # encoding----日志文件编码\n # 实际使用感觉,如果程序是crontab这样定时运行而不是一直运行着,那这个按时间滚动并不生效\n # _handler = logging.handlers.TimedRotatingFileHandler(\n # filename=file_path,\n # when='D',\n # interval=7,\n # backupCount=1,\n # encoding='utf-8',\n # )\n # filename--日志文件\n # mode--日志文件打开模式\n # maxBytes--日志文件最大大小。每次调用打印日志时logging去检测日志大小是否达到设定的上限,如果达到则更换日志文件\n # backupCount--保存的旧日志文件个数。xxx表示当前日志文件,则xxx.1表示上一份日志文件、xxx.2表示上上份日志文件...\n # encoding----日志文件编码\n _handler = logging.handlers.RotatingFileHandler(\n filename=file_path,\n mode='a',\n maxBytes=1024 * 1024 * 100,\n backupCount=1,\n encoding='utf-8',\n )\n # 实际发现这里setLevel并不起作用\n # _handler.setLevel(logging.DEBUG)\n _handler.setFormatter(formatter)\n return _handler\n\n def _gen_file_logger():\n # 如果指定了logger_name那直接采用,如果没有使用日志文件名为logger_name\n nonlocal logger_name\n if not logger_name:\n logger_name = log_file_name\n _file_logger = logging.getLogger(logger_name)\n _file_logger.addHandler(handler)\n _file_logger.setLevel(log_level)\n return _file_logger\n\n log_file_name = _get_log_file_name()\n log_file_dir = r\"E:\\Codes\\Logs\"\n _make_sure_log_dir_exist()\n handler = _gen_file_logger_handler()\n file_logger = _gen_file_logger()\n\n return file_logger\n\n\nclass logs(object):\n def __init__(self):\n self.logger = logging.getLogger(\"\")\n # 设置输出的等级\n LEVELS = {'NOSET': logging.NOTSET,\n 'DEBUG': logging.DEBUG,\n 'INFO': logging.INFO,\n 'WARNING': logging.WARNING,\n 'ERROR': logging.ERROR,\n 'CRITICAL': logging.CRITICAL}\n # 创建文件目录\n logs_dir = \"logs2\"\n if os.path.exists(logs_dir) and os.path.isdir(logs_dir):\n pass\n else:\n os.mkdir(logs_dir)\n # 修改log保存位置\n timestamp = time.strftime(\"%Y-%m-%d\", time.localtime())\n logfilename = '%s.txt' % timestamp\n logfilepath = os.path.join(logs_dir, logfilename)\n rotatingFileHandler = logging.handlers.RotatingFileHandler(filename=logfilepath,\n maxBytes=1024 * 1024 * 50,\n backupCount=5)\n # 设置输出格式\n formatter = logging.Formatter('[%(asctime)s] [%(levelname)s] %(message)s', '%Y-%m-%d %H:%M:%S')\n rotatingFileHandler.setFormatter(formatter)\n # 控制台句柄\n console = logging.StreamHandler()\n console.setLevel(logging.NOTSET)\n console.setFormatter(formatter)\n # 添加内容到日志句柄中\n self.logger.addHandler(rotatingFileHandler)\n self.logger.addHandler(console)\n self.logger.setLevel(logging.NOTSET)\n\n def info(self, message):\n self.logger.info(message)\n\n def debug(self, message):\n self.logger.debug(message)\n\n def warning(self, message):\n self.logger.warning(message)\n\n def error(self, message):\n self.logger.error(message)\n\n\nclass Mylog(object):\n # 根文件夹\n root_dir = sys.path[0]\n # 根目录\n root_path = sys.path[0] + os.path.sep\n # 系统目录分割线\n sys_sep = os.path.sep\n # 配置\n option = {\n 'level': 0, # 日志级别: 0:全部,1:调试,2:警告,3:错误 NOTSET < DEBUG < INFO < WARNING < ERROR < CRITICAL\n 'is_open': True, # 是否开启,如果关闭则不输出也不记录日志\n 'is_print': True, # 是否print输出\n 'is_write': True, # 是否记录到日志文件\n 'is_prefix': True, # 是否在每条日志内容前面加前缀\n 'level_1_prefix': 'Test: ', # 如果开启了每条日志前加前缀,设置日志级别为1的前缀\n 'level_2_prefix': 'Warning: ', # 如果开启了每条日志前加前缀,设置日志级别为2的前缀\n 'level_3_prefix': 'Error: ', # 如果开启了每条日志前加前缀,设置日志级别为3的前缀\n 'root_dir_name': 'mylog', # 存放日志文件的根文件夹名称\n 'dir_name': '' # 自定义存放日志文件的文件名称,此文件夹是在 root_dir_name 文件夹下\n }\n\n def __init__(self, config=None):\n if config is not None:\n self.option.update(dict(config))\n\n # 日志保存的文件夹(全路径)\n save_dir = self.root_path + self.option['root_dir_name']\n\n # 创建文件夹\n if os.path.isdir(save_dir) is not True:\n os.mkdir(save_dir)\n if len(self.option['dir_name']) > 0:\n save_dir += self.sys_sep + self.option['dir_name']\n if os.path.isdir(save_dir) is not True:\n os.mkdir(save_dir)\n\n self.save_dir = save_dir\n self.save_path = save_dir + self.sys_sep\n\n '''\n 输入日志/记录日志\n '''\n\n def log(self, content='', level=0):\n self._print_log(content, level)\n self._write_log(content, level)\n\n '''\n 输入日志\n '''\n\n def _print_log(self, content, level):\n if self.option['is_open'] is True and self.option['is_print'] is True:\n if self.option['level'] == 0 or self.option['level'] == level:\n if level > 0:\n content = self.option['level_' + str(level) + '_prefix'] + content\n print(content)\n\n '''\n 记录日志\n '''\n\n def _write_log(self, content, level):\n if self.option['is_open'] is True and self.option['is_print'] is True:\n if self.option['level'] == 0 or self.option['level'] == level:\n if self.option['is_prefix'] is True:\n today = datetime.date.today()\n file_name = str(today) + '.log'\n now = time.strftime(\"%H:%M:%S\")\n log_file = self.save_path + file_name\n if level > 0:\n content = self.option['level_' + str(level) + '_prefix'] + content\n if os.path.isfile(log_file):\n save_file = open(log_file, 'a')\n else:\n save_file = open(log_file, 'w')\n save_file.write(str(now) + \"\\r\\n\" + content + \"\\r\\n\")\n save_file.close()\n\n\n# 定义MyLog类\nclass MyLog1(object):\n '''这个类用于创建一个自用的log'''\n\n def __init__(self): # 类MyLog的构造函数\n user = getpass.getuser() # 返回用户的登录名\n self.logger = logging.getLogger(user) # 返回一个特定名字的日志\n self.logger.setLevel(logging.DEBUG) # 对显示的日志信息设置一个阈值低于DEBUG级别的不显示\n logFile = './' + sys.argv[1][0:-3] + '.log' # 日志文件名\n formatter = logging.Formatter('%(asctime)-12s $(levelname)-8s %(name)-10s %(message)-12s')\n\n '''日志显示到屏幕上并输出到日志文件内'''\n logHand = logging.FileHandler(logFile) # 输出日志文件,文件名是logFile\n logHand.setFormatter(formatter) # 为logHand以formatter设置格式\n logHand.setLevel(logging.ERROR) # 只有错误才被记录到logfile中\n\n logHandSt = logging.StreamHandler() # class logging.StreamHandler(stream=None)\n # 返回StreamHandler类的实例,如果stream被确定,使用该stream作为日志输出,反之,使用\n # sys.stderr\n logHandSt.setFormatter(formatter) # 为logHandSt以formatter设置格式\n\n self.logger.addHandler(logHand) # 添加特定的handler logHand到日志文件logger中\n self.logger.addHandler(logHandSt) # 添加特定的handler logHandSt到日志文件logger中\n\n '''日志的5个级别对应以下的五个函数'''\n\n def debug(self, msg):\n if self.logger.isEnabledFor(logging.DEBUG):\n self.logger.debug(msg) # 避免msg里有调用函数,可能额外增加计数器了,造成混乱\n # self.logger.debug(msg) # Logs a message with level DEBUG on this logger.\n # The msg is the message format string\n\n def info(self, msg):\n self.logger.info(msg)\n\n def warn(self, msg):\n self.logger.warn(msg)\n\n def error(self, msg):\n self.logger.error(msg)\n\n def critical(self, msg):\n self.logger.critical(msg)\n\n\n# 把日志输出到控制台, 还要写入日志文件\nclass Logger:\n # 性能开关,为提升性能可以关闭这些\n # logging._srcfile = None 模块、程序之类的开关\n logging.logThreads = 0\n logging.logMultiprocessing = 0\n logging.logProcesses = 0\n logging.thread = None # 程序是单进程时可以关闭\n\n path = \"E:/Codes/Logs\"\n\n # 设置输出的等级\n LEVELS = {'NOTSET': logging.NOTSET,\n 'DEBUG': logging.DEBUG,\n 'INFO': logging.INFO,\n 'WARNING': logging.WARNING,\n 'ERROR': logging.ERROR,\n 'CRITICAL': logging.CRITICAL}\n\n # 用字典保存日志输出格式\n format_dict = {0: logging.Formatter('%(message)s'),\n 1: logging.Formatter('%(name)s - %(message)s'),\n 2: logging.Formatter('%(filename)s - %(module)s - %(lineno)d - %(levelname)s - %(message)s'),\n 3: logging.Formatter('%(thread)d - %(threadName)s - %(process)d - %(message)s'),\n 4: logging.Formatter('%(funcName)s - %(created)f - %(levelname)s - %(message)s'),\n 5: logging.Formatter('%(pathname)s - %(levelno)s - %(levelname)s - %(message)s'),\n 6: logging.Formatter('%(asctime)s - %(msecs)d - %(relativeCreated)d - %(levelname)s - %(message)s')}\n\n def __init__(self, log_file, log_tags='', log_level='DEBUG', log_format=0):\n \"\"\"\n 指定保存日志的文件路径,日志级别,以及调用文件\n 将日志存入到指定的文件中\n \"\"\"\n # 创建一个logger\n self.logger = logging.getLogger(log_tags)\n self.logger.setLevel(self.LEVELS[log_level])\n\n # 创建一个handler,用于写入日志文件\n fh = logging.FileHandler(f'{self.path}/{log_file}', mode='w') # 覆盖\n fh.setLevel(self.LEVELS[log_level])\n\n # 再创建一个handler,用于输出到控制台\n # ch = logging.StreamHandler()\n # ch.setLevel(self.LEVELS[log_level])\n\n # 定义handler的输出格式\n # formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n formatter = self.format_dict[int(log_format)]\n fh.setFormatter(formatter)\n # ch.setFormatter(formatter)\n\n # 给logger添加handler\n self.logger.addHandler(fh)\n # self.logger.addHandler(ch)\n\n def get_logger(self):\n return self.logger\n\n def debug(self, msg):\n if self.logger.isEnabledFor(logging.DEBUG):\n self.logger.debug(msg) # 避免msg里有调用函数,可能额外增加计数器了,造成混乱\n # self.logger.debug(msg) # Logs a message with level DEBUG on this logger.\n # The msg is the message format string\n\n def info(self, msg):\n if self.logger.isEnabledFor(logging.DEBUG):\n # 避免msg里有调用函数,可能额外增加计数器了,造成混乱\n self.logger.info(msg)\n\n def warning(self, msg):\n if self.logger.isEnabledFor(logging.WARNING):\n # 避免msg里有调用函数,可能额外增加计数器了,造成混乱\n self.logger.warning(msg)\n\n def error(self, msg):\n if self.logger.isEnabledFor(logging.ERROR):\n # 避免msg里有调用函数,可能额外增加计数器了,造成混乱\n self.logger.error(msg)\n\n def critical(self, msg):\n if self.logger.isEnabledFor(logging.CRITICAL):\n # 避免msg里有调用函数,可能额外增加计数器了,造成混乱\n self.logger.critical(msg)\n\n # 再通过以下方式调用,便是一个简单的日志系统了\n # logger = Logger(log_file='log.txt', log_tags=\"fox\", log_level='DEBUG', log_format=1).get_logger()\n # logger = Logger(log_file='log.txt', log_tags=\"fox\", log_level='DEBUG', log_format=1)\n\n\ndef main():\n # logger = LogConfig().get_console_logger()\n # log_file_name不同,返回的是不同的logger,这样就可以方便地定义多个logger\n logger = LogConfig().get_file_logger('test', 'test.log')\n logger.debug('print by debug')\n logger.info('print by info')\n logger.warning('print by warning')\n\n\nif __name__ == '__main__':\n main()\n log = Logger(log_file='test.log', log_tags=\"fox\", log_level='DEBUG', log_format=2)\n log.debug('dgdsg')\n log.info('dgdsg')\n log.warning('dgdsg')\n","repo_name":"eastdorado/Codes","sub_path":"Logging.py","file_name":"Logging.py","file_ext":"py","file_size_in_byte":16738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39308360464","text":"import os\nimport time\nimport numpy as np\nimport tensorflow as tf\nimport PIL.Image as Image\nimport tensorflow_hub as hub\nimport matplotlib.pylab as plt\n\nfrom tensorflow.keras import layers\n\nIMAGE_SHAPE = (224, 224)\nSAVE_MODELS_DIR = 'saved_models'\nclassifier_url = \"https://hub.tensorflow.google.cn/google/tf2-preview/mobilenet_v2/classification/2\"\nclassifier = tf.keras.Sequential(\n [hub.KerasLayer(classifier_url, input_shape=IMAGE_SHAPE + (3,))]\n)\n\ngrace_hopper = tf.keras.utils.get_file(\n 'image.jpg',\n 'https://storage.googleapis.com/download.tensorflow.org/example_images/grace_hopper.jpg'\n)\n\nlabels_path = tf.keras.utils.get_file(\n 'ImageNetLabels.txt',\n 'https://storage.googleapis.com/download.tensorflow.org/data/ImageNetLabels.txt'\n)\nimagenet_labels = np.array(open(labels_path).read().splitlines())\n\ngrace_hopper = Image.open(grace_hopper).resize(IMAGE_SHAPE)\ngrace_hopper = np.array(grace_hopper) / 255.0\nprint(grace_hopper.shape)\n\nresult = classifier.predict(grace_hopper[np.newaxis, ...])\nprint(result.shape)\npredicted_class = np.argmax(result[0], axis=-1)\nprint(predicted_class)\n\nplt.imshow(grace_hopper)\nplt.axis('off')\npredicted_class_name = imagenet_labels[predicted_class]\n_ = plt.title(\"prediction: \" + predicted_class_name.title())\nplt.show()\n\ndata_root = tf.keras.utils.get_file(\n 'flower_photos',\n 'https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz',\n untar=True\n)\nimage_generator = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1 / 255)\nimage_data = image_generator.flow_from_directory(str(data_root), target_size=IMAGE_SHAPE)\nfor image_batch, label_batch in image_data:\n print(\"image batch shape: \", image_batch.shape)\n print(\"label batch shape: \", label_batch.shape)\n break\n\nresult_batch = classifier.predict(image_batch)\nprint(result_batch.shape)\npredicted_class_name = imagenet_labels[np.argmax(result_batch, axis=-1)]\nprint(predicted_class_name)\n\nplt.figure(figsize=(10, 9))\nplt.subplots_adjust(hspace=0.5)\nfor n in range(30):\n plt.subplot(6, 5, n + 1)\n plt.imshow(image_batch[n])\n plt.title(predicted_class_name[n])\n plt.axis('off')\n plt.suptitle('imagenet predictions')\nplt.show()\n\nfeature_extractor_url = \"https://hub.tensorflow.google.cn/google/tf2-preview/mobilenet_v2/feature_vector/2\"\nfeature_extractor_layer = hub.KerasLayer(feature_extractor_url, input_shape=IMAGE_SHAPE + (3,))\nfeature_batch = feature_extractor_layer(image_batch)\n\nfeature_extractor_layer.trainable = False\nmodel = tf.keras.Sequential([\n feature_extractor_layer,\n layers.Dense(image_data.num_classes)\n])\nmodel.summary()\n\npredictions = model(image_batch)\nprint(predictions.shape)\n\nmodel.compile(\n optimizer='adam',\n loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True),\n metrics=['acc']\n)\n\n\nclass CollectBatchStats(tf.keras.callbacks.Callback):\n def __init__(self):\n super().__init__()\n self.batch_loss = []\n self.batch_acc = []\n\n def on_train_batch_end(self, batch, logs=None):\n self.batch_loss.append(logs['loss'])\n self.batch_acc.append(logs['acc'])\n self.model.reset_metrics()\n\n\nsteps_per_epoch = np.ceil(image_data.samples / image_data.batch_size)\nbatch_stats_callback = CollectBatchStats()\n\nhistory = model.fit_generator(image_data, epochs=2, steps_per_epoch=steps_per_epoch, callbacks=[batch_stats_callback])\nprint(history)\n\nplt.figure()\nplt.ylabel('loss')\nplt.xlabel('train steps')\nplt.ylim([0, 2])\nplt.plot(batch_stats_callback.batch_loss)\nplt.show()\n\nplt.figure()\nplt.ylabel('acc')\nplt.xlabel('train steps')\nplt.ylim([0, 1])\nplt.plot(batch_stats_callback.batch_acc)\nplt.show()\n\nclass_names = sorted(image_data.class_indices.items(), key=lambda pair: pair[1])\nclass_names = np.array([key.title() for key, value in class_names])\nprint(class_names)\n\npredicted_batch = model.predict(image_batch)\npredicted_id = np.argmax(predicted_batch, axis=-1)\npredicted_label_batch = class_names[predicted_id]\n\nlabel_id = np.argmax(label_batch, axis=-1)\n\n\nplt.figure(figsize=(10, 9))\nplt.subplots_adjust(hspace=0.5)\nfor n in range(30):\n plt.subplot(6, 5, n+1)\n plt.imshow(image_batch[n])\n color = \"green\" if predicted_id[n] == label_id[n] else \"red\"\n plt.title(predicted_label_batch[n].title(), color=color)\n plt.axis('off')\n plt.suptitle('model predictions (green: correct, red: incorrect)')\nplt.show()\n\nt = time.time()\nexport_path = f'{SAVE_MODELS_DIR}/{int(t)}'\nif not os.path.exists(export_path):\n os.makedirs(export_path)\n\nmodel.save(export_path, save_format='tf')\nprint(export_path)\n\n\nreloaded = tf.keras.models.load_model(export_path)\nreloaded_result_batch = reloaded.predict(image_batch)\nprint(abs(reloaded_result_batch - predicted_batch).max())","repo_name":"anhuaxiang/transfer_learning_test","sub_path":"tensorflow_hub_transfer_learning.py","file_name":"tensorflow_hub_transfer_learning.py","file_ext":"py","file_size_in_byte":4741,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"27667778354","text":"\"\"\"Defines an operator to extract data from an Oracle database and load it to S3 in an AWS Batch Job.\"\"\"\r\nfrom typing import List\r\nimport json\r\n\r\nfrom airflow.hooks.base_hook import BaseHook\r\nfrom airflow.utils.decorators import apply_defaults\r\n\r\nimport cx_Oracle\r\n\r\nfrom operators.abstract.abstract_batch_operator import PartialAWSBatchOperatorWithTable\r\n\r\n\r\nclass OracleToS3BatchOperator(PartialAWSBatchOperatorWithTable):\r\n \"\"\"Runs an AWS Batch Job to extract data from Oracle to S3.\"\"\"\r\n\r\n @apply_defaults\r\n def __init__(self, conn_id: str, *args, **kwargs):\r\n self.conn_id = conn_id\r\n super().__init__(*args, **kwargs)\r\n \r\n @property\r\n def connection_string(self) -> str:\r\n db_conn = BaseHook.get_connection(self.conn_id)\r\n\r\n connection_string = '{}/{}@{}'.format(\r\n db_conn.login,\r\n db_conn.password,\r\n cx_Oracle.makedsn(db_conn.host,\r\n db_conn.port,\r\n json.loads(db_conn.extra)['db_name'])\r\n )\r\n\r\n return connection_string\r\n\r\n @property\r\n def _job_name(self) -> str:\r\n return 'oracle_to_s3_{}_{}'.format(self.table_schema, self.table_name)\r\n\r\n @property\r\n def _job_definition(self) -> str:\r\n return 'carto-db2-airflow-{}'.format(self.ENVIRONMENT)\r\n\r\n @property\r\n def _command(self) -> List[str]:\r\n command = [\r\n 'databridge_etl_tools',\r\n 'extract',\r\n '--table_name={}'.format(self.table_name),\r\n '--table_schema=gis_{}'.format(self.table_schema),\r\n '--connection_string={}'.format(self.connection_string),\r\n '--s3_bucket={}'.format(self.S3_BUCKET),\r\n '--s3_key={}'.format(self.csv_s3_key),\r\n ]\r\n return command\r\n\r\n @property\r\n def _task_id(self) -> str:\r\n return 'oracle_to_s3_batch_{}_{}'.format(self.table_schema, self.table_name)\r\n","repo_name":"CityOfPhiladelphia/databridge-airflow","sub_path":"plugins/operators/oracle_to_s3_operator.py","file_name":"oracle_to_s3_operator.py","file_ext":"py","file_size_in_byte":1939,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"18981725234","text":"# %% -- IMPORT LIBRARIES\nimport logging\n\n# %% -- SOME TYPES OF LOGS\n# -- Less critical\nlogging.debug(\"debug\")\nlogging.info(\"info\")\n\n# -- More critical\nlogging.error(\"error\")\nlogging.warning(\"warning\")\nlogging.critical(\"critical\")\n\n# %% -- USING BASICCONFIG() TO GENERATE LOG FILE\n# -- format = \"%(asctime)s: %(levelname)s: %(message)s \" --> showing Date/Time - Level of log - message\nlogging.basicConfig(filename=\"D:\\\\00_MASTER OF COMPUTER SCIENCE_MUM\\\\00_Projects\\\\12_Automation Testing_Basic\\\\logs\\\\log1.log\",\n format=\"%(asctime)s: %(levelname)s: %(message)s \",\n level=logging.DEBUG\n)\n\nlogging.debug(\"debug\")\nlogging.info(\"info\")\nlogging.error(\"error\")\nlogging.warning(\"warning\")\nlogging.critical(\"critical\")\n\n# %% -- CREATE A LOGGER OBJECT INSTEAD OF USING THE LOGGING DIRECTLY\nlogging.basicConfig(filename=\"D:\\\\00_MASTER OF COMPUTER SCIENCE_MUM\\\\00_Projects\\\\12_Automation Testing_Basic\\\\logs\\\\log1.log\",\n format=\"%(asctime)s: %(levelname)s: %(message)s \",\n level=logging.DEBUG\n)\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.DEBUG)\n\nlogger.debug(\"debug\")\nlogger.info(\"info\")\nlogger.error(\"error\")\nlogger.warning(\"warning\")\nlogger.critical(\"critical\")\n\n\n","repo_name":"ennguyennguyen/Python_Selenium101","sub_path":"12_logging.py","file_name":"12_logging.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33543179367","text":"from django.urls.conf import path, re_path\nfrom .views import *\n\nurlpatterns = [\n path (r'place', OrderPlaceView.as_view (), name='place'), # 提交订单页面显示\n path(r'commit', OrderCommitView.as_view (), name='commit'), # 提交创建\n path(r'pay', OrderPayView.as_view (), name='pay'), # 订单支付\n path(r'check', CheckPayView.as_view (), name='check'), # 查询支付订单结果\n re_path(r'comment/(?P.+)', CommentView.as_view (), name='comment'), # 订单评论\n]\n","repo_name":"FBI009/FBI009-fresh_mall","sub_path":"fresh_mall1/apps/order/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4347148765","text":"'''\nCrea un programa que pida un número al usuario un número de mes \n(por ejemplo, el 4) y diga cuántos días tiene (por ejemplo, 30) \ny el nombre del mes. Debes usar listas. Para simplificarlo vamos \na suponer que febrero tiene 28 días.\n'''\nlista_meses = ['enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre','diciembre']\nlista_dias = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n\nmes = int(input('Numero de mes..'))\n\nprint('Mes: ' + lista_meses[mes - 1] + ' tiene: ' + str(lista_dias[mes - 1]) + ' dias' )\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"Adrian0207/-LetsGo_Python","sub_path":"Ejercicios_Listas/Ejercicio6.py","file_name":"Ejercicio6.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35891105581","text":"\r\n# Combining the following:\r\n# minimum.py\r\n# button_press.py\r\n# neopixel.py\r\n# mobile_movement.py\r\n# location.py\r\n\r\nimport board\r\nimport neopixel\r\n\r\nfrom adafruit_ble import BLERadio\r\nfrom adafruit_ble.advertising.standard import ProvideServicesAdvertisement\r\nfrom adafruit_ble.services.nordic import UARTService\r\n\r\nfrom adafruit_bluefruit_connect.packet import Packet\r\nfrom adafruit_bluefruit_connect.button_packet import ButtonPacket\r\nfrom adafruit_bluefruit_connect.color_packet import ColorPacket\r\nfrom adafruit_bluefruit_connect.accelerometer_packet import AccelerometerPacket\r\nfrom adafruit_bluefruit_connect.magnetometer_packet import MagnetometerPacket\r\nfrom adafruit_bluefruit_connect.gyro_packet import GyroPacket\r\nfrom adafruit_bluefruit_connect.quaternion_packet import QuaternionPacket\r\nfrom adafruit_bluefruit_connect.location_packet import LocationPacket\r\n\r\n\r\nble = BLERadio()\r\nuart_service = UARTService()\r\nadvertisement = ProvideServicesAdvertisement(uart_service)\r\n\r\npixels = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness=0.1)\r\n\r\nwhile True:\r\n ble.start_advertising(advertisement)\r\n while not ble.connected:\r\n pass\r\n ble.stop_advertising()\r\n\r\n # Now we're connected\r\n\r\n while ble.connected:\r\n if uart_service.in_waiting:\r\n try:\r\n packet = Packet.from_stream(uart_service)\r\n if isinstance(packet, ButtonPacket):\r\n if packet.pressed:\r\n if packet.button == ButtonPacket.BUTTON_1:\r\n # The 1 button was pressed.\r\n print(\"1 button pressed!\")\r\n if packet.button == ButtonPacket.BUTTON_2:\r\n # The 2 button was pressed.\r\n print(\"2 button pressed!\")\r\n if packet.button == ButtonPacket.BUTTON_3:\r\n # The 3 button was pressed.\r\n print(\"3 button pressed!\")\r\n if packet.button == ButtonPacket.BUTTON_4:\r\n # The 4 button was pressed.\r\n print(\"4 button pressed!\")\r\n elif packet.button == ButtonPacket.UP:\r\n # The UP button was pressed.\r\n print(\"UP button pressed!\")\r\n elif packet.button == ButtonPacket.DOWN:\r\n # The DOWN button was pressed.\r\n print(\"DOWN button pressed!\")\r\n elif packet.button == ButtonPacket.LEFT:\r\n # The LEFT button was pressed.\r\n print(\"LEFT button pressed!\")\r\n elif packet.button == ButtonPacket.RIGHT:\r\n # The RIGHT button was pressed.\r\n print(\"RIGHT button pressed!\")\r\n elif isinstance(packet, ColorPacket):\r\n print(packet.color)\r\n pixels.fill(packet.color)\r\n elif isinstance(packet, AccelerometerPacket):\r\n print(\"Acceleration:\", packet.x, packet.y, packet.z)\r\n elif isinstance(packet, MagnetometerPacket):\r\n print(\"Magnetometer:\", packet.x, packet.y, packet.z)\r\n elif isinstance(packet, GyroPacket):\r\n print(\"Gyro:\", packet.x, packet.y, packet.z)\r\n elif isinstance(packet, QuaternionPacket):\r\n print(\"Quaternion:\", packet.x, packet.y, packet.z)\r\n elif isinstance(packet, LocationPacket):\r\n print(\"Latitude:\", packet.latitude)\r\n print(\"Longitude\", packet.longitude)\r\n print(\"Altitude:\", packet.altitude)\r\n except ValueError:\r\n # assume just a string, try to get all bytes after !\r\n # NOTE: when using the BluefruitConnect application, a \"!\" must\r\n # be the first character sent, or this application will block\r\n # on the from_stream call above. May need to customize Packet\r\n # to fix this.\r\n if uart_service.in_waiting:\r\n raw_bytes = uart_service.read(uart_service.in_waiting)\r\n text = raw_bytes.decode().strip()\r\n # print(\"raw bytes =\", raw_bytes)\r\n print(text)\r\n\r\n except Exception as err:\r\n print(err)\r\n\r\n\r\n # If we got here, we lost the connection. Go up to the top and start\r\n # advertising again and waiting for a connection.\r\n\r\n","repo_name":"alpiepho/cp-ble-experiments","sub_path":"feather_nrf52840_express/combo.py","file_name":"combo.py","file_ext":"py","file_size_in_byte":4670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38185853060","text":"\"\"\"Tests brewblox_dev.utils\"\"\"\n\nimport pytest\n\nfrom brewblox_dev import utils\n\nTESTED = utils.__name__\n\n\n@pytest.fixture\ndef mocked_ext(mocker):\n mocked = [\n 'input',\n 'pathlib',\n 'remove',\n 'copy',\n 'check_call',\n 'glob'\n ]\n return {k: mocker.patch(TESTED + '.' + k) for k in mocked}\n\n\n@pytest.mark.parametrize('user_input,expected', [\n (['y'], True),\n (['n'], False),\n (['Y'], True),\n (['N'], False),\n (['Yes'], True),\n (['No'], False),\n (['y', 'n'], True),\n (['n', 'y'], False),\n (['maybe', 'y'], True),\n (['maybe', 'I think so...', 'n'], False),\n ([''], True),\n])\ndef test_user_yes_no_query(mocked_ext, user_input, expected):\n mocked_ext['input'].side_effect = user_input\n assert utils.confirm('Are you sure?') == expected\n\n\ndef test_run(mocked_ext):\n utils.run('cmd')\n mocked_ext['check_call'].assert_called_once_with('cmd', shell=True, stderr=utils.STDOUT)\n\n\ndef test_distcopy(mocked_ext):\n mocked_ext['glob'].side_effect = [\n ['dest1.1', 'dest1.2'],\n ['source1.1', 'source1.2'],\n ['dest2.1', 'dest2.2'],\n ['source2.1', 'source2.2', 'source2.3'],\n ]\n\n utils.distcopy('s', ['d1', 'd2'])\n assert mocked_ext['remove'].call_count == 4\n assert mocked_ext['copy'].call_count == 5\n","repo_name":"BrewBlox/brewblox-dev","sub_path":"test/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"27254290299","text":"class FourCal:\n\n def __init__(self, first=1, second=4):\n self.first = first\n self.second = second\n print(\"생성자\")\n\n def setdata(self, first, second):\n self.first = first\n self.second = second\n\n def add(self):\n result = self.first + self.second\n return result\n \n def div(self):\n result = self.first / self.second\n return result\n\n################################################################\n\nclass MoreFourCal(FourCal): # 클래스 상속 : class 클래스 이름(상속할 클래스 이름)\n def pow(self):\n result = self.first ** self.second\n return result\n\n def div(self): # 메소드 오버라이딩 : 부모 클래스에 있는 메소드를 다시 만드는 것\n if self.second == 0:\n print(\"0으로 나눌 수 없습니다.\")\n return 0\n else:\n return self.first / self.second\n\ncal1 = MoreFourCal(5,0)\ncal2 = MoreFourCal(5,6)\n\nprint(cal1.add()) # 상속 확인\nprint(cal2.add()) # 상속 확인\nprint()\nprint(cal1.pow())\nprint(cal2.pow())\nprint()\nprint(cal1.div())\nprint(cal2.div())","repo_name":"10qpal/kfq_python","sub_path":"05_class/fourcaltest.py","file_name":"fourcaltest.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23949100832","text":"import unittest\n\nfrom modelscope.pipelines import pipeline\nfrom modelscope.utils.constant import Tasks\nfrom modelscope.utils.demo_utils import DemoCompatibilityCheck\nfrom modelscope.utils.test_utils import test_level\n\n\nclass TinyNASClassificationTest(unittest.TestCase, DemoCompatibilityCheck):\n\n def setUp(self) -> None:\n self.task = Tasks.image_classification\n self.model_id = 'damo/cv_tinynas_classification'\n\n @unittest.skipUnless(test_level() >= 0, 'skip test in current test level')\n def test_run(self):\n tinynas_classification = pipeline(\n Tasks.image_classification, model='damo/cv_tinynas_classification')\n result = tinynas_classification('data/test/images/image_wolf.jpeg')\n print(result)\n\n @unittest.skip('demo compatibility test is only enabled on a needed-basis')\n def test_demo_compatibility(self):\n self.compatibility_check()\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"open-models-platform/open.models.llm-rlhf","sub_path":"modelscope/tests/pipelines/test_tinynas_classification.py","file_name":"test_tinynas_classification.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"27962064210","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 20 12:24:43 2020\n\n@author: USER\n\"\"\"\n\n\n# Radio 버튼\n# RadioButton 여러개중에 하나만 선택된다.는 특징\n# html 에서는 name속성을 같게 해줘야 하나만 선택되지만\n# 파이썬에서는 자동으로 단일선택이다.\n\n# text() 버튼의 텍스트를 반환\n# setText() 라벨에 들어갈 텍스트를 설정\n# setChecked() 버튼의 선택 여부를 설정\n# isChecked() 버튼의 선택 여부를 반환\n\n# 시그널\n# 체크박스와 동일\n\nimport sys\nfrom PyQt5.QtWidgets import QApplication, QWidget, QRadioButton\n\nclass MyApp(QWidget):\n \n def __init__(self):\n super().__init__()\n self.initUI()\n\n def initUI(self):\n rbtn1 = QRadioButton('First Button',self)\n rbtn1.move(50,50)\n rbtn1.setChecked(True)\n \n rbtn2 = QRadioButton(self)\n rbtn2.move(50,70)\n rbtn2.setText('Second Button')\n \n self.setGeometry(300, 300, 300, 200)\n self.show()\n \n \nif __name__ == '__main__':\n app = QApplication(sys.argv)\n ex = MyApp()\n sys.exit(app.exec_())","repo_name":"ojjang1/learnPython","sub_path":"anaconda/gui_07_RadioButton.py","file_name":"gui_07_RadioButton.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"27328932359","text":"from math import sqrt\ndef is_prime(x):\n\tfor i in range(2, int(sqrt(x))+1):\n\t\tif x%i == 0:\n\t\t\treturn False\n\treturn True\n \nfor i in range(1000,10000):\n if is_prime(i):\n j = i + 3330\n if is_prime(j):\n k = j + 3330\n if is_prime(k):\n a = list(str(i))\n b = list(str(j))\n c = list(str(k))\n if sorted(a) == sorted(b) and sorted(b) == sorted(c):\n print(f\"Traženi niz brojeva je {i, j, k}.\")","repo_name":"martinjakopec/euler","sub_path":"eul49.py","file_name":"eul49.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"3007246312","text":"import sys\n\nN,A,B = map(int,sys.stdin.readline().split())\n\ntile_1 = list(map(int,sys.stdin.readline().split()))\ntile_2 = list(map(int,sys.stdin.readline().split()))\n\ntile_1.sort(reverse=True)\ntile_2.sort(reverse=True)\n\nidx_1 = 0\nidx_2 = 0\n\nsumation = 0\nnow = 0\n\nif(N%2==1):\n sumation += tile_1[idx_1]\n idx_1 += 1\n now += 1\n\nwhile(idx_1+1 < A and idx_2 < B): #각 타일이 2개 1개 이상 남음\n if(N-now>1): #현재 한 칸 이상 남음\n #그러면 더 큰 것\n val = tile_1[idx_1] + tile_1[idx_1+1]\n \n if(tile_2[idx_2]>=val):\n sumation += tile_2[idx_2]\n idx_2 += 1\n now += 2\n else:\n sumation += val\n idx_1 += 2\n now += 2\n else: #딱 됨\n print(sumation)\n exit()\n \n#tile1이 1개 남았거나 B를 다 씀 \nif(idx_2==B): #B를 다 쓴 경우\n while(now b) - (a < b)\n\nclass CNC(hal.CNC):\n\n def __init__(self, port=\"/dev/ttyUSB0\", homing=True):\n self.port = port\n self.serial_port = serial.Serial(self.port, 115200)\n # TODO: read '#ready' ?\n while self.serial_port.in_waiting == 0:\n time.sleep(0.1) \n r = self.serial_port.readline() \n if homing: self.home()\n self.set_zero()\n self.status = \"idle\"\n self.p = [0, 0, 0]\n self.v = [0, 0, 0]\n self.update_status()\n \n\n def home(self):\n self.__send('h')\n\n \n def has_position_control():\n return True\n\n \n def get_position(self):\n self.update_status()\n return self.p\n\n \n def has_velocity_control():\n return True\n\n \n def get_velocity(self):\n self.update_status()\n return self.v\n\n \n def set_zero(self):\n self.__send('0')\n\n \n def start_spindle(self, ):\n self.__send('S1')\n\n \n def stop_spindle(self, ):\n self.__send('S0')\n\n \n def get_status(self):\n self.update_status()\n return self.status\n\n \n \n def moveat(self, vx, vy, vz):\n self.__send(\"x%d\" % vx)\n self.__send(\"y%d\" % vy)\n self.__send(\"z%d\" % vz)\n\n \n def set_target_pos(self, x, y, z):\n self.__send(\"X%d\" % x)\n self.__send(\"Y%d\" % y)\n self.__send(\"Z%d\" % z)\n\n\n # Dont use, doesn't work yet\n def __wait__(self):\n self.__send(\"W\")\n\n def wait(self):\n time.sleep(0.1) \n self.update_status()\n while self.status == \"moving\":\n time.sleep(0.1) \n self.update_status()\n\n \n def moveto(self, x, y, z, v):\n self.__send(\"X%d\" % x)\n self.__send(\"Y%d\" % y)\n self.__send(\"Z%d\" % z)\n self.__send(\"M%d\" % v)\n\n \n def moveto(self, x, y, z):\n self.moveto(x, y, z, 50)\n\n \n def moveto(self, p, v):\n self.set_target_pos(p[0], p[1], p[2])\n self.moveat(v[0], v[1], v[2])\n\n \n def moveto_z(self, z, vz):\n self.__send(\"Z%d\" % z)\n self.__send(\"z%d\" % vz)\n\n \n \n def update_status(self):\n s = self.__send(\"s\")\n try:\n stat = json.loads(s.decode(\"utf-8\"))\n self.status = stat[\"status\"]\n self.p = stat[\"p\"]\n self.v = stat[\"v\"]\n except KeyError as k:\n print(\"Failed to parse the JSON: missing key\")\n except Exception as e:\n print(\"Failed to parse the JSON: %s\" % str(e))\n print(\"String was: %s\" % s)\n finally:\n pass # dummy statement to avoid empty 'finally' clause\n #print('status=%s, p=%s, v=%s' % (self.status, str(self.p), str(self.v)))\n\n \n def __send(self, s):\n r = False\n try:\n self.serial_port.write(bytes('%s\\n' % s, 'utf-8'))\n time.sleep(0.01) \n r = self.serial_port.readline()\n finally:\n pass # dummy statement to avoid empty 'finally' clause\n if r == False:\n print('cmd=%s: failed' % (s))\n return r;\n\n \nif __name__ == \"__main__\":\n cnc = CNCVelocityControl(\"/dev/ttyACM0\")\n rounds = 3\n xoff = 0\n for round in range(rounds):\n cnc.moveto([xoff, -600, 0], [0, -50, 0])\n cnc.moveto([xoff - 50, -600, 0], [-20, 0, 0])\n cnc.moveto([xoff - 50, 10, 0], [0, 50, 0])\n if (round < rounds - 1):\n cnc.moveto([xoff - 100, 10, 0], [-20, 0, 0])\n xoff -= 100\n\n\n","repo_name":"hanappe/LettuceThink","sub_path":"github/rtscan/cnccontroller.py","file_name":"cnccontroller.py","file_ext":"py","file_size_in_byte":3689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13617916427","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nimport pandas as pd\nfrom discharge_ncs import discharge_ncs\nfrom computeCTA import computeCTA\n#from reco.reco_filter import RecoFilter\n\ndef isNaN(num):\n return num != num\n\ndef filter_CACS(df_data):\n print('Apply filter_CACS_')\n df_CACS = pd.DataFrame(columns=['CACS'])\n for index, row in df_data.iterrows():\n if index % 1000 == 0:\n print('index:', index, '/', len(df_data))\n criteria1 = row['ReconstructionDiameter'] <= 300\n criteria2 = (row['SliceThickness']==3.0) or (row['SliceThickness']==2.5 and row['Site'] in ['P10', 'P13', 'P29'])\n criteria3 = row['Modality'] == 'CT'\n criteria4 = isNaN(row['ContrastBolusAgent'])\n criteria5 = row['Count']>=30 and row['Count']<=90\n result = criteria1 and criteria2 and criteria3 and criteria4 and criteria5\n df_CACS = df_CACS.append({'CACS': result}, ignore_index=True)\n return df_CACS\n\ndef filter_NCS(df_data):\n df = pd.DataFrame()\n df_lung, df_body = discharge_ncs(df_data)\n df['NCS_CACS'] = df_lung\n df['NCS_CTA'] = df_body\n return df\n\ndef filterReconstruction(df_data, settings):\n print('Apply filterReconstruction123')\n ir_description = ['aidr','id', 'asir','imr']\n fbp_description = ['org','fbp']\n ir_kernel = ['I20f','I26f','I30f', 'I31f','I50f', 'I70f']\n fbp_kernel = []\n df_reco = pd.DataFrame(columns=['CACSExtended'])\n for index, row in df_data.iterrows():\n if index % 1000 == 0:\n print('index:', index, '/', len(df_data))\n row['Modality'] == 'CT'\n desc = row['SeriesDescription'] \n kernel = row['ConvolutionKernel'] \n if isNaN(kernel):kernel=''\n \n # Check Cernel\n isir = any(x.lower() in str(desc).lower() for x in ir_description) or any(x.lower() in str(kernel).lower() for x in ir_kernel)\n isfbp = any(x.lower() in str(desc).lower() for x in fbp_description) or any(x.lower() in str(kernel).lower() for x in fbp_kernel)\n if isfbp:\n reco = settings['recoClasses'][0]\n elif isir:\n reco = settings['recoClasses'][1]\n else:\n reco = settings['recoClasses'][2]\n df_reco = df_reco.append({'RECO': reco}, ignore_index=True)\n return df_reco\n\n\n\ndef filter_CTA(settings):\n df_cta = computeCTA(settings)\n df = pd.DataFrame()\n df['phase'] = df_cta['CTA_phase']\n df['arteries'] = df_cta['CTA_arteries']\n df['source'] = df_cta['CTA_source']\n df['CTA'] = df_cta['CTA']\n df.fillna(value=np.nan, inplace=True) \n return df \n\ndef filter_10StepsGuide(df_master_in):\n df_master = df_master_in.copy()\n df_master.replace(to_replace=[np.nan], value=0.0, inplace=True)\n #folderpath_master = 'H:/cloud/cloud_data/Projects/CACSFilter/data/discharge_master/discharge_master_01042020'\n # date = folderpath_master.split('_')[-1]\n # if master_process==False:\n # filepath_master = os.path.join(folderpath_master, 'discharge_master_' + date + '.xlsx')\n # else:\n # filepath_master_tmp = os.path.join(folderpath_master, 'discharge_master_' + date + '.xlsx')\n # folderpath, filename, file_extension = splitFilePath(filepath_master_tmp)\n # filepath_master = os.path.join(folderpath, filename + '_process' + file_extension)\n # #df_master = pd.read_excel(filepath_master, sheet_name='MASTER_'+ date, index_col=0)\n # df_master.replace(to_replace=[np.nan], value=0.0, inplace=True)\n \n idx_manual = ~(df_master['ClassManualCorrection']=='UNDEFINED')\n SeriesClass = df_master['RFCClass']\n SeriesClass[idx_manual]=df_master['ClassManualCorrection'][idx_manual]\n \n df_guide = pd.DataFrame(columns=['GUIDE', 'COMMENT'])\n\n for index, row in df_master.iterrows():\n print('index', index)\n guide=True\n comment=''\n if SeriesClass[index]=='CACS':\n # Check 10-steps guide for CACS\n if row['ReconstructionDiameter'] > 200:\n guide=False\n comment = comment + 'ReconstructionDiameter bigger than 200mm,'\n if not (row['SliceThickness']==3.0) or (row['SliceThickness']==2.5 and row['Site'] in ['P10', 'P13', 'P29']):\n guide=False\n comment = comment + 'SliceThickness not correct,'\n if not row['Modality'] == 'CT':\n guide=False\n comment = comment + 'Modality is not CT,'\n elif SeriesClass[index]=='CTA':\n ConvFilter = 'B35s|Qr36d|FC12|FC51|FC17|B60f|B70f|B30f|B31f|B08s|B19f|B20f|B20s|B30s|B31s|B40f|B41s|B50f|B50s|B65f|B70f|B70s|B80s|Bf32dB80s|Bf32d|Bl57d|Br32d|Bv36d|Bv40f|FC08|FC08-H|FC15|FC18|FC35|FC52|FL03|FL04|FL05|H20f|H31s|IMR1|IMR2|IMR2|Qr36d|T20f|T20s|Tr20f|UB|XCA|YA'\n ConvFilterList = ConvFilter.split(\"|\")\n for filt in ConvFilterList:\n if filt in str(row['ConvolutionKernel']):\n guide=False\n comment = comment + 'FilterKernel ' + filt + ' in ConvolutionKernel,'\n if filt in str(row['SeriesDescription']):\n guide=False\n comment = comment + 'SeriesDescription ' + filt + ' in SeriesDescription,'\n if row['ReconstructionDiameter'] > 260:\n guide=False\n comment = comment + 'ReconstructionDiameter bigger than 260mm,'\n if row['SliceThickness'] >= 0.8:\n guide=False\n comment = comment + 'SliceThickness bigger than 0.8mm,'\n elif SeriesClass[index]=='NCS_CACS':\n if row['ReconstructionDiameter'] < 320:\n guide=False\n comment = comment + 'ReconstructionDiameter smaller than 320mm,'\n if not (row['SliceThickness']==1.0) or (row['SliceThickness']==0.625 and row['Site'] in ['P10', 'P13', 'P29']):\n guide=False\n comment = comment + 'SliceThickness not correct,'\n elif SeriesClass[index]=='NCS_CTA':\n if row['ReconstructionDiameter'] < 320:\n guide=False\n comment = comment + 'ReconstructionDiameter smaller than 320mm,'\n if not (row['SliceThickness']==1.0) or (row['SliceThickness']==0.625 and row['Site'] in ['P10', 'P13', 'P29']):\n guide=False\n comment = comment + 'SliceThickness not correct,'\n else:\n pass\n df_guide = df_guide.append(dict({'GUIDE': guide, 'COMMENT': comment}), ignore_index=True)\n \n return df_guide\n\ndef filer10StepsGuide(settings):\n \n # date = folderpath_master.split('_')[-1]\n # folderpath_components = os.path.join(folderpath_master, 'discharge_components_' + date)\n # if master_process==False:\n # filepath_master = os.path.join(folderpath_master, 'discharge_master_' + date + '.xlsx')\n # else:\n # filepath_master_tmp = os.path.join(folderpath_master, 'discharge_master_' + date + '.xlsx')\n # folderpath, filename, file_extension = splitFilePath(filepath_master_tmp)\n # filepath_master = os.path.join(folderpath, filename + '_process' + file_extension)\n \n filepath_master = settings['filepath_master']\n df_master = pd.read_excel(filepath_master, sheet_name='MASTER_'+ settings['date'], index_col=0)\n #df_master.replace(to_replace=[np.nan], value=0.0, inplace=True)\n \n # Filter according to 10-Steps guide\n df_guide = filter_10StepsGuide(df_master)\n #df_guide = pd.DataFrame(columns=['10-STEPS-GUIDE', '10-STEPS-GUIDE-COMMENT'])\n df_master['10-STEPS-GUIDE'] = df_guide['GUIDE']\n df_master['10-STEPS-GUIDE-COMMENT'] = df_guide['COMMENT']\n\n # Save master\n writer = pd.ExcelWriter(filepath_master, engine=\"openpyxl\", mode=\"a\")\n sheet_name = 'MASTER_'+ settings['date']\n workbook = writer.book\n sheetnames = workbook.sheetnames\n if sheet_name in sheetnames:\n sheet = workbook[sheet_name]\n workbook.remove(sheet)\n df_master.to_excel(writer, sheet_name=sheet_name)\n writer.save()\n\n\ndef filter_CACS_10StepsGuide(df_data):\n df = df_data.copy()\n df.replace(to_replace=[np.nan], value=0.0, inplace=True)\n print('Apply filter_CACS_10StepsGuide')\n df_CACS = pd.DataFrame(columns=['CACS10StepsGuide'])\n for index, row in df.iterrows():\n if index % 1000 == 0:\n print('index:', index, '/', len(df))\n criteria1 = row['ReconstructionDiameter'] <= 200\n criteria2 = (row['SliceThickness']==3.0) or (row['SliceThickness']==2.5 and row['Site'] in ['P10', 'P13', 'P29'])\n criteria3 = row['Modality'] == 'CT'\n criteria4 = isNaN(row['ContrastBolusAgent'])\n criteria5 = row['Count']>=30 and row['Count']<=90\n result = criteria1 and criteria2 and criteria3 and criteria4 and criteria5\n df_CACS = df_CACS.append({'CACS10StepsGuide': result}, ignore_index=True)\n return df_CACS\n\ndef filterReconstructionRF(settings):\n # date = folderpath_master.split('_')[-1]\n # folderpath_components = os.path.join(folderpath_master, 'discharge_components_' + date)\n # filepath_master = os.path.join(folderpath_master, 'discharge_master_' + date + '.xlsx')\n # filepath_fourier = os.path.join(folderpath_components, 'discharge_master_' + date + '_fourier.pkl')\n # filepath_reco = os.path.join(folderpath_components, 'discharge_reco_' + date + '.xlsx')\n # sheet_name ='MASTER_' + date\n # df_master = pd.read_excel(filepath_master, sheet_name=sheet_name)\n #df_master=df_master[0:10]\n #df_reco = predictReco(folderpath_discharge, filepath_fourier, df_master)\n reco = RecoFilter()\n self=reco\n df_master = reco.predictReco(settings)\n \n df_reco = pd.DataFrame()\n df_reco['RFRECO'] = df_master['RFRECO']\n df_reco.to_excel(filepath_reco)\n \n # Write results to master\n writer = pd.ExcelWriter(filepath_master, engine=\"openpyxl\", mode=\"a\")\n workbook = writer.book\n sheet = workbook[sheet_name]\n workbook.remove(sheet)\n df_master.to_excel(writer, sheet_name=sheet_name)\n writer.save()","repo_name":"Berni1557/DISCHARGEMaster","sub_path":"src/filterTenStepsGuide.py","file_name":"filterTenStepsGuide.py","file_ext":"py","file_size_in_byte":10027,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23757970950","text":"import os\nimport re\nimport numpy as np\nimport pandas as pd\nfrom pathlib import Path\n\n\nclass CreateModelData:\n def __init__(self, domain: str):\n \"\"\"\n Класс позволяет создать данные для обучения классификатора и\n провести владиацию качества модели.\n :param domain: Путь до файла доменной области.\n \"\"\"\n self.classes = self.__init_predict(domain)\n\n @staticmethod\n def path(path):\n return Path(os.getcwd(), path)\n\n def __init_predict(self, path: str):\n \"\"\"\n Создание начального набора данных для решения проблемы холодного старта.\n true - Категория поставленная разметчиком.\n subtopic - Каетогрия прдесказанная моделью.\n :param path: Категории доменной области.\n :return: Уникальные классы второго и третьего уровня, которые содежатся в доменной области.\n \"\"\"\n d = pd.read_csv(self.path(path))\n c = list({i.strip().lower() for i in np.append(d['Тема'], d['Подтема']) if type(i) == str})\n d = pd.DataFrame({'phrase': c, 'subtopic': c, 'true': c})\n d.to_csv(self.path('data/processed/init_df.csv'), index=False)\n return c\n\n def __processing(self, d: pd.DataFrame) -> pd.DataFrame:\n \"\"\"\n Метод преобразует данные к формату, который используется для обучения\n классификатора.\n :param d: Набор данных после операции merge.\n :return: Обработанные данные.\n \"\"\"\n d['subtopic'] = d.subtopic.apply(lambda x: str(x).strip().lower())\n d = d.loc[d.subtopic.isin(self.classes)].drop_duplicates('phrase', ignore_index=True)\n # Удаление фраз вида: \"avonтема\"\n return d.drop([i for i, p in enumerate(d.phrase) if re.compile(\"[A-z]+\").findall(p)])\n\n def join_train_data(self, synonyms: str, full: str, left_on: str = 'Synonyms',\n right_on: str = 'item'):\n \"\"\"\n Соеденение размеченных наборов данных в один.\n :param left_on: Левая колонка для операции merge.\n :param right_on: Правая колонка для операции merge.\n :param full: Полный набор данных.\n :param synonyms: Размеченный набор данных.\n \"\"\"\n d = pd.read_csv(self.path(synonyms)).merge(pd.read_csv(self.path(full)), right_on=right_on,\n left_on=left_on, how=\"inner\")\n d = d.loc[d.Result == 1, ['item', 'Topic', 'frequency']].rename(\n columns={'item': 'phrase', 'Topic': 'subtopic'})\n self.__processing(d).to_csv('data/processed/marked-up-join.csv', index=False)\n","repo_name":"SciWake/OLD_Active-learning","sub_path":"src/data/make_dataset.py","file_name":"make_dataset.py","file_ext":"py","file_size_in_byte":3167,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71250159185","text":"import subprocess\nimport utils.files as files\n\n\ndef convert_file_to_mp3(file_path, extra_meta, result_path, result_filename=None):\n\n if result_filename is None and \"author\" in extra_meta and \"title\" in extra_meta:\n result_filename = \"{} - {}\".format(extra_meta[\"title\"], extra_meta[\"author\"])\n\n if result_filename is not None:\n result_filename = files.strip_invalid_chars(result_filename)\\\n .encode(\"utf-8\")\\\n .decode('unicode-escape')\n\n args = [\"-i {}\".format(file_path),\n \"-metadata title=\\\"{}\\\"\".format(extra_meta[\"title\"] if \"title\" in extra_meta else \"\"),\n \"-metadata author=\\\"{}\\\"\".format(extra_meta[\"author\"] if \"author\" in extra_meta else \"\"),\n \"-metadata album=\\\"{}\\\"\".format(extra_meta[\"album\"] if \"album\" in extra_meta else \"\"),\n \"-codec:a libmp3lame\",\n \"\\\"{}.mp3\\\"\".format(result_path + \"/{}\".format(\"result\" if result_filename is None else result_filename))]\n\n # ffmpeg -i \"input.extension\"\n # -metadata title=\"title\" -metadata author=\"artist\" -metadata album=\"album\" -codec:a libmp3lame \"output.mp3\"\n subprocess.call(\"ffmpeg \" + \" \".join(args), shell=True)\n\n return \"{}/{}.mp3\".format(result_path, result_filename)\n","repo_name":"Alex-D-TC/yt-dl","sub_path":"postprocess/transforms.py","file_name":"transforms.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"12740244595","text":"class Solution:\r\n def pivotIndex(self, nums: List[int]) -> int:\r\n total = sum(nums)\r\n left = 0\r\n for idx, num in enumerate(nums):\r\n right = total - num - left\r\n if left == right:\r\n return idx\r\n left += num\r\n return -1\r\n","repo_name":"sandychn/LeetCode-Solutions","sub_path":"Easy/0724-find-pivot-index.py","file_name":"0724-find-pivot-index.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21454424420","text":"#!/usr/bin/env python\n\"\"\"\nCharms have the capability to declare that they support more than\none series. Previously a separate copy of the charm was required for\neach series. An important constraint here is that for a given charm,\nall of the listed series must be for the same distro/OS; it is not\nallowed to offer a single charm for Ubuntu and CentOS for example.\nSupported series are added to charm metadata as follows:\n\n name: mycharm\n summary: \"Great software\"\n description: It works\n series:\n - xenial\n - trusty\n - angsty\n\nThe default series is the first in the list:\n\n juju deploy mycharm\n\nshould deploy a mycharm service running on trusty.\n\nA different, non-default series may be specified:\n\n juju deploy mycharm --series xenial\n\nIt is possible to force the charm to deploy using an unsupported series\n(so long as the underlying OS is compatible):\n\n juju deploy mycharm --series angsty --force\n\n\"\"\"\nfrom __future__ import print_function\n\nimport argparse\nfrom collections import namedtuple\nimport logging\nimport os\nimport subprocess\nimport sys\n\nfrom deploy_stack import BootstrapManager\nfrom jujucharm import (\n Charm,\n local_charm_path,\n)\nfrom utility import (\n add_basic_testing_arguments,\n configure_logging,\n JujuAssertionError,\n temp_dir,\n)\nfrom assess_heterogeneous_control import check_series\n\n\n__metaclass__ = type\n\nlog = logging.getLogger(\"assess_multi_series_charms\")\n\n\nTest = namedtuple(\"Test\", [\"series\", \"service\", \"force\", \"success\", \"machine\",\n \"juju1x_supported\"])\n\n\ndef assess_multi_series_charms(client, devel_series):\n \"\"\"Assess multi series charms.\n\n :param client: Juju client.\n :param devel_series: The series to use for new and unsupported scenarios.\n :type client: jujupy.ModelClient\n :return: None\n \"\"\"\n tests = [\n Test(series=devel_series, service='test0', force=False, success=False,\n machine=None, juju1x_supported=False),\n Test(series=None, service='test1', force=False, success=True,\n machine='0', juju1x_supported=True),\n Test(series=\"trusty\", service='test2', force=False, success=True,\n machine='1', juju1x_supported=True),\n Test(series=\"xenial\", service='test3', force=False, success=True,\n machine='2', juju1x_supported=False),\n Test(series=devel_series, service='test4', force=True, success=True,\n machine='3', juju1x_supported=False),\n ]\n with temp_dir() as repository:\n charm_name = 'dummy'\n charm = Charm(charm_name, 'Test charm', series=['trusty', 'xenial'])\n charm_dir = charm.to_repo_dir(repository)\n charm_path = local_charm_path(\n charm=charm_name, juju_ver=client.version, series='trusty',\n repository=os.path.dirname(charm_dir))\n for test in tests:\n if client.is_juju1x() and not test.juju1x_supported:\n continue\n log.info(\n \"Assessing multi series charms: test: {} charm_dir:{}\".format(\n test, charm_path))\n assert_deploy(client, test, charm_path, repository=repository)\n if test.machine:\n check_series(client, machine=test.machine, series=test.series)\n\n\ndef assert_deploy(client, test, charm_path, repository=None):\n \"\"\"Deploy a charm and assert a success or fail.\n\n :param client: Juju client\n :type client: jujupy.ModelClient\n :param test: Deploy test data.\n :type test: Test\n :param charm_dir:\n :type charm_dir: str\n :param repository: Direcotry path to the repository\n :type repository: str\n :return: None\n \"\"\"\n if test.success:\n client.deploy(charm=charm_path, series=test.series,\n service=test.service, force=test.force,\n repository=repository)\n client.wait_for_started()\n else:\n try:\n client.deploy(charm=charm_path, series=test.series,\n service=test.service, force=test.force,\n repository=repository)\n except subprocess.CalledProcessError:\n return\n raise JujuAssertionError('Assert deploy failed for {}'.format(test))\n\n\ndef parse_args(argv):\n \"\"\"Parse all arguments.\"\"\"\n parser = argparse.ArgumentParser(\n description=\"Test multi series charm feature\")\n add_basic_testing_arguments(parser)\n parser.add_argument(\n '--devel-series', default=\"yakkety\",\n help=\"The series to use when testing new and unsupported scenarios.\")\n return parser.parse_args(argv)\n\n\ndef main(argv=None):\n args = parse_args(argv)\n configure_logging(args.verbose)\n bs_manager = BootstrapManager.from_args(args)\n with bs_manager.booted_context(args.upload_tools):\n assess_multi_series_charms(bs_manager.client, args.devel_series)\n return 0\n\n\nif __name__ == '__main__':\n sys.exit(main())\n","repo_name":"juju/1.25-upgrade","sub_path":"juju2/acceptancetests/assess_multi_series_charms.py","file_name":"assess_multi_series_charms.py","file_ext":"py","file_size_in_byte":4939,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"19161140096","text":"### SRC - Nearly there, just need to fix the direction and add colour attribute.\n\nimport pygame\nimport random\nimport math\n\n# -- Global Constants\n\n# -- Colours\nBLACK = (0,0,0)\nWHITE = (255,255,255)\nBLUE = (50,50,255)\nYELLOW = (255,255,0)\nRED = (255,0,0)\nGREEN = (46,204,113)\nORANGE = (211,84,0)\nPURPLE = (125,60,152)\nAQUA = (22,160,133)\nPINK = (255,89,222)\nCOLOUR = [WHITE,BLUE,YELLOW,RED,GREEN,ORANGE,PURPLE,AQUA,PINK]\n\n# -- Initialise PyGame\npygame.init()\n\n# -- Manages how fast screen refreshes\n\nclock = pygame.time.Clock()\n\n\n# -- Blank Screen\n\nsize = (640,480)\nscreen = pygame.display.set_mode(size)\n\n# -- Title of new window/screen\npygame.display.set_caption(\"Space Invaders\")\n\ninvader_x_coor = [40,90,140,190,240,290,340,390,440,490,540,590, 40,90,140,190,240,290,340,390,440,490,540,590]\ninvader_y_coor = [50,50,50,50,50,50,50,50,50,50,50,50,80,80,80,80,80,80,80,80,80,80,80,80]\n# -- My Classes\n\n \nclass Invader(pygame.sprite.Sprite):\n x_dir = 1\n def __init__(self,colour,x,y, width,height,speed,):\n \n super().__init__()\n self.speed = speed\n self.image = pygame.Surface([width,height])\n self.image.fill(colour)\n self.rect = self.image.get_rect()\n self.rect.x = x\n self.rect.y = y\n\n def update(self):\n # wall_hit_group = pygame.sprite.groupcollide(self,wall_group,False,False)\n self.rect.x = self.rect.x +self.speed * self.x_dir\n \n if self.rect.x > 630:\n self.rect.y+= 40\n self.x_dir = -1\n elif self.rect.x < 0:\n self.rect.y = self.rect.y + 40\n self.x_dir = 1\n elif self.rect.y > 480:\n player.lives\n \nclass Player(pygame.sprite.Sprite):\n def __init__(self, colour, width, height):\n super().__init__()\n self.lives = 5\n self.score = 0\n self.bullet_count = 30\n self.speed = 0\n self.image = pygame.Surface([width,height])\n self.image.fill(colour)\n self.rect = self.image.get_rect()\n self.rect.x = 320\n self.rect.y = (480-height)\n \n def bullet_decrease(self):\n self.bullet_count -= 1\n \n def player_set_speed(self,val):\n self.speed = val\n\n def get_bullet_count(self):\n return self.bullet_count\n\n def get_lives(self):\n return self.lives\n\n def decrease_lives(self):\n self.lives -= 1\n \n def update(self):\n self.rect.x += self.speed\n\n if self.rect.x > 630 or self.rect.x<0:\n self.rect.x -= self.speed\n #end if\n \nclass Bullet(pygame.sprite.Sprite):\n def __init__(self, colour, width, height):\n super().__init__()\n self.speed = -5\n self.image = pygame.Surface([width,height])\n self.image.fill(colour)\n self.rect = self.image.get_rect()\n self.rect.x = player.rect.x + 3 \n self.rect.y = player.rect.y\n\n def update(self):\n self.rect.y += self.speed\n\n \n \n \n \n \nclass Wall(pygame.sprite.Sprite):\n def __init__(self,colour,x,y):\n super().__init__()\n self.image = pygame.Surface([1,480])\n self.rect = self.image.get_rect()\n self.image.fill(colour)\n self.rect.x = x\n self.rect.y = y\n \n \n\n \n\n\n \n \n \n#Sprite Groups\n\nall_sprites_group = pygame.sprite.Group()\ninvader_group = pygame.sprite.Group()\nbullet_group = pygame.sprite.Group()\nwall_group =pygame.sprite.Group()\n\n#set walls\nwallL = Wall(RED,-1,0)\nwallR = Wall(RED, 641,0)\nwall_group.add(wallL)\nwall_group.add(wallR)\nall_sprites_group.add(wallL)\nall_sprites_group.add(wallR)\n\n#add player\nplayer = Player(YELLOW,10,10)\nall_sprites_group.add(player)\n\n#add 10 invaders\nfor i in range(24):\n invader = Invader(AQUA,invader_x_coor[i],invader_y_coor[i],10,10,1) #10px x 10px\n invader_group.add(invader)\n all_sprites_group.add(invader)\n#next i\n\n\n\ngame_over = False\n\n\n### -- Game Loop\nwhile not game_over:\n # -- User input and controls\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n game_over = True\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT:\n player.player_set_speed(-5)\n elif event.key == pygame.K_RIGHT:\n player.player_set_speed(5)\n elif event.key == pygame.K_SPACE:\n if player.bullet_count !=0:\n bullet = Bullet(RED,6,4)\n bullet_group.add(bullet)\n all_sprites_group.add(bullet)\n player.bullet_decrease()\n \n \n\n elif event.type == pygame.KEYUP:\n if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:\n player.player_set_speed(0)\n #End If\n \n \n # -- Game logic goes after this comment\n all_sprites_group.update()\n bullet_hit_group = pygame.sprite.groupcollide(bullet_group,invader_group,True,True)\n player_hit_group = pygame.sprite.spritecollide(player,invader_group,True)\n \n # -- Text\n font = pygame.font.Font('freesansbold.ttf',15)\n textBullets = font.render('Bullets:' + str(player.get_bullet_count()\n ) ,False,WHITE)\n textLives = font.render('Lives:' + str(player.get_lives()),False,WHITE)\n textLivesRect = textLives.get_rect()\n textLivesRect.center = (50,30)\n textRect = textBullets.get_rect()\n textRect.center = (50,50)\n bigfont = pygame.font.Font('freesansbold.ttf',32)\n noBullets =bigfont.render('No Bullets Left',False,RED)\n noBulletRect = noBullets.get_rect()\n noBulletRect.center = (320,200)\n \n \n\n # -- Screen background is BLACK\n screen.fill (BLACK)\n # -- Display text\n screen.blit(textBullets,textRect)\n screen.blit(textLives, textLivesRect)\n if player.bullet_count ==0:\n screen.blit(noBullets,noBulletRect)\n # -- Draw here\n all_sprites_group.draw(screen)\n\n \n\n\n # -- flip display to reveal new position of objects\n pygame.display.flip()\n\n # - The clock ticks over\n clock.tick(60)\n\n#End While - End of game loop\n\npygame.quit()\n\n##while not game_over:\n\n","repo_name":"KUP9752/PekgozKU-Yr12-Computer-Science","sub_path":"Work/PyGame/Space Invader/Space Invaders.py","file_name":"Space Invaders.py","file_ext":"py","file_size_in_byte":6222,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15361286512","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nplt.style.use('ggplot')\n\nfil = input(\"Enter your Excel filename: \")\ndf = pd.read_excel(fil)\nfig, ax = plt.subplots()\nvar1 = input(\"Enter variable:\")\nmy_scatter_plot = ax.boxplot(\n df[var1],\n )\nax.set_title(\"Box plot of cars\")\nplt.show()\n","repo_name":"Kondapsa/Data_Analytics_with_Software","sub_path":"boxplotinput.py","file_name":"boxplotinput.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16277357939","text":"from django.core.management.base import BaseCommand, CommandError\nfrom flixmedia.models import Movie\nfrom flixmedia.views import UUID4_REGEX\nfrom tkinter import Tk\nfrom tkinter.filedialog import askopenfile\nimport os\nimport re\n\nUUID4_REGEX = re.compile(UUID4_REGEX)\n\nclass Command (BaseCommand):\n help = 'Link local video to Movie and Episode.'\n\n def add_arguments(self, parser):\n parser.add_argument('id')\n parser.add_argument('-p', '--path', required=False, type=str, help='Path to video, left empty to use UI file picker')\n parser.add_argument('-o', '--override', action='store_true', help='Delete old video if present.')\n parser.add_argument('-m', '--move', action='store_true', help='Save and move video.')\n\n def handle(self, *args, **options):\n id = options['id']\n path = options['path']\n override = options['override']\n move = options['move']\n\n if not UUID4_REGEX.match(id):\n raise CommandError(f\"'{id}' is not a valid uuid.\")\n\n try:\n movie = Movie.objects.get(pk=id)\n except Movie.DoesNotExist:\n raise CommandError(f\"Movie with id '{id}' does not exists\")\n\n if not override and movie.video:\n raise CommandError(f\"{movie.title} movie video is not null.\")\n\n if not path:\n Tk().withdraw()\n path = askopenfile()\n if not path:\n return\n path = path.name\n elif path and not os.path.exists(path):\n raise CommandError(f\"File {path} does not exists.\")\n\n movie.link_local_video(path, move=move)\n\n self.stdout.write(self.style.SUCCESS(f\"{movie.title} movie video {movie.video.name} with size: {movie.video.size}\"))\n \n \n ","repo_name":"jhetjhet/FreeFlix","sub_path":"flixmedia/management/commands/mvid.py","file_name":"mvid.py","file_ext":"py","file_size_in_byte":1776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71388096786","text":"\"\"\"\nProvides a class to maintain an instance of a particular boat within a fleet\n\"\"\"\n\nfrom typing import Dict, List, Tuple\n\nfrom .. import utils\n\nfrom .handicap import HandicapNumber\nfrom .wind_map import WindMap\n\n\nclass BoatType:\n \"\"\"\n A class to contain the necessary information to construct a boat type for\n Portsmouth Handicap race parameters\n \"\"\"\n\n def __init__(\n self,\n name: str,\n fleet_name: str,\n boat_class: str,\n code: str,\n display_code: str,\n dpn_values: List[HandicapNumber],\n wind_map: WindMap):\n \"\"\"\n Initializes the boat parameter\n :param name: The name of the boat\n :param fleet_name: The name of the fleet the boat is associated with\n :param boat_class: The class of the boat\n :param code: The unique identification code for the given boat class\n :param display_code: Defines the display version of the boat code results\n :param dpn_values: A list of 5 values, identifying [DPN0, DPN1, DPN2, DPN3, DPN4]\n :param wind_map: The wind map to use for obtaining DPN values\n \"\"\"\n self.name = name\n self.fleet_name = fleet_name\n self.boat_class = boat_class.lower()\n self.code = code\n self.display_code = display_code\n self.dpn_values = dpn_values\n self.wind_map = wind_map\n self.__mem_characteristic_tuple = None\n\n def needs_handicap_note(self) -> bool:\n \"\"\"\n Returns true if the note on handicap types is required\n :return: True if any DPN value is not \"standard\" and may be suspect\n \"\"\"\n for dpn in self.dpn_values:\n if dpn is None:\n continue\n elif dpn.get_type() != HandicapNumber.HandicapType.STANDARD:\n return True\n return False\n\n def dpn_for_beaufort(self, beaufort: int) -> HandicapNumber:\n \"\"\"\n Provides the DPN value associated with the input beaufort number. If the boat type doesn't have a specified DPN\n for the provided beaufort number, the highest value that will satisfy the requirements will be returned.\n :param beaufort: The input Beaufort number\n :type beaufort: int\n :return: The DPN value associated with the given beaufort number, or the highest possible DPN index <= beaufort\n \"\"\"\n # Ensure that the beaufort number is an integer\n if type(beaufort) != int:\n raise ValueError('Beaufort number must be of type int')\n\n # Find the ideal index for the given beaufort number\n if beaufort <= 1:\n dpn_ind = 1\n elif beaufort <= 3:\n dpn_ind = 2\n elif beaufort <= 4:\n dpn_ind = 3\n else:\n dpn_ind = 4\n\n # If there is no DPN value at any index, raise an error\n dpn_val = self.dpn_values[dpn_ind]\n if dpn_val is None:\n print(f\"No HC found for {self.code}/{self.name} from {self.fleet_name} for BF={beaufort} - using default DPN value\")\n dpn_val = self.dpn_values[0]\n\n # Return the DPN value\n return dpn_val\n\n def __characteristic_tuple(self) -> Tuple[str, str, str, str]:\n \"\"\"\n Provides a tuple that may be used for internal functions for determining\n equality and hash results\n :return: the characteristic tuple of the boat\n \"\"\"\n if self.__mem_characteristic_tuple is None:\n self.__mem_characteristic_tuple = self.name, self.fleet_name, self.boat_class, self.code\n return self.__mem_characteristic_tuple\n\n def __eq__(self, other) -> bool:\n \"\"\"\n Determines whether the provided object is equal to the current boat class object\n :return: true if the objects are equal\n \"\"\"\n if isinstance(other, BoatType):\n return self.__characteristic_tuple() == other.__characteristic_tuple()\n else:\n return False\n\n def __hash__(self) -> int:\n \"\"\"\n Provides the hash result for the current boat type\n :return: the hash result for the boat\n \"\"\"\n return hash(self.__characteristic_tuple())\n\n @staticmethod\n def load_from_csv(\n csv_table: str,\n fleet_name: str,\n wind_map: WindMap) -> Dict[str, 'BoatType']:\n \"\"\"\n Reads the Portsmouth pre-calculated table from an input CSV file contents\n :param csv_table: The filename to read\n :param fleet_name: The fleet name to associate boats with\n :param wind_map: A wind_map to associate the boat type to\n :return: A dictionary of boats, keyed by the type code\n \"\"\"\n # Initialize the empty dictionary\n boats = dict()\n expected_header = ['boat', 'class', 'code', 'dpn', 'dpn1', 'dpn2', 'dpn3', 'dpn4']\n\n def boat_row_func(row_dict):\n # Extract the DPN values, both the initial and Beaufort values\n dpn_len = len([key for key in row_dict if key.startswith('dpn') and len(key) > len('dpn')])\n dpn_string_values = [row_dict['dpn']]\n dpn_string_values += [row_dict[f'dpn{i + 1}'] for i in range(dpn_len)]\n dpn_values = [HandicapNumber.from_string(v) if len(v) > 0 else None for v in dpn_string_values]\n\n # Extract the name and code\n boat_name = row_dict['boat']\n boat_code = row_dict['code'].lower().replace('/', '_')\n boat_display_code = row_dict['code']\n\n # Extract the boat class from the input parameters\n boat_class = row_dict['class'].lower()\n if row_dict['class'].lower() not in ('centerboard', 'keelboat'):\n print('Unknown boat class {:s} for {:s}'.format(boat_class, boat_name))\n boat_class = 'unknown'\n\n # Check that the primary DPN value is not null\n if dpn_values[0] is None:\n print('Skipping {:s} due to no provided DPN values'.format(boat_code))\n # Otherwise, there is a valid boat definition\n else:\n # Check that the boat code doesn't already exist in the dictionary\n if boat_code in boats:\n raise ValueError('BoatType {:s} already in dictionary'.format(boat_code))\n\n # Create the boat object and set equal to the dictionary for the code\n boats[boat_code] = BoatType(\n name=boat_name,\n fleet_name=fleet_name,\n boat_class=boat_class,\n code=boat_code,\n display_code=boat_display_code,\n dpn_values=dpn_values,\n wind_map=wind_map)\n\n # Call the CSV load function\n utils.load_from_csv(\n csv_data=csv_table,\n row_func=boat_row_func,\n expected_header=expected_header)\n\n return boats\n","repo_name":"cessnao3/PortsmouthRaceCalc","sub_path":"database/fleets/boat.py","file_name":"boat.py","file_ext":"py","file_size_in_byte":6939,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"74744001744","text":"from src.fizzbuzz import fizzbuzz\n\n\ndef test_multiples_of_3_return_fizz():\n fizzTest = fizzbuzz()\n assert fizzTest.multiple(1, 10, {3: \"Fizz\"}) == [\n 1,\n 2,\n \"Fizz\",\n 4,\n 5,\n \"Fizz\",\n 7,\n 8,\n \"Fizz\",\n 10,\n ]\n\n\ndef test_multiples_of_5_return_buzz():\n fizzTest = fizzbuzz()\n assert fizzTest.multiple(1, 10, {5: \"Buzz\"}) == [\n 1,\n 2,\n 3,\n 4,\n \"Buzz\",\n 6,\n 7,\n 8,\n 9,\n \"Buzz\",\n ]\n\n\ndef test_multiples_of_3_and_5_return_fizzbuzz():\n fizzTest = fizzbuzz()\n assert fizzTest.multiple(1, 15, {3: \"Fizz\", 5: \"Buzz\"}) == [\n 1,\n 2,\n \"Fizz\",\n 4,\n \"Buzz\",\n \"Fizz\",\n 7,\n 8,\n \"Fizz\",\n \"Buzz\",\n 11,\n \"Fizz\",\n 13,\n 14,\n \"FizzBuzz\",\n ]\n","repo_name":"enlabedev/python-init","sub_path":"tests/test_fizzbuzz.py","file_name":"test_fizzbuzz.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73448934546","text":"#练习:\n# 写一个程序,输入你的出生日期\n# 1) 算出你已经出生了多少天?\n# 2) 算出你出生那天是星期几?\n\n#方法一\n\nimport time\n#输入你的出生日期\nyear = int(input(\"请输入年: \"))\nmonth = int(input(\"请输入月: \"))\nday = int(input(\"请输入日: \"))\n\n#得到出生时的秒数\nbirthday_second = time.mktime((year,month,day,0,0,0,0,0,0))\n#得到当前时间的秒数\ncur_second = time.time()\n\n#算出你已经出生多少天?\ns = cur_second - birthday_second\nprint(\"您已出生:\", s / 60 / 60 // 24)\n\n#2)算出出生那天是星期几?\nbirthday = (year, month, day, 0, 0, 0, 0, 0, 0)\n#转为秒数\ns = time.mktime(birthday)\n#转回本地时间元组\nt = time.localtime(s)\nweekday = {\n 0:\"星期一\",\n 1:\"星期二\",\n 2:\"星期三\",\n 3:\"星期四\",\n 4:\"星期五\",\n 5:\"星期六\",\n 6:\"星期日\"\n }\nprint(\"您出生那天是:\",weekday[t[6]])\n\n\n\n\n\n\n\n#方法二\n#1.判断一年是闰年\n#判断闰年\ndef is_leapyear(year):\n if year % 400 ==0 or ( year % 100 !=0 and year % 4 == 0):\n return True\n return False\n#今天日期\nimport time \n#判断1900年1月1日至今多少天,1900年1月1日至出生日期多少天\ndef caculate_1900_days():\n #当期日期,年、月、日\n strDate = time.strftime('%Y%m%d', time.localtime(time.time())) #这里格式是‘%Y-%m-%d’。\n current_year = int(strDate[:4])\n current_month = int(strDate[4:6])\n current_day = int(strDate[6:])\n c_days = int(time.strftime('%j',time.localtime(time.time())))\n\n #出生日期、年月日\n birthDate = input(\"请输入出生日期: \") #格式为1990-12-01\n birth_year = int(birthDate.split('-')[0])\n birth_month = int(birthDate.split('-')[1])\n birth_day = int(birthDate.split('-')[2])\n b_days = int(time.strftime('%j',time.strptime(birthDate,'%Y-%m-%d')))\n\n w_days = time.strftime('%W',time.strptime(birthDate,'%Y-%m-%d'))\n\n #基准日期,年月日\n benchmarkDate = '1900-01-01' #格式为1990-12-01\n bench_year = int(benchmarkDate.split('-')[0])\n bench_month = int(benchmarkDate.split('-')[1])\n bench_day = int(benchmarkDate.split('-')[2])\n\n currentdays = (current_year - bench_year) * 365\n birthdays = (birth_year - bench_year) * 365\n\n for tempYear in range(bench_year, current_year, 1):\n if is_leapyear(tempYear):\n currentdays += 1\n for tempYear in range(bench_year, birth_year, 1):\n if is_leapyear(tempYear):\n birthdays += 1\n days = (currentdays + c_days) - (birthdays + b_days)\n return days\ncaculate_1900_days()\n\n","repo_name":"GaoYu/zeroPython","sub_path":"exercise/21_1.py","file_name":"21_1.py","file_ext":"py","file_size_in_byte":2610,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42032972841","text":"\"\"\"\n防止过拟合使用,正则化方法\n\"\"\"\nfrom keras import models\nfrom keras import layers\nfrom keras import regularizers\n\n\ndef build_model():\n model = models.Sequential()\n # 12(0.0001)该层权重矩阵的每个系数都会是网络的总损失增加0.001*weith\n model.add(layers.Dense(16, kernel_regularizer=regularizers.l2(0.0001), activation='relu', input_shape=(1000,)))\n # 添加dropout层降低过拟合。其核心思想是在层中引入噪声,打破不显然的偶然模式,如果没有噪声,网络将会记住这些偶然模式,0.5是舍弃一半的单元\n model.add(layers.Dropout(0.5))\n model.add(layers.Dense(16, kernel_regularizer=regularizers.l2(0.001), activation='relu'))\n model.add(layers.Dense(1, activation='sigmoid'))\n\n return model\n\n","repo_name":"Sparkoor/learning","sub_path":"machineLearning/keraslearn/regular12.py","file_name":"regular12.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12336217362","text":"import json\n\nclass Piece:\n \"\"\"A representation of the color of the pieces.\n\tA piece is Empty if it has not been assigned a color yet. Otherwise it is Black or White.\n \"\"\"\n\n Empty = 0\n Black = 1\n White = 2\n\n @staticmethod\n def serialize(piece):\n if (piece == Piece.Black):\n return 'B'\n if (piece == Piece.White):\n return 'W'\n return ' '\n\n @staticmethod\n def deserialize(string):\n if (string == 'B'):\n return Piece.Black\n if (string == 'W'):\n return Piece.White\n return Piece.Empty\n\n\nclass Board:\n \"\"\"A representation of the board.\n\tContains a board located in variable board that is filled with 24 empty positions.\n\tContains all mill possibilities located in variable lines.\n \"\"\"\n\n lines = [\n [0, 1, 2],\n [3, 4, 5],\n [6, 7, 8],\n [9, 10, 11],\n [12, 13, 14],\n [15, 16, 17],\n [18, 19, 20],\n [21, 22, 23],\n [0, 9, 21],\n [3, 10, 18],\n [6, 11, 15],\n [8, 12, 17],\n [5, 13, 20],\n [2, 14, 23],\n [0, 3, 6],\n [2, 5, 8],\n [15, 18, 21],\n [17, 20, 23],\n [1, 4, 7],\n [16, 19, 22]\n ]\n\n position_count = 24\n\n def __init__(self):\n \"\"\"Constructor for Board.\n Initializes an instance with an empty board.\"\"\"\n self.board = [Piece.Empty] * self.position_count\n\n def pieces_of_type_on_board(self, piece):\n \"\"\"Counts how many of the given piece is on the board.\n\n Keyword arguments:\n piece -- The piece to count.\n return -- The amount of the given piece that is on the board.\n \"\"\"\n count = 0\n for piece_in_board in self.board:\n if (piece == piece_in_board):\n count += 1\n return count\n\n def positions_are_adjacent(self, position, other_position):\n \"\"\"Checks if the given position and the given other_position are adjacent to each other on the board.\n\n Keyword arguments:\n position -- The first position.\n other_position -- The second position.\n return -- True if both positions are adjacent to each other. Otherwise False.\n \"\"\"\n if (position == other_position):\n return False\n\n lines = self.get_lines_for_position(position)\n for line in lines:\n if (other_position in line):\n if (abs(line.index(position) - line.index(other_position)) == 1):\n return True\n\n return False\n\n def get_lines_for_position(self, position):\n \"\"\"Looks for which lines the given position can be in.\n It will go through every line to find those who contain the given position.\n\t\tIt will then return all lines that contains the given position.\n\n Keyword arguments:\n position -- The position to look for in lines.\n return -- An array of all lines the given position can be in.\n \"\"\"\n found_lines = []\n\n for line in self.lines:\n if (position in line):\n found_lines.append(line)\n\n return found_lines\n\n def has_three_at_position(self, piece, position):\n \"\"\"Checks wether the given piece on the given position is in a mill.\n\n Keyword arguments:\n piece -- The piece to check if it is in a mill.\n position -- The position to look for in possible mills.\n return -- True if the given piece on the given position is in a mill. Otherwise False.\n \"\"\"\n lines = self.get_lines_for_position(position)\n for line in lines:\n line_full = True\n for position in line:\n if (self.board[position] != piece):\n line_full = False\n break\n if (line_full):\n return True\n\n return False\n\n def get_mill_at_position(self, piece, position):\n \"\"\"Returns a line that contains the given position and piece if it is a mill.\n\n Keyword arguments:\n piece -- The piece to check if it is in a mill.\n position -- The position to look for in possible mills.\n return -- Returns the line that is a mill given the piece and position. Otherwise returns an empty line.\n \"\"\"\n lines = self.get_lines_for_position(position)\n for line in lines:\n line_full = True\n for position in line:\n if (self.board[position] != piece):\n line_full = False\n break\n if (line_full):\n return line\n\n return []\n\n def get_other_piece(self, piece):\n \"\"\"Gets the opposite color of the given piece.\n If the given piece is Piece.Black it will return Piece.White and vice versa. Otherwise it will return Piece.Empty.\n\n Keyword arguments:\n piece -- The given color to get its opposite color.\n return -- Returns Piece.White if the given piece is Piece.Black and vice versa. Otherwise it will return Piece.Empty.\n \"\"\"\n if (piece == Piece.Black):\n return Piece.White\n if (piece == Piece.White):\n return Piece.Black\n return Piece.Empty\n\n def __getitem__(self, index):\n \"\"\"Gets what is on the given position on the board.\n\n Keyword arguments:\n index -- An index on the board\n return -- Returns what is on the given index on the board.\n \"\"\"\n return self.board[index]\n\n def __setitem__(self, index, value):\n \"\"\"Updates the board on the given index with the given value.\n\n Keyword arguments:\n index -- An index on the board to place the given value.\n value -- The value to be placed on the given index on the board.\n return -- Returns nothing. Sets the given value on the given index on the board.\n \"\"\"\n self.board[index] = value\n\n def serialize(self):\n array = [' '] * Board.position_count\n for i in range(24):\n array[i] = Piece.serialize(self.board[i])\n\n return array\n\n @staticmethod\n def deserialize(array):\n board = Board()\n for i in range(24):\n board[i] = Piece.deserialize(array[i])\n \n return board","repo_name":"Nusrat-16/Software-engineering-and-project-management","sub_path":"src/game platform/board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":6262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11054233442","text":"from Easyload import *\n\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import QIcon\nfrom PyQt5.QtCore import *\nfrom PyQt5 import QtCore\nfrom multiprocessing import Pool\nfrom multiprocessing.dummy import Pool as ThreadPool\n\nclass MOOC_Downloading(QMainWindow):\n def __init__(self):\n super().__init__()\n self.refSettings()\n self.settings['mob_token'] = ''\n self.initUI()\n \n def initUI(self):\n #任务栏\n self.statusBar()\n\n #菜单栏\n menubar = self.menuBar()\n fileMenu = menubar.addMenu('&设置')\n helpMenu = menubar.addMenu('&帮助')\n \n switchAction = QAction('&切换用户', self)\n switchAction.setShortcut('Alt+Q')\n switchAction.setStatusTip('切换登录账号')\n switchAction.triggered.connect(self.switchUser)\n fileMenu.addAction(switchAction)\n \n courseAction = QAction('&订阅课程', self)\n courseAction.setShortcut('Alt+D')\n courseAction.setStatusTip('修改订阅课程配置')\n courseAction.triggered.connect(self.courseConfig)\n fileMenu.addAction(courseAction)\n\n settingAction = QAction('&全局配置', self)\n settingAction.setShortcut('Alt+S')\n settingAction.setStatusTip('修改全局配置')\n settingAction.triggered.connect(self.chSettings)\n fileMenu.addAction(settingAction)\n\n aboutAction = QAction('&关于', self)\n aboutAction.setShortcut('Alt+A')\n aboutAction.setStatusTip('关于本程序')\n aboutAction.triggered.connect(self.about)\n helpMenu.addAction(aboutAction)\n\n helpAction = QAction('&使用帮助', self)\n helpAction.setShortcut('Alt+H')\n helpAction.setStatusTip('使用帮助')\n helpAction.triggered.connect(self.about)\n helpMenu.addAction(helpAction)\n\n self.canvas = Canvas(self.settings)\n self.setCentralWidget(self.canvas)\n\n self.setGeometry(300, 300, 1000, 500)\n self.setWindowTitle('MOOC_Downloading')\n self.setWindowIcon(QIcon('timg.ico'))\n self.switchUser()\n self.show()\n\n def switchUser(self):\n LoginDialog(self.settings).exec_()\n self.refSettings()\n\n def courseConfig(self):\n if self.settings.get('mob_token'):\n CourseDialog(self.settings).exec_()\n self.refSettings()\n else:\n self.canvas.infoText.append('请先登录!\\n')\n\n def chSettings(self):\n SettingsDialog(self.settings).exec_()\n self.refSettings()\n\n def about(self):\n AboutDialog().exec_()\n\n def help(self):\n pass\n\n def refSettings(self):\n try:\n with open('data/settings.json', 'rb') as f:\n self.settings = json.loads(f.read().decode())\n except:\n self.settings = {}\n\n def saveSettings(self):\n with open('data/settings.json', 'wb') as f:\n f.write(json.dumps(self.settings).encode())\n\n def closeEvent(self, event):\n reply = QMessageBox.question(self, '不开心,哼',\n \"真的要走吗?\", QMessageBox.Yes |\n QMessageBox.No, QMessageBox.No)\n \n if reply == QMessageBox.Yes:\n event.accept()\n else:\n event.ignore()\n\nclass Canvas(QWidget):\n def __init__(self, settings):\n super().__init__()\n self.settings = settings\n self.infoQ = queue.Queue()\n self.workQ = []\n self.taskQ = queue.Queue()\n self.initUI()\n \n \n def initUI(self):\n # 任务显示栏\n self.taskBox = QVBoxLayout()\n self.taskBar1 = TaskBar({})\n self.taskBar2 = TaskBar({})\n\n # 信息提示栏\n self.infoBox = QVBoxLayout()\n ## 信息提示框\n self.infoLbl = QLabel('提示信息')\n self.infoText = QTextEdit()\n\n ## 操作按钮\n self.operationBox = QHBoxLayout()\n self.decButton = QPushButton(\"-\")\n self.startButton = QPushButton(\"|>\")\n self.startButton.clicked.connect(self.start)\n self.incButton = QPushButton(\"+\")\n self.sumVelLbl = QLabel('总速度:0kb/s')\n \n # 全局布局\n self.operationBox.addWidget(self.decButton)\n self.operationBox.addWidget(self.startButton)\n self.operationBox.addWidget(self.incButton)\n self.operationBox.addWidget(self.sumVelLbl)\n self.operationBox.addStretch(1)\n self.taskBox.addWidget(self.taskBar1)\n self.taskBox.addWidget(self.taskBar2)\n self.taskBox.addStretch(1)\n self.infoBox.addWidget(self.infoLbl)\n self.infoBox.addWidget(self.infoText)\n self.infoBox.addLayout(self.operationBox)\n self.mainLayout = QHBoxLayout()\n self.mainLayout.addLayout(self.taskBox)\n self.mainLayout.addLayout(self.infoBox)\n self.setLayout(self.mainLayout)\n\n self.infoTimer = QTimer()\n self.infoTimer.setInterval(100)\n self.infoTimer.start()\n self.infoTimer.timeout.connect(self.refreshInfo)\n\n self.taskTimer = QTimer()\n self.taskTimer.setInterval(1000)\n self.taskTimer.start()\n self.taskTimer.timeout.connect(self.refreshTask)\n\n self.show()\n\n def refreshInfo(self):\n if not self.infoQ.empty():\n self.infoText.append(self.infoQ.get())\n if self.taskQ.empty():\n self.startButton.setText('|>')\n else:\n self.startButton.setText('||')\n \n def refreshTask(self):\n pass\n #self.taskBox.clear()\n #self.configs = {}\n #for courseware in self.workQ:\n # config['name'] = courseware.name\n # config['localsize'] = courseware.f.local_size/1024\n # config['size'] = courseware.f.size/1024\n # config['speed'] = (config['localsize'] - self.configs.get(courseware.name, {'localsize':0})['localsize'])/1024\n # if config['size'] and config['size'] >= config['localsize']:\n # config['progress'] = int(config['localsize']/config['size'])\n # else:\n # config['progress'] = 0\n # config['flag'] = courseware.f.flag\n # self.configs[courseware.name] = config\n # self.taskBox.addWidget(TaskBar(config))\n\n def start(self):\n def download(args):\n for courseware in coursewares:\n courseware.download(*args)\n \n #def scan(_queue):\n # time.sleep()\n # _queue.put((1,))\n\n #th = threading.Thread(target=scan,args=(self.notify_queue,))\n #th.setDaemon(True)\n #th.start()\n try:\n courses = []\n self.startButton.setText('||')\n self.infoText.append('[Info]初始化课件中……')\n for courseConfig in self.settings.get('courseConfigs',[]):\n coursewares = getcoursewares(courseConfig.get('courseinfo'), \\\n self.settings.get(platform.system()+'Root', os.path.expanduser(\"~\")+os.sep+'Desktop'), \\\n self.settings.get('mob_token'), \\\n courseConfig.get('sharpness','sd'), \\\n self.infoQ)\n if courseConfig.get('isLoad',False):\n courses.append((coursewares, courseConfig.get('weekNum',[0]), courseConfig.get('loadType',[1,3,4])))\n self.infoText.append('[Info]初始化完成,开始下载')\n for course in courses:\n coursewares = course[0]\n self.infoText.append('[Info]当前下载课程:{}'.format(coursewares[0].coursename))\n general_view(courseConfig.get('courseinfo'), self.settings.get(platform.system()+'Root', os.path.expanduser(\"~\")+os.sep+'Desktop'))\n playlist(coursewares[0].coursename, coursewares, self.settings.get(platform.system()+'Root', os.path.expanduser(\"~\")+os.sep+'Desktop'),'RP')\n\n for courseware in coursewares:\n self.taskQ.put((courseware, course[1], course[2]))\n thpl = ThreadPool(self.settings.get('processNum', 5), self.taskQ, self.workQ)\n\n #th = threading.Thread(target=download, args=(course[-2:],))\n #th.setDaemon(True)\n #th.start()\n \n #pool=ThreadPool(10)\n #for courseware in coursewares:\n # pool.apply_async(courseware.download, args=(course[1], course[2]))\n #pool.close()\n #pool.join()\n \n #for courseware in coursewares:\n # courseware.download(*course[-2:])\n self.startButton.setText('|>')\n except Exception as e:\n print(e)\n \nclass ThreadPool():\n def __init__(self, num, taskQ, workQ):\n self.num = num\n self.taskQ = taskQ\n self.workQ = workQ\n self.threads = []\n for n in range(num):\n th = threading.Thread(target=self.run)\n th.setDaemon(True)\n self.threads.append(th)\n th.start()\n\n def run(self):\n while True:\n if not self.taskQ.empty():\n task = self.taskQ.get()\n self.workQ.append(task[0])\n task[0].download(*task[1:])\n del self.workQ[self.workQ.index(task[0])]\n else:\n break\n\nclass TaskBar(QFrame):\n def __init__(self, config):\n super().__init__()\n self.config = config\n self.initUI()\n \n def initUI(self):\n self.fileLbl = QLabel('当前下载:{} {}MB/{}MB {} kb/s'.format(self.config.get('name','xxx'),\n self.config.get('localsize',0),\n self.config.get('size', 0),\n self.config.get('speed', 0)))\n self.pbar = QProgressBar()\n self.pbar.setGeometry(30, 40, 200, 25)\n self.pbar.setValue(self.config.get('progress',0))\n if self.config.get('flag', True):\n self.pauseButton = QPushButton(\"||\")\n else:\n self.pauseButton = QPushButton(\"|>\")\n self.cancelButton = QPushButton(\"X\")\n\n self.controlBox = QHBoxLayout()\n self.controlBox.addWidget(self.pbar)\n self.controlBox.addWidget(self.pauseButton)\n self.controlBox.addWidget(self.cancelButton)\n self.mainLayout = QVBoxLayout()\n self.mainLayout.addWidget(self.fileLbl)\n self.mainLayout.addLayout(self.controlBox)\n self.setLayout(self.mainLayout)\n \n self.show()\n\nclass LoginDialog(QDialog):\n def __init__(self, settings):\n super().__init__()\n self.settings = settings\n self.initUI()\n\n def initUI(self):\n self.setWindowTitle(\"登录\") # 窗口标题\n self.setGeometry(400,400,300,200) # 窗口位置与大小\n \n self.usernameLbl = QLabel('账号:')\n self.passwordLbl = QLabel('密码:')\n if self.settings.get('mob-token'):\n self.stateLbl = QLabel('当前用户:{}'.format(self.settings['username']))\n else:\n self.stateLbl = QLabel('状态:未登录')\n \n self.username = QLineEdit()\n self.password = QLineEdit()\n self.isAutoLogin = QCheckBox('记住密码')\n\n self.loginBtn = QPushButton('登录')\n self.loginBtn.clicked.connect(self.login)\n self.cancelBtn = QPushButton('取消')\n self.cancelBtn.clicked.connect(self.close)\n self.hBtnsLayout = QHBoxLayout()\n self.hBtnsLayout.addWidget(self.loginBtn)\n self.hBtnsLayout.addWidget(self.cancelBtn)\n\n self.vlayout = QVBoxLayout()\n self.glayout = QGridLayout()\n self.glayout.addWidget(self.usernameLbl,0,0)\n self.glayout.addWidget(self.passwordLbl,1,0)\n self.glayout.addWidget(self.isAutoLogin,2,0)\n self.glayout.addWidget(self.username,0,1)\n self.glayout.addWidget(self.password,1,1)\n self.vlayout.addLayout(self.glayout)\n self.vlayout.addWidget(self.stateLbl)\n self.vlayout.addLayout(self.hBtnsLayout)\n self.setLayout(self.vlayout)\n\n if self.settings.get('isAutoLogin'):\n self.isAutoLogin.setChecked(True)\n self.username.setText(self.settings['username'])\n self.password.setText('*' * self.settings['passwordLen'])\n else:\n self.isAutoLogin.setChecked(False)\n self.show()\n\n def login(self):\n username = self.username.text()\n password = self.password.text()\n flag=hashlib.md5()\n flag.update(password.encode('utf-8'))\n passwd = flag.hexdigest()\n if username == 'sharing':\n username = 's_sharing@126.com'\n self.username.setText(username)\n passwd = 'e10adc3949ba59abbe56e057f20f883e'\n self.password.setText('*' * 6)\n if self.settings.get('isAutoLogin') and \\\n username == self.settings['username'] and \\\n password == '*' * self.settings['passwordLen']:\n passwd = self.settings['passwd']\n self.stateLbl.setText('登录中...')\n self.stateLbl.adjustSize()\n results = gettoken(username,passwd)\n if results[1] == 0:\n self.stateLbl.setText('登录成功')\n self.settings['mob_token'] = results[0]\n self.settings['isAutoLogin'] = self.isAutoLogin.isChecked()\n self.settings['username'] = username\n self.settings['passwordLen'] = len(password)\n self.settings['passwd'] = passwd\n with open('data/settings.json', 'wb') as f:\n f.write(json.dumps(self.settings).encode())\n self.close()\n elif results[1] == 100:\n self.stateLbl.setText('账号或密码错误,请重新登录')\n else:\n self.stateLbl.setText('发生未知错误,错误码{}'.format(results[1]))\n\nclass SettingsDialog(QDialog):\n def __init__(self, settings):\n super().__init__()\n self.settings = settings\n self.initUI()\n \n def initUI(self):\n self.setWindowTitle(\"全局配置\") # 窗口标题\n self.setGeometry(400,400,300,200) # 窗口位置与大小\n \n self.pathLbl = QLabel('路径:')\n self.processNumLbl = QLabel('进程数:')\n \n self.path = QLineEdit()\n self.processNum = QComboBox()\n for n in range(10):\n self.processNum.addItem(str(n+1))\n\n self.pathBtn = QPushButton(\"...\")\n self.pathBtn.clicked.connect(self.selectPath)\n self.isAutoSetting = QCheckBox('自动配置')\n self.isAutoSetting.toggle()\n\n self.saveBtn = QPushButton('保存')\n self.saveBtn.clicked.connect(self.save)\n self.cancelBtn = QPushButton('取消')\n self.cancelBtn.clicked.connect(self.close)\n self.hBtnsLayout = QHBoxLayout()\n self.hBtnsLayout.addWidget(self.saveBtn)\n self.hBtnsLayout.addWidget(self.cancelBtn)\n\n self.glayout = QGridLayout()\n self.vlayout = QVBoxLayout()\n self.glayout.addWidget(self.pathLbl,0,0)\n self.glayout.addWidget(self.processNumLbl,1,0)\n self.glayout.addWidget(self.path,0,1,1,2)\n self.glayout.addWidget(self.processNum,1,1)\n self.glayout.addWidget(self.pathBtn,0,3)\n self.glayout.addWidget(self.isAutoSetting,1,2)\n self.vlayout.addLayout(self.glayout)\n self.vlayout.addLayout(self.hBtnsLayout)\n self.setLayout(self.vlayout)\n\n self.isAutoSetting.setChecked(self.settings.get('isAutoSetting',False))\n self.path.setText(self.settings.get(platform.system()+'Root',''))\n self.processNum.setCurrentIndex(self.settings.get('processNum', 1)- 1)\n \n self.show()\n\n def selectPath(self):\n root = self.path.text() if os.path.exists(self.path.text()) else os.path.expanduser(\"~\")+os.sep+'Desktop'\n dirPath = QFileDialog.getExistingDirectory(self, \"选择下载根目录\", root)\n if dirPath:\n self.path.setText(dirPath)\n \n def save(self):\n self.settings[platform.system()+'Root'] = self.path.text()\n self.settings['processNum'] = self.processNum.currentIndex() + 1\n self.settings['isAutoSetting'] = self.isAutoSetting.isChecked()\n with open('data/settings.json', 'wb') as f:\n f.write(json.dumps(self.settings).encode())\n self.close()\n\nclass CourseDialog(QDialog):\n def __init__(self,settings):\n super().__init__()\n self.settings = settings\n self.initUI()\n \n def initUI(self):\n self.setWindowTitle(\"课程配置\") # 窗口标题\n self.setGeometry(400,400,1000,250) # 窗口位置与大小\n\n self.tableWidget = QTableWidget(self)\n #self.tableWidget.setGeometry(340, 160, 224, 100)\n self.widths = (60, 200, 200, 200, 200)\n self.tableWidget.setColumnCount(len(self.widths))\n for colNum in range(len(self.widths)):\n self.tableWidget.setColumnWidth(colNum, self.widths[colNum])\n\n self.tableWidget.setHorizontalHeaderLabels(('是否下载', '课程号', '周次', '清晰度', '类型'))\n self.tableWidget.setSelectionMode(QTableWidget.NoSelection)\n self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Fixed) # 表头不可拖动\n self.courseConfigs = []\n\n for rowNum in range(len(self.settings['courseConfigs'])):\n self.tableWidget.insertRow(rowNum)\n courseConfigWdts = CourseConfigWdts(rowNum, self.settings, self.settings['courseConfigs'][rowNum])\n self.courseConfigs.append(courseConfigWdts)\n for colNum in range(len(courseConfigWdts.Wdts)):\n self.tableWidget.setCellWidget(rowNum, colNum, courseConfigWdts.Wdts[colNum])\n\n for rowNum in range(3):\n rowNum += len(self.settings['courseConfigs'])\n self.tableWidget.insertRow(rowNum)\n courseConfigWdts = CourseConfigWdts(rowNum, self.settings, {})\n self.courseConfigs.append(courseConfigWdts)\n for colNum in range(len(courseConfigWdts.Wdts)):\n self.tableWidget.setCellWidget(rowNum, colNum, courseConfigWdts.Wdts[colNum])\n #self.tableWidget.setItem(count, 0, QTableWidgetItem('item0'))\n \n self.addLineBtn = QPushButton('新增空白列')\n self.addLineBtn.clicked.connect(self.addLine)\n self.saveBtn = QPushButton('保存')\n self.saveBtn.clicked.connect(self.save)\n self.cancelBtn = QPushButton('取消')\n self.cancelBtn.clicked.connect(self.close)\n self.hBtnsLayout = QHBoxLayout()\n self.hBtnsLayout.addStretch(1)\n self.hBtnsLayout.addWidget(self.addLineBtn)\n self.hBtnsLayout.addWidget(self.saveBtn)\n self.hBtnsLayout.addWidget(self.cancelBtn)\n \n self.vlayout = QVBoxLayout()\n self.vlayout.addWidget(self.tableWidget)\n self.vlayout.addStretch(1)\n self.vlayout.addLayout(self.hBtnsLayout)\n\n self.setLayout(self.vlayout)\n self.show()\n \n def save(self):\n self.settings['courseConfigs'] = []\n for courseConfig in self.courseConfigs:\n courseConfig = courseConfig.getConfig()\n if courseConfig.get('tid'):\n self.settings['courseConfigs'].append(dict(courseConfig))\n with open('data/settings.json', 'wb') as f:\n f.write(json.dumps(self.settings).encode())\n self.close()\n\n def addLine(self):\n rowNum = len(self.settings['courseConfigs'])\n self.tableWidget.insertRow(rowNum)\n courseConfigWdts = CourseConfigWdts(rowNum, self.settings, {})\n self.courseConfigs.append(courseConfigWdts)\n for colNum in range(len(courseConfigWdts.Wdts)):\n self.tableWidget.setCellWidget(rowNum, colNum, courseConfigWdts.Wdts[colNum])\n\nclass CourseConfigWdts():\n def __init__(self, id, settings, config={}):\n self.id = id\n self.settings = settings\n self.config = config\n \n self.isLoad = QCheckBox()\n self.tid = QLineEdit()\n self.tidBtn = QPushButton('...')\n self.tidBtn.clicked.connect(lambda : self.selectTid())\n self.weekNumStart = QComboBox()\n self.weekNumStart.addItem(\"1\")\n self.weekNumSep = QLabel('~')\n self.weekNumEnd = QComboBox()\n self.weekNumEnd.addItem(\"1\")\n self.isShd = QRadioButton('超清')\n self.isHd = QRadioButton('高清')\n self.isSd = QRadioButton('标清')\n self.isSd.toggle()\n self.loadType1 = QCheckBox('视频')\n self.loadType1.toggle()\n self.loadType3 = QCheckBox('文档')\n self.loadType3.toggle()\n self.loadType4 = QCheckBox('附件')\n self.loadType4.toggle()\n\n self.isloadWdt = self.newWdts([self.isLoad])\n self.tidWdt = self.newWdts([self.tid, self.tidBtn])\n self.weekNumWdt = self.newWdts([self.weekNumStart, self.weekNumSep, self.weekNumEnd])\n self.sharpnessWdt = self.newWdts([self.isShd, self.isHd, self.isSd])\n self.loadTypeWdt = self.newWdts([self.loadType1, self.loadType3, self.loadType4])\n\n self.lbls = ('是否下载', '课程号', '周次', '类型', '清晰度')\n self.Wdts = (self.isloadWdt, self.tidWdt, self.weekNumWdt, self.loadTypeWdt, self.sharpnessWdt)\n\n if self.config:\n try:\n self.refInfo(self.config['tid'])\n except Exception as e:\n print(e)\n self.isLoad.setChecked(self.config.get('isLoad',False))\n self.tid.setText(self.config.get('tid',''))\n self.weekNumStart.setCurrentIndex(self.config.get('weekNum', [0])[0])\n self.weekNumEnd.setCurrentIndex(self.config.get('weekNum', [0])[-1])\n self.loadType1.setChecked(1 in self.config.get('loadType', [1,3,4]))\n self.loadType3.setChecked(3 in self.config.get('loadType', [1,3,4]))\n self.loadType4.setChecked(4 in self.config.get('loadType', [1,3,4]))\n self.isSd.setChecked(self.config.get('sharpness', 'sd') == 'sd')\n self.isShd.setChecked(self.config['sharpness'] == 'shd')\n self.isHd.setChecked(self.config['sharpness'] == 'hd')\n \n \n\n def newWdts(self, wdts):\n widget = QWidget()\n hLayout = QHBoxLayout()\n for wdt in wdts:\n hLayout.addWidget(wdt)\n hLayout.setContentsMargins(5,2,5,2)\n widget.setLayout(hLayout)\n return widget\n\n def refInfo(self, tid):\n self.courseinfo = get_courseinfo(tid, self.settings.get('mob_token'))\n self.courseDto = self.courseinfo.get('results').get('courseDto')\n self.cid = self.courseDto.get('id')\n self.coursename = self.courseDto.get('name')\n self.chapters = self.courseinfo.get('results').get('termDto').get('chapters')\n self.config['courseinfo'] = self.courseinfo\n self.config['courseDto'] = self.courseDto\n self.config['cid'] = self.cid\n self.config['coursename'] = self.coursename\n self.config['chapters'] = self.chapters\n for weekNum in range(len(self.chapters)):\n num = str(weekNum + 1)\n if self.weekNumStart.findText(num) == -1:\n self.weekNumStart.addItem(num)\n if self.weekNumEnd.findText(num) == -1:\n self.weekNumEnd.addItem(num)\n\n def selectTid(self):\n selectTidDialog = SelectTidDialog()\n if selectTidDialog.exec_():\n tid = selectTidDialog.getTid()\n self.tid.setText(tid)\n self.refInfo(tid)\n\n def getConfig(self):\n if self.tid.text():\n self.config['id'] = self.id\n self.config['isLoad'] = self.isLoad.isChecked()\n self.config['tid'] = self.tid.text()\n self.config['weekNum'] = list(range(self.weekNumStart.currentIndex(), self.weekNumEnd.currentIndex()+1))\n p = [1,3,4]\n self.config['loadType'] = list(filter(lambda b:(self.loadType1.isChecked(),self.loadType3.isChecked(),self.loadType4.isChecked())[p.index(b)], p))\n self.config['sharpness'] = ['shd', 'hd', 'sd'][(self.isShd.isChecked(), self.isHd.isChecked(), self.isSd.isChecked()).index(True)]\n else:\n self.config = {}\n #print(self.config)\n return self.config\n\nclass SelectTidDialog(QDialog):\n def __init__(self):\n super().__init__()\n self.initUI()\n \n def initUI(self):\n self.setWindowTitle(\"课程号查询\") # 窗口标题\n self.setGeometry(400,400,400,250) # 窗口位置与大小\n\n self.cid = QLineEdit()\n self.selectBtn = QPushButton('Search')\n self.selectBtn.clicked.connect(self.search)\n self.tidRbs = QFrame()\n self.vRbsLayout = QVBoxLayout()\n self.vRbsLayout.addStretch(1)\n self.tidRbs.setLayout(self.vRbsLayout)\n \n self.buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) #窗口中建立确认和取消按钮\n self.vlayout = QVBoxLayout()\n self.selectBox = QHBoxLayout()\n self.selectBox.addWidget(self.cid)\n self.selectBox.addWidget(self.selectBtn)\n self.vlayout.addLayout(self.selectBox)\n self.vlayout.addWidget(self.tidRbs)\n self.vlayout.addStretch(1)\n\n self.hBtnsLayout = QHBoxLayout()\n self.hBtnsLayout.addStretch(1)\n self.hBtnsLayout.addWidget(self.buttons)\n self.vlayout.addLayout(self.hBtnsLayout)\n \n self.buttons.accepted.connect(self.accept)\n self.buttons.rejected.connect(self.reject)\n \n self.setLayout(self.vlayout)\n self.show()\n\n def search(self):\n #self.tidRbs = QFrame()\n #self.vRbsLayout.clear()\n self.coursename, self.terminfos = getterminfos(self.cid.text())\n if self.coursename:\n self.vRbsLayout.addWidget(QLabel('课程名:{}'.format(self.coursename)))\n self.Rbs = []\n for termnum in range(len(self.terminfos)):\n terminfo = self.terminfos[termnum]\n rb = QRadioButton('第%d次开课:'%(termnum+1)+terminfo['text']+',课程号:'+terminfo['id'])\n self.Rbs.append(rb)\n self.vRbsLayout.addWidget(rb)\n else:\n self.vRbsLayout.addWidget(QLabel('未匹配到任何课程,请重试'))\n #self.vRbsLayout.addStretch(1)\n #self.tidRbs.setLayout(self.vRbsLayout)\n \n def getTid(self):\n for index in range(len(self.Rbs)):\n if self.Rbs[index].isChecked():\n return self.terminfos[index]['id']\n\nclass AboutDialog(QDialog):\n def __init__(self):\n super().__init__()\n self.initUI()\n \n def initUI(self):\n self.setWindowTitle(\"关于\") # 窗口标题\n self.setGeometry(400,400,300,200) # 窗口位置与大小\n\n try:\n self.versionLbl = QLabel('版本号:{}'.format('.'.join(list(map(lambda x:str(x),version)))))\n except Exception as e:\n print(e)\n self.selectNewVer = QPushButton('检查更新')\n self.newVerInfoLbl = QLabel('当前版本已为最新版本!')\n \n self.buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) #窗口中建立确认和取消按钮\n self.vlayout = QVBoxLayout()\n self.vlayout.addWidget(self.versionLbl)\n self.vlayout.addWidget(self.selectNewVer)\n self.vlayout.addWidget(self.newVerInfoLbl)\n #self.vlayout.addStretch(1)\n\n self.hBtnsLayout = QHBoxLayout()\n self.hBtnsLayout.addStretch(1)\n self.hBtnsLayout.addWidget(self.buttons)\n self.vlayout.addLayout(self.hBtnsLayout)\n \n self.buttons.accepted.connect(self.accept)\n self.buttons.rejected.connect(self.reject)\n \n self.setLayout(self.vlayout)\n self.show()\n \nif __name__ == '__main__':\n \n app = QApplication(sys.argv)\n ex = MOOC_Downloading()\n sys.exit(app.exec_()) \n","repo_name":"ghwolf1/MOOC_Downloading","sub_path":"GUI.py","file_name":"GUI.py","file_ext":"py","file_size_in_byte":28253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"9756286841","text":"from imageai.Prediction import ImagePrediction\nimport os\n\nexecution_path = os.getcwd()\n\nprediction = ImagePrediction()\nprediction.setModelTypeAsResNet()\nprediction.setModelPath(os.path.join(execution_path, \"models/resnet50_weights_tf_dim_ordering_tf_kernels.h5\")) #\"DenseNet-BC-121-32.h5\"))\nprediction.loadModel()\n\npredictions, probabilities = prediction.predictImage(os.path.join(execution_path, \"images/B005tqTBqrY.jpg\"), result_count=5 )\nfor eachPrediction, eachProbability in zip(predictions, probabilities):\n print(eachPrediction , \" : \" , eachProbability)\n","repo_name":"Amin-Azar/Indoor-Object-Detection","sub_path":"prediction.py","file_name":"prediction.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"4872788152","text":"#~/usr/bin/python3\n\n'''\nQuestion: Let s be a string that contains a sequence of decimal numbers separated by commas, e.g., s = '1.23,2.4,3.123'. Write a program that prints the sum of the numbers in s.\n'''\n\ns = '1.23,2.4,3.123'\nsum_ = 0\nfor x in s.split(\",\"):\n\tsum_ = sum_ + float(x)\nprint(sum_)\n","repo_name":"abhisharma7/RandomCode","sub_path":"Chapter3/finger_exercise_2_string.py","file_name":"finger_exercise_2_string.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"45666156636","text":"def make_divisor(n):\n div = []\n for i in range(1, n+1):\n if n % i == 0:\n div.append(i)\n return div\n\ndef solution(left, right):\n answer = 0\n for i in range(left, right+1):\n if len(make_divisor(i)) % 2 == 0:\n answer += i\n else:\n answer -= i\n \n return answer","repo_name":"seunga2590/Coding_test","sub_path":"프로그래머스/lv1/77884. 약수의 개수와 덧셈/약수의 개수와 덧셈.py","file_name":"약수의 개수와 덧셈.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20242216197","text":"from typing import Any\n\nimport yaml\n\n\ndef load_config_yaml() -> Any:\n with open(\"../conf/config.yaml\", \"r\") as stream:\n try:\n config = (yaml.safe_load(stream))\n except yaml.YAMLError as exc:\n print(exc)\n return config\n","repo_name":"bikash-jha2829/tweets_stream","sub_path":"utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42799770715","text":"# Ref: https://nextjournal.com/gkoehler/pytorch-mnist\n\nimport torch\nimport torchvision\nimport torch.nn.functional as F\n\n\nimport matplotlib.pyplot as plt\n\ndef displayImages(training_data,training_targets):\n fig = plt.figure()\n for i in range(6):\n plt.subplot(2,3,i+1)\n plt.tight_layout()\n plt.imshow(training_data[i][0], cmap='gray', interpolation='none')\n plt.title(\"Ground Truth: {}\".format(training_targets[i]))\n plt.xticks([])\n plt.yticks([])\n plt.show()\n\n\n\n\n\n# For repeatable experiments we have to set random seeds for anything using random number generation\nrandom_seed = 1\n# cuDNN uses nondeterministic algorithms which can be disabled\ntorch.backends.cudnn.enabled = False\ntorch.manual_seed(random_seed)\n\nn_epochs = 1\nbatch_size_train = 64\nbatch_size_test = 1000\nlearning_rate = 0.01\nmomentum = 0.5\nlog_interval = 10\n\n# num_workers > 1 to use subprocesses to asynchronously load data or using pinned RAM (via pin_memory)\n# to speed up RAM to GPU transfers.\n\nnum_workers=4\n\n\n\n\ndata_transformer=torchvision.transforms.Compose([\n torchvision.transforms.ToTensor(),\n torchvision.transforms.Normalize((0.1307,), (0.3081,))])\n\n\ntrain_dataset=torchvision.datasets.MNIST(root='../data', train= True, transform = data_transformer, download = True)\ntest_dataset=torchvision.datasets.MNIST(root='../data', train= False, transform = data_transformer, download = True)\n\n\ntrain_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size_train,\n shuffle=True, num_workers=num_workers)\n\n\ntest_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size_test,\n shuffle=True, num_workers=num_workers)\n\ntrain_iter=iter(train_loader)\n\n\nexample_data, example_targets=train_iter.next()\n# Batch size of train, Number of Channels, Height, Width\nprint(\"Batch size of train, Number of Channels, Height, Width:\", example_data.shape)\nprint(example_targets.data)\n\n# \"lables:\",\ndisplayImages(example_data, example_targets)\n\n\ntrain_losses = []\ntrain_counter = []\ntest_losses = []\ntest_counter = [i*len(train_loader.dataset) for i in range(n_epochs + 1)]\n\n\n\nclass Net(torch.nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1=torch.nn.Conv2d(in_channels = 1,out_channels = 10,kernel_size=5)\n self.conv2=torch.nn.Conv2d(in_channels = 10,out_channels = 20,kernel_size=5)\n self.conv2_drop = torch.nn.Dropout2d()\n self.fc1 = torch.nn.Linear(320, 50)\n self.fc2 = torch.nn.Linear(50, 10)\n def forward(self,x):\n x = F.relu(F.max_pool2d(self.conv1(x), 2))\n x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))\n x = x.view(-1, 320)\n x = F.relu(self.fc1(x))\n x = F.dropout(x, training=self.training)\n x = self.fc2(x)\n return F.log_softmax(x)\n\n def reset_parameters(self):\n print(\"****************** reset parameters happend ****************** \")\n\n def initialize_weight(self):\n for m in self.modules():\n if isinstance(m, torch.nn.Conv2d):\n torch.nn.init.kaiming_uniform_(m.weight)\n elif isinstance(m,torch.nn.BatchNorm2d):\n pass\n\ndef train(n_epochs,optimizer,network,criterion):\n network.train()\n\n for epoch in range(n_epochs):\n for batch_idx, (data, target) in enumerate(train_loader):\n optimizer.zero_grad()\n output = network(data)\n loss = criterion(output, target)\n loss.backward()\n optimizer.step()\n if batch_idx % log_interval == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_idx * len(data), len(train_loader.dataset),\n 100. * batch_idx / len(train_loader), loss.item()))\n train_losses.append(loss.item())\n train_counter.append(\n (batch_idx * 64) + ((epoch - 1) * len(train_loader.dataset)))\n torch.save(network.state_dict(), '../saved_networks/MNIST/model.pth')\n torch.save(optimizer.state_dict(), '../saved_networks/MNIST/optimizer.pth')\n\n\n\n\ndef test(network,test_loader,criterion):\n network.eval()\n test_loss = 0\n correct = 0\n with torch.no_grad():\n for data, target in test_loader:\n output = network(data)\n # test_loss += F.nll_loss(output, target, size_average=False).item()\n test_loss += criterion(output, target).item()\n pred = output.data.max(1, keepdim=True)[1]\n print(\"output.shape: \",output.shape)\n print(\"pred: \",pred)\n print(\"pred.shape:\", pred.shape)\n correct += pred.eq(target.data.view_as(pred)).sum()\n test_loss /= len(test_loader.dataset)\n test_losses.append(test_loss)\n print('\\nTest set: Avg. loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\\n'.format(\n test_loss, correct, len(test_loader.dataset),\n 100. * correct / len(test_loader.dataset)))\n\n\n\nnetwork=Net()\n\n# optimizer=torch.optim.Adam(network.parameters())\noptimizer = torch.optim.SGD(network.parameters(), lr=learning_rate, momentum=momentum)\n# criterion=F.nll_loss()\ncriterion=torch.nn.NLLLoss()\n\n# example_data, example_targets\n\n\n\noutput = network.forward(example_data[0:1])\nloss = criterion(output, example_targets[0:1])\n\nprint(\"example_targets[0:1]: \",example_targets[0:1])\nprint(\"example_data[0:1].shape: \",example_data[0:1].shape)\nprint(\"output: \",output)\nprint(\"output: \",output.exp())\nprint(\"loss:\", loss)\nprint(\"loss.item(): \",loss.item())\n\n\n\n\n\n# train(n_epochs,optimizer,network,criterion)\n# test(network,test_loader,criterion)\n\n\n\n\n\n","repo_name":"behnamasadi/PyTorchTutorial","sub_path":"learning_steps_strategy/MNIST_classification.py","file_name":"MNIST_classification.py","file_ext":"py","file_size_in_byte":5752,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"41033363381","text":"class Solution:\n def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:\n sentence = ' ' + sentence\n searchWord = ' ' + searchWord\n L = len(searchWord)\n save = 0\n for i in range(len(sentence)):\n if sentence[i] == ' ': save += 1\n if sentence[i:i + L] == searchWord:\n return save\n return -1\n\n\na = Solution()\nprint(a.isPrefixOfWord(\"i use triple pillow\",\"pill\"))","repo_name":"lishx-archive/Leetcode","sub_path":"比赛/190场周赛/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33706882151","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport mplhep as hep\nfrom scipy.signal import savgol_filter\nfrom scipy.signal import find_peaks\nfrom scipy.signal import argrelextrema\nfrom sklearn.preprocessing import *\n\nhep.style.use(\"CMS\")\n\ndata = pd.read_csv(r\"Abs Laser\\Data\\06-03-2023\\A\\ALL2.CSV\")\n\n\nx_axis = data['in s']\n# channel_1 = np.array(data['C1 in V'])\n# channel_2 = np.array(data['C2 in V'])\nchannel_1 = np.array(data['C1 in V'])\nchannel_2 = np.array(data['C2 in V'])\n# print(len(channel_2))\nrel_size=0.07\nwindow_length = round(rel_size*len(channel_2)/2)*2+1\nprint(window_length)\n\nc1_filter = savgol_filter(channel_1,window_length,3)\nc2_filter = savgol_filter(channel_2,window_length,3)\n\nindex_c1 = np.array(find_peaks(-1*c1_filter,distance=20))\nindex_c2 = np.array(find_peaks(-1*c2_filter,distance=20))\n# print(index_c1)\npeaks_c1 = c1_filter[index_c1[0]]\npeaks_c2 = c2_filter[index_c2[0]]\n\n\n\nc1_max = min(channel_1)\nc2_max = min(channel_2)\n\n# channel_1 = channel_1/min(channel_1)\n# channel_2 = channel_2/min(channel_2)\n\n# scaler = MinMaxScaler()\n# scaler.fit(channel_1)\n\n# c1_norm = scaler.transform(channel_1)\n# c2_norm = scaler.transform(channel_2)\ntrain_df = pd.DataFrame({'colA': channel_1})\ntest_df = pd.DataFrame({'colA': channel_2})\n\n# scaler = MinMaxScaler()\n# scaler = MaxAbsScaler()\n# scaler = Normalizer()\nscaler = StandardScaler()\nscaler.fit(train_df)\n\nc1_norm = scaler.transform(train_df)\nc2_norm = scaler.transform(test_df)\n# print(c1_max,c2_max)\n# plt.plot(x_axis,np.log(channel_1),label=\"Log Channel 1\")\n\n# plt.plot(x_axis,channel_1,label=\"Channel 1\")\n# plt.plot(x_axis,channel_2,label=\"Channel 2\")\nplt.plot(x_axis,c1_norm,label=\"Channel 1\")\nplt.plot(x_axis,c2_norm,label=\"Channel 2\")\nplt.plot(x_axis,channel_2-channel_1,label=\"Channel Difference\")\n# plt.plot(x_axis,c2_norm-c1_norm,label=\"Channel Difference\")\n\n# # plt.plot(x_axis,c1_filter,label=\"Filter C1\")\n# # plt.plot(x_axis,c2_filter,label=\"Filter C2\")\n# # plt.scatter(x_axis[index_c1[0]],peaks_c1,color='black')\n# # plt.scatter(x_axis[index_c2[0]],peaks_c2,color='red')\n\nplt.grid(alpha=0.5)\nplt.legend(loc=\"upper right\")\nplt.xlabel(\"Time (seconds)\")\nplt.ylabel(\"Voltage\")\nplt.show()\n\n","repo_name":"Jacob-J-E/Y3Lab","sub_path":"Abs_Laser/initial.py","file_name":"initial.py","file_ext":"py","file_size_in_byte":2196,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"74851372304","text":"\"\"\"\n# -*- coding: utf-8 -*-\n@author: Hongzhi Fu\n\"\"\"\n\nimport random\nimport time\n\n# implementation of heap sort\n# to sort a random array with 10,000 elements\n# two metrics (\"number of comparison\" and \"consumed time\") for efficiency evaluation\n# time complexity: Θ(nlog n) in all cases\n# space complexity: Θ(1)\n# stability: unstable\n\nrandom.seed(1) # for reproducibility\n\ndef heaplify(array, temp_idx, size):\n cnt = 0\n temp_val = array[temp_idx] # store value temporarily\n heap = False\n while not heap and 2 * temp_idx + 1 < size:\n j = 2 * temp_idx + 1 # index of left child\n # right child exists\n if j < size - 1:\n # compare two children\n if array[j] < array[j+1]:\n j = j + 1\n cnt += 1\n # whether violate heap property or not\n if array[j] <= temp_val:\n heap = True\n else:\n array[temp_idx] = array[j]\n temp_idx = j # update temp_idx\n cnt += 1\n array[temp_idx] = temp_val\n return cnt\n\ndef heap_sort(array):\n cnt = 0\n for i in range((len(array)-2)//2, -1, -1):\n cnt += heaplify(array, i, len(array))\n for i in range(len(array)-1, -1, -1):\n array[0], array[i] = array[i], array[0] # swap the first element with the last one\n cnt += heaplify(array, 0, i)\n return cnt\n\n\ntime_in_total = 0\nepoch = 5 # num of iteration\ntotal_comparison = 0\n\nfor i in range(epoch):\n time_start = time.time()\n array = [random.randint(0,10000) for i in range(10000)]\n comparison = heap_sort(array)\n time_finish = time.time()\n total_comparison += comparison\n time_in_total += time_finish - time_start\n print(\"Epoch {}: \\n number of comparison: {}\\n time consumed: {:.4f} s\".format(i+1, comparison, time_finish-time_start))\nprint(\"average number of comparison: %d\" % (total_comparison/epoch))\nprint('average time consumed: {:.4f} s'.format(time_in_total/epoch))\n\n","repo_name":"infinityglow/Algorithm-and-Complexity","sub_path":"Transform and Conquer/Heap Sort/heap sort.py","file_name":"heap sort.py","file_ext":"py","file_size_in_byte":1939,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"48"} +{"seq_id":"11141432400","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom astropy import units\nfrom astropy.io import fits\nfrom photutils import EllipticalAnnulus,CircularAnnulus,EllipticalAperture,RectangularAperture\nfrom photutils import aperture_photometry\nfrom mcmax3d_analysis.mcmax3d_convolution import convolve_observation\nimport matplotlib.gridspec as gridspec\nimport sys\nfrom astropy.table import Table\nplt.style.use('fancy')\n\n\ndef toAU(x,y,xc,yc,pxsize,d):\n\n ############################################################\n #\n # d: distance to the source in pc\n # pxsize: pixel scale in arcsec/px\n #\n # Return: Length in AU\n #\n ############################################################\n\n dr=((x-xc)**2+(y-yc)**2)**0.5\n dr=(dr*pxsize)\n dr=(dr*units.arcsec).to(units.rad).value\n dr=dr*((d*units.pc).to(units.au).value)\n if x<=xc:\n return +1.0*dr\n else:\n return -1.0*dr\n\n\ndef topx(l,pxsize,d):\n\n ############################################################\n #\n # d: distance to the source in pc\n # pxsize: pixel scale in arcsec/px\n #\n # Return: Length in pixels\n #\n ############################################################\n\n x=(l*units.au).to(units.pc).value\n x=((x/d)*units.rad).to(units.arcsec).value\n x=x/pxsize\n return x\n\n\ndef get_profile(file,pxsize,PA_disk,inc,d,size,padir,widir,dr,**kwargs):\n \n ############################################################\n # \n # Extract a radial cut of the brightness along diffent \n # position angles.\n # \n # file: the fits file of the observation\n # pxsize: pixel scale (arcsec/px)\n # PA_aperture: position angle of the aperture measured east-north (deg)\n # inc: disk's inclination (deg)\n # d: distance to the source (pc)\n # size: semi-major axis of the disk (AU)\n # padir: position angle of the desired direction (deg)\n # widir: width of the cone along the desired direction (deg)\n # dr: width of the annulus (AU)\n # \n # The ouput is a matrix whose the rows and columns represent\n # the position angle and the radial distance of the flux \n # measurement.\n #\n ############################################################\n\n\n ############################################################\n # Load ALMA data\n if kwargs['type']=='obs':\n hdulist=fits.open(file)\n data_obs=hdulist[0].data[0][0]\n \"\"\"\n xc=hdulist[0].header['CRPIX1']\n yc=hdulist[0].header['CRPIX2']\n \"\"\"\n xc=data_obs.shape[1]*0.5\n yc=data_obs.shape[0]*0.5\n \n elif kwargs['type']=='mod':\n hdulist=fits.open(file)\n data_obs=hdulist[0].data\n xc=data_obs.shape[0]*0.5\n yc=data_obs.shape[1]*0.5\n \n\n ############################################################\n # Derived properties\n angle_annulus=((PA_disk-90.0)*units.deg).to(units.rad).value \n if padir<270.0:\n padir=padir+90.0\n else:\n padir=padir-270.0\n e=np.sin((inc*units.deg).to(units.rad).value) \n d_au=(d*units.pc).to(units.au).value \n xc_array=[]\n yc_array=[]\n\n\n ############################################################\n # Creating elliptical aperture\n linear_lim=2*(size) # AU\n angular_lim=linear_lim/d_au # rad\n angular_lim=(angular_lim*units.rad).to(units.arcsec).value # arcsec\n pixel_lim=int(round(angular_lim/pxsize))\n dr=topx(dr,pxsize,d) # width of each annular aperture\n a_in_array=[]\n for i in np.arange(yc+dr,yc+0.5*pixel_lim,dr):\n a_in_array.append(i-xc)\n a_out_array=[i+dr for i in a_in_array]\n b_out_array=[i*(1-e**2)**0.5 for i in a_out_array]\n a_in_array=np.array(a_in_array)\n a_out_array=np.array(a_out_array)\n apertures=[EllipticalAnnulus((yc,xc),a_in=ain,a_out=aout,b_out=bout,theta=angle_annulus)\n for (ain,aout,bout) in zip(a_in_array,a_out_array,b_out_array)]\n\n print(\"Number of annular apertures: %d\"%len(apertures))\n \"\"\"\n # Do a check?\n plt.imshow(data_obs)\n apertures[-1].plot(color='red',lw=1)\n plt.show()\n \"\"\"\n\n ############################################################\n # Determine Nbins\n Nbins=round(360.0/widir)\n\n\n ############################################################\n # Define class \"Bin\"\n class Bin:\n def __init__(self,ID,theta_min,theta_max,plist):\n self.ID=ID\n self.theta_min=theta_min\n self.theta_max=theta_max\n self.plist=plist\n\n def showFlux(self):\n i=0\n for pixel in self.plist:\n print(i,aperture_data[pixel[0],pixel[1]])\n i+=1\n\n def getArea(self,aperture):\n value=aperture.area/Nbins\n return value\n\n def getFlux(self):\n flux=0.0\n for pixel in self.plist:\n flux+=aperture_data[pixel[0],pixel[1]]\n return flux\n\n def getTheta(self):\n value=(self.theta_max-self.theta_min)*0.5+self.theta_min\n return value\n\n def getError_beam(self,aperture):\n beam_x=0.074 # arcsec\n beam_y=0.057 # arcsec\n flux_array=[]\n for pixel in self.plist:\n flux_array.append(aperture_data[pixel[0],pixel[1]])\n area=aperture.area/Nbins\n flux_array=np.array(flux_array)#/area\n sigma=np.std(flux_array)\n beam_area=np.pi*(beam_x)*(beam_y)/(4*np.log(2)) \n Nbeam=((aperture.area*pxsize**2)/Nbins)/beam_area\n return sigma/(Nbeam)**0.5\n\n def getError_pixel(self,aperture):\n flux_array=[]\n for pixel in self.plist:\n flux_array.append(aperture_data[pixel[0],pixel[1]])\n area=aperture.area/Nbins\n flux_array=np.array(flux_array)/area\n sigma=np.std(flux_array)\n Npixel=len(self.plist)\n return sigma/(Npixel)**0.5\n \n M=[]\n E_beam=[]\n E_pixel=[]\n \n a_in_array=[i*pxsize*d for i in a_in_array]\n a_out_array=[i*pxsize*d for i in a_out_array]\n a_mid=np.array([(j-i)*0.5+i for (j,i) in zip(a_out_array,a_in_array)])\n \n meanpxn=[]\n for ii in range(0,len(apertures)):\n\n ############################################################\n # Creating bin\n sbin=Bin(ii,padir-0.5*widir,padir+0.5*widir,[]) \n\n\n ############################################################\n # Creating aperture mask\n mask=apertures[ii].to_mask(method=\"center\")\n \"\"\"\n # Do a check?\n plt.imshow(mask)\n plt.colorbar()\n plt.show()\n \"\"\"\n\n ############################################################\n # Extracting pixels located inside the aperture\n aperture_data=mask.multiply(data_obs)\n \"\"\"\n # Do a check?\n plt.imshow(aperture_data)\n plt.colorbar()\n plt.show()\n \"\"\"\n\n ############################################################\n # Creating array of pixel's index within the aperture \n # relative to the star\n pixel_list=[]\n ycc=int(aperture_data.shape[0]*0.5)\n xcc=int(aperture_data.shape[1]*0.5)\n for i in range(0,aperture_data.shape[1]): # Over columns \n for j in range(0,aperture_data.shape[0]): # Over rows\n if aperture_data[j,i]!=0.0:\n pixel_list.append((j-ycc,i-xcc))\n\n\n ############################################################\n # Filling in sbin data\n for point in pixel_list:\n phi=np.arctan2(point[0],point[1])\n if phi<0.0:\n phi=2*np.pi+phi\n phi=phi*180.0/np.pi\n if sbin.theta_min<=phi 0:\n sdofitspath = sdofitspath + sdofitspathtmp\n if len(sdofitspath) == 0:\n if isexists:\n return sdofitspath\n else:\n raise ValueError(\n 'No SDO file found under {} at the time range of {} to {}. Download the data with EvtBrowser first.'.format(\n datadir,\n jdtimestr[0],\n jdtimestr[1]))\n sdofits = [os.path.basename(ll) for ll in sdofitspath]\n sdotimeline = Time(\n [insertchar(insertchar(ll.split('.')[2].replace('T', ' ').replace('Z', ''), ':', -4), ':', -2) for ll in\n sdofits],\n format='iso', scale='utc')\n sdofitspathnew = [x for (y, x) in sorted(zip(sdotimeline.jd, sdofitspath))]\n sdofitsnew = [os.path.basename(ll) for ll in sdofitspathnew]\n sdotimelinenew = Time(\n [insertchar(insertchar(ll.split('.')[2].replace('T', ' ').replace('Z', ''), ':', -4), ':', -2) for ll in\n sdofitsnew], format='iso',\n scale='utc')\n sdofile = list(\n np.array(sdofitspathnew)[\n np.where(np.logical_and(trange[0].jd <= sdotimelinenew.jd, sdotimelinenew.jd <= trange[1].jd))[0]])\n return sdofile\n else:\n jdtimstr = trange.iso\n ymd = jdtimstr.split(' ')[0].split('-')\n if ignoreymdpath:\n sdofitspath = glob.glob(\n os.path.join(datadir,'aia.lev1_*Z.{}.{}.fits'.format(wavelength,suffix)))\n else:\n sdofitspath = glob.glob(\n datadir + '/{}/{}/{}/aia.lev1_*Z.{}.{}.fits'.format(ymd[0], ymd[1], ymd[2], wavelength,suffix))\n if len(sdofitspath) == 0:\n return [] # raise ValueError('No SDO file found under {}.'.format(datadir))\n sdofits = [os.path.basename(ll) for ll in sdofitspath]\n sdotimeline = Time(\n [insertchar(insertchar(ll.split('.')[2].replace('T', ' ').replace('Z', ''), ':', -4), ':', -2) for ll in\n sdofits],\n format='iso', scale='utc')\n if timtol < np.min(np.abs(sdotimeline.jd - trange.jd)):\n return [] # raise ValueError('No SDO file found at the select timestamp. Download the data with EvtBrowser first.')\n idxaia = np.argmin(np.abs(sdotimeline.jd - trange.jd))\n sdofile = sdofitspath[idxaia]\n if isexists:\n return sdofile\n else:\n try:\n sdomap = sunpy.map.Map(sdofile)\n return sdomap\n except:\n raise ValueError('File not found or invalid input')\n\n\ndef get_map_corner_coord(sunpymap):\n bottom_left_coord = sunpymap.bottom_left_coord\n top_right_coord = sunpymap.top_right_coord\n if hasattr(sunpymap.top_right_coord, 'Tx'):\n x0, y0 = bottom_left_coord.Tx, bottom_left_coord.Ty\n x1, y1 = top_right_coord.Tx, top_right_coord.Ty\n else:\n x0, y0 = bottom_left_coord.lon, bottom_left_coord.lat\n x1, y1 = top_right_coord.lon, top_right_coord.lat\n unit = x0.unit\n return np.array([x0.value, x1.value, y0.value, y1.value]) * unit\n","repo_name":"suncasa/suncasa-src","sub_path":"suncasa/utils/stputils.py","file_name":"stputils.py","file_ext":"py","file_size_in_byte":9316,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"48"} +{"seq_id":"26302993407","text":"import random\nfrom flask import Flask, request, render_template\n\napp = Flask(__name__)\n\n\ndef initialize_game():\n global human_cards, computer_cards, draw_pile, cards\n\n # Card deck initialization\n weights = [9, 8, 7, 6, 5, 4, 3, 2, 1, 1]\n cards = random.choices(range(10), weights=weights, k=100)\n\n # Card allocation to players\n human_cards = cards[:4]\n computer_cards = cards[4:8]\n draw_pile = cards[8:]\n\ndef human_turn():\n global human_cards, draw_pile\n card_index = int(request.form['card_index'])\n human_cards[card_index] = draw_pile.pop()\n\ndef computer_turn():\n global computer_cards, draw_pile\n max_card_index = computer_cards.index(max(computer_cards))\n computer_cards[max_card_index] = draw_pile.pop()\n\ndef game():\n global human_cards, computer_cards, draw_pile, discard_pile, last_round, human_turn\n initialize_game()\n human_turn = True\n while not last_round:\n if human_turn:\n human_turn()\n else:\n computer_turn()\n if len(draw_pile) == 0:\n last_round = True\n human_turn = not human_turn\n last_round()\n\n@app.route('/')\ndef index():\n game()\n return render_template('index.html', human_cards=human_cards, computer_cards=computer_cards)\n\n@app.route('/replace_card', methods=['POST'])\ndef replace_card():\n global human_cards, cards\n\n # get the card index from the form data\n card_index = int(request.form['card_index'])\n\n # draw a new card from the deck\n new_card = cards.pop()\n\n # render the replace card template with the new card value\n return render_template('replace_card.html',\n new_card=new_card, old_card=human_cards[card_index],\n card_index=card_index,\n human_cards=human_cards)\n\n@app.route('/replace_card_confirm', methods=['POST'])\ndef replace_card_confirm():\n global human_cards, human_turn\n\n # get the card index and whether to keep the card from the form data\n card_index = int(request.form['card_index'])\n keep_card = request.form.get('keep_card')\n\n # if the player chooses to keep the card, update their hand\n if keep_card == 'true':\n human_cards[card_index] = int(request.form['new_card'])\n\n # end the human turn\n human_turn = False\n\n # render the index template with the updated hands\n return render_template('index.html', human_cards=human_cards, computer_cards=computer_cards)\n\n\n@app.route('/last_round', methods=['POST'])\ndef last_round():\n computer_turn()\n return render_template('result.html', human_score=sum(human_cards), computer_score=sum(computer_cards))\n\nif __name__ == '__main__':\n app.run()\n","repo_name":"robert-sturrock/rat_a_tat_cat","sub_path":"scratch.py","file_name":"scratch.py","file_ext":"py","file_size_in_byte":2694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"24647252528","text":"import nltk\nimport math\nimport json\nfrom collections import Counter\n\nwith open('gulo_train.txt', 'r') as file:\n data = file.read()\n\ntokens = nltk.word_tokenize(data)\nlength = len(tokens)\nprint(length)\n\nc=Counter(tokens)\n\nlogprobs={}\nfor t,count in c.items():\n logprobs[t]=math.log2(count)-math.log2(length)+math.log2(10**9)\n\nwith open('freqs.txt','w') as f:\n json.dump(logprobs, f)","repo_name":"vboyce/amaze-natural-stories","sub_path":"Prep_code/make_unigrams.py","file_name":"make_unigrams.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"26955789007","text":"import xlsxwriter as exc\r\nimport PySimpleGUI as sg\r\nimport convert as con\r\n\r\n\r\nsg.theme('DarkAmber')\r\ndef works(data,workbook,worksheet,file):\r\n judul = [\"Name\",\"Height (cm)\",\"Weight (cm)\",\"BMI\",\"Status\"]\r\n worksheet.write(0,0,judul[0])\r\n worksheet.write(0,1,judul[1])\r\n worksheet.write(0,2,judul[2])\r\n worksheet.write(0,3,judul[3])\r\n worksheet.write(0,4,judul[4])\r\n\r\n row=1\r\n col=0\r\n for nama,tb,bb,bmi,stat in data:\r\n worksheet.write(row,col,nama)\r\n worksheet.write(row,col+1,tb)\r\n worksheet.write(row,col+2,bb)\r\n worksheet.write(row,col+3,bmi)\r\n worksheet.write(row,col+4,stat)\r\n row+=1\r\n\r\n workbook.close()\r\n\r\n layout = [\r\n [sg.Text('\\n'*4)],\r\n [sg.Text('\\n\\t Convert file to CSV ? ',)],\r\n [sg.Text('\\n\\n\\t '),sg.Submit(\"Yes\",size=(8,2)), sg.Cancel('No',size=(8,2))]\r\n ]\r\n window = sg.Window('BMI to Excel',layout, size = (350,400))\r\n event,values = window.read()\r\n if event=='Yes':\r\n con.convert(file)\r\n window.close()\r\n else:\r\n window.close()\r\n sg.popup(\"Done\")\r\n \r\ndef inp(n,workbook,worksheet,file):\r\n data=[0]*n\r\n count=0\r\n for i in range(n):\r\n layout = [\r\n [sg.Text(\"\\n\")],\r\n [sg.Text(\"Data\"),sg.Text(i+1),sg.Text('\\n')],\r\n [sg.Text('Name : '),sg.Input(),sg.Text('\\n')],\r\n [sg.Text('Height (cm) : '),sg.Input(),sg.Text('\\n')],\r\n [sg.Text('Weight (kg) : '),sg.Input(),sg.Text('\\n')],\r\n [sg.Text('\\n'*2)],\r\n [sg.Text('\\t'),sg.Submit(size=(8,2)), sg.Cancel('Exit',size=(8,2))]\r\n\r\n ]\r\n window = sg.Window('BMI to Excel',layout, size = (350,400))\r\n event,values = window.read() \r\n window.close()\r\n if event==sg.WIN_CLOSED or event==\"Exit\":\r\n window.close() \r\n return inp_awal()\r\n break;\r\n elif event==\"Submit\":\r\n count+=1\r\n data[i]=[]*len(values)\r\n for j in range(len(values)):\r\n if j==1 or j==2:\r\n data[i].append(int(values[j]))\r\n else:\r\n data[i].append(values[j])\r\n bmi=int(values[2])/((int(values[1])/100)*(int(values[1])/100))\r\n data[i].append(bmi)\r\n if bmi<18.5:\r\n data[i].append(\"Underweight\")\r\n elif 18.5<=bmi<25:\r\n data[i].append(\"Normal\")\r\n elif 25<=bmi<40:\r\n data[i].append(\"Overweight\")\r\n elif bmi>=40:\r\n data[i].append(\"Obesse\")\r\n\r\n if count==n:\r\n return works(data,workbook,worksheet,file)\r\n\r\n# sg.theme_previewer()\r\ndef inp_awal():\r\n layout = [\r\n [sg.Text('\\n\\n\\nFile Name : ')],\r\n [sg.InputText()],\r\n [sg.Text('\\nData Total : ',)],\r\n [sg.InputText()],\r\n [sg.Text(\"\\n\"*20+\"\\t\"),sg.Submit(size=(8,2)), sg.Cancel('Exit',size=(8,2))]\r\n ]\r\n window = sg.Window('BMI to Excel',layout, size = (350,400))\r\n while True:\r\n event, values = window.read()\r\n window.close()\r\n if event==sg.WIN_CLOSED or event==\"Cancel\":\r\n break;\r\n elif event==\"Submit\":\r\n file=values[0]\r\n n = int(values[1])\r\n workbook = exc.Workbook(file+\".xlsx\")\r\n worksheet = workbook.add_worksheet()\r\n return inp(n,workbook,worksheet,file)\r\n\r\ninp_awal()","repo_name":"tantowish/Multiple-BMI-to-Excel-CSV","sub_path":"multiple_BMI_to_Excel_CSV.py","file_name":"multiple_BMI_to_Excel_CSV.py","file_ext":"py","file_size_in_byte":3425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41813444487","text":"# kode for bit:bot\n\n# IMPORTS\nfrom microbit import *\nimport radio\nimport neopixel\n\n# OPPSTART\ndisplay.show(Image.SKULL) # logo på microbit\ncolor = (248, 24, 148) # NeoPixel farge for å bruke på lys\nnp = neopixel.NeoPixel(pin13, 12) # variabel for neopixel\n\n# INITIALISERING\nignition = False # variabel for status tenning\n\n# RADIO INNSTILLINGER\nkanal = 1 # må matche med kontroller\nradio.config(channel=kanal)\nradio.on()\n\n\n# FUNKSJONER\n\ndef move(speed, tilt):\n \"\"\"Funksjon for å bevege roboten.\n Tar inn argumentene speed (int, 0-1023) og steer (int, -1023 - 1023)\"\"\"\n direction = 0\n left = 0\n right = 0\n if speed < 0:\n # fremover\n direction = 0\n left = int(min(abs(speed), 1023) * min(1, ((1023+max(-1023, 2*tilt))/1023)))\n right = int(min(abs(speed), 1023) * min(1, ((1023-min(1023, 2*tilt))/1023)))\n # print(\"left: %d right: %d\" %(left, right)) # DEBUG\n elif speed > 0:\n # revers\n direction = 1\n left = 1023 - int(min(abs(speed), 1023) * min(1, ((1023+max(-1023, 2*tilt))/1023)))\n right = 1023 - int(min(abs(speed), 1023) * min(1, ((1023-min(1023, 2*tilt))/1023)))\n # print(\"left: %d right: %d\" %(left, right)) # DEBUG\n\n # skriver til motorer\n pin8.write_digital(direction) # retning venstre motor\n pin12.write_digital(direction) # retning høyre motor\n pin0.write_analog(left) # hastighet venstre motor\n pin1.write_analog(right) # hastighet høyre motor\n\ndef honk():\n pin14.write_digital(1)\n sleep(100)\n pin14.write_digital(0)\n sleep(50)\n pin14.write_digital(1)\n sleep(100)\n pin14.write_digital(0)\n sleep(50)\n pin14.write_digital(1)\n sleep(200)\n pin14.write_digital(0)\n\n\n# SKRIPT\nwhile True:\n msg = radio.receive()\n if msg is not None:\n speed, tilt, ign, horn = [int(val) for val in msg.split(':')]\n if ign:\n print(\"ignition!\")\n # tenning av / på\n if ignition: # hvis tenning er på -> slå av tenning\n ignition = False\n np.clear()\n else: # hvis tenning av -> skru på tenning\n ignition = True\n for i in range(12):\n np[i] = color\n np.show() # slår på lys\n move(0, 0)\n elif ignition: # hvis tenning på\n move(speed, tilt) # -> kjør robot\n\n if horn:\n honk()\n else:\n # hvis ikke noe beskjed fra kontroller, gjør ingenting\n move(0, 0)\n sleep(20) # oppdater hvert 20 ms","repo_name":"newboarg/ProgModX-20-21","sub_path":"remote_bitbot.py","file_name":"remote_bitbot.py","file_ext":"py","file_size_in_byte":2571,"program_lang":"python","lang":"no","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32605179056","text":"import vcf\n\nfrom biothings.utils.dataload import dict_sweep, unlist, value_convert_to_number\nfrom utils.hgvs import get_hgvs_from_vcf\n\n\ndef _map_line_to_json(doc_key, item):\n chrom = item.CHROM\n chromStart = item.POS\n ref = item.REF\n info = item.INFO\n _filter = item.FILTER\n try:\n baseqranksum = info['BaseQRankSum']\n except:\n baseqranksum = None\n try:\n clippingranksum = info['ClippingRankSum']\n except:\n clippingranksum = None\n try:\n mqranksum = info['MQRankSum']\n except:\n mqranksum = None\n try:\n readposranksum = info['ReadPosRankSum']\n except:\n readposranksum = None\n try:\n qd = info['QD']\n except:\n qd = None\n try:\n inbreedingcoeff = info['InbreedingCoeff']\n except:\n inbreedingcoeff = None\n # convert vcf object to string\n item.ALT = [str(alt) for alt in item.ALT]\n # if multiallelic, put all variants as a list in multi-allelic field\n hgvs_list = None\n if len(item.ALT) > 1:\n hgvs_list = [get_hgvs_from_vcf(chrom, chromStart, ref, alt, mutant_type=False) for alt in item.ALT]\n for i, alt in enumerate(item.ALT):\n (HGVS, var_type) = get_hgvs_from_vcf(chrom, chromStart, ref, alt, mutant_type=True)\n if HGVS is None:\n return\n assert len(item.ALT) == len(info['AC']), \"Expecting length of item.ALT= length of info.AC, but not for %s\" % (HGVS)\n assert len(item.ALT) == len(info['AF']), \"Expecting length of item.ALT= length of info.AF, but not for %s\" % (HGVS)\n assert len(item.ALT) == len(info['Hom_AFR']), \"Expecting length of item.ALT= length of HOM_AFR, but not for %s\" % (HGVS)\n one_snp_json = {\n \"_id\": HGVS,\n doc_key : {\n \"chrom\": chrom,\n \"pos\": chromStart,\n \"filter\": _filter,\n \"multi-allelic\": hgvs_list,\n \"ref\": ref,\n \"alt\": alt,\n \"alleles\": item.ALT,\n \"type\": var_type,\n \"ac\": {\n \"ac\": info['AC'][i],\n \"ac_afr\": info['AC_AFR'][i],\n \"ac_amr\": info['AC_AMR'][i],\n \"ac_adj\": info['AC_Adj'][i],\n \"ac_eas\": info['AC_EAS'][i],\n \"ac_fin\": info['AC_FIN'][i],\n \"ac_het\": info['AC_Het'][i],\n \"ac_hom\": info['AC_Hom'][i],\n \"ac_nfe\": info['AC_NFE'][i],\n \"ac_oth\": info['AC_OTH'][i],\n \"ac_sas\": info['AC_SAS'][i],\n \"ac_male\": info['AC_MALE'][i],\n \"ac_female\": info['AC_FEMALE'][i]\n },\n \"af\": info['AF'][i],\n \"an\": {\n \"an\": info['AN'],\n \"an_afr\": info['AN_AFR'],\n \"an_amr\": info['AN_AMR'],\n \"an_adj\": info['AN_Adj'],\n \"an_eas\": info['AN_EAS'],\n \"an_fin\": info['AN_FIN'],\n \"an_nfe\": info['AN_NFE'],\n \"an_oth\": info['AN_OTH'],\n \"an_sas\": info['AN_SAS'],\n \"an_female\": info['AN_FEMALE'],\n \"an_male\": info['AN_MALE']\n\n },\n \"baseqranksum\": baseqranksum,\n \"clippingranksum\": clippingranksum,\n \"fs\": info['FS'],\n \"het\": {\n \"het_afr\": info['Het_AFR'],\n \"het_amr\": info['Het_AMR'],\n \"het_eas\": info['Het_EAS'],\n \"het_fin\": info['Het_FIN'],\n \"het_nfe\": info['Het_NFE'],\n \"het_oth\": info['Het_OTH'],\n \"het_sas\": info['Het_SAS']\n },\n \"hom\": {\n \"hom_afr\": info['Hom_AFR'],\n \"hom_amr\": info['Hom_AMR'],\n \"hom_eas\": info['Hom_EAS'],\n \"hom_fin\": info['Hom_FIN'],\n \"hom_nfe\": info['Hom_NFE'],\n \"hom_oth\": info['Hom_OTH'],\n \"hom_sas\": info['Hom_SAS']\n },\n \"inbreedingcoeff\": inbreedingcoeff,\n \"mq\": {\n \"mq\": info['MQ'],\n \"mq0\": info['MQ0'],\n \"mqranksum\": mqranksum\n },\n \"ncc\": info['NCC'],\n \"qd\": qd,\n \"readposranksum\": readposranksum,\n \"vqslod\": info['VQSLOD'],\n \"culprit\": info['culprit']\n }\n }\n obj = (dict_sweep(unlist(value_convert_to_number(one_snp_json)), [None]))\n yield obj\n\n\ndef load_data(doc_key,input_file):\n vcf_reader = vcf.Reader(open(input_file, 'r'))\n for record in vcf_reader:\n for record_mapped in _map_line_to_json(doc_key,record):\n yield record_mapped\n","repo_name":"biothings/myvariant.info","sub_path":"src/hub/dataload/sources/exac/exac_parser.py","file_name":"exac_parser.py","file_ext":"py","file_size_in_byte":4946,"program_lang":"python","lang":"en","doc_type":"code","stars":84,"dataset":"github-code","pt":"48"} +{"seq_id":"16824711009","text":"r\"\"\"\nA utility module to easily load common VirTex models (optionally with pretrained\nweights) using a single line of code.\n\nGet our full best performing VirTex model (with pretrained weights as):\n\n>>> import virtex.model_zoo as mz\n>>> model = mz.get(\"width_ablations/bicaptioning_R_50_L1_H2048.yaml\", pretrained=True)\n\nAny config available in ``configs/`` directory under project root can be\nspecified here, although this command need not be executed from project root.\nFor more details on available models, refer :doc:`usage/model_zoo`.\n\nPart of this code is adapted from Detectron2's model zoo; which was originally\nimplemented by the developers of this codebase, with reviews and further\nchanges by Detectron2 developers.\n\"\"\"\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\nimport os\nimport pkg_resources\n\nfrom fvcore.common.download import download\nimport torch\n\nfrom virtex.config import Config\nfrom virtex.factories import PretrainingModelFactory\nfrom virtex.utils.checkpointing import CheckpointManager\n\n\nclass _ModelZooUrls:\n r\"\"\"Mapping from config names to URL suffixes of pretrained weights.\"\"\"\n\n URL_PREFIX = \"https://www.dropbox.com/s\"\n\n CONFIG_PATH_TO_DB_ID = {\n\n # Pretraining Task Ablations\n \"task_ablations/bicaptioning_R_50_L1_H2048.yaml\": \"mbeeso8wyieq8wy\",\n \"task_ablations/captioning_R_50_L1_H2048.yaml\": \"r6zen9k43m5oo58\",\n \"task_ablations/token_classification_R_50.yaml\": \"o4p9lki505r0mef\",\n \"task_ablations/multilabel_classification_R_50.yaml\": \"hbspp3jv3u8h3bc\",\n \"task_ablations/masked_lm_R_50_L1_H2048.yaml\": \"ldzrk6vem4mg6bl\",\n\n # Width Ablations\n \"width_ablations/bicaptioning_R_50_L1_H512.yaml\": \"o9fr69jjqfn8a65\",\n \"width_ablations/bicaptioning_R_50_L1_H768.yaml\": \"1zxglqrrbfufv9d\",\n \"width_ablations/bicaptioning_R_50_L1_H1024.yaml\": \"pdat4tvhnqxel64\",\n \"width_ablations/bicaptioning_R_50_L1_H2048.yaml\": \"mbeeso8wyieq8wy\",\n\n # Depth Ablations\n \"depth_ablations/bicaptioning_R_50_L1_H1024.yaml\": \"pdat4tvhnqxel64\",\n \"depth_ablations/bicaptioning_R_50_L2_H1024.yaml\": \"ft1vtt4okirzjgo\",\n \"depth_ablations/bicaptioning_R_50_L3_H1024.yaml\": \"5ldo1rcsnrshmjr\",\n \"depth_ablations/bicaptioning_R_50_L4_H1024.yaml\": \"zgiit2wcluuq3xh\",\n\n # Backbone Ablations\n \"backbone_ablations/bicaptioning_R_50_L1_H1024.yaml\": \"pdat4tvhnqxel64\",\n \"backbone_ablations/bicaptioning_R_50W2X_L1_H1024.yaml\": \"5o198ux709r6376\",\n \"backbone_ablations/bicaptioning_R_101_L1_H1024.yaml\": \"bb74jubt68cpn80\",\n }\n\n\ndef get(config_path: str, pretrained: bool = False):\n r\"\"\"\n Get a model specified by relative path under Detectron2's official\n ``configs/`` directory.\n\n Args:\n config_path: Name of config file relative to ``configs/`` directory\n under project root. (E.g. ``width_ablations/bicaptioning_R_50_L1_H2048.yaml``)\n pretrained: If ``True``, will initialize the model with the pretrained\n weights. If ``False``, the weights will be initialized randomly.\n \"\"\"\n\n # Get the original path to config file (shipped with inside the package).\n _pkg_config_path = pkg_resources.resource_filename(\n \"virtex.model_zoo\", os.path.join(\"configs\", config_path)\n )\n if not os.path.exists(_pkg_config_path):\n raise RuntimeError(\"{} not available in Model Zoo!\".format(config_path))\n\n _C = Config(_pkg_config_path)\n model = PretrainingModelFactory.from_config(_C)\n\n if pretrained:\n # Get URL for the checkpoint for this config path.\n if config_path in _ModelZooUrls.CONFIG_PATH_TO_DB_ID:\n\n dropbox_id = _ModelZooUrls.CONFIG_PATH_TO_DB_ID[config_path]\n filename = os.path.basename(config_path).replace(\".yaml\", \".pth\")\n\n checkpoint_url = f\"{_ModelZooUrls.URL_PREFIX}/{dropbox_id}/{filename}?dl=1\"\n else:\n raise RuntimeError(\"{} not available in Model Zoo!\".format(config_path))\n\n # Download the pretrained model weights and save with a sensible name.\n # This will be downloaded only if it does not exist.\n checkpoint_path = download(\n checkpoint_url,\n dir=os.path.expanduser(\"~/.torch/virtex_cache\"),\n filename=os.path.basename(config_path).replace(\".yaml\", \".pth\")\n )\n CheckpointManager(model=model).load(checkpoint_path)\n\n return model\n","repo_name":"kdexd/virtex","sub_path":"virtex/model_zoo/model_zoo.py","file_name":"model_zoo.py","file_ext":"py","file_size_in_byte":4425,"program_lang":"python","lang":"en","doc_type":"code","stars":550,"dataset":"github-code","pt":"48"} +{"seq_id":"12708685664","text":"from django.http import HttpResponse,HttpResponseRedirect\nfrom django.shortcuts import render,get_object_or_404\nfrom django.template import loader\nfrom .models import User\nfrom django.urls import reverse\nfrom datetime import datetime\nfrom django.utils.dateparse import parse_datetime\n\ndef login(request):\n\ttemplate = loader.get_template('to_do/login.html')\n\treturn HttpResponse(template.render({},request))\n\n\ndef home(request):\n\tlatest_task_list = Task.objects.order_by('due_date')\n\ttemplate = loader.get_template('to_do/home.html')\n\tcontext = {\n\t\t'latest_task_list' : latest_task_list\n\t}\n\treturn HttpResponse(template.render(context, request))\n\ndef completed(request):\n\tlatest_task_list = Task.objects.order_by('due_date')\n\ttemplate = loader.get_template('to_do/completed.html')\n\tcontext = {\n\t\t'latest_task_list' : latest_task_list\n\t}\n\treturn HttpResponse(template.render(context, request))\n\ndef newtask(request):\n\tif request.method == 'POST':\n\t\tif request.POST.get('task') and request.POST.get('date'):\n\t\t\tdate=request.POST.get('date')\n\t\t\ttime=request.POST.get('time')\n\t\t\tdate_time=str(date)+\" \"+str(time)\n\t\t\ttask=Task()\n\t\t\ttask.task_text=request.POST.get('task')\n\t\t\ttask.due_date=datetime.strptime(date_time, \"%Y-%m-%d %H:%M\")\n\t\t\ttask.save()\n\t\treturn HttpResponseRedirect(reverse('todo:home'))\n\telse:\n\t\treturn HttpResponseRedirect(reverse('todo:home'))\n\ndef change(request,task_id):\n\tif task_id:\t\n\t\ttask=get_object_or_404(Task, pk=task_id)\n\t\tprint(str(task.status) + \" \" + str(task_id))\n\t\tif task.status==1:\n\t\t\ttask.status -= 1\n\t\t\ttask.save()\n\t\t\treturn HttpResponseRedirect(reverse('todo:completed'))\n\t\telse:\n\t\t\ttask.status += 1\n\t\t\ttask.save()\n\t\treturn HttpResponseRedirect(reverse('todo:home'))\n","repo_name":"namansingh3502/django-learning","sub_path":"app1/to_do/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1699,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16839947317","text":"from __future__ import print_function\n\nfrom ..framework import core\nfrom ..fluid.layer_helper import LayerHelper\nfrom ..fluid.data_feeder import check_variable_and_dtype\n\n# TODO: define functions to get tensor attributes\nfrom ..fluid.layers import rank # noqa: F401\nfrom ..fluid.layers import shape # noqa: F401\nimport paddle\nfrom paddle import _C_ops\nfrom paddle.static import Variable\nfrom ..fluid.framework import _in_legacy_dygraph, in_dygraph_mode\n\n__all__ = []\n\n\ndef _complex_to_real_dtype(dtype):\n if dtype == core.VarDesc.VarType.COMPLEX64:\n return core.VarDesc.VarType.FP32\n elif dtype == core.VarDesc.VarType.COMPLEX128:\n return core.VarDesc.VarType.FP64\n else:\n return dtype\n\n\ndef _real_to_complex_dtype(dtype):\n if dtype == core.VarDesc.VarType.FP32:\n return core.VarDesc.VarType.COMPLEX64\n elif dtype == core.VarDesc.VarType.FP64:\n return core.VarDesc.VarType.COMPLEX128\n else:\n return dtype\n\n\ndef is_complex(x):\n \"\"\"Return whether x is a tensor of complex data type(complex64 or complex128).\n\n Args:\n x (Tensor): The input tensor.\n\n Returns:\n bool: True if the data type of the input is complex data type, otherwise false.\n\n Examples:\n .. code-block:: python\n\n import paddle\n\n x = paddle.to_tensor([1 + 2j, 3 + 4j])\n print(paddle.is_complex(x))\n # True\n\n x = paddle.to_tensor([1.1, 1.2])\n print(paddle.is_complex(x))\n # False\n\n x = paddle.to_tensor([1, 2, 3])\n print(paddle.is_complex(x))\n # False\n \"\"\"\n if not isinstance(x, (paddle.Tensor, paddle.static.Variable)):\n raise TypeError(\"Expected Tensor, but received type of x: {}\".format(\n type(x)))\n dtype = x.dtype\n is_complex_dtype = (dtype == core.VarDesc.VarType.COMPLEX64 or\n dtype == core.VarDesc.VarType.COMPLEX128)\n return is_complex_dtype\n\n\ndef is_floating_point(x):\n \"\"\"\n Returns whether the dtype of `x` is one of paddle.float64, paddle.float32, paddle.float16, and paddle.bfloat16.\n\n Args:\n x (Tensor): The input tensor.\n\n Returns:\n bool: True if the dtype of `x` is floating type, otherwise false.\n\n Examples:\n .. code-block:: python\n\n import paddle\n\n x = paddle.arange(1., 5., dtype='float32')\n y = paddle.arange(1, 5, dtype='int32')\n print(paddle.is_floating_point(x))\n # True\n print(paddle.is_floating_point(y))\n # False\n \"\"\"\n if not isinstance(x, (paddle.Tensor, paddle.static.Variable)):\n raise TypeError(\"Expected Tensor, but received type of x: {}\".format(\n type(x)))\n dtype = x.dtype\n is_fp_dtype = (dtype == core.VarDesc.VarType.FP32 or\n dtype == core.VarDesc.VarType.FP64 or\n dtype == core.VarDesc.VarType.FP16 or\n dtype == core.VarDesc.VarType.BF16)\n return is_fp_dtype\n\n\ndef is_integer(x):\n \"\"\"Return whether x is a tensor of integeral data type.\n\n Args:\n x (Tensor): The input tensor.\n\n Returns:\n bool: True if the data type of the input is integer data type, otherwise false.\n\n Examples:\n .. code-block:: python\n\n import paddle\n\n x = paddle.to_tensor([1 + 2j, 3 + 4j])\n print(paddle.is_integer(x))\n # False\n\n x = paddle.to_tensor([1.1, 1.2])\n print(paddle.is_integer(x))\n # False\n\n x = paddle.to_tensor([1, 2, 3])\n print(paddle.is_integer(x))\n # True\n \"\"\"\n if not isinstance(x, (paddle.Tensor, paddle.static.Variable)):\n raise TypeError(\"Expected Tensor, but received type of x: {}\".format(\n type(x)))\n dtype = x.dtype\n is_int_dtype = (dtype == core.VarDesc.VarType.UINT8 or\n dtype == core.VarDesc.VarType.INT8 or\n dtype == core.VarDesc.VarType.INT16 or\n dtype == core.VarDesc.VarType.INT32 or\n dtype == core.VarDesc.VarType.INT64)\n return is_int_dtype\n\n\ndef real(x, name=None):\n \"\"\"\n Returns a new tensor containing real values of the input tensor.\n\n Args:\n x (Tensor): the input tensor, its data type could be complex64 or complex128.\n name (str, optional): The default value is None. Normally there is no need for\n user to set this property. For more information, please refer to :ref:`api_guide_Name` .\n \n Returns:\n Tensor: a tensor containing real values of the input tensor.\n\n Examples:\n .. code-block:: python\n\n import paddle\n\n x = paddle.to_tensor(\n [[1 + 6j, 2 + 5j, 3 + 4j], [4 + 3j, 5 + 2j, 6 + 1j]])\n # Tensor(shape=[2, 3], dtype=complex64, place=CUDAPlace(0), stop_gradient=True,\n # [[(1+6j), (2+5j), (3+4j)],\n # [(4+3j), (5+2j), (6+1j)]])\n\n real_res = paddle.real(x)\n # Tensor(shape=[2, 3], dtype=float32, place=CUDAPlace(0), stop_gradient=True,\n # [[1., 2., 3.],\n # [4., 5., 6.]])\n\n real_t = x.real()\n # Tensor(shape=[2, 3], dtype=float32, place=CUDAPlace(0), stop_gradient=True,\n # [[1., 2., 3.],\n # [4., 5., 6.]])\n \"\"\"\n if in_dygraph_mode():\n return _C_ops.final_state_real(x)\n if _in_legacy_dygraph():\n return _C_ops.real(x)\n\n check_variable_and_dtype(x, 'x', ['complex64', 'complex128'], 'real')\n helper = LayerHelper('real', **locals())\n out = helper.create_variable_for_type_inference(\n dtype=_complex_to_real_dtype(helper.input_dtype()))\n helper.append_op(type='real', inputs={'X': x}, outputs={'Out': out})\n return out\n\n\ndef imag(x, name=None):\n \"\"\"\n Returns a new tensor containing imaginary values of input tensor.\n\n Args:\n x (Tensor): the input tensor, its data type could be complex64 or complex128.\n name (str, optional): The default value is None. Normally there is no need for\n user to set this property. For more information, please refer to :ref:`api_guide_Name` .\n\n Returns:\n Tensor: a tensor containing imaginary values of the input tensor.\n\n Examples:\n .. code-block:: python\n\n import paddle\n\n x = paddle.to_tensor(\n [[1 + 6j, 2 + 5j, 3 + 4j], [4 + 3j, 5 + 2j, 6 + 1j]])\n # Tensor(shape=[2, 3], dtype=complex64, place=CUDAPlace(0), stop_gradient=True,\n # [[(1+6j), (2+5j), (3+4j)],\n # [(4+3j), (5+2j), (6+1j)]])\n\n imag_res = paddle.imag(x)\n # Tensor(shape=[2, 3], dtype=float32, place=CUDAPlace(0), stop_gradient=True,\n # [[6., 5., 4.],\n # [3., 2., 1.]])\n\n imag_t = x.imag()\n # Tensor(shape=[2, 3], dtype=float32, place=CUDAPlace(0), stop_gradient=True,\n # [[6., 5., 4.],\n # [3., 2., 1.]])\n \"\"\"\n if in_dygraph_mode():\n return _C_ops.final_state_imag(x)\n if _in_legacy_dygraph():\n return _C_ops.imag(x)\n\n check_variable_and_dtype(x, 'x', ['complex64', 'complex128'], 'imag')\n helper = LayerHelper('imag', **locals())\n out = helper.create_variable_for_type_inference(\n dtype=_complex_to_real_dtype(helper.input_dtype()))\n helper.append_op(type='imag', inputs={'X': x}, outputs={'Out': out})\n return out\n","repo_name":"EnnSou/ooss-paddle2.3","sub_path":"python/paddle/tensor/attribute.py","file_name":"attribute.py","file_ext":"py","file_size_in_byte":7549,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"2097308018","text":"'''\nDaxiang trading robot main entry\n'''\nimport sys\nimport argparse\nfrom src.coinflex_flypig import CoinflexFlypig\nfrom src.coinflex_turtle import CoinflexTurtle\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"strategy\", help=\"Stratege to run\")\n parser.add_argument(\"config\", help=\"Config file for the stratege\")\n args = parser.parse_args()\n \n strategy = args.strategy\n config_file = args.config\n\n if strategy == \"flypig\":\n coinflexFlypig = CoinflexFlypig(config_file)\n coinflexFlypig.websocket_app.wst.join()\n coinflexFlypig.websocket_app.check_thread.join()\n \n elif strategy == \"turtle\":\n coinflexTurtle = CoinflexTurtle(config_file)\n coinflexTurtle.websocket_app.wst.join()\n coinflexTurtle.websocket_app.check_thread.join()","repo_name":"tw7613781/daxiang_trade","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"48"} +{"seq_id":"73352939026","text":"import numpy as np\nfrom typing import List\n\nfrom brainio.assemblies import walk_coords, array_is_element, DataAssembly\n\n\ndef ci_error(samples, center, confidence=.95):\n low, high = 100 * ((1 - confidence) / 2), 100 * (1 - ((1 - confidence) / 2))\n confidence_below, confidence_above = np.nanpercentile(samples, low), np.nanpercentile(samples, high)\n confidence_below, confidence_above = center - confidence_below, confidence_above - center\n return confidence_below, confidence_above\n\n\ndef manual_merge(*elements: List[DataAssembly], on='neuroid') -> DataAssembly:\n \"\"\"\n Manually merge a set of assemblies where xarray's automated merge might fail.\n This function likely covers only covers a small number of use-cases, and should thus be used with caution.\n \"\"\"\n dims = elements[0].dims\n assert all(element.dims == dims for element in elements[1:])\n merge_index = dims.index(on)\n # the coordinates in the merge index should have the same keys\n assert _coords_match(elements, dim=on,\n match_values=False), f\"coords in {[element[on] for element in elements]} do not match\"\n # all other dimensions, their coordinates and values should already align\n for dim in set(dims) - {on}:\n assert _coords_match(elements, dim=dim,\n match_values=True), f\"coords in {[element[dim] for element in elements]} do not match\"\n # merge values without meta\n merged_values = np.concatenate([element.values for element in elements], axis=merge_index)\n # piece together with meta\n result = type(elements[0])(merged_values, coords={\n **{coord: (dims, values)\n for coord, dims, values in walk_coords(elements[0])\n if not array_is_element(dims, on)},\n **{coord: (dims, np.concatenate([element[coord].values for element in elements]))\n for coord, dims, _ in walk_coords(elements[0])\n if array_is_element(dims, on)}}, dims=elements[0].dims)\n return result\n\n\ndef _coords_match(elements, dim, match_values=False):\n \"\"\" Helper method for `manual_merge` \"\"\"\n first_coords = [(key, tuple(value)) if match_values else key for _, key, value in walk_coords(elements[0][dim])]\n other_coords = [[(key, tuple(value)) if match_values else key for _, key, value in walk_coords(element[dim])]\n for element in elements[1:]]\n return all(tuple(first_coords) == tuple(coords) for coords in other_coords)\n","repo_name":"brain-score/language","sub_path":"brainscore_language/benchmark_helpers/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2457,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"48"} +{"seq_id":"23970233330","text":"from unittest import TestCase\nimport pandas as pd\nfrom additional_tables.radio_tables import MassCalcification\nimport mock\nimport module\n\n\n\nclass TestRadiology(TestCase):\n\n def __init__(self, table, col_list):\n super().__init__()\n self.table = table\n self.col_list = col_list\n\n def test_function(self):\n with mock.patch.object(__builtins__, 'input', lambda: 'some_input'):\n assert module == 'expected_output'\n\n if __name__ == \"__main__\":\n import helper_function.pccm_names as pccm_names\n table = 'mammography'\n col_list = pccm_names.names_radio_mass(table)\n # execute only if run as a script\n masscalc = MassCalcification(table, mammo_breast='right_breast', file_number='test', user_name='dk')\n masscalc.mammo_mass('1')\n masscalc.multiple_mass()\n\n\n TestCase.assertIs(self)\n pass\n","repo_name":"shwetakadupccm/pccm_db_sk","sub_path":"reports/test_radiology.py","file_name":"test_radiology.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25655244015","text":"import heapq as hq\n\n\ndef solve():\n N, M = map(int, input().split())\n pl = list(map(lambda x: int(x) * (-1), input().split()))\n hq.heapify(pl)\n\n for _ in range(M):\n tmp = hq.heappop(pl)\n hq.heappush(pl, (-1) * (-tmp // 2))\n\n print(-sum(pl))\n\n\nif __name__ == '__main__':\n solve()\n","repo_name":"yuly3/atcoder","sub_path":"ABC/ABC141/D.py","file_name":"D.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"32361389807","text":"import keras\nimport re\nimport joblib\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\n\nimport tensorflow as tf\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.layers import Embedding, LSTM, Dense , Softmax \nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.preprocessing.text import Tokenizer\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\nfrom keras.layers import Layer\nimport keras.backend as K\nimport warnings\nwarnings.filterwarnings('ignore')\n################################################################\nfrom preprocessing import *\nfrom enc_dec import *\nfrom dataloader import *\nfrom callbacks import *\nfrom attention import *\n# importing the zipfile module\nfrom zipfile import ZipFile\nimport os\nimport json\n\nactual_path = os.getcwd()\nprint(actual_path)\n\ndata = get_data(actual_path)\ndata['english'] = data['english'].apply(preprocess)\ndata['italian'] = data['italian'].apply(preprocess_ita)\n\nprint(\"Input/Output example\")\nprint(\"Italian sentence : %s\" % data.loc[1000][1])\nprint(\"English sentence : %s\" % data.loc[1000][0])\nprint()\nprint(\"Italian sentence : %s\" % data.loc[2000][1])\nprint(\"English sentence : %s\" % data.loc[2000][0])\nprint()\nprint(\"Italian sentence : %s\" % data.loc[3000][1])\nprint(\"English sentence : %s\" % data.loc[3000][0])\nprint()\n\ninp_lengths = data['italian'].str.split().apply(len)\nout_lengths = data['english'].str.split().apply(len)\n\ndef show_length_pencentile(range,language,length):\n for r in range:\n print('{}th percentile of {} sequence is :{}'.format(round(r, 1), language,round(np.percentile(length, r))))\n\ninput_maxlen = np.round(np.percentile(inp_lengths,99.9))\noutput_maxlen = np.round(np.percentile(out_lengths,99.9))\n\nprint('Maximum Sequence Length for Italian Language: ', input_maxlen)\nprint('Maximum Sequence Length for English Language: ', output_maxlen)\n\n\ndata['ita_lengths'] = data['italian'].str.split().apply(len)\ndata = data[data['ita_lengths'] < input_maxlen ]\ndata['eng_lengths'] = data['english'].str.split().apply(len)\ndata = data[data['eng_lengths'] < output_maxlen]\n\ninput_sentence = data['italian'].values\ndata['encoder_inp'] = data['italian'].astype(str)\ndata['english_inp'] = ' '+data['english'].astype(str)+' '\noutput_sentence = data['english_inp'].values\n\ntrain,test = train_test_split(data,test_size=0.1, random_state=4)\ntrain,validation = train_test_split(train,test_size=0.1, random_state=4)\njoblib.dump(test, \"./dataset/test.pkl\")\n\n# joblib.load(\"model.pkl\")\n# with open('./dataset/test.pickle', 'wb') as handle:\n# pickle.dump(test, handle, protocol=pickle.HIGHEST_PROTOCOL)\n# print(train.shape, validation.shape,test.shape)\n\ntrain['decoder_inp'] = ' '+train['english'].astype(str)\ntrain['decoder_out'] = train['english'].astype(str)+' '\n\nvalidation['decoder_inp'] = ' '+validation['english'].astype(str)\nvalidation['decoder_out'] = validation['english'].astype(str)+' '\n\nip_token = Tokenizer(filters='')\nip_token.fit_on_texts(input_sentence)\n\nop_token = Tokenizer(filters='!\"#$%&()*+,-./:;=?@[\\\\]^_`{|}~\\t\\n')\nop_token.fit_on_texts(output_sentence)\n\n# joblib.dump(ip_token, \"./dataset/ita_tokenizer.pickle\")\n# joblib.dump(op_token, \"./dataset/eng_tokenizer.pickle\")\nip_token_json = ip_token.to_json()\nwith open('./dataset/ita_tokenizer.json', 'w', encoding='utf-8') as f:\n f.write(json.dumps(ip_token_json, ensure_ascii=False))\nop_token_json = op_token.to_json()\nwith open('./dataset/eng_tokenizer.json', 'w', encoding='utf-8') as f:\n f.write(json.dumps(op_token_json, ensure_ascii=False))\n# with open('./dataset/ita_tokenizer.pickle', 'wb') as handle:\n# pickle.dump(ip_token, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\n# with open('./dataset/eng_tokenizer.pickle', 'wb') as handle:\n# pickle.dump(op_token, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\ntrain_enc_inp = ip_token.texts_to_sequences(train['encoder_inp'])\ntrain_dec_inp = op_token.texts_to_sequences(train['decoder_inp'])\ntrain_dec_out = op_token.texts_to_sequences(train['decoder_out'])\n\nval_enc_inp = ip_token.texts_to_sequences(validation['encoder_inp'])\nval_dec_inp = op_token.texts_to_sequences(validation['decoder_inp'])\nval_dec_out = op_token.texts_to_sequences(validation['decoder_out'])\n\ntrain_encoder_seq = pad_sequences(train_enc_inp, padding='post')\ntrain_decoder_inp_seq = pad_sequences(train_dec_inp, padding='post')\ntrain_decoder_out_seq = pad_sequences(train_dec_out, padding='post')\n\nval_encoder_seq = pad_sequences(val_enc_inp, padding='post')\nval_decoder_inp_seq = pad_sequences(val_dec_inp, padding='post')\nval_decoder_out_seq = pad_sequences(val_dec_out, padding='post')\n\ninput_vocab_size=len(ip_token.word_index)+1\noutput_vocab_size=len(op_token.word_index)+1\n\nmodel = Encoder_Decoder(input_vocab_size,output_vocab_size)\nmodel.compile(optimizer=tf.keras.optimizers.Adam(),loss='sparse_categorical_crossentropy',metrics=[\"accuracy\"])\ntrain_steps=train.shape[0]//512\nvalid_steps=validation.shape[0]//512\n\nmodel.fit([train_encoder_seq,train_decoder_inp_seq],train_decoder_out_seq, \n validation_data = ([val_encoder_seq,val_decoder_inp_seq],val_decoder_out_seq), \n steps_per_epoch = 400, \n epochs=35,callbacks = [tensor, checkpoint,csv_logger])\nmodel.summary()\nmodel.save_weights('./attention/encDecModel.tf')\n","repo_name":"Ankit-93/Language-Translation","sub_path":"components/ingestion.py","file_name":"ingestion.py","file_ext":"py","file_size_in_byte":5365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38122272220","text":"def evalRPN(tokens) -> int:\n stack = []\n for c in tokens:\n if c == \"+\":\n stack.append(stack.pop() + stack.pop())\n elif c == \"-\":\n a, b = stack.pop(), stack.pop()\n stack.append(b - a)\n elif c == \"*\":\n stack.append(stack.pop() * stack.pop())\n elif c == \"/\":\n a, b = stack.pop(), stack.pop()\n stack.append(int(b / a))\n else:\n stack.append(int(c))\n return stack[0]\n\ndef test():\n test_cases = [\n {\n \"name\": \"simple case 1\",\n \"input\": [\"2\",\"1\",\"+\",\"3\",\"*\"],\n \"expected\": 9\n },\n {\n \"name\": \"simple case 2\",\n \"input\": [\"4\",\"13\",\"5\",\"/\",\"+\"],\n \"expected\": 6\n },\n {\n \"name\": \"simple case 3\",\n \"input\": [\"10\",\"6\",\"9\",\"3\",\"+\",\"-11\",\"*\",\"/\",\"*\",\"17\",\"+\",\"5\",\"+\"],\n \"expected\": 22\n }\n ]\n\n for test_case in test_cases:\n assert test_case[\"expected\"] == evalRPN(test_case[\"input\"]), test_case[\"name\"]\n\nif __name__ == \"__main__\":\n from datetime import datetime\n start_time = datetime.now()\n test()\n print(\"Everything passed\")\n end_time = datetime.now()\n print('Duration: {}'.format(end_time - start_time))\n","repo_name":"0xspringtime/leetcode","sub_path":"0150.py","file_name":"0150.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"38122194210","text":"# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\ndef buildTree(preorder, inorder):\n # A helper function to build the tree\n def helper(in_left = 0, in_right = len(inorder)):\n nonlocal pre_idx\n # If there is no elements to construct subtrees\n if in_left == in_right:\n return None\n \n # Pick up pre_idx element as a root\n root_val = preorder[pre_idx]\n root = TreeNode(root_val)\n\n # Root splits inorder list into left and right subtrees\n index = idx_map[root_val]\n\n # Increment pre_idx\n pre_idx += 1\n\n # Build left and right subtrees\n # Be careful with the off-by-one to avoid overflows\n root.left = helper(in_left, index)\n root.right = helper(index + 1, in_right)\n return root\n \n # Start from the first preorder element\n pre_idx = 0\n # Build a hashmap to store value -> its index relations\n idx_map = {val:idx for idx, val in enumerate(inorder)} \n return helper()\n#time O(n)\n#space O(n)\n","repo_name":"0xspringtime/leetcode","sub_path":"0105n.py","file_name":"0105n.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"8133737959","text":"from setuptools import setup, find_packages\n\nwith open(\"requirements.txt\") as f:\n\tinstall_requires = f.read().strip().split(\"\\n\")\n\n# get version from __version__ variable in my_sample_project/__init__.py\nfrom my_sample_project import __version__ as version\n\nsetup(\n\tname=\"my_sample_project\",\n\tversion=version,\n\tdescription=\"A Sample Test App\",\n\tauthor=\"scopen\",\n\tauthor_email=\"florian.henry@scopen.fr\",\n\tpackages=find_packages(),\n\tzip_safe=False,\n\tinclude_package_data=True,\n\tinstall_requires=install_requires\n)\n","repo_name":"FHenry/erpnext_my_sample_project","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8589593494","text":"import unittest\nfrom typing import NewType, Dict\n\nimport hypothesis.strategies as st\n\nfrom grapl_analyzerlib.grapl_client import GraphClient\nfrom grapl_analyzerlib.nodes.process import ProcessView\nfrom grapl_analyzerlib.node_types import PropType\nfrom grapl_analyzerlib.test_utils.dgraph_utils import random_key_for_test, upsert\nfrom grapl_analyzerlib.test_utils.strategies.misc import text_dgraph_compat\n\nProcessProps = NewType(\"ProcessProps\", Dict[str, PropType])\n\n\ndef process_props_strategy() -> st.SearchStrategy[ProcessProps]:\n return st.builds(\n ProcessProps,\n st.builds(\n dict,\n node_key=st.just(\"mutated in get_or_create_process\"),\n process_id=st.integers(min_value=1, max_value=2 ** 32),\n created_timestamp=st.integers(min_value=0, max_value=2 ** 48),\n terminate_time=st.integers(min_value=0, max_value=2 ** 48),\n image_name=text_dgraph_compat(),\n process_name=text_dgraph_compat(),\n arguments=text_dgraph_compat(),\n ),\n )\n\n\ndef get_or_create_process(\n test: unittest.TestCase, graph_client: GraphClient, node_props: ProcessProps\n) -> ProcessView:\n # Introduce randomness here, because otherwise Hypothesis would generate\n # key collisions at the @given stage\n node_key = random_key_for_test(test)\n return upsert(graph_client, \"Process\", ProcessView, node_key, node_props)\n","repo_name":"macasieb/grapl","sub_path":"src/python/grapl_analyzerlib/grapl_analyzerlib/test_utils/strategies/process_view_strategy.py","file_name":"process_view_strategy.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"24211633996","text":"import logging\nimport os\nfrom logging import LogRecord\nfrom logging.handlers import RotatingFileHandler\n\n\n# def painting(string: str, color: str) -> str:\n# colors = {'red' : \"\\x1b[31;20m\",\n# 'bold_red': \"\\x1b[31;1m\",\n# 'green' : \"\\x1b[32;20m\",\n# 'yellow' : \"\\x1b[33;20m\",\n# 'blue' : \"\\x1b[34;1m\",\n# 'gray' : \"\\x1b[38;2m\"}\n\n# return f'\\x1b[0m{colors[color]}{string}\\x1b[0m'\n\n\nclass CustomStreamFormatter(logging.Formatter):\n \"\"\"Used for custom conversion of the log entry representation to text.\n\n The custom stream formatter has its own attributes for each logging level.\n Redefined formatting method from the log.The Formatter class is used to\n convert a log entry into color text of a given format.\n\n Attributes:\n colors: ascii_colors ([color_code;20m)\n\n DEBUG : grey color\n INFO : green color\n WARNING : yellow color\n ERROR : red color\n CRITICAL: bold red color\n \"\"\"\n\n # Color сodes of ascii\n grey = \"\\x1b[38;20m\"\n green = \"\\x1b[32;20m\"\n yellow = \"\\x1b[33;20m\"\n red = \"\\x1b[31;20m\"\n bold_red = \"\\x1b[31;1m\"\n reset = \"\\x1b[0m\"\n format = \"%(asctime)s - [%(levelname)s] - %(name)s - (%(filename)s).%(funcName)s(%(lineno)d) - %(message)s\"\n\n FORMATS = {logging.DEBUG: grey + format + reset,\n logging.INFO: green + format + reset,\n logging.WARNING: yellow + format + reset,\n logging.ERROR: red + format + reset,\n logging.CRITICAL: bold_red + format + reset}\n\n def format(self, record: logging.LogRecord) -> str:\n \"\"\"Redefined method to get the required log output format\n \"\"\" \n\n log_format = self.FORMATS.get(record.levelno)\n formatter = logging.Formatter(log_format)\n return formatter.format(record)\n\n\nclass CustomFileFormatter(CustomStreamFormatter):\n \"\"\"Used to convert a log entry for writing to a file without using colored lines.\n \"\"\"\n\n format = \"\"\"[%(levelname)s] %(name)s %(asctime)s:\\n\\tFile \"%(filename)s\", line %(lineno)d, in %(funcName)s\\n%(message)s\\n\"\"\"\n\n FORMATS = {logging.DEBUG: format,\n logging.INFO: format,\n logging.WARNING: format,\n logging.ERROR: format,\n logging.CRITICAL: format}\n \n def format(self, record: LogRecord) -> str:\n # Call format method of class CustomStreamFormatter\n return super().format(record)\n\n\ndef get_file_handler():\n # Setup file handler\n if not os.path.exists('logs'):\n os.mkdir('logs')\n\n # Issue #1: when log file overflow RotatingFileHandler working with error:\n # PermissionError: [WinError 32]\n # temporary solution make log file is infinity.\n # If maxBytes is zero, rollover never occurs\n file_handler = RotatingFileHandler('logs/log.log',\n maxBytes=0,\n backupCount=0,\n encoding='UTF-8')\n file_handler.setFormatter(CustomFileFormatter())\n file_handler.setLevel(logging.DEBUG)\n return file_handler\n\n\ndef get_stream_handler():\n # Setup stream handler (i.e. console)\n stream_handler = logging.StreamHandler()\n stream_handler.setFormatter(CustomStreamFormatter())\n stream_handler.setLevel(logging.DEBUG)\n return stream_handler\n\n\ndef get_logger(sreaming: bool, name: str | None = 'ROOT',) -> logging.Logger:\n\n logger = logging.getLogger(name)\n # Set general debug level for view all levels\n logger.setLevel(logging.DEBUG)\n\n if sreaming == True:\n logger.addHandler(get_stream_handler())\n logger.addHandler(get_file_handler())\n\n return logger","repo_name":"Towareesh/practice_flask","sub_path":"customlogger/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3749,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"70106969426","text":"from os.path import dirname, abspath, join\nfrom subprocess import call\n\nfrom setuptools import setup, find_packages, Command\n\nfrom daylistudent import __version__\n\nthis_dir = abspath(dirname(__file__))\n\n# Readme\nwith open(join(this_dir, 'README.md'), encoding='utf-8') as file:\n readme = file.read()\n\n# License\nwith open(join(this_dir, 'LICENSE'), encoding='utf-8') as file:\n license = file.read()\n\n# Requirements\nwith open(join(this_dir, 'requirements.txt')) as file:\n requirements = file.read().splitlines()\n\n\nclass RunTests(Command):\n \"\"\"Run all tests.\"\"\"\n description = 'run tests'\n user_options = []\n\n def initialize_options(self):\n pass\n\n def finalize_options(self):\n pass\n\n def run(self):\n \"\"\"Run all tests!\"\"\"\n error = call(['py.test', '--cov=daylistudent',\n '--cov-report=term-missing'])\n raise SystemExit(error)\n\n\nsetup(\n name='DailyStudent',\n version=__version__,\n description='A server for the app Dayli Student written in Python.',\n long_description=readme,\n author='André Bento and Jorge Silva',\n author_email='apbento@student.dei.uc.pt',\n url='https://github.com/EatBloOD/CM_FinalProject.git',\n license=license,\n classifiers=[\n 'Intended Audience :: Developers',\n 'Topic :: Utilities',\n 'License :: Public Domain',\n 'Natural Language :: English',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.6',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.2',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.6',\n ],\n keywords='cli',\n packages=find_packages(exclude=('tests*', 'docs')),\n install_requires=requirements,\n extras_require={\n 'test': ['coverage', 'pytest', 'pytest-cov'],\n },\n entry_points={\n 'console_scripts': [\n 'daylistudent=daylistudent.cli:cli',\n ],\n },\n cmdclass={'test': RunTests},\n)\n","repo_name":"JorgeADSilva/CM_FinalProject","sub_path":"DayliStudent_BackEnd/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2185,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11677673227","text":"\"\"\" PIM_MIB \n\nThe MIB module for management of PIM routers.\n\n\"\"\"\nfrom ydk.entity_utils import get_relative_entity_path as _get_relative_entity_path\nfrom ydk.types import Entity, EntityPath, Identity, Enum, YType, YLeaf, YLeafList, YList, LeafDataList, Bits, Empty, Decimal64\nfrom ydk.filters import YFilter\nfrom ydk.errors import YPYError, YPYModelError\nfrom ydk.errors.error_handler import handle_type_error as _handle_type_error\n\n\n\nclass PimMib(Entity):\n \"\"\"\n \n \n .. attribute:: pim\n \n \t\n \t**type**\\: :py:class:`Pim `\n \n .. attribute:: pimcandidaterptable\n \n \tThe (conceptual) table listing the IP multicast groups for which the local router is to advertise itself as a Candidate\\-RP when the value of pimComponentCRPHoldTime is non\\-zero. If this table is empty, then the local router will advertise itself as a Candidate\\-RP for all groups (providing the value of pimComponentCRPHoldTime is non\\- zero)\n \t**type**\\: :py:class:`Pimcandidaterptable `\n \n .. attribute:: pimcomponenttable\n \n \tThe (conceptual) table containing objects specific to a PIM domain. One row exists for each domain to which the router is connected. A PIM\\-SM domain is defined as an area of the network over which Bootstrap messages are forwarded. Typically, a PIM\\-SM router will be a member of exactly one domain. This table also supports, however, routers which may form a border between two PIM\\-SM domains and do not forward Bootstrap messages between them\n \t**type**\\: :py:class:`Pimcomponenttable `\n \n .. attribute:: piminterfacetable\n \n \tThe (conceptual) table listing the router's PIM interfaces. IGMP and PIM are enabled on all interfaces listed in this table\n \t**type**\\: :py:class:`Piminterfacetable `\n \n .. attribute:: pimipmroutenexthoptable\n \n \tThe (conceptual) table listing PIM\\-specific information on a subset of the rows of the ipMRouteNextHopTable defined in the IP Multicast MIB\n \t**type**\\: :py:class:`Pimipmroutenexthoptable `\n \n .. attribute:: pimipmroutetable\n \n \tThe (conceptual) table listing PIM\\-specific information on a subset of the rows of the ipMRouteTable defined in the IP Multicast MIB\n \t**type**\\: :py:class:`Pimipmroutetable `\n \n .. attribute:: pimneighbortable\n \n \tThe (conceptual) table listing the router's PIM neighbors\n \t**type**\\: :py:class:`Pimneighbortable `\n \n .. attribute:: pimrpsettable\n \n \tThe (conceptual) table listing PIM information for candidate Rendezvous Points (RPs) for IP multicast groups. When the local router is the BSR, this information is obtained from received Candidate\\-RP\\-Advertisements. When the local router is not the BSR, this information is obtained from received RP\\-Set messages\n \t**type**\\: :py:class:`Pimrpsettable `\n \n .. attribute:: pimrptable\n \n \tThe (conceptual) table listing PIM version 1 information for the Rendezvous Points (RPs) for IP multicast groups. This table is deprecated since its function is replaced by the pimRPSetTable for PIM version 2\n \t**type**\\: :py:class:`Pimrptable `\n \n \t**status**\\: deprecated\n \n \n\n \"\"\"\n\n _prefix = 'PIM-MIB'\n _revision = '2000-09-28'\n\n def __init__(self):\n super(PimMib, self).__init__()\n self._top_entity = None\n\n self.yang_name = \"PIM-MIB\"\n self.yang_parent_name = \"PIM-MIB\"\n\n self.pim = PimMib.Pim()\n self.pim.parent = self\n self._children_name_map[\"pim\"] = \"pim\"\n self._children_yang_names.add(\"pim\")\n\n self.pimcandidaterptable = PimMib.Pimcandidaterptable()\n self.pimcandidaterptable.parent = self\n self._children_name_map[\"pimcandidaterptable\"] = \"pimCandidateRPTable\"\n self._children_yang_names.add(\"pimCandidateRPTable\")\n\n self.pimcomponenttable = PimMib.Pimcomponenttable()\n self.pimcomponenttable.parent = self\n self._children_name_map[\"pimcomponenttable\"] = \"pimComponentTable\"\n self._children_yang_names.add(\"pimComponentTable\")\n\n self.piminterfacetable = PimMib.Piminterfacetable()\n self.piminterfacetable.parent = self\n self._children_name_map[\"piminterfacetable\"] = \"pimInterfaceTable\"\n self._children_yang_names.add(\"pimInterfaceTable\")\n\n self.pimipmroutenexthoptable = PimMib.Pimipmroutenexthoptable()\n self.pimipmroutenexthoptable.parent = self\n self._children_name_map[\"pimipmroutenexthoptable\"] = \"pimIpMRouteNextHopTable\"\n self._children_yang_names.add(\"pimIpMRouteNextHopTable\")\n\n self.pimipmroutetable = PimMib.Pimipmroutetable()\n self.pimipmroutetable.parent = self\n self._children_name_map[\"pimipmroutetable\"] = \"pimIpMRouteTable\"\n self._children_yang_names.add(\"pimIpMRouteTable\")\n\n self.pimneighbortable = PimMib.Pimneighbortable()\n self.pimneighbortable.parent = self\n self._children_name_map[\"pimneighbortable\"] = \"pimNeighborTable\"\n self._children_yang_names.add(\"pimNeighborTable\")\n\n self.pimrpsettable = PimMib.Pimrpsettable()\n self.pimrpsettable.parent = self\n self._children_name_map[\"pimrpsettable\"] = \"pimRPSetTable\"\n self._children_yang_names.add(\"pimRPSetTable\")\n\n self.pimrptable = PimMib.Pimrptable()\n self.pimrptable.parent = self\n self._children_name_map[\"pimrptable\"] = \"pimRPTable\"\n self._children_yang_names.add(\"pimRPTable\")\n\n\n class Pim(Entity):\n \"\"\"\n \n \n .. attribute:: pimjoinpruneinterval\n \n \tThe default interval at which periodic PIM\\-SM Join/Prune messages are to be sent\n \t**type**\\: int\n \n \t**range:** \\-2147483648..2147483647\n \n \t**units**\\: seconds\n \n \n\n \"\"\"\n\n _prefix = 'PIM-MIB'\n _revision = '2000-09-28'\n\n def __init__(self):\n super(PimMib.Pim, self).__init__()\n\n self.yang_name = \"pim\"\n self.yang_parent_name = \"PIM-MIB\"\n\n self.pimjoinpruneinterval = YLeaf(YType.int32, \"pimJoinPruneInterval\")\n\n def __setattr__(self, name, value):\n self._check_monkey_patching_error(name, value)\n with _handle_type_error():\n if name in self.__dict__ and isinstance(self.__dict__[name], YList):\n raise YPYModelError(\"Attempt to assign value of '{}' to YList ldata. \"\n \"Please use list append or extend method.\"\n .format(value))\n if isinstance(value, Enum.YLeaf):\n value = value.name\n if name in (\"pimjoinpruneinterval\") and name in self.__dict__:\n if isinstance(value, YLeaf):\n self.__dict__[name].set(value.get())\n elif isinstance(value, YLeafList):\n super(PimMib.Pim, self).__setattr__(name, value)\n else:\n self.__dict__[name].set(value)\n else:\n if hasattr(value, \"parent\") and name != \"parent\":\n if hasattr(value, \"is_presence_container\") and value.is_presence_container:\n value.parent = self\n elif value.parent is None and value.yang_name in self._children_yang_names:\n value.parent = self\n super(PimMib.Pim, self).__setattr__(name, value)\n\n def has_data(self):\n return self.pimjoinpruneinterval.is_set\n\n def has_operation(self):\n return (\n self.yfilter != YFilter.not_set or\n self.pimjoinpruneinterval.yfilter != YFilter.not_set)\n\n def get_segment_path(self):\n path_buffer = \"\"\n path_buffer = \"pim\" + path_buffer\n\n return path_buffer\n\n def get_entity_path(self, ancestor):\n path_buffer = \"\"\n if (ancestor is None):\n path_buffer = \"PIM-MIB:PIM-MIB/%s\" % self.get_segment_path()\n else:\n path_buffer = _get_relative_entity_path(self, ancestor, path_buffer)\n\n leaf_name_data = LeafDataList()\n if (self.pimjoinpruneinterval.is_set or self.pimjoinpruneinterval.yfilter != YFilter.not_set):\n leaf_name_data.append(self.pimjoinpruneinterval.get_name_leafdata())\n\n entity_path = EntityPath(path_buffer, leaf_name_data)\n return entity_path\n\n def get_child_by_name(self, child_yang_name, segment_path):\n child = self._get_child_by_seg_name([child_yang_name, segment_path])\n if child is not None:\n return child\n\n return None\n\n def has_leaf_or_child_of_name(self, name):\n if(name == \"pimJoinPruneInterval\"):\n return True\n return False\n\n def set_value(self, value_path, value, name_space, name_space_prefix):\n if(value_path == \"pimJoinPruneInterval\"):\n self.pimjoinpruneinterval = value\n self.pimjoinpruneinterval.value_namespace = name_space\n self.pimjoinpruneinterval.value_namespace_prefix = name_space_prefix\n\n\n class Piminterfacetable(Entity):\n \"\"\"\n The (conceptual) table listing the router's PIM interfaces.\n IGMP and PIM are enabled on all interfaces listed in this\n table.\n \n .. attribute:: piminterfaceentry\n \n \tAn entry (conceptual row) in the pimInterfaceTable\n \t**type**\\: list of :py:class:`Piminterfaceentry `\n \n \n\n \"\"\"\n\n _prefix = 'PIM-MIB'\n _revision = '2000-09-28'\n\n def __init__(self):\n super(PimMib.Piminterfacetable, self).__init__()\n\n self.yang_name = \"pimInterfaceTable\"\n self.yang_parent_name = \"PIM-MIB\"\n\n self.piminterfaceentry = YList(self)\n\n def __setattr__(self, name, value):\n self._check_monkey_patching_error(name, value)\n with _handle_type_error():\n if name in self.__dict__ and isinstance(self.__dict__[name], YList):\n raise YPYModelError(\"Attempt to assign value of '{}' to YList ldata. \"\n \"Please use list append or extend method.\"\n .format(value))\n if isinstance(value, Enum.YLeaf):\n value = value.name\n if name in () and name in self.__dict__:\n if isinstance(value, YLeaf):\n self.__dict__[name].set(value.get())\n elif isinstance(value, YLeafList):\n super(PimMib.Piminterfacetable, self).__setattr__(name, value)\n else:\n self.__dict__[name].set(value)\n else:\n if hasattr(value, \"parent\") and name != \"parent\":\n if hasattr(value, \"is_presence_container\") and value.is_presence_container:\n value.parent = self\n elif value.parent is None and value.yang_name in self._children_yang_names:\n value.parent = self\n super(PimMib.Piminterfacetable, self).__setattr__(name, value)\n\n\n class Piminterfaceentry(Entity):\n \"\"\"\n An entry (conceptual row) in the pimInterfaceTable.\n \n .. attribute:: piminterfaceifindex \n \n \tThe ifIndex value of this PIM interface\n \t**type**\\: int\n \n \t**range:** 1..2147483647\n \n .. attribute:: piminterfaceaddress\n \n \tThe IP address of the PIM interface\n \t**type**\\: str\n \n \t**pattern:** (([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])\\\\.){3}([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])(%[\\\\p{N}\\\\p{L}]+)?\n \n .. attribute:: piminterfacecbsrpreference\n \n \tThe preference value for the local interface as a candidate bootstrap router. The value of \\-1 is used to indicate that the local interface is not a candidate BSR interface\n \t**type**\\: int\n \n \t**range:** \\-1..255\n \n .. attribute:: piminterfacedr\n \n \tThe Designated Router on this PIM interface. For point\\-to\\- point interfaces, this object has the value 0.0.0.0\n \t**type**\\: str\n \n \t**pattern:** (([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])\\\\.){3}([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])(%[\\\\p{N}\\\\p{L}]+)?\n \n .. attribute:: piminterfacehellointerval\n \n \tThe frequency at which PIM Hello messages are transmitted on this interface\n \t**type**\\: int\n \n \t**range:** \\-2147483648..2147483647\n \n \t**units**\\: seconds\n \n .. attribute:: piminterfacejoinpruneinterval\n \n \tThe frequency at which PIM Join/Prune messages are transmitted on this PIM interface. The default value of this object is the pimJoinPruneInterval\n \t**type**\\: int\n \n \t**range:** \\-2147483648..2147483647\n \n \t**units**\\: seconds\n \n .. attribute:: piminterfacemode\n \n \tThe configured mode of this PIM interface. A value of sparseDense is only valid for PIMv1\n \t**type**\\: :py:class:`Piminterfacemode `\n \n .. attribute:: piminterfacenetmask\n \n \tThe network mask for the IP address of the PIM interface\n \t**type**\\: str\n \n \t**pattern:** (([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])\\\\.){3}([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])(%[\\\\p{N}\\\\p{L}]+)?\n \n .. attribute:: piminterfacestatus\n \n \tThe status of this entry. Creating the entry enables PIM on the interface; destroying the entry disables PIM on the interface\n \t**type**\\: :py:class:`Rowstatus `\n \n \n\n \"\"\"\n\n _prefix = 'PIM-MIB'\n _revision = '2000-09-28'\n\n def __init__(self):\n super(PimMib.Piminterfacetable.Piminterfaceentry, self).__init__()\n\n self.yang_name = \"pimInterfaceEntry\"\n self.yang_parent_name = \"pimInterfaceTable\"\n\n self.piminterfaceifindex = YLeaf(YType.int32, \"pimInterfaceIfIndex\")\n\n self.piminterfaceaddress = YLeaf(YType.str, \"pimInterfaceAddress\")\n\n self.piminterfacecbsrpreference = YLeaf(YType.int32, \"pimInterfaceCBSRPreference\")\n\n self.piminterfacedr = YLeaf(YType.str, \"pimInterfaceDR\")\n\n self.piminterfacehellointerval = YLeaf(YType.int32, \"pimInterfaceHelloInterval\")\n\n self.piminterfacejoinpruneinterval = YLeaf(YType.int32, \"pimInterfaceJoinPruneInterval\")\n\n self.piminterfacemode = YLeaf(YType.enumeration, \"pimInterfaceMode\")\n\n self.piminterfacenetmask = YLeaf(YType.str, \"pimInterfaceNetMask\")\n\n self.piminterfacestatus = YLeaf(YType.enumeration, \"pimInterfaceStatus\")\n\n def __setattr__(self, name, value):\n self._check_monkey_patching_error(name, value)\n with _handle_type_error():\n if name in self.__dict__ and isinstance(self.__dict__[name], YList):\n raise YPYModelError(\"Attempt to assign value of '{}' to YList ldata. \"\n \"Please use list append or extend method.\"\n .format(value))\n if isinstance(value, Enum.YLeaf):\n value = value.name\n if name in (\"piminterfaceifindex\",\n \"piminterfaceaddress\",\n \"piminterfacecbsrpreference\",\n \"piminterfacedr\",\n \"piminterfacehellointerval\",\n \"piminterfacejoinpruneinterval\",\n \"piminterfacemode\",\n \"piminterfacenetmask\",\n \"piminterfacestatus\") and name in self.__dict__:\n if isinstance(value, YLeaf):\n self.__dict__[name].set(value.get())\n elif isinstance(value, YLeafList):\n super(PimMib.Piminterfacetable.Piminterfaceentry, self).__setattr__(name, value)\n else:\n self.__dict__[name].set(value)\n else:\n if hasattr(value, \"parent\") and name != \"parent\":\n if hasattr(value, \"is_presence_container\") and value.is_presence_container:\n value.parent = self\n elif value.parent is None and value.yang_name in self._children_yang_names:\n value.parent = self\n super(PimMib.Piminterfacetable.Piminterfaceentry, self).__setattr__(name, value)\n\n class Piminterfacemode(Enum):\n \"\"\"\n Piminterfacemode\n\n The configured mode of this PIM interface. A value of\n\n sparseDense is only valid for PIMv1.\n\n .. data:: dense = 1\n\n .. data:: sparse = 2\n\n .. data:: sparseDense = 3\n\n \"\"\"\n\n dense = Enum.YLeaf(1, \"dense\")\n\n sparse = Enum.YLeaf(2, \"sparse\")\n\n sparseDense = Enum.YLeaf(3, \"sparseDense\")\n\n\n def has_data(self):\n return (\n self.piminterfaceifindex.is_set or\n self.piminterfaceaddress.is_set or\n self.piminterfacecbsrpreference.is_set or\n self.piminterfacedr.is_set or\n self.piminterfacehellointerval.is_set or\n self.piminterfacejoinpruneinterval.is_set or\n self.piminterfacemode.is_set or\n self.piminterfacenetmask.is_set or\n self.piminterfacestatus.is_set)\n\n def has_operation(self):\n return (\n self.yfilter != YFilter.not_set or\n self.piminterfaceifindex.yfilter != YFilter.not_set or\n self.piminterfaceaddress.yfilter != YFilter.not_set or\n self.piminterfacecbsrpreference.yfilter != YFilter.not_set or\n self.piminterfacedr.yfilter != YFilter.not_set or\n self.piminterfacehellointerval.yfilter != YFilter.not_set or\n self.piminterfacejoinpruneinterval.yfilter != YFilter.not_set or\n self.piminterfacemode.yfilter != YFilter.not_set or\n self.piminterfacenetmask.yfilter != YFilter.not_set or\n self.piminterfacestatus.yfilter != YFilter.not_set)\n\n def get_segment_path(self):\n path_buffer = \"\"\n path_buffer = \"pimInterfaceEntry\" + \"[pimInterfaceIfIndex='\" + self.piminterfaceifindex.get() + \"']\" + path_buffer\n\n return path_buffer\n\n def get_entity_path(self, ancestor):\n path_buffer = \"\"\n if (ancestor is None):\n path_buffer = \"PIM-MIB:PIM-MIB/pimInterfaceTable/%s\" % self.get_segment_path()\n else:\n path_buffer = _get_relative_entity_path(self, ancestor, path_buffer)\n\n leaf_name_data = LeafDataList()\n if (self.piminterfaceifindex.is_set or self.piminterfaceifindex.yfilter != YFilter.not_set):\n leaf_name_data.append(self.piminterfaceifindex.get_name_leafdata())\n if (self.piminterfaceaddress.is_set or self.piminterfaceaddress.yfilter != YFilter.not_set):\n leaf_name_data.append(self.piminterfaceaddress.get_name_leafdata())\n if (self.piminterfacecbsrpreference.is_set or self.piminterfacecbsrpreference.yfilter != YFilter.not_set):\n leaf_name_data.append(self.piminterfacecbsrpreference.get_name_leafdata())\n if (self.piminterfacedr.is_set or self.piminterfacedr.yfilter != YFilter.not_set):\n leaf_name_data.append(self.piminterfacedr.get_name_leafdata())\n if (self.piminterfacehellointerval.is_set or self.piminterfacehellointerval.yfilter != YFilter.not_set):\n leaf_name_data.append(self.piminterfacehellointerval.get_name_leafdata())\n if (self.piminterfacejoinpruneinterval.is_set or self.piminterfacejoinpruneinterval.yfilter != YFilter.not_set):\n leaf_name_data.append(self.piminterfacejoinpruneinterval.get_name_leafdata())\n if (self.piminterfacemode.is_set or self.piminterfacemode.yfilter != YFilter.not_set):\n leaf_name_data.append(self.piminterfacemode.get_name_leafdata())\n if (self.piminterfacenetmask.is_set or self.piminterfacenetmask.yfilter != YFilter.not_set):\n leaf_name_data.append(self.piminterfacenetmask.get_name_leafdata())\n if (self.piminterfacestatus.is_set or self.piminterfacestatus.yfilter != YFilter.not_set):\n leaf_name_data.append(self.piminterfacestatus.get_name_leafdata())\n\n entity_path = EntityPath(path_buffer, leaf_name_data)\n return entity_path\n\n def get_child_by_name(self, child_yang_name, segment_path):\n child = self._get_child_by_seg_name([child_yang_name, segment_path])\n if child is not None:\n return child\n\n return None\n\n def has_leaf_or_child_of_name(self, name):\n if(name == \"pimInterfaceIfIndex\" or name == \"pimInterfaceAddress\" or name == \"pimInterfaceCBSRPreference\" or name == \"pimInterfaceDR\" or name == \"pimInterfaceHelloInterval\" or name == \"pimInterfaceJoinPruneInterval\" or name == \"pimInterfaceMode\" or name == \"pimInterfaceNetMask\" or name == \"pimInterfaceStatus\"):\n return True\n return False\n\n def set_value(self, value_path, value, name_space, name_space_prefix):\n if(value_path == \"pimInterfaceIfIndex\"):\n self.piminterfaceifindex = value\n self.piminterfaceifindex.value_namespace = name_space\n self.piminterfaceifindex.value_namespace_prefix = name_space_prefix\n if(value_path == \"pimInterfaceAddress\"):\n self.piminterfaceaddress = value\n self.piminterfaceaddress.value_namespace = name_space\n self.piminterfaceaddress.value_namespace_prefix = name_space_prefix\n if(value_path == \"pimInterfaceCBSRPreference\"):\n self.piminterfacecbsrpreference = value\n self.piminterfacecbsrpreference.value_namespace = name_space\n self.piminterfacecbsrpreference.value_namespace_prefix = name_space_prefix\n if(value_path == \"pimInterfaceDR\"):\n self.piminterfacedr = value\n self.piminterfacedr.value_namespace = name_space\n self.piminterfacedr.value_namespace_prefix = name_space_prefix\n if(value_path == \"pimInterfaceHelloInterval\"):\n self.piminterfacehellointerval = value\n self.piminterfacehellointerval.value_namespace = name_space\n self.piminterfacehellointerval.value_namespace_prefix = name_space_prefix\n if(value_path == \"pimInterfaceJoinPruneInterval\"):\n self.piminterfacejoinpruneinterval = value\n self.piminterfacejoinpruneinterval.value_namespace = name_space\n self.piminterfacejoinpruneinterval.value_namespace_prefix = name_space_prefix\n if(value_path == \"pimInterfaceMode\"):\n self.piminterfacemode = value\n self.piminterfacemode.value_namespace = name_space\n self.piminterfacemode.value_namespace_prefix = name_space_prefix\n if(value_path == \"pimInterfaceNetMask\"):\n self.piminterfacenetmask = value\n self.piminterfacenetmask.value_namespace = name_space\n self.piminterfacenetmask.value_namespace_prefix = name_space_prefix\n if(value_path == \"pimInterfaceStatus\"):\n self.piminterfacestatus = value\n self.piminterfacestatus.value_namespace = name_space\n self.piminterfacestatus.value_namespace_prefix = name_space_prefix\n\n def has_data(self):\n for c in self.piminterfaceentry:\n if (c.has_data()):\n return True\n return False\n\n def has_operation(self):\n for c in self.piminterfaceentry:\n if (c.has_operation()):\n return True\n return self.yfilter != YFilter.not_set\n\n def get_segment_path(self):\n path_buffer = \"\"\n path_buffer = \"pimInterfaceTable\" + path_buffer\n\n return path_buffer\n\n def get_entity_path(self, ancestor):\n path_buffer = \"\"\n if (ancestor is None):\n path_buffer = \"PIM-MIB:PIM-MIB/%s\" % self.get_segment_path()\n else:\n path_buffer = _get_relative_entity_path(self, ancestor, path_buffer)\n\n leaf_name_data = LeafDataList()\n\n entity_path = EntityPath(path_buffer, leaf_name_data)\n return entity_path\n\n def get_child_by_name(self, child_yang_name, segment_path):\n child = self._get_child_by_seg_name([child_yang_name, segment_path])\n if child is not None:\n return child\n\n if (child_yang_name == \"pimInterfaceEntry\"):\n for c in self.piminterfaceentry:\n segment = c.get_segment_path()\n if (segment_path == segment):\n return c\n c = PimMib.Piminterfacetable.Piminterfaceentry()\n c.parent = self\n local_reference_key = \"ydk::seg::%s\" % segment_path\n self._local_refs[local_reference_key] = c\n self.piminterfaceentry.append(c)\n return c\n\n return None\n\n def has_leaf_or_child_of_name(self, name):\n if(name == \"pimInterfaceEntry\"):\n return True\n return False\n\n def set_value(self, value_path, value, name_space, name_space_prefix):\n pass\n\n\n class Pimneighbortable(Entity):\n \"\"\"\n The (conceptual) table listing the router's PIM neighbors.\n \n .. attribute:: pimneighborentry\n \n \tAn entry (conceptual row) in the pimNeighborTable\n \t**type**\\: list of :py:class:`Pimneighborentry `\n \n \n\n \"\"\"\n\n _prefix = 'PIM-MIB'\n _revision = '2000-09-28'\n\n def __init__(self):\n super(PimMib.Pimneighbortable, self).__init__()\n\n self.yang_name = \"pimNeighborTable\"\n self.yang_parent_name = \"PIM-MIB\"\n\n self.pimneighborentry = YList(self)\n\n def __setattr__(self, name, value):\n self._check_monkey_patching_error(name, value)\n with _handle_type_error():\n if name in self.__dict__ and isinstance(self.__dict__[name], YList):\n raise YPYModelError(\"Attempt to assign value of '{}' to YList ldata. \"\n \"Please use list append or extend method.\"\n .format(value))\n if isinstance(value, Enum.YLeaf):\n value = value.name\n if name in () and name in self.__dict__:\n if isinstance(value, YLeaf):\n self.__dict__[name].set(value.get())\n elif isinstance(value, YLeafList):\n super(PimMib.Pimneighbortable, self).__setattr__(name, value)\n else:\n self.__dict__[name].set(value)\n else:\n if hasattr(value, \"parent\") and name != \"parent\":\n if hasattr(value, \"is_presence_container\") and value.is_presence_container:\n value.parent = self\n elif value.parent is None and value.yang_name in self._children_yang_names:\n value.parent = self\n super(PimMib.Pimneighbortable, self).__setattr__(name, value)\n\n\n class Pimneighborentry(Entity):\n \"\"\"\n An entry (conceptual row) in the pimNeighborTable.\n \n .. attribute:: pimneighboraddress \n \n \tThe IP address of the PIM neighbor for which this entry contains information\n \t**type**\\: str\n \n \t**pattern:** (([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])\\\\.){3}([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])(%[\\\\p{N}\\\\p{L}]+)?\n \n .. attribute:: pimneighborexpirytime\n \n \tThe minimum time remaining before this PIM neighbor will be aged out\n \t**type**\\: int\n \n \t**range:** 0..4294967295\n \n .. attribute:: pimneighborifindex\n \n \tThe value of ifIndex for the interface used to reach this PIM neighbor\n \t**type**\\: int\n \n \t**range:** 1..2147483647\n \n .. attribute:: pimneighbormode\n \n \tThe active PIM mode of this neighbor. This object is deprecated for PIMv2 routers since all neighbors on the interface must be either dense or sparse as determined by the protocol running on the interface\n \t**type**\\: :py:class:`Pimneighbormode `\n \n \t**status**\\: deprecated\n \n .. attribute:: pimneighboruptime\n \n \tThe time since this PIM neighbor (last) became a neighbor of the local router\n \t**type**\\: int\n \n \t**range:** 0..4294967295\n \n \n\n \"\"\"\n\n _prefix = 'PIM-MIB'\n _revision = '2000-09-28'\n\n def __init__(self):\n super(PimMib.Pimneighbortable.Pimneighborentry, self).__init__()\n\n self.yang_name = \"pimNeighborEntry\"\n self.yang_parent_name = \"pimNeighborTable\"\n\n self.pimneighboraddress = YLeaf(YType.str, \"pimNeighborAddress\")\n\n self.pimneighborexpirytime = YLeaf(YType.uint32, \"pimNeighborExpiryTime\")\n\n self.pimneighborifindex = YLeaf(YType.int32, \"pimNeighborIfIndex\")\n\n self.pimneighbormode = YLeaf(YType.enumeration, \"pimNeighborMode\")\n\n self.pimneighboruptime = YLeaf(YType.uint32, \"pimNeighborUpTime\")\n\n def __setattr__(self, name, value):\n self._check_monkey_patching_error(name, value)\n with _handle_type_error():\n if name in self.__dict__ and isinstance(self.__dict__[name], YList):\n raise YPYModelError(\"Attempt to assign value of '{}' to YList ldata. \"\n \"Please use list append or extend method.\"\n .format(value))\n if isinstance(value, Enum.YLeaf):\n value = value.name\n if name in (\"pimneighboraddress\",\n \"pimneighborexpirytime\",\n \"pimneighborifindex\",\n \"pimneighbormode\",\n \"pimneighboruptime\") and name in self.__dict__:\n if isinstance(value, YLeaf):\n self.__dict__[name].set(value.get())\n elif isinstance(value, YLeafList):\n super(PimMib.Pimneighbortable.Pimneighborentry, self).__setattr__(name, value)\n else:\n self.__dict__[name].set(value)\n else:\n if hasattr(value, \"parent\") and name != \"parent\":\n if hasattr(value, \"is_presence_container\") and value.is_presence_container:\n value.parent = self\n elif value.parent is None and value.yang_name in self._children_yang_names:\n value.parent = self\n super(PimMib.Pimneighbortable.Pimneighborentry, self).__setattr__(name, value)\n\n class Pimneighbormode(Enum):\n \"\"\"\n Pimneighbormode\n\n The active PIM mode of this neighbor. This object is\n\n deprecated for PIMv2 routers since all neighbors on the\n\n interface must be either dense or sparse as determined by\n\n the protocol running on the interface.\n\n .. data:: dense = 1\n\n .. data:: sparse = 2\n\n \"\"\"\n\n dense = Enum.YLeaf(1, \"dense\")\n\n sparse = Enum.YLeaf(2, \"sparse\")\n\n\n def has_data(self):\n return (\n self.pimneighboraddress.is_set or\n self.pimneighborexpirytime.is_set or\n self.pimneighborifindex.is_set or\n self.pimneighbormode.is_set or\n self.pimneighboruptime.is_set)\n\n def has_operation(self):\n return (\n self.yfilter != YFilter.not_set or\n self.pimneighboraddress.yfilter != YFilter.not_set or\n self.pimneighborexpirytime.yfilter != YFilter.not_set or\n self.pimneighborifindex.yfilter != YFilter.not_set or\n self.pimneighbormode.yfilter != YFilter.not_set or\n self.pimneighboruptime.yfilter != YFilter.not_set)\n\n def get_segment_path(self):\n path_buffer = \"\"\n path_buffer = \"pimNeighborEntry\" + \"[pimNeighborAddress='\" + self.pimneighboraddress.get() + \"']\" + path_buffer\n\n return path_buffer\n\n def get_entity_path(self, ancestor):\n path_buffer = \"\"\n if (ancestor is None):\n path_buffer = \"PIM-MIB:PIM-MIB/pimNeighborTable/%s\" % self.get_segment_path()\n else:\n path_buffer = _get_relative_entity_path(self, ancestor, path_buffer)\n\n leaf_name_data = LeafDataList()\n if (self.pimneighboraddress.is_set or self.pimneighboraddress.yfilter != YFilter.not_set):\n leaf_name_data.append(self.pimneighboraddress.get_name_leafdata())\n if (self.pimneighborexpirytime.is_set or self.pimneighborexpirytime.yfilter != YFilter.not_set):\n leaf_name_data.append(self.pimneighborexpirytime.get_name_leafdata())\n if (self.pimneighborifindex.is_set or self.pimneighborifindex.yfilter != YFilter.not_set):\n leaf_name_data.append(self.pimneighborifindex.get_name_leafdata())\n if (self.pimneighbormode.is_set or self.pimneighbormode.yfilter != YFilter.not_set):\n leaf_name_data.append(self.pimneighbormode.get_name_leafdata())\n if (self.pimneighboruptime.is_set or self.pimneighboruptime.yfilter != YFilter.not_set):\n leaf_name_data.append(self.pimneighboruptime.get_name_leafdata())\n\n entity_path = EntityPath(path_buffer, leaf_name_data)\n return entity_path\n\n def get_child_by_name(self, child_yang_name, segment_path):\n child = self._get_child_by_seg_name([child_yang_name, segment_path])\n if child is not None:\n return child\n\n return None\n\n def has_leaf_or_child_of_name(self, name):\n if(name == \"pimNeighborAddress\" or name == \"pimNeighborExpiryTime\" or name == \"pimNeighborIfIndex\" or name == \"pimNeighborMode\" or name == \"pimNeighborUpTime\"):\n return True\n return False\n\n def set_value(self, value_path, value, name_space, name_space_prefix):\n if(value_path == \"pimNeighborAddress\"):\n self.pimneighboraddress = value\n self.pimneighboraddress.value_namespace = name_space\n self.pimneighboraddress.value_namespace_prefix = name_space_prefix\n if(value_path == \"pimNeighborExpiryTime\"):\n self.pimneighborexpirytime = value\n self.pimneighborexpirytime.value_namespace = name_space\n self.pimneighborexpirytime.value_namespace_prefix = name_space_prefix\n if(value_path == \"pimNeighborIfIndex\"):\n self.pimneighborifindex = value\n self.pimneighborifindex.value_namespace = name_space\n self.pimneighborifindex.value_namespace_prefix = name_space_prefix\n if(value_path == \"pimNeighborMode\"):\n self.pimneighbormode = value\n self.pimneighbormode.value_namespace = name_space\n self.pimneighbormode.value_namespace_prefix = name_space_prefix\n if(value_path == \"pimNeighborUpTime\"):\n self.pimneighboruptime = value\n self.pimneighboruptime.value_namespace = name_space\n self.pimneighboruptime.value_namespace_prefix = name_space_prefix\n\n def has_data(self):\n for c in self.pimneighborentry:\n if (c.has_data()):\n return True\n return False\n\n def has_operation(self):\n for c in self.pimneighborentry:\n if (c.has_operation()):\n return True\n return self.yfilter != YFilter.not_set\n\n def get_segment_path(self):\n path_buffer = \"\"\n path_buffer = \"pimNeighborTable\" + path_buffer\n\n return path_buffer\n\n def get_entity_path(self, ancestor):\n path_buffer = \"\"\n if (ancestor is None):\n path_buffer = \"PIM-MIB:PIM-MIB/%s\" % self.get_segment_path()\n else:\n path_buffer = _get_relative_entity_path(self, ancestor, path_buffer)\n\n leaf_name_data = LeafDataList()\n\n entity_path = EntityPath(path_buffer, leaf_name_data)\n return entity_path\n\n def get_child_by_name(self, child_yang_name, segment_path):\n child = self._get_child_by_seg_name([child_yang_name, segment_path])\n if child is not None:\n return child\n\n if (child_yang_name == \"pimNeighborEntry\"):\n for c in self.pimneighborentry:\n segment = c.get_segment_path()\n if (segment_path == segment):\n return c\n c = PimMib.Pimneighbortable.Pimneighborentry()\n c.parent = self\n local_reference_key = \"ydk::seg::%s\" % segment_path\n self._local_refs[local_reference_key] = c\n self.pimneighborentry.append(c)\n return c\n\n return None\n\n def has_leaf_or_child_of_name(self, name):\n if(name == \"pimNeighborEntry\"):\n return True\n return False\n\n def set_value(self, value_path, value, name_space, name_space_prefix):\n pass\n\n\n class Pimipmroutetable(Entity):\n \"\"\"\n The (conceptual) table listing PIM\\-specific information on\n a subset of the rows of the ipMRouteTable defined in the IP\n Multicast MIB.\n \n .. attribute:: pimipmrouteentry\n \n \tAn entry (conceptual row) in the pimIpMRouteTable. There is one entry per entry in the ipMRouteTable whose incoming interface is running PIM\n \t**type**\\: list of :py:class:`Pimipmrouteentry `\n \n \n\n \"\"\"\n\n _prefix = 'PIM-MIB'\n _revision = '2000-09-28'\n\n def __init__(self):\n super(PimMib.Pimipmroutetable, self).__init__()\n\n self.yang_name = \"pimIpMRouteTable\"\n self.yang_parent_name = \"PIM-MIB\"\n\n self.pimipmrouteentry = YList(self)\n\n def __setattr__(self, name, value):\n self._check_monkey_patching_error(name, value)\n with _handle_type_error():\n if name in self.__dict__ and isinstance(self.__dict__[name], YList):\n raise YPYModelError(\"Attempt to assign value of '{}' to YList ldata. \"\n \"Please use list append or extend method.\"\n .format(value))\n if isinstance(value, Enum.YLeaf):\n value = value.name\n if name in () and name in self.__dict__:\n if isinstance(value, YLeaf):\n self.__dict__[name].set(value.get())\n elif isinstance(value, YLeafList):\n super(PimMib.Pimipmroutetable, self).__setattr__(name, value)\n else:\n self.__dict__[name].set(value)\n else:\n if hasattr(value, \"parent\") and name != \"parent\":\n if hasattr(value, \"is_presence_container\") and value.is_presence_container:\n value.parent = self\n elif value.parent is None and value.yang_name in self._children_yang_names:\n value.parent = self\n super(PimMib.Pimipmroutetable, self).__setattr__(name, value)\n\n\n class Pimipmrouteentry(Entity):\n \"\"\"\n An entry (conceptual row) in the pimIpMRouteTable. There\n is one entry per entry in the ipMRouteTable whose incoming\n interface is running PIM.\n \n .. attribute:: ipmroutegroup \n \n \t\n \t**type**\\: str\n \n \t**pattern:** (([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])\\\\.){3}([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])(%[\\\\p{N}\\\\p{L}]+)?\n \n \t**refers to**\\: :py:class:`ipmroutegroup `\n \n .. attribute:: ipmroutesource \n \n \t\n \t**type**\\: str\n \n \t**pattern:** (([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])\\\\.){3}([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])(%[\\\\p{N}\\\\p{L}]+)?\n \n \t**refers to**\\: :py:class:`ipmroutesource `\n \n .. attribute:: ipmroutesourcemask \n \n \t\n \t**type**\\: str\n \n \t**pattern:** (([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])\\\\.){3}([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])(%[\\\\p{N}\\\\p{L}]+)?\n \n \t**refers to**\\: :py:class:`ipmroutesourcemask `\n \n .. attribute:: pimipmrouteassertmetric\n \n \tThe metric advertised by the assert winner on the upstream interface, or 0 if no such assert is in received\n \t**type**\\: int\n \n \t**range:** \\-2147483648..2147483647\n \n .. attribute:: pimipmrouteassertmetricpref\n \n \tThe preference advertised by the assert winner on the upstream interface, or 0 if no such assert is in effect\n \t**type**\\: int\n \n \t**range:** \\-2147483648..2147483647\n \n .. attribute:: pimipmrouteassertrptbit\n \n \tThe value of the RPT\\-bit advertised by the assert winner on the upstream interface, or false if no such assert is in effect\n \t**type**\\: bool\n \n .. attribute:: pimipmrouteflags\n \n \tThis object describes PIM\\-specific flags related to a multicast state entry. See the PIM Sparse Mode specification for the meaning of the RPT and SPT bits\n \t**type**\\: str\n \n \t**length:** 1\n \n .. attribute:: pimipmrouteupstreamasserttimer\n \n \tThe time remaining before the router changes its upstream neighbor back to its RPF neighbor. This timer is called the Assert timer in the PIM Sparse and Dense mode specification. A value of 0 indicates that no Assert has changed the upstream neighbor away from the RPF neighbor\n \t**type**\\: int\n \n \t**range:** 0..4294967295\n \n \n\n \"\"\"\n\n _prefix = 'PIM-MIB'\n _revision = '2000-09-28'\n\n def __init__(self):\n super(PimMib.Pimipmroutetable.Pimipmrouteentry, self).__init__()\n\n self.yang_name = \"pimIpMRouteEntry\"\n self.yang_parent_name = \"pimIpMRouteTable\"\n\n self.ipmroutegroup = YLeaf(YType.str, \"ipMRouteGroup\")\n\n self.ipmroutesource = YLeaf(YType.str, \"ipMRouteSource\")\n\n self.ipmroutesourcemask = YLeaf(YType.str, \"ipMRouteSourceMask\")\n\n self.pimipmrouteassertmetric = YLeaf(YType.int32, \"pimIpMRouteAssertMetric\")\n\n self.pimipmrouteassertmetricpref = YLeaf(YType.int32, \"pimIpMRouteAssertMetricPref\")\n\n self.pimipmrouteassertrptbit = YLeaf(YType.boolean, \"pimIpMRouteAssertRPTBit\")\n\n self.pimipmrouteflags = YLeaf(YType.str, \"pimIpMRouteFlags\")\n\n self.pimipmrouteupstreamasserttimer = YLeaf(YType.uint32, \"pimIpMRouteUpstreamAssertTimer\")\n\n def __setattr__(self, name, value):\n self._check_monkey_patching_error(name, value)\n with _handle_type_error():\n if name in self.__dict__ and isinstance(self.__dict__[name], YList):\n raise YPYModelError(\"Attempt to assign value of '{}' to YList ldata. \"\n \"Please use list append or extend method.\"\n .format(value))\n if isinstance(value, Enum.YLeaf):\n value = value.name\n if name in (\"ipmroutegroup\",\n \"ipmroutesource\",\n \"ipmroutesourcemask\",\n \"pimipmrouteassertmetric\",\n \"pimipmrouteassertmetricpref\",\n \"pimipmrouteassertrptbit\",\n \"pimipmrouteflags\",\n \"pimipmrouteupstreamasserttimer\") and name in self.__dict__:\n if isinstance(value, YLeaf):\n self.__dict__[name].set(value.get())\n elif isinstance(value, YLeafList):\n super(PimMib.Pimipmroutetable.Pimipmrouteentry, self).__setattr__(name, value)\n else:\n self.__dict__[name].set(value)\n else:\n if hasattr(value, \"parent\") and name != \"parent\":\n if hasattr(value, \"is_presence_container\") and value.is_presence_container:\n value.parent = self\n elif value.parent is None and value.yang_name in self._children_yang_names:\n value.parent = self\n super(PimMib.Pimipmroutetable.Pimipmrouteentry, self).__setattr__(name, value)\n\n def has_data(self):\n return (\n self.ipmroutegroup.is_set or\n self.ipmroutesource.is_set or\n self.ipmroutesourcemask.is_set or\n self.pimipmrouteassertmetric.is_set or\n self.pimipmrouteassertmetricpref.is_set or\n self.pimipmrouteassertrptbit.is_set or\n self.pimipmrouteflags.is_set or\n self.pimipmrouteupstreamasserttimer.is_set)\n\n def has_operation(self):\n return (\n self.yfilter != YFilter.not_set or\n self.ipmroutegroup.yfilter != YFilter.not_set or\n self.ipmroutesource.yfilter != YFilter.not_set or\n self.ipmroutesourcemask.yfilter != YFilter.not_set or\n self.pimipmrouteassertmetric.yfilter != YFilter.not_set or\n self.pimipmrouteassertmetricpref.yfilter != YFilter.not_set or\n self.pimipmrouteassertrptbit.yfilter != YFilter.not_set or\n self.pimipmrouteflags.yfilter != YFilter.not_set or\n self.pimipmrouteupstreamasserttimer.yfilter != YFilter.not_set)\n\n def get_segment_path(self):\n path_buffer = \"\"\n path_buffer = \"pimIpMRouteEntry\" + \"[ipMRouteGroup='\" + self.ipmroutegroup.get() + \"']\" + \"[ipMRouteSource='\" + self.ipmroutesource.get() + \"']\" + \"[ipMRouteSourceMask='\" + self.ipmroutesourcemask.get() + \"']\" + path_buffer\n\n return path_buffer\n\n def get_entity_path(self, ancestor):\n path_buffer = \"\"\n if (ancestor is None):\n path_buffer = \"PIM-MIB:PIM-MIB/pimIpMRouteTable/%s\" % self.get_segment_path()\n else:\n path_buffer = _get_relative_entity_path(self, ancestor, path_buffer)\n\n leaf_name_data = LeafDataList()\n if (self.ipmroutegroup.is_set or self.ipmroutegroup.yfilter != YFilter.not_set):\n leaf_name_data.append(self.ipmroutegroup.get_name_leafdata())\n if (self.ipmroutesource.is_set or self.ipmroutesource.yfilter != YFilter.not_set):\n leaf_name_data.append(self.ipmroutesource.get_name_leafdata())\n if (self.ipmroutesourcemask.is_set or self.ipmroutesourcemask.yfilter != YFilter.not_set):\n leaf_name_data.append(self.ipmroutesourcemask.get_name_leafdata())\n if (self.pimipmrouteassertmetric.is_set or self.pimipmrouteassertmetric.yfilter != YFilter.not_set):\n leaf_name_data.append(self.pimipmrouteassertmetric.get_name_leafdata())\n if (self.pimipmrouteassertmetricpref.is_set or self.pimipmrouteassertmetricpref.yfilter != YFilter.not_set):\n leaf_name_data.append(self.pimipmrouteassertmetricpref.get_name_leafdata())\n if (self.pimipmrouteassertrptbit.is_set or self.pimipmrouteassertrptbit.yfilter != YFilter.not_set):\n leaf_name_data.append(self.pimipmrouteassertrptbit.get_name_leafdata())\n if (self.pimipmrouteflags.is_set or self.pimipmrouteflags.yfilter != YFilter.not_set):\n leaf_name_data.append(self.pimipmrouteflags.get_name_leafdata())\n if (self.pimipmrouteupstreamasserttimer.is_set or self.pimipmrouteupstreamasserttimer.yfilter != YFilter.not_set):\n leaf_name_data.append(self.pimipmrouteupstreamasserttimer.get_name_leafdata())\n\n entity_path = EntityPath(path_buffer, leaf_name_data)\n return entity_path\n\n def get_child_by_name(self, child_yang_name, segment_path):\n child = self._get_child_by_seg_name([child_yang_name, segment_path])\n if child is not None:\n return child\n\n return None\n\n def has_leaf_or_child_of_name(self, name):\n if(name == \"ipMRouteGroup\" or name == \"ipMRouteSource\" or name == \"ipMRouteSourceMask\" or name == \"pimIpMRouteAssertMetric\" or name == \"pimIpMRouteAssertMetricPref\" or name == \"pimIpMRouteAssertRPTBit\" or name == \"pimIpMRouteFlags\" or name == \"pimIpMRouteUpstreamAssertTimer\"):\n return True\n return False\n\n def set_value(self, value_path, value, name_space, name_space_prefix):\n if(value_path == \"ipMRouteGroup\"):\n self.ipmroutegroup = value\n self.ipmroutegroup.value_namespace = name_space\n self.ipmroutegroup.value_namespace_prefix = name_space_prefix\n if(value_path == \"ipMRouteSource\"):\n self.ipmroutesource = value\n self.ipmroutesource.value_namespace = name_space\n self.ipmroutesource.value_namespace_prefix = name_space_prefix\n if(value_path == \"ipMRouteSourceMask\"):\n self.ipmroutesourcemask = value\n self.ipmroutesourcemask.value_namespace = name_space\n self.ipmroutesourcemask.value_namespace_prefix = name_space_prefix\n if(value_path == \"pimIpMRouteAssertMetric\"):\n self.pimipmrouteassertmetric = value\n self.pimipmrouteassertmetric.value_namespace = name_space\n self.pimipmrouteassertmetric.value_namespace_prefix = name_space_prefix\n if(value_path == \"pimIpMRouteAssertMetricPref\"):\n self.pimipmrouteassertmetricpref = value\n self.pimipmrouteassertmetricpref.value_namespace = name_space\n self.pimipmrouteassertmetricpref.value_namespace_prefix = name_space_prefix\n if(value_path == \"pimIpMRouteAssertRPTBit\"):\n self.pimipmrouteassertrptbit = value\n self.pimipmrouteassertrptbit.value_namespace = name_space\n self.pimipmrouteassertrptbit.value_namespace_prefix = name_space_prefix\n if(value_path == \"pimIpMRouteFlags\"):\n self.pimipmrouteflags = value\n self.pimipmrouteflags.value_namespace = name_space\n self.pimipmrouteflags.value_namespace_prefix = name_space_prefix\n if(value_path == \"pimIpMRouteUpstreamAssertTimer\"):\n self.pimipmrouteupstreamasserttimer = value\n self.pimipmrouteupstreamasserttimer.value_namespace = name_space\n self.pimipmrouteupstreamasserttimer.value_namespace_prefix = name_space_prefix\n\n def has_data(self):\n for c in self.pimipmrouteentry:\n if (c.has_data()):\n return True\n return False\n\n def has_operation(self):\n for c in self.pimipmrouteentry:\n if (c.has_operation()):\n return True\n return self.yfilter != YFilter.not_set\n\n def get_segment_path(self):\n path_buffer = \"\"\n path_buffer = \"pimIpMRouteTable\" + path_buffer\n\n return path_buffer\n\n def get_entity_path(self, ancestor):\n path_buffer = \"\"\n if (ancestor is None):\n path_buffer = \"PIM-MIB:PIM-MIB/%s\" % self.get_segment_path()\n else:\n path_buffer = _get_relative_entity_path(self, ancestor, path_buffer)\n\n leaf_name_data = LeafDataList()\n\n entity_path = EntityPath(path_buffer, leaf_name_data)\n return entity_path\n\n def get_child_by_name(self, child_yang_name, segment_path):\n child = self._get_child_by_seg_name([child_yang_name, segment_path])\n if child is not None:\n return child\n\n if (child_yang_name == \"pimIpMRouteEntry\"):\n for c in self.pimipmrouteentry:\n segment = c.get_segment_path()\n if (segment_path == segment):\n return c\n c = PimMib.Pimipmroutetable.Pimipmrouteentry()\n c.parent = self\n local_reference_key = \"ydk::seg::%s\" % segment_path\n self._local_refs[local_reference_key] = c\n self.pimipmrouteentry.append(c)\n return c\n\n return None\n\n def has_leaf_or_child_of_name(self, name):\n if(name == \"pimIpMRouteEntry\"):\n return True\n return False\n\n def set_value(self, value_path, value, name_space, name_space_prefix):\n pass\n\n\n class Pimrptable(Entity):\n \"\"\"\n The (conceptual) table listing PIM version 1 information\n for the Rendezvous Points (RPs) for IP multicast groups.\n This table is deprecated since its function is replaced by\n the pimRPSetTable for PIM version 2.\n \n .. attribute:: pimrpentry\n \n \tAn entry (conceptual row) in the pimRPTable. There is one entry per RP address for each IP multicast group\n \t**type**\\: list of :py:class:`Pimrpentry `\n \n \t**status**\\: deprecated\n \n \n\n \"\"\"\n\n _prefix = 'PIM-MIB'\n _revision = '2000-09-28'\n\n def __init__(self):\n super(PimMib.Pimrptable, self).__init__()\n\n self.yang_name = \"pimRPTable\"\n self.yang_parent_name = \"PIM-MIB\"\n\n self.pimrpentry = YList(self)\n\n def __setattr__(self, name, value):\n self._check_monkey_patching_error(name, value)\n with _handle_type_error():\n if name in self.__dict__ and isinstance(self.__dict__[name], YList):\n raise YPYModelError(\"Attempt to assign value of '{}' to YList ldata. \"\n \"Please use list append or extend method.\"\n .format(value))\n if isinstance(value, Enum.YLeaf):\n value = value.name\n if name in () and name in self.__dict__:\n if isinstance(value, YLeaf):\n self.__dict__[name].set(value.get())\n elif isinstance(value, YLeafList):\n super(PimMib.Pimrptable, self).__setattr__(name, value)\n else:\n self.__dict__[name].set(value)\n else:\n if hasattr(value, \"parent\") and name != \"parent\":\n if hasattr(value, \"is_presence_container\") and value.is_presence_container:\n value.parent = self\n elif value.parent is None and value.yang_name in self._children_yang_names:\n value.parent = self\n super(PimMib.Pimrptable, self).__setattr__(name, value)\n\n\n class Pimrpentry(Entity):\n \"\"\"\n An entry (conceptual row) in the pimRPTable. There is one\n entry per RP address for each IP multicast group.\n \n .. attribute:: pimrpgroupaddress \n \n \tThe IP multicast group address for which this entry contains information about an RP\n \t**type**\\: str\n \n \t**pattern:** (([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])\\\\.){3}([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])(%[\\\\p{N}\\\\p{L}]+)?\n \n \t**status**\\: deprecated\n \n .. attribute:: pimrpaddress \n \n \tThe unicast address of the RP\n \t**type**\\: str\n \n \t**pattern:** (([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])\\\\.){3}([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])(%[\\\\p{N}\\\\p{L}]+)?\n \n \t**status**\\: deprecated\n \n .. attribute:: pimrplastchange\n \n \tThe value of sysUpTime at the time when the corresponding instance of pimRPState last changed its value\n \t**type**\\: int\n \n \t**range:** 0..4294967295\n \n \t**status**\\: deprecated\n \n .. attribute:: pimrprowstatus\n \n \tThe status of this row, by which new entries may be created, or old entries deleted from this table\n \t**type**\\: :py:class:`Rowstatus `\n \n \t**status**\\: deprecated\n \n .. attribute:: pimrpstate\n \n \tThe state of the RP\n \t**type**\\: :py:class:`Pimrpstate `\n \n \t**status**\\: deprecated\n \n .. attribute:: pimrpstatetimer\n \n \tThe minimum time remaining before the next state change. When pimRPState is up, this is the minimum time which must expire until it can be declared down. When pimRPState is down, this is the time until it will be declared up (in order to retry)\n \t**type**\\: int\n \n \t**range:** 0..4294967295\n \n \t**status**\\: deprecated\n \n \n\n \"\"\"\n\n _prefix = 'PIM-MIB'\n _revision = '2000-09-28'\n\n def __init__(self):\n super(PimMib.Pimrptable.Pimrpentry, self).__init__()\n\n self.yang_name = \"pimRPEntry\"\n self.yang_parent_name = \"pimRPTable\"\n\n self.pimrpgroupaddress = YLeaf(YType.str, \"pimRPGroupAddress\")\n\n self.pimrpaddress = YLeaf(YType.str, \"pimRPAddress\")\n\n self.pimrplastchange = YLeaf(YType.uint32, \"pimRPLastChange\")\n\n self.pimrprowstatus = YLeaf(YType.enumeration, \"pimRPRowStatus\")\n\n self.pimrpstate = YLeaf(YType.enumeration, \"pimRPState\")\n\n self.pimrpstatetimer = YLeaf(YType.uint32, \"pimRPStateTimer\")\n\n def __setattr__(self, name, value):\n self._check_monkey_patching_error(name, value)\n with _handle_type_error():\n if name in self.__dict__ and isinstance(self.__dict__[name], YList):\n raise YPYModelError(\"Attempt to assign value of '{}' to YList ldata. \"\n \"Please use list append or extend method.\"\n .format(value))\n if isinstance(value, Enum.YLeaf):\n value = value.name\n if name in (\"pimrpgroupaddress\",\n \"pimrpaddress\",\n \"pimrplastchange\",\n \"pimrprowstatus\",\n \"pimrpstate\",\n \"pimrpstatetimer\") and name in self.__dict__:\n if isinstance(value, YLeaf):\n self.__dict__[name].set(value.get())\n elif isinstance(value, YLeafList):\n super(PimMib.Pimrptable.Pimrpentry, self).__setattr__(name, value)\n else:\n self.__dict__[name].set(value)\n else:\n if hasattr(value, \"parent\") and name != \"parent\":\n if hasattr(value, \"is_presence_container\") and value.is_presence_container:\n value.parent = self\n elif value.parent is None and value.yang_name in self._children_yang_names:\n value.parent = self\n super(PimMib.Pimrptable.Pimrpentry, self).__setattr__(name, value)\n\n class Pimrpstate(Enum):\n \"\"\"\n Pimrpstate\n\n The state of the RP.\n\n .. data:: up = 1\n\n .. data:: down = 2\n\n \"\"\"\n\n up = Enum.YLeaf(1, \"up\")\n\n down = Enum.YLeaf(2, \"down\")\n\n\n def has_data(self):\n return (\n self.pimrpgroupaddress.is_set or\n self.pimrpaddress.is_set or\n self.pimrplastchange.is_set or\n self.pimrprowstatus.is_set or\n self.pimrpstate.is_set or\n self.pimrpstatetimer.is_set)\n\n def has_operation(self):\n return (\n self.yfilter != YFilter.not_set or\n self.pimrpgroupaddress.yfilter != YFilter.not_set or\n self.pimrpaddress.yfilter != YFilter.not_set or\n self.pimrplastchange.yfilter != YFilter.not_set or\n self.pimrprowstatus.yfilter != YFilter.not_set or\n self.pimrpstate.yfilter != YFilter.not_set or\n self.pimrpstatetimer.yfilter != YFilter.not_set)\n\n def get_segment_path(self):\n path_buffer = \"\"\n path_buffer = \"pimRPEntry\" + \"[pimRPGroupAddress='\" + self.pimrpgroupaddress.get() + \"']\" + \"[pimRPAddress='\" + self.pimrpaddress.get() + \"']\" + path_buffer\n\n return path_buffer\n\n def get_entity_path(self, ancestor):\n path_buffer = \"\"\n if (ancestor is None):\n path_buffer = \"PIM-MIB:PIM-MIB/pimRPTable/%s\" % self.get_segment_path()\n else:\n path_buffer = _get_relative_entity_path(self, ancestor, path_buffer)\n\n leaf_name_data = LeafDataList()\n if (self.pimrpgroupaddress.is_set or self.pimrpgroupaddress.yfilter != YFilter.not_set):\n leaf_name_data.append(self.pimrpgroupaddress.get_name_leafdata())\n if (self.pimrpaddress.is_set or self.pimrpaddress.yfilter != YFilter.not_set):\n leaf_name_data.append(self.pimrpaddress.get_name_leafdata())\n if (self.pimrplastchange.is_set or self.pimrplastchange.yfilter != YFilter.not_set):\n leaf_name_data.append(self.pimrplastchange.get_name_leafdata())\n if (self.pimrprowstatus.is_set or self.pimrprowstatus.yfilter != YFilter.not_set):\n leaf_name_data.append(self.pimrprowstatus.get_name_leafdata())\n if (self.pimrpstate.is_set or self.pimrpstate.yfilter != YFilter.not_set):\n leaf_name_data.append(self.pimrpstate.get_name_leafdata())\n if (self.pimrpstatetimer.is_set or self.pimrpstatetimer.yfilter != YFilter.not_set):\n leaf_name_data.append(self.pimrpstatetimer.get_name_leafdata())\n\n entity_path = EntityPath(path_buffer, leaf_name_data)\n return entity_path\n\n def get_child_by_name(self, child_yang_name, segment_path):\n child = self._get_child_by_seg_name([child_yang_name, segment_path])\n if child is not None:\n return child\n\n return None\n\n def has_leaf_or_child_of_name(self, name):\n if(name == \"pimRPGroupAddress\" or name == \"pimRPAddress\" or name == \"pimRPLastChange\" or name == \"pimRPRowStatus\" or name == \"pimRPState\" or name == \"pimRPStateTimer\"):\n return True\n return False\n\n def set_value(self, value_path, value, name_space, name_space_prefix):\n if(value_path == \"pimRPGroupAddress\"):\n self.pimrpgroupaddress = value\n self.pimrpgroupaddress.value_namespace = name_space\n self.pimrpgroupaddress.value_namespace_prefix = name_space_prefix\n if(value_path == \"pimRPAddress\"):\n self.pimrpaddress = value\n self.pimrpaddress.value_namespace = name_space\n self.pimrpaddress.value_namespace_prefix = name_space_prefix\n if(value_path == \"pimRPLastChange\"):\n self.pimrplastchange = value\n self.pimrplastchange.value_namespace = name_space\n self.pimrplastchange.value_namespace_prefix = name_space_prefix\n if(value_path == \"pimRPRowStatus\"):\n self.pimrprowstatus = value\n self.pimrprowstatus.value_namespace = name_space\n self.pimrprowstatus.value_namespace_prefix = name_space_prefix\n if(value_path == \"pimRPState\"):\n self.pimrpstate = value\n self.pimrpstate.value_namespace = name_space\n self.pimrpstate.value_namespace_prefix = name_space_prefix\n if(value_path == \"pimRPStateTimer\"):\n self.pimrpstatetimer = value\n self.pimrpstatetimer.value_namespace = name_space\n self.pimrpstatetimer.value_namespace_prefix = name_space_prefix\n\n def has_data(self):\n for c in self.pimrpentry:\n if (c.has_data()):\n return True\n return False\n\n def has_operation(self):\n for c in self.pimrpentry:\n if (c.has_operation()):\n return True\n return self.yfilter != YFilter.not_set\n\n def get_segment_path(self):\n path_buffer = \"\"\n path_buffer = \"pimRPTable\" + path_buffer\n\n return path_buffer\n\n def get_entity_path(self, ancestor):\n path_buffer = \"\"\n if (ancestor is None):\n path_buffer = \"PIM-MIB:PIM-MIB/%s\" % self.get_segment_path()\n else:\n path_buffer = _get_relative_entity_path(self, ancestor, path_buffer)\n\n leaf_name_data = LeafDataList()\n\n entity_path = EntityPath(path_buffer, leaf_name_data)\n return entity_path\n\n def get_child_by_name(self, child_yang_name, segment_path):\n child = self._get_child_by_seg_name([child_yang_name, segment_path])\n if child is not None:\n return child\n\n if (child_yang_name == \"pimRPEntry\"):\n for c in self.pimrpentry:\n segment = c.get_segment_path()\n if (segment_path == segment):\n return c\n c = PimMib.Pimrptable.Pimrpentry()\n c.parent = self\n local_reference_key = \"ydk::seg::%s\" % segment_path\n self._local_refs[local_reference_key] = c\n self.pimrpentry.append(c)\n return c\n\n return None\n\n def has_leaf_or_child_of_name(self, name):\n if(name == \"pimRPEntry\"):\n return True\n return False\n\n def set_value(self, value_path, value, name_space, name_space_prefix):\n pass\n\n\n class Pimrpsettable(Entity):\n \"\"\"\n The (conceptual) table listing PIM information for\n candidate Rendezvous Points (RPs) for IP multicast groups.\n When the local router is the BSR, this information is\n obtained from received Candidate\\-RP\\-Advertisements. When\n the local router is not the BSR, this information is\n obtained from received RP\\-Set messages.\n \n .. attribute:: pimrpsetentry\n \n \tAn entry (conceptual row) in the pimRPSetTable\n \t**type**\\: list of :py:class:`Pimrpsetentry `\n \n \n\n \"\"\"\n\n _prefix = 'PIM-MIB'\n _revision = '2000-09-28'\n\n def __init__(self):\n super(PimMib.Pimrpsettable, self).__init__()\n\n self.yang_name = \"pimRPSetTable\"\n self.yang_parent_name = \"PIM-MIB\"\n\n self.pimrpsetentry = YList(self)\n\n def __setattr__(self, name, value):\n self._check_monkey_patching_error(name, value)\n with _handle_type_error():\n if name in self.__dict__ and isinstance(self.__dict__[name], YList):\n raise YPYModelError(\"Attempt to assign value of '{}' to YList ldata. \"\n \"Please use list append or extend method.\"\n .format(value))\n if isinstance(value, Enum.YLeaf):\n value = value.name\n if name in () and name in self.__dict__:\n if isinstance(value, YLeaf):\n self.__dict__[name].set(value.get())\n elif isinstance(value, YLeafList):\n super(PimMib.Pimrpsettable, self).__setattr__(name, value)\n else:\n self.__dict__[name].set(value)\n else:\n if hasattr(value, \"parent\") and name != \"parent\":\n if hasattr(value, \"is_presence_container\") and value.is_presence_container:\n value.parent = self\n elif value.parent is None and value.yang_name in self._children_yang_names:\n value.parent = self\n super(PimMib.Pimrpsettable, self).__setattr__(name, value)\n\n\n class Pimrpsetentry(Entity):\n \"\"\"\n An entry (conceptual row) in the pimRPSetTable.\n \n .. attribute:: pimrpsetcomponent \n \n \t A number uniquely identifying the component. Each protocol instance connected to a separate domain should have a different index value\n \t**type**\\: int\n \n \t**range:** 1..255\n \n .. attribute:: pimrpsetgroupaddress \n \n \tThe IP multicast group address which, when combined with pimRPSetGroupMask, gives the group prefix for which this entry contains information about the Candidate\\-RP\n \t**type**\\: str\n \n \t**pattern:** (([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])\\\\.){3}([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])(%[\\\\p{N}\\\\p{L}]+)?\n \n .. attribute:: pimrpsetgroupmask \n \n \tThe multicast group address mask which, when combined with pimRPSetGroupAddress, gives the group prefix for which this entry contains information about the Candidate\\-RP\n \t**type**\\: str\n \n \t**pattern:** (([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])\\\\.){3}([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])(%[\\\\p{N}\\\\p{L}]+)?\n \n .. attribute:: pimrpsetaddress \n \n \tThe IP address of the Candidate\\-RP\n \t**type**\\: str\n \n \t**pattern:** (([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])\\\\.){3}([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])(%[\\\\p{N}\\\\p{L}]+)?\n \n .. attribute:: pimrpsetexpirytime\n \n \tThe minimum time remaining before the Candidate\\-RP will be declared down. If the local router is not the BSR, this value is 0\n \t**type**\\: int\n \n \t**range:** 0..4294967295\n \n .. attribute:: pimrpsetholdtime\n \n \tThe holdtime of a Candidate\\-RP. If the local router is not the BSR, this value is 0\n \t**type**\\: int\n \n \t**range:** 0..255\n \n \t**units**\\: seconds\n \n \n\n \"\"\"\n\n _prefix = 'PIM-MIB'\n _revision = '2000-09-28'\n\n def __init__(self):\n super(PimMib.Pimrpsettable.Pimrpsetentry, self).__init__()\n\n self.yang_name = \"pimRPSetEntry\"\n self.yang_parent_name = \"pimRPSetTable\"\n\n self.pimrpsetcomponent = YLeaf(YType.int32, \"pimRPSetComponent\")\n\n self.pimrpsetgroupaddress = YLeaf(YType.str, \"pimRPSetGroupAddress\")\n\n self.pimrpsetgroupmask = YLeaf(YType.str, \"pimRPSetGroupMask\")\n\n self.pimrpsetaddress = YLeaf(YType.str, \"pimRPSetAddress\")\n\n self.pimrpsetexpirytime = YLeaf(YType.uint32, \"pimRPSetExpiryTime\")\n\n self.pimrpsetholdtime = YLeaf(YType.int32, \"pimRPSetHoldTime\")\n\n def __setattr__(self, name, value):\n self._check_monkey_patching_error(name, value)\n with _handle_type_error():\n if name in self.__dict__ and isinstance(self.__dict__[name], YList):\n raise YPYModelError(\"Attempt to assign value of '{}' to YList ldata. \"\n \"Please use list append or extend method.\"\n .format(value))\n if isinstance(value, Enum.YLeaf):\n value = value.name\n if name in (\"pimrpsetcomponent\",\n \"pimrpsetgroupaddress\",\n \"pimrpsetgroupmask\",\n \"pimrpsetaddress\",\n \"pimrpsetexpirytime\",\n \"pimrpsetholdtime\") and name in self.__dict__:\n if isinstance(value, YLeaf):\n self.__dict__[name].set(value.get())\n elif isinstance(value, YLeafList):\n super(PimMib.Pimrpsettable.Pimrpsetentry, self).__setattr__(name, value)\n else:\n self.__dict__[name].set(value)\n else:\n if hasattr(value, \"parent\") and name != \"parent\":\n if hasattr(value, \"is_presence_container\") and value.is_presence_container:\n value.parent = self\n elif value.parent is None and value.yang_name in self._children_yang_names:\n value.parent = self\n super(PimMib.Pimrpsettable.Pimrpsetentry, self).__setattr__(name, value)\n\n def has_data(self):\n return (\n self.pimrpsetcomponent.is_set or\n self.pimrpsetgroupaddress.is_set or\n self.pimrpsetgroupmask.is_set or\n self.pimrpsetaddress.is_set or\n self.pimrpsetexpirytime.is_set or\n self.pimrpsetholdtime.is_set)\n\n def has_operation(self):\n return (\n self.yfilter != YFilter.not_set or\n self.pimrpsetcomponent.yfilter != YFilter.not_set or\n self.pimrpsetgroupaddress.yfilter != YFilter.not_set or\n self.pimrpsetgroupmask.yfilter != YFilter.not_set or\n self.pimrpsetaddress.yfilter != YFilter.not_set or\n self.pimrpsetexpirytime.yfilter != YFilter.not_set or\n self.pimrpsetholdtime.yfilter != YFilter.not_set)\n\n def get_segment_path(self):\n path_buffer = \"\"\n path_buffer = \"pimRPSetEntry\" + \"[pimRPSetComponent='\" + self.pimrpsetcomponent.get() + \"']\" + \"[pimRPSetGroupAddress='\" + self.pimrpsetgroupaddress.get() + \"']\" + \"[pimRPSetGroupMask='\" + self.pimrpsetgroupmask.get() + \"']\" + \"[pimRPSetAddress='\" + self.pimrpsetaddress.get() + \"']\" + path_buffer\n\n return path_buffer\n\n def get_entity_path(self, ancestor):\n path_buffer = \"\"\n if (ancestor is None):\n path_buffer = \"PIM-MIB:PIM-MIB/pimRPSetTable/%s\" % self.get_segment_path()\n else:\n path_buffer = _get_relative_entity_path(self, ancestor, path_buffer)\n\n leaf_name_data = LeafDataList()\n if (self.pimrpsetcomponent.is_set or self.pimrpsetcomponent.yfilter != YFilter.not_set):\n leaf_name_data.append(self.pimrpsetcomponent.get_name_leafdata())\n if (self.pimrpsetgroupaddress.is_set or self.pimrpsetgroupaddress.yfilter != YFilter.not_set):\n leaf_name_data.append(self.pimrpsetgroupaddress.get_name_leafdata())\n if (self.pimrpsetgroupmask.is_set or self.pimrpsetgroupmask.yfilter != YFilter.not_set):\n leaf_name_data.append(self.pimrpsetgroupmask.get_name_leafdata())\n if (self.pimrpsetaddress.is_set or self.pimrpsetaddress.yfilter != YFilter.not_set):\n leaf_name_data.append(self.pimrpsetaddress.get_name_leafdata())\n if (self.pimrpsetexpirytime.is_set or self.pimrpsetexpirytime.yfilter != YFilter.not_set):\n leaf_name_data.append(self.pimrpsetexpirytime.get_name_leafdata())\n if (self.pimrpsetholdtime.is_set or self.pimrpsetholdtime.yfilter != YFilter.not_set):\n leaf_name_data.append(self.pimrpsetholdtime.get_name_leafdata())\n\n entity_path = EntityPath(path_buffer, leaf_name_data)\n return entity_path\n\n def get_child_by_name(self, child_yang_name, segment_path):\n child = self._get_child_by_seg_name([child_yang_name, segment_path])\n if child is not None:\n return child\n\n return None\n\n def has_leaf_or_child_of_name(self, name):\n if(name == \"pimRPSetComponent\" or name == \"pimRPSetGroupAddress\" or name == \"pimRPSetGroupMask\" or name == \"pimRPSetAddress\" or name == \"pimRPSetExpiryTime\" or name == \"pimRPSetHoldTime\"):\n return True\n return False\n\n def set_value(self, value_path, value, name_space, name_space_prefix):\n if(value_path == \"pimRPSetComponent\"):\n self.pimrpsetcomponent = value\n self.pimrpsetcomponent.value_namespace = name_space\n self.pimrpsetcomponent.value_namespace_prefix = name_space_prefix\n if(value_path == \"pimRPSetGroupAddress\"):\n self.pimrpsetgroupaddress = value\n self.pimrpsetgroupaddress.value_namespace = name_space\n self.pimrpsetgroupaddress.value_namespace_prefix = name_space_prefix\n if(value_path == \"pimRPSetGroupMask\"):\n self.pimrpsetgroupmask = value\n self.pimrpsetgroupmask.value_namespace = name_space\n self.pimrpsetgroupmask.value_namespace_prefix = name_space_prefix\n if(value_path == \"pimRPSetAddress\"):\n self.pimrpsetaddress = value\n self.pimrpsetaddress.value_namespace = name_space\n self.pimrpsetaddress.value_namespace_prefix = name_space_prefix\n if(value_path == \"pimRPSetExpiryTime\"):\n self.pimrpsetexpirytime = value\n self.pimrpsetexpirytime.value_namespace = name_space\n self.pimrpsetexpirytime.value_namespace_prefix = name_space_prefix\n if(value_path == \"pimRPSetHoldTime\"):\n self.pimrpsetholdtime = value\n self.pimrpsetholdtime.value_namespace = name_space\n self.pimrpsetholdtime.value_namespace_prefix = name_space_prefix\n\n def has_data(self):\n for c in self.pimrpsetentry:\n if (c.has_data()):\n return True\n return False\n\n def has_operation(self):\n for c in self.pimrpsetentry:\n if (c.has_operation()):\n return True\n return self.yfilter != YFilter.not_set\n\n def get_segment_path(self):\n path_buffer = \"\"\n path_buffer = \"pimRPSetTable\" + path_buffer\n\n return path_buffer\n\n def get_entity_path(self, ancestor):\n path_buffer = \"\"\n if (ancestor is None):\n path_buffer = \"PIM-MIB:PIM-MIB/%s\" % self.get_segment_path()\n else:\n path_buffer = _get_relative_entity_path(self, ancestor, path_buffer)\n\n leaf_name_data = LeafDataList()\n\n entity_path = EntityPath(path_buffer, leaf_name_data)\n return entity_path\n\n def get_child_by_name(self, child_yang_name, segment_path):\n child = self._get_child_by_seg_name([child_yang_name, segment_path])\n if child is not None:\n return child\n\n if (child_yang_name == \"pimRPSetEntry\"):\n for c in self.pimrpsetentry:\n segment = c.get_segment_path()\n if (segment_path == segment):\n return c\n c = PimMib.Pimrpsettable.Pimrpsetentry()\n c.parent = self\n local_reference_key = \"ydk::seg::%s\" % segment_path\n self._local_refs[local_reference_key] = c\n self.pimrpsetentry.append(c)\n return c\n\n return None\n\n def has_leaf_or_child_of_name(self, name):\n if(name == \"pimRPSetEntry\"):\n return True\n return False\n\n def set_value(self, value_path, value, name_space, name_space_prefix):\n pass\n\n\n class Pimipmroutenexthoptable(Entity):\n \"\"\"\n The (conceptual) table listing PIM\\-specific information on\n a subset of the rows of the ipMRouteNextHopTable defined in\n the IP Multicast MIB.\n \n .. attribute:: pimipmroutenexthopentry\n \n \tAn entry (conceptual row) in the pimIpMRouteNextHopTable. There is one entry per entry in the ipMRouteNextHopTable whose interface is running PIM and whose ipMRouteNextHopState is pruned(1)\n \t**type**\\: list of :py:class:`Pimipmroutenexthopentry `\n \n \n\n \"\"\"\n\n _prefix = 'PIM-MIB'\n _revision = '2000-09-28'\n\n def __init__(self):\n super(PimMib.Pimipmroutenexthoptable, self).__init__()\n\n self.yang_name = \"pimIpMRouteNextHopTable\"\n self.yang_parent_name = \"PIM-MIB\"\n\n self.pimipmroutenexthopentry = YList(self)\n\n def __setattr__(self, name, value):\n self._check_monkey_patching_error(name, value)\n with _handle_type_error():\n if name in self.__dict__ and isinstance(self.__dict__[name], YList):\n raise YPYModelError(\"Attempt to assign value of '{}' to YList ldata. \"\n \"Please use list append or extend method.\"\n .format(value))\n if isinstance(value, Enum.YLeaf):\n value = value.name\n if name in () and name in self.__dict__:\n if isinstance(value, YLeaf):\n self.__dict__[name].set(value.get())\n elif isinstance(value, YLeafList):\n super(PimMib.Pimipmroutenexthoptable, self).__setattr__(name, value)\n else:\n self.__dict__[name].set(value)\n else:\n if hasattr(value, \"parent\") and name != \"parent\":\n if hasattr(value, \"is_presence_container\") and value.is_presence_container:\n value.parent = self\n elif value.parent is None and value.yang_name in self._children_yang_names:\n value.parent = self\n super(PimMib.Pimipmroutenexthoptable, self).__setattr__(name, value)\n\n\n class Pimipmroutenexthopentry(Entity):\n \"\"\"\n An entry (conceptual row) in the pimIpMRouteNextHopTable.\n There is one entry per entry in the ipMRouteNextHopTable\n whose interface is running PIM and whose\n ipMRouteNextHopState is pruned(1).\n \n .. attribute:: ipmroutenexthopgroup \n \n \t\n \t**type**\\: str\n \n \t**pattern:** (([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])\\\\.){3}([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])(%[\\\\p{N}\\\\p{L}]+)?\n \n \t**refers to**\\: :py:class:`ipmroutenexthopgroup `\n \n .. attribute:: ipmroutenexthopsource \n \n \t\n \t**type**\\: str\n \n \t**pattern:** (([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])\\\\.){3}([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])(%[\\\\p{N}\\\\p{L}]+)?\n \n \t**refers to**\\: :py:class:`ipmroutenexthopsource `\n \n .. attribute:: ipmroutenexthopsourcemask \n \n \t\n \t**type**\\: str\n \n \t**pattern:** (([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])\\\\.){3}([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])(%[\\\\p{N}\\\\p{L}]+)?\n \n \t**refers to**\\: :py:class:`ipmroutenexthopsourcemask `\n \n .. attribute:: ipmroutenexthopifindex \n \n \t\n \t**type**\\: int\n \n \t**range:** 1..2147483647\n \n \t**refers to**\\: :py:class:`ipmroutenexthopifindex `\n \n .. attribute:: ipmroutenexthopaddress \n \n \t\n \t**type**\\: str\n \n \t**pattern:** (([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])\\\\.){3}([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])(%[\\\\p{N}\\\\p{L}]+)?\n \n \t**refers to**\\: :py:class:`ipmroutenexthopaddress `\n \n .. attribute:: pimipmroutenexthopprunereason\n \n \tThis object indicates why the downstream interface was pruned, whether in response to a PIM prune message or due to PIM Assert processing\n \t**type**\\: :py:class:`Pimipmroutenexthopprunereason `\n \n \n\n \"\"\"\n\n _prefix = 'PIM-MIB'\n _revision = '2000-09-28'\n\n def __init__(self):\n super(PimMib.Pimipmroutenexthoptable.Pimipmroutenexthopentry, self).__init__()\n\n self.yang_name = \"pimIpMRouteNextHopEntry\"\n self.yang_parent_name = \"pimIpMRouteNextHopTable\"\n\n self.ipmroutenexthopgroup = YLeaf(YType.str, \"ipMRouteNextHopGroup\")\n\n self.ipmroutenexthopsource = YLeaf(YType.str, \"ipMRouteNextHopSource\")\n\n self.ipmroutenexthopsourcemask = YLeaf(YType.str, \"ipMRouteNextHopSourceMask\")\n\n self.ipmroutenexthopifindex = YLeaf(YType.str, \"ipMRouteNextHopIfIndex\")\n\n self.ipmroutenexthopaddress = YLeaf(YType.str, \"ipMRouteNextHopAddress\")\n\n self.pimipmroutenexthopprunereason = YLeaf(YType.enumeration, \"pimIpMRouteNextHopPruneReason\")\n\n def __setattr__(self, name, value):\n self._check_monkey_patching_error(name, value)\n with _handle_type_error():\n if name in self.__dict__ and isinstance(self.__dict__[name], YList):\n raise YPYModelError(\"Attempt to assign value of '{}' to YList ldata. \"\n \"Please use list append or extend method.\"\n .format(value))\n if isinstance(value, Enum.YLeaf):\n value = value.name\n if name in (\"ipmroutenexthopgroup\",\n \"ipmroutenexthopsource\",\n \"ipmroutenexthopsourcemask\",\n \"ipmroutenexthopifindex\",\n \"ipmroutenexthopaddress\",\n \"pimipmroutenexthopprunereason\") and name in self.__dict__:\n if isinstance(value, YLeaf):\n self.__dict__[name].set(value.get())\n elif isinstance(value, YLeafList):\n super(PimMib.Pimipmroutenexthoptable.Pimipmroutenexthopentry, self).__setattr__(name, value)\n else:\n self.__dict__[name].set(value)\n else:\n if hasattr(value, \"parent\") and name != \"parent\":\n if hasattr(value, \"is_presence_container\") and value.is_presence_container:\n value.parent = self\n elif value.parent is None and value.yang_name in self._children_yang_names:\n value.parent = self\n super(PimMib.Pimipmroutenexthoptable.Pimipmroutenexthopentry, self).__setattr__(name, value)\n\n class Pimipmroutenexthopprunereason(Enum):\n \"\"\"\n Pimipmroutenexthopprunereason\n\n This object indicates why the downstream interface was\n\n pruned, whether in response to a PIM prune message or due to\n\n PIM Assert processing.\n\n .. data:: other = 1\n\n .. data:: prune = 2\n\n .. data:: assert_ = 3\n\n \"\"\"\n\n other = Enum.YLeaf(1, \"other\")\n\n prune = Enum.YLeaf(2, \"prune\")\n\n assert_ = Enum.YLeaf(3, \"assert\")\n\n\n def has_data(self):\n return (\n self.ipmroutenexthopgroup.is_set or\n self.ipmroutenexthopsource.is_set or\n self.ipmroutenexthopsourcemask.is_set or\n self.ipmroutenexthopifindex.is_set or\n self.ipmroutenexthopaddress.is_set or\n self.pimipmroutenexthopprunereason.is_set)\n\n def has_operation(self):\n return (\n self.yfilter != YFilter.not_set or\n self.ipmroutenexthopgroup.yfilter != YFilter.not_set or\n self.ipmroutenexthopsource.yfilter != YFilter.not_set or\n self.ipmroutenexthopsourcemask.yfilter != YFilter.not_set or\n self.ipmroutenexthopifindex.yfilter != YFilter.not_set or\n self.ipmroutenexthopaddress.yfilter != YFilter.not_set or\n self.pimipmroutenexthopprunereason.yfilter != YFilter.not_set)\n\n def get_segment_path(self):\n path_buffer = \"\"\n path_buffer = \"pimIpMRouteNextHopEntry\" + \"[ipMRouteNextHopGroup='\" + self.ipmroutenexthopgroup.get() + \"']\" + \"[ipMRouteNextHopSource='\" + self.ipmroutenexthopsource.get() + \"']\" + \"[ipMRouteNextHopSourceMask='\" + self.ipmroutenexthopsourcemask.get() + \"']\" + \"[ipMRouteNextHopIfIndex='\" + self.ipmroutenexthopifindex.get() + \"']\" + \"[ipMRouteNextHopAddress='\" + self.ipmroutenexthopaddress.get() + \"']\" + path_buffer\n\n return path_buffer\n\n def get_entity_path(self, ancestor):\n path_buffer = \"\"\n if (ancestor is None):\n path_buffer = \"PIM-MIB:PIM-MIB/pimIpMRouteNextHopTable/%s\" % self.get_segment_path()\n else:\n path_buffer = _get_relative_entity_path(self, ancestor, path_buffer)\n\n leaf_name_data = LeafDataList()\n if (self.ipmroutenexthopgroup.is_set or self.ipmroutenexthopgroup.yfilter != YFilter.not_set):\n leaf_name_data.append(self.ipmroutenexthopgroup.get_name_leafdata())\n if (self.ipmroutenexthopsource.is_set or self.ipmroutenexthopsource.yfilter != YFilter.not_set):\n leaf_name_data.append(self.ipmroutenexthopsource.get_name_leafdata())\n if (self.ipmroutenexthopsourcemask.is_set or self.ipmroutenexthopsourcemask.yfilter != YFilter.not_set):\n leaf_name_data.append(self.ipmroutenexthopsourcemask.get_name_leafdata())\n if (self.ipmroutenexthopifindex.is_set or self.ipmroutenexthopifindex.yfilter != YFilter.not_set):\n leaf_name_data.append(self.ipmroutenexthopifindex.get_name_leafdata())\n if (self.ipmroutenexthopaddress.is_set or self.ipmroutenexthopaddress.yfilter != YFilter.not_set):\n leaf_name_data.append(self.ipmroutenexthopaddress.get_name_leafdata())\n if (self.pimipmroutenexthopprunereason.is_set or self.pimipmroutenexthopprunereason.yfilter != YFilter.not_set):\n leaf_name_data.append(self.pimipmroutenexthopprunereason.get_name_leafdata())\n\n entity_path = EntityPath(path_buffer, leaf_name_data)\n return entity_path\n\n def get_child_by_name(self, child_yang_name, segment_path):\n child = self._get_child_by_seg_name([child_yang_name, segment_path])\n if child is not None:\n return child\n\n return None\n\n def has_leaf_or_child_of_name(self, name):\n if(name == \"ipMRouteNextHopGroup\" or name == \"ipMRouteNextHopSource\" or name == \"ipMRouteNextHopSourceMask\" or name == \"ipMRouteNextHopIfIndex\" or name == \"ipMRouteNextHopAddress\" or name == \"pimIpMRouteNextHopPruneReason\"):\n return True\n return False\n\n def set_value(self, value_path, value, name_space, name_space_prefix):\n if(value_path == \"ipMRouteNextHopGroup\"):\n self.ipmroutenexthopgroup = value\n self.ipmroutenexthopgroup.value_namespace = name_space\n self.ipmroutenexthopgroup.value_namespace_prefix = name_space_prefix\n if(value_path == \"ipMRouteNextHopSource\"):\n self.ipmroutenexthopsource = value\n self.ipmroutenexthopsource.value_namespace = name_space\n self.ipmroutenexthopsource.value_namespace_prefix = name_space_prefix\n if(value_path == \"ipMRouteNextHopSourceMask\"):\n self.ipmroutenexthopsourcemask = value\n self.ipmroutenexthopsourcemask.value_namespace = name_space\n self.ipmroutenexthopsourcemask.value_namespace_prefix = name_space_prefix\n if(value_path == \"ipMRouteNextHopIfIndex\"):\n self.ipmroutenexthopifindex = value\n self.ipmroutenexthopifindex.value_namespace = name_space\n self.ipmroutenexthopifindex.value_namespace_prefix = name_space_prefix\n if(value_path == \"ipMRouteNextHopAddress\"):\n self.ipmroutenexthopaddress = value\n self.ipmroutenexthopaddress.value_namespace = name_space\n self.ipmroutenexthopaddress.value_namespace_prefix = name_space_prefix\n if(value_path == \"pimIpMRouteNextHopPruneReason\"):\n self.pimipmroutenexthopprunereason = value\n self.pimipmroutenexthopprunereason.value_namespace = name_space\n self.pimipmroutenexthopprunereason.value_namespace_prefix = name_space_prefix\n\n def has_data(self):\n for c in self.pimipmroutenexthopentry:\n if (c.has_data()):\n return True\n return False\n\n def has_operation(self):\n for c in self.pimipmroutenexthopentry:\n if (c.has_operation()):\n return True\n return self.yfilter != YFilter.not_set\n\n def get_segment_path(self):\n path_buffer = \"\"\n path_buffer = \"pimIpMRouteNextHopTable\" + path_buffer\n\n return path_buffer\n\n def get_entity_path(self, ancestor):\n path_buffer = \"\"\n if (ancestor is None):\n path_buffer = \"PIM-MIB:PIM-MIB/%s\" % self.get_segment_path()\n else:\n path_buffer = _get_relative_entity_path(self, ancestor, path_buffer)\n\n leaf_name_data = LeafDataList()\n\n entity_path = EntityPath(path_buffer, leaf_name_data)\n return entity_path\n\n def get_child_by_name(self, child_yang_name, segment_path):\n child = self._get_child_by_seg_name([child_yang_name, segment_path])\n if child is not None:\n return child\n\n if (child_yang_name == \"pimIpMRouteNextHopEntry\"):\n for c in self.pimipmroutenexthopentry:\n segment = c.get_segment_path()\n if (segment_path == segment):\n return c\n c = PimMib.Pimipmroutenexthoptable.Pimipmroutenexthopentry()\n c.parent = self\n local_reference_key = \"ydk::seg::%s\" % segment_path\n self._local_refs[local_reference_key] = c\n self.pimipmroutenexthopentry.append(c)\n return c\n\n return None\n\n def has_leaf_or_child_of_name(self, name):\n if(name == \"pimIpMRouteNextHopEntry\"):\n return True\n return False\n\n def set_value(self, value_path, value, name_space, name_space_prefix):\n pass\n\n\n class Pimcandidaterptable(Entity):\n \"\"\"\n The (conceptual) table listing the IP multicast groups for\n which the local router is to advertise itself as a\n Candidate\\-RP when the value of pimComponentCRPHoldTime is\n non\\-zero. If this table is empty, then the local router\n \n \n \n \n \n will advertise itself as a Candidate\\-RP for all groups\n (providing the value of pimComponentCRPHoldTime is non\\-\n zero).\n \n .. attribute:: pimcandidaterpentry\n \n \tAn entry (conceptual row) in the pimCandidateRPTable\n \t**type**\\: list of :py:class:`Pimcandidaterpentry `\n \n \n\n \"\"\"\n\n _prefix = 'PIM-MIB'\n _revision = '2000-09-28'\n\n def __init__(self):\n super(PimMib.Pimcandidaterptable, self).__init__()\n\n self.yang_name = \"pimCandidateRPTable\"\n self.yang_parent_name = \"PIM-MIB\"\n\n self.pimcandidaterpentry = YList(self)\n\n def __setattr__(self, name, value):\n self._check_monkey_patching_error(name, value)\n with _handle_type_error():\n if name in self.__dict__ and isinstance(self.__dict__[name], YList):\n raise YPYModelError(\"Attempt to assign value of '{}' to YList ldata. \"\n \"Please use list append or extend method.\"\n .format(value))\n if isinstance(value, Enum.YLeaf):\n value = value.name\n if name in () and name in self.__dict__:\n if isinstance(value, YLeaf):\n self.__dict__[name].set(value.get())\n elif isinstance(value, YLeafList):\n super(PimMib.Pimcandidaterptable, self).__setattr__(name, value)\n else:\n self.__dict__[name].set(value)\n else:\n if hasattr(value, \"parent\") and name != \"parent\":\n if hasattr(value, \"is_presence_container\") and value.is_presence_container:\n value.parent = self\n elif value.parent is None and value.yang_name in self._children_yang_names:\n value.parent = self\n super(PimMib.Pimcandidaterptable, self).__setattr__(name, value)\n\n\n class Pimcandidaterpentry(Entity):\n \"\"\"\n An entry (conceptual row) in the pimCandidateRPTable.\n \n .. attribute:: pimcandidaterpgroupaddress \n \n \tThe IP multicast group address which, when combined with pimCandidateRPGroupMask, identifies a group prefix for which the local router will advertise itself as a Candidate\\-RP\n \t**type**\\: str\n \n \t**pattern:** (([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])\\\\.){3}([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])(%[\\\\p{N}\\\\p{L}]+)?\n \n .. attribute:: pimcandidaterpgroupmask \n \n \tThe multicast group address mask which, when combined with pimCandidateRPGroupMask, identifies a group prefix for which the local router will advertise itself as a Candidate\\-RP\n \t**type**\\: str\n \n \t**pattern:** (([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])\\\\.){3}([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])(%[\\\\p{N}\\\\p{L}]+)?\n \n .. attribute:: pimcandidaterpaddress\n \n \tThe (unicast) address of the interface which will be advertised as a Candidate\\-RP\n \t**type**\\: str\n \n \t**pattern:** (([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])\\\\.){3}([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])(%[\\\\p{N}\\\\p{L}]+)?\n \n .. attribute:: pimcandidaterprowstatus\n \n \tThe status of this row, by which new entries may be created, or old entries deleted from this table\n \t**type**\\: :py:class:`Rowstatus `\n \n \n\n \"\"\"\n\n _prefix = 'PIM-MIB'\n _revision = '2000-09-28'\n\n def __init__(self):\n super(PimMib.Pimcandidaterptable.Pimcandidaterpentry, self).__init__()\n\n self.yang_name = \"pimCandidateRPEntry\"\n self.yang_parent_name = \"pimCandidateRPTable\"\n\n self.pimcandidaterpgroupaddress = YLeaf(YType.str, \"pimCandidateRPGroupAddress\")\n\n self.pimcandidaterpgroupmask = YLeaf(YType.str, \"pimCandidateRPGroupMask\")\n\n self.pimcandidaterpaddress = YLeaf(YType.str, \"pimCandidateRPAddress\")\n\n self.pimcandidaterprowstatus = YLeaf(YType.enumeration, \"pimCandidateRPRowStatus\")\n\n def __setattr__(self, name, value):\n self._check_monkey_patching_error(name, value)\n with _handle_type_error():\n if name in self.__dict__ and isinstance(self.__dict__[name], YList):\n raise YPYModelError(\"Attempt to assign value of '{}' to YList ldata. \"\n \"Please use list append or extend method.\"\n .format(value))\n if isinstance(value, Enum.YLeaf):\n value = value.name\n if name in (\"pimcandidaterpgroupaddress\",\n \"pimcandidaterpgroupmask\",\n \"pimcandidaterpaddress\",\n \"pimcandidaterprowstatus\") and name in self.__dict__:\n if isinstance(value, YLeaf):\n self.__dict__[name].set(value.get())\n elif isinstance(value, YLeafList):\n super(PimMib.Pimcandidaterptable.Pimcandidaterpentry, self).__setattr__(name, value)\n else:\n self.__dict__[name].set(value)\n else:\n if hasattr(value, \"parent\") and name != \"parent\":\n if hasattr(value, \"is_presence_container\") and value.is_presence_container:\n value.parent = self\n elif value.parent is None and value.yang_name in self._children_yang_names:\n value.parent = self\n super(PimMib.Pimcandidaterptable.Pimcandidaterpentry, self).__setattr__(name, value)\n\n def has_data(self):\n return (\n self.pimcandidaterpgroupaddress.is_set or\n self.pimcandidaterpgroupmask.is_set or\n self.pimcandidaterpaddress.is_set or\n self.pimcandidaterprowstatus.is_set)\n\n def has_operation(self):\n return (\n self.yfilter != YFilter.not_set or\n self.pimcandidaterpgroupaddress.yfilter != YFilter.not_set or\n self.pimcandidaterpgroupmask.yfilter != YFilter.not_set or\n self.pimcandidaterpaddress.yfilter != YFilter.not_set or\n self.pimcandidaterprowstatus.yfilter != YFilter.not_set)\n\n def get_segment_path(self):\n path_buffer = \"\"\n path_buffer = \"pimCandidateRPEntry\" + \"[pimCandidateRPGroupAddress='\" + self.pimcandidaterpgroupaddress.get() + \"']\" + \"[pimCandidateRPGroupMask='\" + self.pimcandidaterpgroupmask.get() + \"']\" + path_buffer\n\n return path_buffer\n\n def get_entity_path(self, ancestor):\n path_buffer = \"\"\n if (ancestor is None):\n path_buffer = \"PIM-MIB:PIM-MIB/pimCandidateRPTable/%s\" % self.get_segment_path()\n else:\n path_buffer = _get_relative_entity_path(self, ancestor, path_buffer)\n\n leaf_name_data = LeafDataList()\n if (self.pimcandidaterpgroupaddress.is_set or self.pimcandidaterpgroupaddress.yfilter != YFilter.not_set):\n leaf_name_data.append(self.pimcandidaterpgroupaddress.get_name_leafdata())\n if (self.pimcandidaterpgroupmask.is_set or self.pimcandidaterpgroupmask.yfilter != YFilter.not_set):\n leaf_name_data.append(self.pimcandidaterpgroupmask.get_name_leafdata())\n if (self.pimcandidaterpaddress.is_set or self.pimcandidaterpaddress.yfilter != YFilter.not_set):\n leaf_name_data.append(self.pimcandidaterpaddress.get_name_leafdata())\n if (self.pimcandidaterprowstatus.is_set or self.pimcandidaterprowstatus.yfilter != YFilter.not_set):\n leaf_name_data.append(self.pimcandidaterprowstatus.get_name_leafdata())\n\n entity_path = EntityPath(path_buffer, leaf_name_data)\n return entity_path\n\n def get_child_by_name(self, child_yang_name, segment_path):\n child = self._get_child_by_seg_name([child_yang_name, segment_path])\n if child is not None:\n return child\n\n return None\n\n def has_leaf_or_child_of_name(self, name):\n if(name == \"pimCandidateRPGroupAddress\" or name == \"pimCandidateRPGroupMask\" or name == \"pimCandidateRPAddress\" or name == \"pimCandidateRPRowStatus\"):\n return True\n return False\n\n def set_value(self, value_path, value, name_space, name_space_prefix):\n if(value_path == \"pimCandidateRPGroupAddress\"):\n self.pimcandidaterpgroupaddress = value\n self.pimcandidaterpgroupaddress.value_namespace = name_space\n self.pimcandidaterpgroupaddress.value_namespace_prefix = name_space_prefix\n if(value_path == \"pimCandidateRPGroupMask\"):\n self.pimcandidaterpgroupmask = value\n self.pimcandidaterpgroupmask.value_namespace = name_space\n self.pimcandidaterpgroupmask.value_namespace_prefix = name_space_prefix\n if(value_path == \"pimCandidateRPAddress\"):\n self.pimcandidaterpaddress = value\n self.pimcandidaterpaddress.value_namespace = name_space\n self.pimcandidaterpaddress.value_namespace_prefix = name_space_prefix\n if(value_path == \"pimCandidateRPRowStatus\"):\n self.pimcandidaterprowstatus = value\n self.pimcandidaterprowstatus.value_namespace = name_space\n self.pimcandidaterprowstatus.value_namespace_prefix = name_space_prefix\n\n def has_data(self):\n for c in self.pimcandidaterpentry:\n if (c.has_data()):\n return True\n return False\n\n def has_operation(self):\n for c in self.pimcandidaterpentry:\n if (c.has_operation()):\n return True\n return self.yfilter != YFilter.not_set\n\n def get_segment_path(self):\n path_buffer = \"\"\n path_buffer = \"pimCandidateRPTable\" + path_buffer\n\n return path_buffer\n\n def get_entity_path(self, ancestor):\n path_buffer = \"\"\n if (ancestor is None):\n path_buffer = \"PIM-MIB:PIM-MIB/%s\" % self.get_segment_path()\n else:\n path_buffer = _get_relative_entity_path(self, ancestor, path_buffer)\n\n leaf_name_data = LeafDataList()\n\n entity_path = EntityPath(path_buffer, leaf_name_data)\n return entity_path\n\n def get_child_by_name(self, child_yang_name, segment_path):\n child = self._get_child_by_seg_name([child_yang_name, segment_path])\n if child is not None:\n return child\n\n if (child_yang_name == \"pimCandidateRPEntry\"):\n for c in self.pimcandidaterpentry:\n segment = c.get_segment_path()\n if (segment_path == segment):\n return c\n c = PimMib.Pimcandidaterptable.Pimcandidaterpentry()\n c.parent = self\n local_reference_key = \"ydk::seg::%s\" % segment_path\n self._local_refs[local_reference_key] = c\n self.pimcandidaterpentry.append(c)\n return c\n\n return None\n\n def has_leaf_or_child_of_name(self, name):\n if(name == \"pimCandidateRPEntry\"):\n return True\n return False\n\n def set_value(self, value_path, value, name_space, name_space_prefix):\n pass\n\n\n class Pimcomponenttable(Entity):\n \"\"\"\n The (conceptual) table containing objects specific to a PIM\n domain. One row exists for each domain to which the router\n is connected. A PIM\\-SM domain is defined as an area of the\n network over which Bootstrap messages are forwarded.\n Typically, a PIM\\-SM router will be a member of exactly one\n domain. This table also supports, however, routers which\n may form a border between two PIM\\-SM domains and do not\n forward Bootstrap messages between them.\n \n .. attribute:: pimcomponententry\n \n \tAn entry (conceptual row) in the pimComponentTable\n \t**type**\\: list of :py:class:`Pimcomponententry `\n \n \n\n \"\"\"\n\n _prefix = 'PIM-MIB'\n _revision = '2000-09-28'\n\n def __init__(self):\n super(PimMib.Pimcomponenttable, self).__init__()\n\n self.yang_name = \"pimComponentTable\"\n self.yang_parent_name = \"PIM-MIB\"\n\n self.pimcomponententry = YList(self)\n\n def __setattr__(self, name, value):\n self._check_monkey_patching_error(name, value)\n with _handle_type_error():\n if name in self.__dict__ and isinstance(self.__dict__[name], YList):\n raise YPYModelError(\"Attempt to assign value of '{}' to YList ldata. \"\n \"Please use list append or extend method.\"\n .format(value))\n if isinstance(value, Enum.YLeaf):\n value = value.name\n if name in () and name in self.__dict__:\n if isinstance(value, YLeaf):\n self.__dict__[name].set(value.get())\n elif isinstance(value, YLeafList):\n super(PimMib.Pimcomponenttable, self).__setattr__(name, value)\n else:\n self.__dict__[name].set(value)\n else:\n if hasattr(value, \"parent\") and name != \"parent\":\n if hasattr(value, \"is_presence_container\") and value.is_presence_container:\n value.parent = self\n elif value.parent is None and value.yang_name in self._children_yang_names:\n value.parent = self\n super(PimMib.Pimcomponenttable, self).__setattr__(name, value)\n\n\n class Pimcomponententry(Entity):\n \"\"\"\n An entry (conceptual row) in the pimComponentTable.\n \n .. attribute:: pimcomponentindex \n \n \tA number uniquely identifying the component. Each protocol instance connected to a separate domain should have a different index value. Routers that only support membership in a single PIM\\-SM domain should use a pimComponentIndex value of 1\n \t**type**\\: int\n \n \t**range:** 1..255\n \n .. attribute:: pimcomponentbsraddress\n \n \tThe IP address of the bootstrap router (BSR) for the local PIM region\n \t**type**\\: str\n \n \t**pattern:** (([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])\\\\.){3}([0\\-9]\\|[1\\-9][0\\-9]\\|1[0\\-9][0\\-9]\\|2[0\\-4][0\\-9]\\|25[0\\-5])(%[\\\\p{N}\\\\p{L}]+)?\n \n .. attribute:: pimcomponentbsrexpirytime\n \n \tThe minimum time remaining before the bootstrap router in the local domain will be declared down. For candidate BSRs, this is the time until the component sends an RP\\-Set message. For other routers, this is the time until it may accept an RP\\-Set message from a lower candidate BSR\n \t**type**\\: int\n \n \t**range:** 0..4294967295\n \n .. attribute:: pimcomponentcrpholdtime\n \n \tThe holdtime of the component when it is a candidate RP in the local domain. The value of 0 is used to indicate that the local system is not a Candidate\\-RP\n \t**type**\\: int\n \n \t**range:** 0..255\n \n \t**units**\\: seconds\n \n .. attribute:: pimcomponentstatus\n \n \tThe status of this entry. Creating the entry creates another protocol instance; destroying the entry disables a protocol instance\n \t**type**\\: :py:class:`Rowstatus `\n \n \n\n \"\"\"\n\n _prefix = 'PIM-MIB'\n _revision = '2000-09-28'\n\n def __init__(self):\n super(PimMib.Pimcomponenttable.Pimcomponententry, self).__init__()\n\n self.yang_name = \"pimComponentEntry\"\n self.yang_parent_name = \"pimComponentTable\"\n\n self.pimcomponentindex = YLeaf(YType.int32, \"pimComponentIndex\")\n\n self.pimcomponentbsraddress = YLeaf(YType.str, \"pimComponentBSRAddress\")\n\n self.pimcomponentbsrexpirytime = YLeaf(YType.uint32, \"pimComponentBSRExpiryTime\")\n\n self.pimcomponentcrpholdtime = YLeaf(YType.int32, \"pimComponentCRPHoldTime\")\n\n self.pimcomponentstatus = YLeaf(YType.enumeration, \"pimComponentStatus\")\n\n def __setattr__(self, name, value):\n self._check_monkey_patching_error(name, value)\n with _handle_type_error():\n if name in self.__dict__ and isinstance(self.__dict__[name], YList):\n raise YPYModelError(\"Attempt to assign value of '{}' to YList ldata. \"\n \"Please use list append or extend method.\"\n .format(value))\n if isinstance(value, Enum.YLeaf):\n value = value.name\n if name in (\"pimcomponentindex\",\n \"pimcomponentbsraddress\",\n \"pimcomponentbsrexpirytime\",\n \"pimcomponentcrpholdtime\",\n \"pimcomponentstatus\") and name in self.__dict__:\n if isinstance(value, YLeaf):\n self.__dict__[name].set(value.get())\n elif isinstance(value, YLeafList):\n super(PimMib.Pimcomponenttable.Pimcomponententry, self).__setattr__(name, value)\n else:\n self.__dict__[name].set(value)\n else:\n if hasattr(value, \"parent\") and name != \"parent\":\n if hasattr(value, \"is_presence_container\") and value.is_presence_container:\n value.parent = self\n elif value.parent is None and value.yang_name in self._children_yang_names:\n value.parent = self\n super(PimMib.Pimcomponenttable.Pimcomponententry, self).__setattr__(name, value)\n\n def has_data(self):\n return (\n self.pimcomponentindex.is_set or\n self.pimcomponentbsraddress.is_set or\n self.pimcomponentbsrexpirytime.is_set or\n self.pimcomponentcrpholdtime.is_set or\n self.pimcomponentstatus.is_set)\n\n def has_operation(self):\n return (\n self.yfilter != YFilter.not_set or\n self.pimcomponentindex.yfilter != YFilter.not_set or\n self.pimcomponentbsraddress.yfilter != YFilter.not_set or\n self.pimcomponentbsrexpirytime.yfilter != YFilter.not_set or\n self.pimcomponentcrpholdtime.yfilter != YFilter.not_set or\n self.pimcomponentstatus.yfilter != YFilter.not_set)\n\n def get_segment_path(self):\n path_buffer = \"\"\n path_buffer = \"pimComponentEntry\" + \"[pimComponentIndex='\" + self.pimcomponentindex.get() + \"']\" + path_buffer\n\n return path_buffer\n\n def get_entity_path(self, ancestor):\n path_buffer = \"\"\n if (ancestor is None):\n path_buffer = \"PIM-MIB:PIM-MIB/pimComponentTable/%s\" % self.get_segment_path()\n else:\n path_buffer = _get_relative_entity_path(self, ancestor, path_buffer)\n\n leaf_name_data = LeafDataList()\n if (self.pimcomponentindex.is_set or self.pimcomponentindex.yfilter != YFilter.not_set):\n leaf_name_data.append(self.pimcomponentindex.get_name_leafdata())\n if (self.pimcomponentbsraddress.is_set or self.pimcomponentbsraddress.yfilter != YFilter.not_set):\n leaf_name_data.append(self.pimcomponentbsraddress.get_name_leafdata())\n if (self.pimcomponentbsrexpirytime.is_set or self.pimcomponentbsrexpirytime.yfilter != YFilter.not_set):\n leaf_name_data.append(self.pimcomponentbsrexpirytime.get_name_leafdata())\n if (self.pimcomponentcrpholdtime.is_set or self.pimcomponentcrpholdtime.yfilter != YFilter.not_set):\n leaf_name_data.append(self.pimcomponentcrpholdtime.get_name_leafdata())\n if (self.pimcomponentstatus.is_set or self.pimcomponentstatus.yfilter != YFilter.not_set):\n leaf_name_data.append(self.pimcomponentstatus.get_name_leafdata())\n\n entity_path = EntityPath(path_buffer, leaf_name_data)\n return entity_path\n\n def get_child_by_name(self, child_yang_name, segment_path):\n child = self._get_child_by_seg_name([child_yang_name, segment_path])\n if child is not None:\n return child\n\n return None\n\n def has_leaf_or_child_of_name(self, name):\n if(name == \"pimComponentIndex\" or name == \"pimComponentBSRAddress\" or name == \"pimComponentBSRExpiryTime\" or name == \"pimComponentCRPHoldTime\" or name == \"pimComponentStatus\"):\n return True\n return False\n\n def set_value(self, value_path, value, name_space, name_space_prefix):\n if(value_path == \"pimComponentIndex\"):\n self.pimcomponentindex = value\n self.pimcomponentindex.value_namespace = name_space\n self.pimcomponentindex.value_namespace_prefix = name_space_prefix\n if(value_path == \"pimComponentBSRAddress\"):\n self.pimcomponentbsraddress = value\n self.pimcomponentbsraddress.value_namespace = name_space\n self.pimcomponentbsraddress.value_namespace_prefix = name_space_prefix\n if(value_path == \"pimComponentBSRExpiryTime\"):\n self.pimcomponentbsrexpirytime = value\n self.pimcomponentbsrexpirytime.value_namespace = name_space\n self.pimcomponentbsrexpirytime.value_namespace_prefix = name_space_prefix\n if(value_path == \"pimComponentCRPHoldTime\"):\n self.pimcomponentcrpholdtime = value\n self.pimcomponentcrpholdtime.value_namespace = name_space\n self.pimcomponentcrpholdtime.value_namespace_prefix = name_space_prefix\n if(value_path == \"pimComponentStatus\"):\n self.pimcomponentstatus = value\n self.pimcomponentstatus.value_namespace = name_space\n self.pimcomponentstatus.value_namespace_prefix = name_space_prefix\n\n def has_data(self):\n for c in self.pimcomponententry:\n if (c.has_data()):\n return True\n return False\n\n def has_operation(self):\n for c in self.pimcomponententry:\n if (c.has_operation()):\n return True\n return self.yfilter != YFilter.not_set\n\n def get_segment_path(self):\n path_buffer = \"\"\n path_buffer = \"pimComponentTable\" + path_buffer\n\n return path_buffer\n\n def get_entity_path(self, ancestor):\n path_buffer = \"\"\n if (ancestor is None):\n path_buffer = \"PIM-MIB:PIM-MIB/%s\" % self.get_segment_path()\n else:\n path_buffer = _get_relative_entity_path(self, ancestor, path_buffer)\n\n leaf_name_data = LeafDataList()\n\n entity_path = EntityPath(path_buffer, leaf_name_data)\n return entity_path\n\n def get_child_by_name(self, child_yang_name, segment_path):\n child = self._get_child_by_seg_name([child_yang_name, segment_path])\n if child is not None:\n return child\n\n if (child_yang_name == \"pimComponentEntry\"):\n for c in self.pimcomponententry:\n segment = c.get_segment_path()\n if (segment_path == segment):\n return c\n c = PimMib.Pimcomponenttable.Pimcomponententry()\n c.parent = self\n local_reference_key = \"ydk::seg::%s\" % segment_path\n self._local_refs[local_reference_key] = c\n self.pimcomponententry.append(c)\n return c\n\n return None\n\n def has_leaf_or_child_of_name(self, name):\n if(name == \"pimComponentEntry\"):\n return True\n return False\n\n def set_value(self, value_path, value, name_space, name_space_prefix):\n pass\n\n def has_data(self):\n return (\n (self.pim is not None and self.pim.has_data()) or\n (self.pimcandidaterptable is not None and self.pimcandidaterptable.has_data()) or\n (self.pimcomponenttable is not None and self.pimcomponenttable.has_data()) or\n (self.piminterfacetable is not None and self.piminterfacetable.has_data()) or\n (self.pimipmroutenexthoptable is not None and self.pimipmroutenexthoptable.has_data()) or\n (self.pimipmroutetable is not None and self.pimipmroutetable.has_data()) or\n (self.pimneighbortable is not None and self.pimneighbortable.has_data()) or\n (self.pimrpsettable is not None and self.pimrpsettable.has_data()) or\n (self.pimrptable is not None and self.pimrptable.has_data()))\n\n def has_operation(self):\n return (\n self.yfilter != YFilter.not_set or\n (self.pim is not None and self.pim.has_operation()) or\n (self.pimcandidaterptable is not None and self.pimcandidaterptable.has_operation()) or\n (self.pimcomponenttable is not None and self.pimcomponenttable.has_operation()) or\n (self.piminterfacetable is not None and self.piminterfacetable.has_operation()) or\n (self.pimipmroutenexthoptable is not None and self.pimipmroutenexthoptable.has_operation()) or\n (self.pimipmroutetable is not None and self.pimipmroutetable.has_operation()) or\n (self.pimneighbortable is not None and self.pimneighbortable.has_operation()) or\n (self.pimrpsettable is not None and self.pimrpsettable.has_operation()) or\n (self.pimrptable is not None and self.pimrptable.has_operation()))\n\n def get_segment_path(self):\n path_buffer = \"\"\n path_buffer = \"PIM-MIB:PIM-MIB\" + path_buffer\n\n return path_buffer\n\n def get_entity_path(self, ancestor):\n path_buffer = \"\"\n if (not ancestor is None):\n raise YPYModelError(\"ancestor has to be None for top-level node\")\n\n path_buffer = self.get_segment_path()\n leaf_name_data = LeafDataList()\n\n entity_path = EntityPath(path_buffer, leaf_name_data)\n return entity_path\n\n def get_child_by_name(self, child_yang_name, segment_path):\n child = self._get_child_by_seg_name([child_yang_name, segment_path])\n if child is not None:\n return child\n\n if (child_yang_name == \"pim\"):\n if (self.pim is None):\n self.pim = PimMib.Pim()\n self.pim.parent = self\n self._children_name_map[\"pim\"] = \"pim\"\n return self.pim\n\n if (child_yang_name == \"pimCandidateRPTable\"):\n if (self.pimcandidaterptable is None):\n self.pimcandidaterptable = PimMib.Pimcandidaterptable()\n self.pimcandidaterptable.parent = self\n self._children_name_map[\"pimcandidaterptable\"] = \"pimCandidateRPTable\"\n return self.pimcandidaterptable\n\n if (child_yang_name == \"pimComponentTable\"):\n if (self.pimcomponenttable is None):\n self.pimcomponenttable = PimMib.Pimcomponenttable()\n self.pimcomponenttable.parent = self\n self._children_name_map[\"pimcomponenttable\"] = \"pimComponentTable\"\n return self.pimcomponenttable\n\n if (child_yang_name == \"pimInterfaceTable\"):\n if (self.piminterfacetable is None):\n self.piminterfacetable = PimMib.Piminterfacetable()\n self.piminterfacetable.parent = self\n self._children_name_map[\"piminterfacetable\"] = \"pimInterfaceTable\"\n return self.piminterfacetable\n\n if (child_yang_name == \"pimIpMRouteNextHopTable\"):\n if (self.pimipmroutenexthoptable is None):\n self.pimipmroutenexthoptable = PimMib.Pimipmroutenexthoptable()\n self.pimipmroutenexthoptable.parent = self\n self._children_name_map[\"pimipmroutenexthoptable\"] = \"pimIpMRouteNextHopTable\"\n return self.pimipmroutenexthoptable\n\n if (child_yang_name == \"pimIpMRouteTable\"):\n if (self.pimipmroutetable is None):\n self.pimipmroutetable = PimMib.Pimipmroutetable()\n self.pimipmroutetable.parent = self\n self._children_name_map[\"pimipmroutetable\"] = \"pimIpMRouteTable\"\n return self.pimipmroutetable\n\n if (child_yang_name == \"pimNeighborTable\"):\n if (self.pimneighbortable is None):\n self.pimneighbortable = PimMib.Pimneighbortable()\n self.pimneighbortable.parent = self\n self._children_name_map[\"pimneighbortable\"] = \"pimNeighborTable\"\n return self.pimneighbortable\n\n if (child_yang_name == \"pimRPSetTable\"):\n if (self.pimrpsettable is None):\n self.pimrpsettable = PimMib.Pimrpsettable()\n self.pimrpsettable.parent = self\n self._children_name_map[\"pimrpsettable\"] = \"pimRPSetTable\"\n return self.pimrpsettable\n\n if (child_yang_name == \"pimRPTable\"):\n if (self.pimrptable is None):\n self.pimrptable = PimMib.Pimrptable()\n self.pimrptable.parent = self\n self._children_name_map[\"pimrptable\"] = \"pimRPTable\"\n return self.pimrptable\n\n return None\n\n def has_leaf_or_child_of_name(self, name):\n if(name == \"pim\" or name == \"pimCandidateRPTable\" or name == \"pimComponentTable\" or name == \"pimInterfaceTable\" or name == \"pimIpMRouteNextHopTable\" or name == \"pimIpMRouteTable\" or name == \"pimNeighborTable\" or name == \"pimRPSetTable\" or name == \"pimRPTable\"):\n return True\n return False\n\n def set_value(self, value_path, value, name_space, name_space_prefix):\n pass\n\n def clone_ptr(self):\n self._top_entity = PimMib()\n return self._top_entity\n\n","repo_name":"juancsosap/yangtraining","sub_path":"tools/ydk-py-master/cisco-ios-xe/ydk/models/cisco_ios_xe/PIM_MIB.py","file_name":"PIM_MIB.py","file_ext":"py","file_size_in_byte":136655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5224648360","text":"# %% [markdown]\n# 진행절차는 다음과 같다.\n# 1. 기존 백테스트.py 생성하는 중간 파일과 최대한 같도록 pandas를 이용하여 코드를 자성한다.\n# 아래 코드는 수행후에 중간 생성 파일과 비교하여 같음을 확인했다.\n# 2. 새로 복제한 코드를 bt.algo 클래스로 재작성한다.\n# 이때도 우선 같은 결과를 도출하도록 작성한 후 일반적인 lookback 및\n# lag를 도입하여 기존 결과와 비교분석하면서 개선한다.\n#\n# %%\nimport numpy as np\nimport pandas as pd\n# %%\nprices = pd.read_csv('raw_utf8.csv', index_col=0, parse_dates=True)\n# %% [markdown]\n# ## 백테스트.py의 평균수익률 계산\n# %%\n# 백테스트.py의 평균수익률 계산\nm6 = (prices.pct_change(182-30) + 1).shift(30)\nm9 = (prices.pct_change(273-30) + 1).shift(30)\nm12 = (prices.pct_change(365-30) + 1).shift(30)\n평균수익률 = (m6+m9+m12)/3\n평균수익률\n# %% [markdown]\n# ## 이산성 및 IDM 계산\n\n# %%\n이산성시그널_df = prices.pct_change(30)\\\n .apply(lambda x: pd.Series(np.where(x>0.0, 1, 0), index=x.index))\n이산성시그널_df\n# %%\n상승일비중 = 이산성시그널_df.rolling(366).mean()\n상승일비중\n# %%\n하락일비중 = 1 - 상승일비중\n하락일비중\n# %%\n이산성 = (하락일비중-상승일비중) * -1\n이산성\n# %%\nIDM = 평균수익률 * 이산성\nIDM\n# %%\n##################################################\n# 백테스팅을 위한 전략 클래스 작성\nclass StatIDMomentumScore(bt.Algo):\n def __init__(self, lookback=pd.DateOffset(years=2), #FIXME : 12개월이되어야 하지만 원 알고리즘을 테스트한다.\n lag=pd.DateOffset(months=1)):\n super(StatIDMomentumScore, self).__init__()\n self.lookback = lookback\n self.lag = lag\n\n def __call__(self, target):\n selected = target.temp['selected']\n t0 = target.now - self.lag\n # prc = target.universe.loc[(t0 - self.lookback):t0,selected] # FIXME 12개월치의 데이터를 뽑는다.\n prc = target.universe.loc[t0-self.lookback:t0,selected]\n # print(t0, prc.iloc[-365:-30])\n #6, 9, 12개월 평균모멘텀스코어\n # print(prc.iloc[-183:-30])\n \n #2002.2.1 -> 2002.1.2 -> 2001.8.3 -> 2001.5.4 -> 2001.2.1\n #백테트.py와 맞춘 수익률\n m6_returns = (prc.iloc[-183:-30].calc_total_return()+1) # 1달제외 6개월 수익률 (현재 prices가 공휴일포함 데이터임)\n m9_returns = (prc.iloc[-274:-30].calc_total_return()+1) # 1달제외 9개월 수익률\n m12_returns = (prc.iloc[-366:-30].calc_total_return()+1) # 1달제외 12개월 수익률\n average_returns = (m6_returns+m9_returns+m12_returns)/3\n # print(f\"{t0}\\n===average_returns : \\n{average_returns}\\n\")\n \n # ID 계산 최근 30일 제외\n # dropna에 주의 해야 한다. 조선이 0이 있어 문제가 되므로 모든 column이 nan일 때만 drop한다.\n # print(prc[-(365+30):])\n #print(f\"{t0} len {len(prc[-(366+30):].pct_change(30).dropna(how='all'))}\")\n pos_percent = np.where(prc[-(366+30):].pct_change(30).dropna(how='all') > 0.0, 1, 0).mean(axis=0)\n neg_percent = 1 - pos_percent\n ID = (neg_percent - pos_percent)\n # print(f\"ID===\\n{ID}\")\n\n target.temp['stat'] = average_returns * ID * -1\n return True\n # %% \ndef bt_SectorIDMomentum(name, n, tickers, prices):\n st = bt.Strategy(name,\n algos = [\n bt.algos.RunAfterDate('2002-1-2'),\n bt.algos.RunMonthly(),\n bt.algos.SelectAll(),\n bt.algos.SelectThese(tickers),\n StatIDMomentumScore(lag=pd.DateOffset(days=0)),\n bt.algos.SelectN(n=n, sort_descending=True),\n # bt.algos.PrintDate(),\n bt.algos.WeighEqually(),\n # bt.algos.PrintTempData(),\n bt.algos.Rebalance()\n ],\n )\n return bt.Backtest(st, prices)\n# %%\ntickers = list(prices.columns[:-4])#+['현금']\nbt_id1 = bt_SectorIDMomentum(\"base1.ID상대모멘텀\", n=1, tickers=tickers, prices=prices)\nbt_id2 = bt_SectorIDMomentum(\"base2.ID상대모멘텀\", n=2, tickers=tickers, prices=prices)\nbt_id3 = bt_SectorIDMomentum(\"base3.ID상대모멘텀\", n=3, tickers=tickers, prices=prices)\n# %%\nr = bt.run(bt_id1, bt_id2, bt_id3)\n# %%\nr.set_date_range(\"2002-02-01\")\nr.display()\n","repo_name":"hermian/USAP","sub_path":"백테스트복제.py","file_name":"백테스트복제.py","file_ext":"py","file_size_in_byte":4598,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19846258888","text":"import scanpy as sc\nimport re\nimport ontology\nimport sys\nimport pandas as pd\n\nfield = sys.argv[1]\ntype_field = sys.argv[2]\ndataset_file = sys.argv[3]\nlookup_table_file = sys.argv[4]\n\n# Read shendure big data\n\ndataset = sc.read(dataset_file, 'r')\ncell_types = dataset.obs.loc[:,[field]].drop_duplicates()\ncell_types = list(cell_types.iloc[:,0])\ncell_types = pd.DataFrame({field: cell_types, field + 'lookup_name' : cell_types, 'ontology_term_id' : '', 'ontology_term_name' : '', 'final' : 'True', 'type' : type_field})\n\n# Creeate look up table\n\nfor i in range(cell_types.shape[0]):\n \n stripped_cell_type = cell_types.loc[i,field].lower()\n stripped_cell_type = re.sub('_', ' ', stripped_cell_type)\n \n try: \n suggested_term=ontology.lookup_candidate_term(stripped_cell_type, ontology='cl', method='select')\n except:\n suggested_term=[['','']]\n \n \n if len(suggested_term) > 0:\n # store top hit\n cell_types.loc[i,'ontology_term_id'] = suggested_term[0][0]\n cell_types.loc[i,'ontology_term_name'] = suggested_term[0][1]\n \n cell_types.loc[i, field + 'lookup_name'] = stripped_cell_type\n \ncell_types.to_csv(lookup_table_file, sep='\\t', index=False)\n","repo_name":"kishorikonwar/single-cell-curation","sub_path":"datasets/tabula_muris_senis/scripts/create_ontology_lookup_table.py","file_name":"create_ontology_lookup_table.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"5848507780","text":"import time\n\n\ndef time_trial(func):\n def wrapper(*args, **kwargs):\n start = time.perf_counter()\n result = func(*args, **kwargs)\n end = time.perf_counter()\n run_time = start - end\n func_name = (\"Function Name {}\".format(repr(func.__name__)))\n refinshed = (\"Finished {} in {} secs\".format(repr(func.__name__), round(run_time, 3)))\n\n Question_OneTestResults = {\n \"Problem Number\": func_name,\n \"Test Start Time\": f\"{start}\",\n \"Test Start end\": f\"{end}\",\n \"refinshed\": f\"{refinshed}\",\n \"Result\": f\"{result}\",\n }\n return (Question_OneTestResults)\n\n return wrapper\n","repo_name":"Rah-Jose-Israel/Philosophy-of-This_Project","sub_path":"logging_TimeTrials.py","file_name":"logging_TimeTrials.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41369656354","text":"import airflow.utils.dates\nfrom airflow import DAG\nfrom airflow.operators.bash import BashOperator\nfrom airflow.operators.python import PythonOperator\nfrom airflow.providers.microsoft.mssql.operators.mssql import MsSqlOperator\n\n#Defining DAG\ndag = DAG(\n dag_id=\"wikipediaPageViews\",\n start_date=airflow.utils.dates.days_ago(0),\n schedule_interval=\"@hourly\",\n catchup=False,\n template_searchpath=\"/tmp\"\n)\n\n#Task 1: Obtain Data from source\nget_data = BashOperator(\n task_id=\"get_data\",\n bash_command=(\n \"curl -o /tmp/wikipageviews_{{execution_date}}.gz \"\n \"https://dumps.wikimedia.org/other/pageviews/\"\n \"{{ execution_date.year }}/\" \n \"{{ execution_date.year }}-\"\n \"{{ '{:02}'.format(execution_date.month) }}/\"\n \"pageviews-{{ execution_date.year }}\"\n \"{{ '{:02}'.format(execution_date.month) }}\"\n \"{{ '{:02}'.format(execution_date.day) }}-\"\n \"{{ '{:02}'.format(execution_date.hour) }}0000.gz\" \n ),\n dag=dag,\n)\n\n#Task 2: Unzip the extracted file\nextract_gz = BashOperator(\n task_id=\"extract_gz\",\n bash_command=\"gunzip --force /tmp/wikipageviews_{{execution_date}}.gz\",\n dag=dag,\n)\n\n#Python callable function used in Python operator\ndef _fetch_pageviews(pagenames,**context):\n result = dict.fromkeys(pagenames, 0)\n with open(f\"/tmp/wikipageviews_{context['execution_date']}\", \"r\") as f: \n for line in f:\n domain_code, page_title, view_counts, _ = line.split(\" \") \n if domain_code == \"en\" and page_title in pagenames: \n result[page_title] = view_counts\n \n with open(f\"/tmp/sqlserver_query.sql\", \"w\") as f:\n f.write(f\"Delete from pageview_counts where datetime='{context['execution_date']}';\")\n for pagename, pageviewcount in result.items(): \n f.write(\n \"INSERT INTO pageview_counts VALUES (\"\n f\"'{pagename}', {pageviewcount}, '{context['execution_date']}'\"\n \");\\n\"\n )\n\n#Task 3: Perform transformation and generate sql script\nfetch_pageviews = PythonOperator(\n task_id=\"fetch_pageviews\",\n python_callable=_fetch_pageviews,\n op_kwargs={\n \"pagenames\": {\n \"Google\",\n \"Amazon\",\n \"Apple\",\n \"Microsoft\",\n \"Facebook\",\n }\n },\n dag=dag,\n)\n\n#Task 4: Inserts data into SQL server\nwrite_to_sqlserever = MsSqlOperator(\n task_id=\"write_to_sqlserever\",\n mssql_conn_id=\"my_sqlserver\", \n sql=\"sqlserver_query.sql\", \n database=\"master\", \n dag=dag,\n)\n\n#Defining task dependencies\nget_data>>extract_gz>>fetch_pageviews>>write_to_sqlserever\n","repo_name":"VIVEK-JADHAV/wikipediaPageViews","sub_path":"dags/wikipediaPageViews.py","file_name":"wikipediaPageViews.py","file_ext":"py","file_size_in_byte":2684,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72779056145","text":"# Function for handling forward direction\ndef move_forward(position, direction):\n new_position = position.copy()\n if direction == \"N\":\n new_position[1] += 1\n elif direction == \"E\":\n new_position[0] += 1\n elif direction == \"U\":\n new_position[2] += 1\n elif direction == \"S\":\n new_position[1] -= 1\n elif direction == \"W\":\n new_position[0] -= 1\n elif direction == \"D\":\n new_position[2] -= 1\n \n return new_position\n\n# Function for handling backward direction\ndef move_backward(position, direction):\n new_position = position.copy()\n if direction == \"N\":\n new_position[1] -= 1\n elif direction == \"E\":\n new_position[0] -= 1\n elif direction == \"U\":\n new_position[2] -= 1\n elif direction == \"S\":\n new_position[1] += 1\n elif direction == \"W\":\n new_position[0] += 1\n elif direction == \"D\":\n new_position[2] += 1\n \n return new_position\n\n\n# Function for handling direction changed\ndef change_direction(initial_direction, rotate_to):\n # Define a dictionary to handle the direction changes\n direction_changes = {\n \"NL\": \"W\", # North to Left becomes West\n \"SL\": \"E\", # South to Left becomes East\n \"EL\": \"N\", # East to Left becomes North\n \"WL\": \"S\", # West to Left becomes South\n \"UL\": \"W\", # Up to Left becomes West\n \"DL\": \"E\", # Down to Left becomes East\n \"NR\": \"E\", # North to Right becomes East\n \"SR\": \"W\", # South to Right becomes West\n \"ER\": \"S\", # East to Right becomes South\n \"WR\": \"N\", # West to Right becomes North\n \"UR\": \"E\", # Up to Right becomes East\n \"DR\": \"W\", # Down to Right becomes West\n }\n\n # Create a key based on the initial direction and rotation instruction\n key = initial_direction + rotate_to\n\n # If the key is in the dictionary, return the resulting direction\n if key in direction_changes:\n return direction_changes[key]\n\n # If the key is not in the dictionary, return the initial direction (no rotation)\n return initial_direction\n\n\n# Code to execute Command\ndef execute_commands(commands, initial):\n position = initial[\"position\"].copy()\n direction = initial[\"direction\"]\n\n for command in commands:\n if command == \"f\":\n position = move_forward(position, direction)\n elif command == \"b\":\n position = move_backward(position, direction)\n else:\n direction = change_direction(direction, command)\n\n return {\n \"position\": position,\n \"direction\": direction,\n }","repo_name":"Namra-23/Incubyte_Assessment","sub_path":"Incubyte.py","file_name":"Incubyte.py","file_ext":"py","file_size_in_byte":2612,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"29305219016","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom mod4.utils import analytic, quad_int\nfrom mod4.diffeq import funker_plank\n\nLx, Lv = 4, 4\nx0, v0 = 2, 0.0\n\nt0 = 0.1\nt1 = 20\n\nphysical_params = dict(omega_squared=1, gamma=1.0, sigma= 0.8)\nintegration_params = dict(dt=0.1, n_steps=(1*int((t1 - t0)/0.1)))\n\nprint(integration_params)\nx, v = np.linspace(-Lx ,Lx, 80, endpoint=False), np.linspace(-Lv, Lv, 80, endpoint=False)\nX, V = np.meshgrid(x,v)\n\np0 = analytic(X, V, t0, x0, v0, physical_params)\nprint(\"innit norm\",quad_int(np.real(p0), x, v))\nprint(\"max abs init\",np.max(np.abs(p0)))\nplt.contourf(np.real(p0))\nplt.show()\n\nfig, axes = plt.subplot_mosaic([['exact', 'cbar', 'numeric']], width_ratios=[1, 0.1, 1], constrained_layout=True)\nlevels = np.linspace(0,0.5, 30)\n\np_an = np.real(analytic(X,V, t1, x0, v0, physical_params))\nmappable = axes['exact'].contourf(X, V,p_an, levels=levels)\n\np_num, norm = funker_plank(np.real(p0), x, v, physical_params, integration_params)\naxes['numeric'].contourf(X, V, p_num, levels=levels)\n\nplt.colorbar(mappable, cax=axes['cbar'])\n\naxes['exact'].set_aspect('equal')\naxes['numeric'].set_aspect('equal')\n\naxes['numeric'].set_title(\"numeric\")\naxes['exact'].set_title('exact')\nplt.show()","repo_name":"djanloo/mod4","sub_path":"exact_result.py","file_name":"exact_result.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1244109954","text":"import pygame\nimport random\n\npygame.init()\n\n#define screen size\n\nscreen_width = 1000\nscreen_height = 1000\n\n#create screen\n\nscreen = pygame.display.set_mode((screen_width,screen_height))\n\n#create player and give it image saved in folder as well as enemy\n\nplayer = pygame.image.load(\"player.jpg\")\nenemy = pygame.image.load(\"enemy.png\")\nenemy2 = pygame.image.load(\"monster.jpg\")\nenemy3 = pygame.image.load(\"image.png\")\nprize = pygame.image.load(\"prize.jpg\")\n\n#get the width and hight of the above images in order to detect boundary.\n\nimage_height = player.get_height()\nimage_width = player.get_width()\nenemy_height = enemy.get_height()\nenemy_width = enemy.get_width()\nenemy2_height = enemy2.get_height()\nenemy2_width = enemy2.get_width()\nenemy3_height = enemy3.get_height()\nenemy3_width = enemy3.get_width()\nprize_height = prize.get_height()\nprize_width = prize.get_width()\n\n\nprint(\"This is the height of the player image: \" +str(image_height))\nprint(\"This is the width of the player image: \" +str(image_width))\n\n\n#store the position of the player and enemy as variable.\n\nplayerXPosition = 100\nplayerYPosition = 50\n\n#make the enemy start off screen and at random y position.\n\nenemyXPosition = screen_width\nenemyYPosition = random.randint(0, screen_height - enemy_height)\n\nenemy2XPosition = 400\nenemy2YPosition = 70\n\nenemy3XPosition = 600\nenemy3YPosition = 800\n\nprizeXPosition = 700\nprizeYPosition = 70\n\n#check if up or down key is pressed.\n\nkeyUp = False\nkeyDown = False\nkeyLeft = False\nkeyRight = False\n\n#create game loop to refresh/update the screen window and apply changes to represent real time game play.\n\nwhile 1:\n\n screen.fill(0) #this clears the screen.\n screen.blit(player, (playerXPosition, playerYPosition)) #draws image selected to point specified on screen.\n screen.blit(enemy, (enemyXPosition, enemyYPosition))\n screen.blit(enemy2, (enemy2XPosition, enemy2YPosition))\n screen.blit(enemy3, (enemy3XPosition, enemy3YPosition))\n screen.blit(prize, (prizeXPosition, prizeYPosition))\n\n pygame.display.flip() #updates screeen\n\n for event in pygame.event.get(): #loops through events in the game.\n\n if event.type == pygame.QUIT:\n pygame.quit()\n exit(0)\n\n if event.type == pygame.KEYDOWN: #Checks if down key is pressed.\n\n if event.key == pygame.K_UP:\n keyUp = True #Test if key pressed is one we want.\n\n if event.key == pygame.K_DOWN:\n keyDown = True\n\n if event.key == pygame.K_LEFT:\n keyLeft = True\n\n if event.key == pygame.K_RIGHT:\n keyRight = True\n\n if event.type == pygame.KEYUP: #checks if up key is pressed.\n\n if event.key == pygame.K_UP:\n keyUp = False\n\n if event.key == pygame.K_DOWN:\n keyDown = False\n\n if event.key == pygame.K_LEFT:\n keyLeft = False\n\n if event.key == pygame.K_RIGHT:\n keyRight = False\n\n \n \n\n \n\n# Check key pressed values and move image accordingly.\n\n if keyUp == True:\n if playerYPosition > 0 : #ensure user does not move image above the window.\n playerYPosition -= 1\n \n if keyDown == True:\n if playerYPosition < screen_height - image_height:\n playerYPosition += 1 #ensure player does not move image bllow screen.\n\n if keyLeft == True:\n if playerXPosition > 0 :\n playerXPosition -= 1\n\n if keyRight == True:\n if playerXPosition < screen_width - image_width:\n playerXPosition += 1\n\n\n# Check for collision with enemy.\n# Add bounding boxes around images.\n# Test if these boxes intercept. If they do there is a collision.\n\n #bounding box for player:\n\n playerBox = pygame.Rect(player.get_rect())\n\n playerBox.top = playerYPosition\n playerBox.left = playerXPosition #updates playerbox position.\n\n #bounding box for enemy:\n\n enemyBox = pygame.Rect(enemy.get_rect())\n\n enemyBox.top = enemyYPosition\n enemyBox.left = enemyXPosition #updates enemy box position.\n\n enemy2Box = pygame.Rect(enemy.get_rect())\n\n enemy2Box.top = enemy2YPosition\n enemy2Box.left = enemy2XPosition\n\n enemy3Box = pygame.Rect(enemy3.get_rect())\n\n enemy3Box.top = enemy3YPosition\n enemy3Box.left = enemy3XPosition\n\n #bounding box for prize.\n\n prizeBox = pygame.Rect(prize.get_rect())\n\n prizeBox.top = prizeYPosition\n prizeBox.left = prizeXPosition \n\n #test colliosn of Boxes:\n\n if playerBox.colliderect(enemyBox):\n\n #display \"you lose\"\n\n print(\"You lose!\")\n\n #quit game and exit window:\n\n pygame.quit()\n exit(0)\n\n if playerBox.colliderect(enemy2Box):\n\n #display \"you lose\"\n\n print(\"You lose!\")\n\n #quit game and exit window:\n\n pygame.quit()\n exit(0)\n\n if playerBox.colliderect(enemy3Box):\n\n #display \"you lose\"\n\n print(\"You lose!\")\n\n #quit game and exit window:\n\n pygame.quit()\n exit(0) \n\n #if the enemy is off screen user wins:\n\n\n if playerBox.colliderect(prizeBox):\n\n #display \"you win\"\n\n print(\"YOU WIN!\")\n\n #quit game and exit window:\n\n pygame.quit()\n exit(0)\n\n if enemyXPosition < 0 - enemy_width:\n\n\n\n #display \"you win!\"\n\n print(\"You win!\")\n\n #Quit and exit\n\n pygame.quit()\n\n exit(0)\n\n\n #make enemy approach player.\n\n enemyXPosition -= 0.15\n\n enemy3YPosition -= 0.15\n\n #=======================game loop logic ends here. ===============================\n\n \n\n \n\n \n \n\n\n\n\n","repo_name":"RhyssOwenn/MyProjects","sub_path":"Capstone projects/Capstone project 2 lv 1/Jakes first game.py","file_name":"Jakes first game.py","file_ext":"py","file_size_in_byte":5681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74397758865","text":"'''\nCreated on May, 2014\n\n@author: Léonard Gérard leonard.gerard@sri.com\n'''\n\nfrom radler.astutils.names import QualifiedName\nfrom radler.astutils.tools import write_file\nfrom radler.radlr.errors import internal_error\nfrom radler.radlr.rast import AstVisitor\nfrom radler.radlr.ros import rosutils\nfrom radler.radlr.ros.rosutils import qn_dir, qn_msgfile, filepath, \\\n qn_dir\n\n\ntemplates = {\n'cmakeliststxt': \"\"\"\ncmake_minimum_required(VERSION 2.8.3)\nproject({namespace})\nset(CMAKE_MODULE_PATH ${{CMAKE_MODULE_PATH}}\n {package_dirs}\n)\n{packages}\nfind_package(catkin REQUIRED roscpp message_generation)\n{static_libs}\n\n\nadd_definitions(-DIN_RADL_GENERATED_CONTEXT)\n\nadd_message_files(FILES\n {msg_files}\n)\ngenerate_messages(DEPENDENCIES)\n\ncatkin_package(\n LIBRARIES {namespace}\n CATKIN_DEPENDS roscpp message_runtime\n)\ninclude_directories(\n include src ${{catkin_INCLUDE_DIRS}}\n)\n{executables}\n{targetincludes}\n{dependencies}\n{link_libraries}\n\ninstall(TARGETS\n {node_to_install}\n {lib_to_install}\n ARCHIVE DESTINATION ${{CATKIN_PACKAGE_LIB_DESTINATION}}\n LIBRARY DESTINATION ${{CATKIN_PACKAGE_LIB_DESTINATION}}\n RUNTIME DESTINATION ${{CATKIN_PACKAGE_BIN_DESTINATION}}\n)\n\n\"\"\"\n,'packages': \"find_package({name} REQUIRED {components})\"\n,'executables': \"add_executable({name} {sources})\"\n,'node_to_install':\"{name}\"\n,'targetincludes': \"\"\"\ntarget_include_directories({name}\n PUBLIC\n {dirs}\n {libdirs}\n)\"\"\"\n,'dependencies': \"add_dependencies({name} {namespace}_generate_messages_cpp)\"\n,'link_libraries': \"\"\"\ntarget_link_libraries({name}\n ${{catkin_LIBRARIES}}\n {libs}\n)\"\"\"\n,'package_dirs': \"{dir}\"\n,'libs': '${{{libname}_LIBRARIES}}'\n,'libdirs': '${{{libname}_INCLUDE_DIRS}}'\n,'lib_to_install': '{name}'\n,'static_libs': \"\"\"\nadd_library({name} STATIC\n {sources})\nset({name}_LIBRARIES {name})\nset({name}_INCLUDE_DIRS {headers})\n\"\"\"\n}\n\nseparators = {\n'packages': '\\n'\n,'executables' : '\\n'\n,'targetincludes': '\\n'\n,'dependencies': '\\n'\n,'link_libraries': '\\n'\n,'package_dirs': '\\n '\n,'libs': ' '\n,'libdirs': ' '\n,'static_libs': '\\n'\n,'sources': '\\n '\n,'node_to_install': '\\n '\n,'lib_to_install': '\\n '\n}\n\n\ndef app(d, s):\n v = templates[s].format(**d)\n if s not in d or not d[s]: d[s] = v\n else: d[s] = separators[s].join((d[s], v))\n\nlib_templates = ['libs', 'libdirs']\n\ndef _from_cxx(visitor, cxx, d):\n _, d = visitor.node_mapred(cxx, d)\n #give the correct root to relative paths\n pwd = rosutils.user_file_relativepath / cxx._pwd\n d['dirs'].add(pwd)\n for c in cxx['FILENAME']:\n d['sources'].add(pwd / c._val)\n for l in cxx['LIB']:\n if l._kind == 'cmake_library':\n d['libname'] = l['CMAKE_MODULE']._val\n elif l._kind == 'static_library':\n d['libname'] = l._qname.name()\n else:\n internal_error(\"unknown library type\")\n for t in lib_templates: app(d, t)\n return (), d\n\n\nnt = ['executables', 'targetincludes', 'dependencies', 'link_libraries',\n 'node_to_install']\n\ndef _from_node(visitor, node, d):\n d['name'] = node._qname.name()\n #this node generated file, makes it correctly relative to the cmakefile\n srcfile = d['gened_cpp_files'][node._qname].relative_to(d['localroot'])\n d['sources'] = {str(srcfile)}\n\n #gather needed data\n d['dirs'] = set()\n for t in lib_templates: d[t] = ''\n visitor = visitor.update({'cxx_file': _from_cxx,\n 'cxx_class': _from_cxx})\n _, d = visitor.node_mapred(node, d)\n d['dirs'] = '\"{}\"'.format('\" \"'.join(map(str,d['dirs'])))\n d['sources'] = ' '.join(map(str,d['sources']))\n\n for t in nt: app(d, t)\n return (), d\n\n\nlt = ['packages', 'package_dirs']\n\ndef _from_catkinlib(visitor, lib, d):\n d['name'] = lib['CMAKE_MODULE']._val\n d['components'] = ' '.join(c._val for c in lib['COMPONENTS'])\n d['dir'] = str('${CMAKE_CURRENT_SOURCE_DIR}'\n / rosutils.user_file_relativepath\n /lib._pwd)\n for t in lt: app(d, t)\n return (), d\n\n\nsl = ['static_libs', 'targetincludes', 'dependencies', 'link_libraries',\n 'lib_to_install']\n\ndef _from_staticlib(visitor, lib, d):\n d['name'] = lib._qname.name()\n d['sources'] = set()\n d['dirs'] = set()\n for t in lib_templates: d[t] = ''\n _, d = visitor.update({'cxx_file': _from_cxx}).node_mapred(lib, d)\n d['dirs'] = '\"{}\"'.format('\" \"'.join(map(str,d['dirs'])))\n d['sources'] = ' '.join(map(str, d['sources']))\n cwd = rosutils.user_file_relativepath / lib._pwd\n d['headers'] = ' '.join(str(cwd / h._val) for h in lib['HEADER_PATHS'])\n\n for t in sl: app(d, t)\n return (), d\n\n\n_visitor = AstVisitor({'node' : _from_node,\n 'cmake_library': _from_catkinlib,\n 'static_library': _from_staticlib})\n\n\ndef gen(msg_list, gened_cpp_files, ast):\n #The Cmakefile waits for msg files relative to the msg dir\n msg_dir = filepath(qn_msgfile(QualifiedName(ast._qname, '', True)))\n msg_files = (str(m.relative_to(msg_dir)) for m in msg_list)\n localroot = qn_dir(ast._qname)\n d = {'namespace' : ast._qname.name(),\n 'msg_files' : '\\n '.join(msg_files),\n 'gened_cpp_files' : gened_cpp_files,\n 'localroot' : localroot}\n for t in nt: d[t] = ''\n for t in lt: d[t] = ''\n for t in sl: d[t] = ''\n _visitor.visit(ast, d)\n app(d, 'cmakeliststxt')\n write_file(filepath(localroot / \"CMakeLists.txt\"), d['cmakeliststxt'])\n\n\n","repo_name":"xiaohe27/radlm","sub_path":"radler/radlr/ros/roscmake.py","file_name":"roscmake.py","file_ext":"py","file_size_in_byte":5433,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19564962901","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Apr 27 11:39:17 2018\r\n\r\n@author: yang\r\n\"\"\"\r\n\r\nfrom utils import initialize,forward,compute_cost,backprop,update_p,load_data\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n#%matplotlib inline\r\ndef train(X, Y, layers_dims, learning_rate = 0.01, num_iterations = 3000, \r\n print_cost=False,lambd=0,if_add_reg=False,keep_prob=1):#lr was 0.009\r\n np.random.seed(1)\r\n costs = [] \r\n parameters = initialize(layers_dims) \r\n l = len(layers_dims)-1\r\n for i in range(0, num_iterations):\r\n AL, caches = forward(X, parameters,keep_prob)\r\n cost = compute_cost(AL,Y,l,lambd,parameters,if_add_reg)\r\n grads = backprop(AL, Y, caches, lambd,middle_layer_activation=\"relu\",\r\n last_activation=\"sigmoid\",add_reg=if_add_reg,keep_prob=1)\r\n parameters = update_p(parameters, grads, learning_rate)\r\n if print_cost and i % 100 == 0:\r\n print (\"Cost after iteration %i: %f\" %(i, cost))\r\n if print_cost and i % 100 == 0:\r\n costs.append(cost)\r\n plt.plot(np.squeeze(costs))\r\n plt.ylabel('cost')\r\n plt.xlabel('iterations (per tens)')\r\n plt.title(\"Learning rate =\" + str(learning_rate))\r\n plt.show() \r\n return parameters \r\n\r\ndef data_preprocessing():\r\n train_x_orig, train_y, test_x_orig, test_y, classes = load_data()\r\n print (\"The original shape of each input image is:{}\".format(train_x_orig[0].shape))\r\n plt.figure(1)\r\n for i in range(3):\r\n plt.subplot(1,3,i+1)\r\n plt.imshow(train_x_orig[i])\r\n train_x_flatten = train_x_orig.reshape(train_x_orig.shape[0], -1).T \r\n test_x_flatten = test_x_orig.reshape(test_x_orig.shape[0], -1).T\r\n X_train = train_x_flatten/255.\r\n X_test = test_x_flatten/255.\r\n print (\"X_train's shape: \" + str(X_train.shape))\r\n print (\"X_test's shape: \" + str(X_test.shape))\r\n dim_ori = train_x_orig.shape[1]*train_x_orig.shape[2]*train_x_orig.shape[3]\r\n return X_train, train_y, X_test, test_y,dim_ori\r\n\r\ndef predict(X, y, parameters,keep_prob=1):\r\n m = X.shape[1]\r\n p = np.zeros((1,m))\r\n probas, caches = forward(X, parameters,keep_prob)\r\n for i in range(0, probas.shape[1]):\r\n if probas[0,i] > 0.5:\r\n p[0,i] = 1\r\n else:\r\n p[0,i] = 0\r\n print(\"Test Accuracy is: \" + str(np.sum((p == y)/m))) \r\n return p\r\n\r\nX_tr,y_tr,X_te,y_te,dim_ori = data_preprocessing()\r\nlayers_dims = [dim_ori, 20, 16, 10,1]\r\nparameters = train(X_tr,y_tr, layers_dims,learning_rate=0.01,\r\n num_iterations=2000, print_cost=True, lambd=0,\r\n if_add_reg=False,keep_prob=0.8)\r\nresult = predict(X_te,y_te,parameters,keep_prob=1)","repo_name":"Nandayang/DL-with-python","sub_path":"DNN/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2720,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"48"} +{"seq_id":"11906231622","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\n\nnlist = [0]\ni = 1\n\nwhile nlist[-1] != 999 or nlist == [0]:\n nlist.append(int(input(\"Entrer la \"+str(i)+\" note ( Saisir 999 pour terminer ): \")))\n i += 1\ndel nlist[0], nlist[-1]\n\nprint(\"La meilleure note est de : \",max(nlist))\nprint(\"La moyenne est de : \", sum(nlist)/len(nlist))\n\nsommed = 0\n\nfor i in nlist:\n sommed += (int(i) - sum(nlist)/len(nlist))**2\n\nprint(\"L'ecart type est de : \", (sommed/(len(nlist)-1))**1/2)\n","repo_name":"3wnbr1/TD-Informatique-ECAM","sub_path":"SUP/TD2/Ex11.py","file_name":"Ex11.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30743368334","text":"import json\n\nfrom application.config.paths import FILES_OUTPUT_PATH\n\n\ndef to_processing_response(name_file: str = None) -> None:\n path_to_file = FILES_OUTPUT_PATH.joinpath(f\"{name_file}.json\")\n with open(path_to_file) as file:\n response_dict = json.load(file)\n number_of_astronauts = response_dict.get(\"number\", {})\n print(f\"The number of people in space at this moment: {number_of_astronauts}-astronauts\")\n\n\nif __name__ == \"__main__\":\n to_processing_response()\n","repo_name":"Hillel-i-Python-Pro-i-2022-12-27/homework__kulyk__kyrylo__hw5","sub_path":"application/requests_example/response_processing.py","file_name":"response_processing.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22909316162","text":"import datetime\n\nfrom flask_jwt_extended import get_jwt_identity\n\nfrom app.models.baseModel import BaseModel\nfrom app.models.messages.message import Message\nfrom app.models.packages.errors import PackageNotFoundError, NotEnoughBalanceToSendPackageError\nfrom app.models.users.user import User\n\n\nclass Package(BaseModel):\n def __init__(self, body=None, campaign=None, number_list=list(), script=None, messages=list(), send_time=None,\n _id=None, created_date=None):\n self.body = body\n self.number_list = number_list\n self.script = script\n self.messages = [Message(**message) for message in messages] if messages else messages\n self.send_time = send_time\n self.campaign = campaign\n self.created_date = created_date if created_date else datetime.datetime.now()\n super().__init__(_id)\n\n def prepare_messages(self):\n user_id = get_jwt_identity()\n messages = list()\n default_body = \"\"\n if self.script:\n default_body = self.script.body\n else:\n default_body = self.body\n\n if self.campaign:\n [messages.append(Message(default_body, phone_number, send_time=self.send_time, user_id=user_id, package_id=self._id)) for\n phone_number in self.campaign.numbers]\n\n [messages.append(Message(default_body, phone_number, send_time=self.send_time, user_id=user_id, package_id=self._id)) for\n phone_number in self.number_list]\n\n for message in self.messages:\n if message.body == '' or message.body is None:\n message.body = default_body\n messages.append(message)\n return messages\n\n def get_package_data(self, user: User):\n messages_sent = self.prepare_messages()\n count_messages = len(messages_sent)\n json = self.json()\n json['messages_sent'] = [message.json() for message in messages_sent]\n json['count_messages'] = count_messages\n json['messages_cost'] = count_messages * user.sms_cost\n\n return json\n\n def send_messages(self):\n user_id = get_jwt_identity()\n user = User.get_by_id(user_id)\n messages_to_send = self.prepare_messages()\n total_cost = len(messages_to_send)* user.sms_cost\n if total_cost < user.balance and user.user_type == \"pre\":\n raise NotEnoughBalanceToSendPackageError(f\"El usuario cuenta con {user.balance} y se necesita {total_cost}\")\n [message.send() for message in messages_to_send]\n user.balance -= (messages_to_send * user.sms_cost)\n user.update_mongo()\n return messages_to_send\n\n @classmethod\n def add_package(cls, data, user: User):\n package = cls(**data)\n user.packages.append(package)\n user.update_mongo()\n return package\n\n @classmethod\n def get_package(cls, package_id, user: User):\n for package in user.packages:\n if package.json().get(\"_id\") == package_id:\n return package\n\n raise PackageNotFoundError(\"El paquete de mensajes enviados con el id dado no ha sido encontrado\")\n\n @classmethod\n def get_packages(cls, user):\n return user.packages\n","repo_name":"iThinkEmo/Iualia-doc-sphinx","sub_path":"app/models/packages/package.py","file_name":"package.py","file_ext":"py","file_size_in_byte":3199,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35565150210","text":"import pygame\n\n\nclass Enemies(pygame.sprite.Sprite):\n\n def __init__(self, health_max=100, velocity=5, attack=100):\n super().__init__()\n self.health = health_max\n self.health_max = health_max\n self.attack = attack\n self.gold = 15\n self.velocity = velocity\n self.image = pygame.image.load('img/zombie1.png')\n self.rect = self.image.get_rect()\n self.rect.x = 150\n self.rect.y = 1200\n self.chemin = {0: [150, 150, 90], 1: [670, 150, 0], 2: [670, 1050, -90], 3: [1050, 1050, 0], 4: [1050, 150, 90], 5: [1450, 150, 0],\n 6: [1450, 1050, -90], 7: [1700, 1050, 0], 8: [1700, 100, 90]}\n self.pos = 0\n\n def move(self):\n if self.pos == 9:\n return self.attack\n if self.chemin[self.pos][0] == self.rect.x and self.chemin[self.pos][1] == self.rect.y:\n self.pos += 1\n return 0\n if self.chemin[self.pos][0] != self.rect.x:\n if self.chemin[self.pos][0] > self.rect.x:\n self.rect.x += self.velocity\n else:\n self.rect.x -= self.velocity\n\n if self.chemin[self.pos][1] != self.rect.y:\n if self.chemin[self.pos][1] > self.rect.y:\n self.rect.y += self.velocity\n else:\n self.rect.y -= self.velocity\n return 0\n\n def bar_health(self, surface):\n bar_red = (225, 0, 0)\n bar_black = (0, 0, 0)\n bar_pos_red = [self.rect.x - 5, self.rect.y - 10, self.health / 1.5, 7]\n bar_pos_black = [self.rect.x - 5, self.rect.y - 10, self.health_max / 1.5, 7]\n pygame.draw.rect(surface, bar_black, bar_pos_black)\n pygame.draw.rect(surface, bar_red, bar_pos_red)\n","repo_name":"Hugoatlan/Game-jam","sub_path":"Class/enemies.py","file_name":"enemies.py","file_ext":"py","file_size_in_byte":1746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10017991644","text":"import os\nfrom setuptools import setup\nfrom glob import glob\n\npackage_name = 'hagen_robot_controller'\n\nsetup(\n name=package_name,\n version='0.0.0',\n packages=[package_name],\n data_files=[\n ('share/ament_index/resource_index/packages',\n ['resource/' + package_name]),\n ('share/' + package_name, ['package.xml']),\n (os.path.join('share', package_name), glob('launch/*.launch.py'))\n ],\n install_requires=['setuptools'],\n zip_safe=True,\n maintainer='todo',\n maintainer_email='todo@todo.todo',\n description='TODO: Package description',\n license='TODO: License declaration',\n tests_require=['pytest'],\n entry_points={\n 'console_scripts': [\n 'robot_controller = hagen_robot_controller.robot_controller:main',\n 'robot_estimator = hagen_robot_controller.robot_estimator:main'\n ],\n },\n)","repo_name":"GPrathap/ros2_intro","sub_path":"hagen_robot/hagen_robot_controller/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"29528488866","text":"import get_random_nums\n\ndef insert_sort(nums):\n for i in range(1 , len(nums)):\n temp = nums[i]\n for j in range (0 , i)[::-1]:\n if temp >= nums[j]:\n nums[j+1] = temp\n break\n else:\n nums[j+1] = nums[j]\n if j == 0:\n nums[0] = temp #当前元素是本轮最小元素时,赋值\n return nums\n\n\n\nif __name__ == \"__main__\":\n nums = get_random_nums.get_nums(20)\n print(nums)\n new_nums = insert_sort(nums)\n print(new_nums)","repo_name":"chenyutcmn/leetcode_record","sub_path":"common_algorithm/insert_sort.py","file_name":"insert_sort.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74121420626","text":"# https://atcoder.jp/contests/joi2012ho/submissions/17063338\n# B - たのしいカードゲーム (Card Game is Fun)\nimport sys\n\nsys.setrecursionlimit(10 ** 7)\ninput = sys.stdin.readline\nf_inf = float('inf')\nmod = 10 ** 9 + 7\n\n\ndef resolve():\n ab = list(map(int, input().split()))\n if len(ab) == 2:\n a, b = ab\n else:\n a = ab[0]\n b = int(input())\n A = list(map(int, input().split()))\n B = list(map(int, input().split()))\n\n dp = [0] * (b + 1)\n for i in range(a):\n next_dp = [0] * (b + 1)\n for j in range(b):\n if A[i] == B[j]:\n next_dp[j + 1] = max(next_dp[j + 1], dp[j] + 1)\n else:\n next_dp[j + 1] = dp[j + 1]\n dp = next_dp\n print(max(dp))\n\n\nif __name__ == '__main__':\n resolve()\n","repo_name":"happa64/AtCoder_Beginner_Contest","sub_path":"JOI/JOI_2012/JOI_2012_B.py","file_name":"JOI_2012_B.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"27968175889","text":"import numpy as np\nimport scipy as sp\nfrom scipy import constants\nimport qutip as qt\nimport qutip as qt\nimport qutip.settings as settings\n\nsettings.atol = 1e-12 # Setting the absolute tolerance for qutip\n\nclass circuit_cap: # Class for the circuit capacitively coupled qubit\n\n ## INITIALIZATION ##\n\n def __init__(self, Cc=3.1e-15, qubit_list=[]): # Cc in fF and qubit_list is a list of qubit objects (probe, target)\n\n self.qubit_list = qubit_list\n self.Cc = Cc\n self.probe = self.qubit_list[0]\n self.target = self.qubit_list[1]\n self.ncut = self.probe.ncut\n\n self.init_operator() # Initialize the charge basis operators for the circuit qubit\n\n def print_params(self): # Print the parameters of the qubit in a nice way\n\n self.get_detunning(update=True)\n print(f'Ejp: {self.probe.Ej * 1e-9 / constants.h} GHz')\n print(f'Ecp: {self.probe.Ec * 1e-9 / constants.h} GHz')\n print(f'Cjp: {self.probe.C * 1e15} fF')\n print(f'Ejp/Ecp probe: {np.real(self.probe.Ej/self.probe.Ec)}')\n print(f'w_probe: {self.omega_probe * 1e-9 / constants.h} GHz')\n print(f'ng probe: {self.probe.ng}')\n print(f'Ejt: {self.target.Ej * 1e-9 / constants.h} GHz')\n print(f'Ec: {self.target.Ec * 1e-9 / constants.h} GHz')\n print(f'Cjt: {self.target.C* 1e15} fF')\n print(f'Ejt/Ect target: {np.real(self.target.Ej/self.target.Ec)}')\n print(f'w_target: {self.omega_target * 1e-9 / constants.h} GHz')\n print(f'ng target: {self.target.ng}')\n print(f'detunning: {self.detunning * 1e-9 / constants.h} GHz')\n print(f'Cc: {self.Cc * 1e15} fF')\n\n def init_operator(self): # Initialize the charge basis operators for the circuit qubit\n self.probe.init_operator()\n self.target.init_operator()\n self.I_cb = self.probe.I_cb # Identity for qubit (charge basis)\n self.q_op_cb = self.probe.n_cb # Charge operator (charge basis)\n self.e_iphi_op_cb = sp.sparse.diags(np.ones(2 * self.ncut, dtype=np.complex_), offsets=1)\n self.q1_q1 = qt.tensor((self.probe.n_cb + self.probe.ng_cb) * (self.probe.n_cb + self.probe.ng_cb), self.target.I_cb)\n self.q1_q2 = qt.tensor((self.probe.n_cb + self.probe.ng_cb), (self.target.n_cb + self.target.ng_cb))\n self.q2_q2 = qt.tensor(self.probe.I_cb, (self.target.n_cb + self.target.ng_cb) * (self.target.n_cb + self.target.ng_cb))\n\n ## GET KIN AND POT ##\n\n def get_kinetic_circuit(self):\n self.init_operator()\n\n C_mat = [\n [self.probe.C + self.Cc, -self.Cc],\n [-self.Cc, self.target.C + self.Cc]\n ] # Capacitance matrix\n\n C_mat_inverse = np.linalg.inv(C_mat)\n \n kin = C_mat_inverse[0][0] * self.q1_q1\n kin += 2 * C_mat_inverse[0][1] * self.q1_q2\n kin += C_mat_inverse[1][1] * self.q2_q2\n\n kin *= 4 * 0.5 * constants.e **2 \n\n return kin\n\n def get_potential_circuit(self):\n self.init_operator()\n\n potential = -0.5*self.probe.Ej * qt.tensor(self.probe.e_iphi_op_cb + self.probe.e_iphi_op_cb.trans(), self.target.I_cb)\n potential += -0.5*self.target.Ej * qt.tensor(self.probe.I_cb, self.target.e_iphi_op_cb + self.target.e_iphi_op_cb.trans())\n\n return potential\n\n def get_kinetic_probe(self):\n self.init_operator()\n\n kin = self.probe.get_kinetic()\n\n return kin\n\n def get_potential_probe(self):\n self.init_operator()\n\n potential = self.probe.get_potential()\n \n return potential\n\n def get_kinetic_target(self):\n self.init_operator()\n\n kin = self.target.get_kinetic()\n \n return kin\n\n def get_potential_target(self):\n self.init_operator()\n\n potential = self.target.get_potential()\n return potential\n\n ## GET H ##\n\n def get_H_circuit(self):\n self.H_circuit = self.get_kinetic_circuit() + self.get_potential_circuit()\n \n return self.H_circuit\n \n def get_H_probe(self):\n self.H_probe = self.get_kinetic_probe() + self.get_potential_probe()\n \n return self.H_probe\n \n def get_H_target(self):\n self.H_target = self.get_kinetic_target() + self.get_potential_target()\n \n return self.H_target\n\n ## DIAGONALISE ##\n\n def diagonalise_circuit(self, update=False):\n if update:\n self.get_H_circuit()\n else:\n try:\n self.H_circuit\n except AttributeError:\n self.get_H_circuit()\n\n self.eig_values_circuit, self.eig_vectors_circuit = self.H_circuit.eigenstates(eigvals = 10)\n\n return self.eig_values_circuit, self.eig_vectors_circuit\n\n def diagonalise_probe(self,update=False):\n if update:\n self.get_H_probe()\n else:\n try:\n self.Ham_probe\n except AttributeError:\n self.get_H_probe()\n \n self.eig_values_probe, self.eig_vectors_probe = self.H_probe.eigenstates(eigvals = 2)\n\n return self.eig_values_probe, self.eig_vectors_probe\n\n def diagonalise_target(self,update=False):\n if update:\n self.get_H_target()\n else:\n try:\n self.H_target\n except AttributeError:\n self.get_H_target()\n \n self.eig_values_target, self.eig_vectors_target = self.H_target.eigenstates(eigvals = 10)\n\n return self.eig_values_target, self.eig_vectors_target\n\n ## GET QUBIT STATES ##\n\n def init_qubit_states(self, update=False):\n if update:\n self.diagonalise_probe(update=True)\n self.diagonalise_target(update=True)\n self.diagonalise_circuit(update=True)\n else:\n try:\n self.eig_values_probe\n self.eig_values_target\n except AttributeError:\n self.diagonalise_probe()\n self.diagonalise_target()\n self.diagonalise_circuit()\n\n # self.state_p0eb = self.eig_vectors_probe[0].T\n # self.state_p1eb = self.eig_vectors_probe[1].T\n # self.state_target = []\n\n self.state_product_ebeb = []\n\n for i in range(len(self.eig_vectors_probe)):\n for j in range(len(self.eig_vectors_target)):\n self.state_product_ebeb.append(qt.tensor(self.eig_vectors_probe[i], self.eig_vectors_target[j]))\n\n # self.state_target_0_cb = sp.sparse.csr_matrix((2 * self.ncut + 1,1))\n # self.state_target_0_cb[self.ncut] = 1\n # self.state_target_1_cb = sp.sparse.csr_matrix((2 * self.ncut + 1,1))\n # self.state_target_1_cb[self.ncut + 1] = 1\n\n # c = sp.sparse.csr_matrix((2 * self.ncut + 1,1))\n # c[self.ncut] = 1\n # self.state_product_ebcb = []\n\n # for i in range(len(self.eig_vectors_probe)):\n # for j in range(2 * self.ncut + 1):\n # self.state_product_ebcb.append(sp.sparse.kron(self.eig_vectors_probe[i], c.T).T)\n\n def get_omega_probe(self, update=False): # Get the frequency of the probe qubit\n if update:\n self.diagonalise_probe(update=True)\n else:\n try:\n self.eig_values_probe\n except AttributeError:\n self.diagonalise_probe()\n\n self.omega_probe = self.eig_values_probe[1] - self.eig_values_probe[0]\n\n\n return self.omega_probe\n \n def get_omega_target(self, update=False): # Get the frequency of the target qubit\n if update:\n self.diagonalise_target(update=True)\n else:\n try:\n self.eig_values_target\n except AttributeError:\n self.diagonalise_target()\n\n self.omega_target = self.eig_values_target[1] - self.eig_values_target[0]\n\n return self.omega_target\n \n def get_detunning(self, update=False): # Get the detunning between the probe and target qubit\n if update:\n self.get_omega_probe(update=True)\n self.get_omega_target(update=True)\n else:\n try:\n self.omega_probe\n self.omega_target\n except AttributeError:\n self.get_omega_probe()\n self.get_omega_target()\n\n self.detunning = self.omega_probe - self.omega_target\n\n return self.detunning\n \n ## CALCULATION FIRST TRY ##\n\n def get_U_circuit(self, update=False):\n if update:\n self.init_qubit_states(update=True)\n else:\n try:\n self.state_p0eb\n self.state_p1eb\n except AttributeError:\n self.init_qubit_states()\n try:\n self.H_circuit\n except AttributeError:\n self.get_H_circuit()\n\n self.U_raw = self.H_circuit - qt.tensor(self.H_probe, self.target.I_cb) - qt.tensor(self.probe.I_cb, self.H_target)\n\n # size_ebcb = len(self.state_product_ebcb)\n # self.U_ebcb = np.zeros((size_ebcb, size_ebcb), dtype=object)\n\n # for i in range(size_ebcb):\n # for j in range(size_ebcb):\n # self.U_ebcb[i,j] = np.real(self.hc(self.state_product_ebcb[i]).dot(self.U_raw.dot(self.state_product_ebcb[j])).toarray()[0][0])\n \n size_ebeb = len(self.state_product_ebeb)\n self.U_ebeb = np.zeros((size_ebeb, size_ebeb), dtype=object)\n\n for i in range(size_ebeb):\n for j in range(size_ebeb):\n self.U_ebeb[i,j] = float(np.real((self.state_product_ebeb[i].dag() * self.U_raw * self.state_product_ebeb[j]).full()))\n self.U_ebeb = self.U_ebeb.astype(float)\n\n return self.U_ebeb, self.U_raw\n\n def extract_U_zz(self, update=False):\n if update:\n self.get_U_circuit(update=True)\n else:\n try:\n # self.U_ebcb\n self.U_ebeb\n except AttributeError:\n self.get_U_circuit()\n \n size_ebeb = len(self.state_product_ebeb)\n self.U_zz_ebeb = np.zeros((size_ebeb, size_ebeb), dtype=object)\n\n for i in range(size_ebeb):\n self.U_zz_ebeb[i,i] = self.U_ebeb[i,i]\n\n # size_ebcb = len(self.state_product_ebcb)\n # self.U_zz_ebcb = np.zeros((size_ebcb, size_ebcb), dtype=object)\n\n # for i in range(size_ebcb):\n # self.U_zz_ebcb[i,i] = self.U_ebcb[i,i]\n self.U_zz_ebeb = self.U_zz_ebeb.astype(float)\n\n return self.U_zz_ebeb\n\n def extract_U_zx(self, update=False):\n if update:\n self.get_U_circuit(update=True)\n else:\n try:\n # self.U_ebcb\n self.U_ebeb\n except AttributeError:\n self.get_U_circuit()\n \n size_ebeb = len(self.state_product_ebeb)\n self.U_zx_ebeb = np.zeros((size_ebeb, size_ebeb), dtype=object)\n\n for i in range(size_ebeb):\n for j in range(size_ebeb):\n if i != j:\n self.U_zx_ebeb[i,j] = self.U_ebeb[i,j]\n\n # size_ebcb = len(self.state_product_ebcb)\n # self.U_zx_ebcb = np.zeros((size_ebcb, size_ebcb), dtype=object)\n \n # for i in range(size_ebcb):\n # for j in range(size_ebcb):\n # if i != j:\n # self.U_zx_ebcb[i,j] = self.U_ebcb[i,j]\n self.U_zx_ebeb = self.U_zx_ebeb.astype(float)\n\n return self.U_zx_ebeb\n\n def get_g_parr(self, update=False):\n if update:\n self.init_qubit_states(update=True)\n else:\n try:\n self.state_product_ebeb\n except AttributeError:\n self.init_qubit_states()\n try:\n self.H_circuit\n except AttributeError:\n self.get_H_circuit()\n\n U_cache = self.H_circuit - qt.tensor(self.H_probe, self.target.I_cb) - qt.tensor(self.probe.I_cb, self.H_target)\n self.g_parr = np.abs(np.real(qt.tensor(self.eig_vectors_probe[0], self.eig_vectors_target[0]).dag() * U_cache * qt.tensor(self.eig_vectors_probe[0], self.eig_vectors_target[0] )))\n self.g_parr = float(self.g_parr)\n\n return self.g_parr\n\n def get_g_perp(self, update=False):\n if update:\n self.init_qubit_states(update=True)\n else:\n try:\n self.state_product_ebeb\n except AttributeError:\n self.init_qubit_states()\n\n U_cache = self.H_circuit - qt.tensor(self.H_probe, self.target.I_cb) - qt.tensor(self.I_cb, self.H_target)\n self.g_perp = np.abs(np.real(qt.tensor(self.eig_vectors_probe[0], self.eig_vectors_target[0]).dag() * U_cache * qt.tensor(self.eig_vectors_probe[1], self.eig_vectors_target[0])))\n self.g_perp = float(self.g_perp)\n\n return self.g_perp\n \n ## CALCULATION SECOND TRY ##\n\n def get_gparr2(self, update=False):\n if update:\n self.init_qubit_states(update=True)\n else:\n try:\n self.state_product_ebeb\n except AttributeError:\n self.init_qubit_states()\n try:\n self.H_circuit\n except AttributeError:\n self.get_H_circuit()\n \n self.state_probe_plus = 2**-0.5 * (self.eig_vectors_probe[0] + self.eig_vectors_probe[1])\n self.state_probe_minus = 2**-0.5 * (self.eig_vectors_probe[0] - self.eig_vectors_probe[1])\n self.state_target_plus = 2**-0.5 * (self.eig_vectors_target[0] + self.eig_vectors_target[1])\n self.state_target_minus = 2**-0.5 * (self.eig_vectors_target[0] - self.eig_vectors_target[1])\n\n self.state_product_ebeb_pp = qt.tensor(self.state_probe_plus, self.state_target_plus)\n # self.state_product_ebeb_pm = qt.tensor(self.state_probe_plus, self.state_target_minus)\n # self.state_product_ebeb_mp = qt.tensor(self.state_probe_minus, self.state_target_plus)\n self.state_product_ebeb_mm = qt.tensor(self.state_probe_minus, self.state_target_minus)\n\n g_parr = self.state_product_ebeb_pp.dag() * self.H_circuit * self.state_product_ebeb_mm\n\n g_parr = float(np.real(g_parr))\n\n return g_parr\n\n def get_gperp2(self, update=False):\n if update:\n self.init_qubit_states(update=True)\n else:\n try:\n self.state_product_ebeb\n except AttributeError:\n self.init_qubit_states()\n try:\n self.H_circuit\n except AttributeError:\n self.get_H_circuit()\n \n # self.state_probe_plus = 2**-0.5 * (self.eig_vectors_probe[0] + self.eig_vectors_probe[1])\n # self.state_probe_minus = 2**-0.5 * (self.eig_vectors_probe[0] - self.eig_vectors_probe[1])\n self.state_target_plus = 2**-0.5 * (self.eig_vectors_target[0] + self.eig_vectors_target[1])\n self.state_target_minus = 2**-0.5 * (self.eig_vectors_target[0] - self.eig_vectors_target[1])\n\n self.state_product_ebeb_0p = qt.tensor(self.eig_vectors_probe[0], self.state_target_plus)\n # self.state_product_ebeb_1p = qt.tensor(self.eig_vectors_probe[1], self.state_target_plus)\n # self.state_product_ebeb_0m = qt.tensor(self.eig_vectors_probe[0], self.state_target_minus)\n self.state_product_ebeb_1m = qt.tensor(self.eig_vectors_probe[1], self.state_target_minus)\n\n g_perp = self.state_product_ebeb_0p.dag() * self.H_circuit * self.state_product_ebeb_1m\n\n g_perp = float(np.real(g_perp))\n\n return g_perp\n \n ## CALCULATION IN CHARGE BASIS ##\n\n def get_U_cb(self, update=False): \n if update:\n self.init_qubit_states(update=True)\n else:\n try:\n self.state_product_ebeb\n except AttributeError:\n self.init_qubit_states()\n try:\n self.H_circuit\n except AttributeError:\n self.get_H_circuit()\n\n self.U_cb = self.H_circuit - qt.tensor(self.H_probe, self.target.I_cb) - qt.tensor(self.probe.I_cb, self.H_target)\n self.U_cb = np.real(self.U_cb.full())\n\n return self.U_cb\n \n def get_g_parr_cb(self, update=False):\n if update:\n self.init_qubit_states(update=True)\n self.get_U_cb(update=True)\n else:\n try:\n self.state_product_ebeb\n except AttributeError:\n self.init_qubit_states()\n try:\n self.U_cb\n except AttributeError:\n self.get_U_cb()\n \n self.state_target_cb_0 = qt.basis(2 * self.ncut + 1, 0)\n self.state_target_cb_1 = qt.basis(2 * self.ncut + 1, 1)\n self.state_probe_plus = 2**-0.5 * (self.eig_vectors_probe[0] + self.eig_vectors_probe[1])\n self.state_probe_minus = 2**-0.5 * (self.eig_vectors_probe[0] - self.eig_vectors_probe[1])\n\n self.state_product_ebeb_p0_ebcb = qt.tensor(self.state_probe_plus, self.state_target_cb_0)\n self.state_product_ebeb_p1_ebcb = qt.tensor(self.state_probe_plus, self.state_target_cb_1)\n self.state_product_ebeb_m0_ebcb = qt.tensor(self.state_probe_minus, self.state_target_cb_0)\n self.state_product_ebeb_m1_ebcb = qt.tensor(self.state_probe_minus, self.state_target_cb_1)\n\n self.g_parr_cb = self.state_product_ebeb_p1_ebcb.dag() * self.H_circuit * self.state_product_ebeb_m1_ebcb - self.state_product_ebeb_p0_ebcb.dag() * self.H_circuit * self.state_product_ebeb_m0_ebcb\n self.g_parr_cb = float(np.real(self.g_parr_cb))\n\n return self.g_parr_cb\n \n def get_g_perp_cb(self, update=False):\n if update:\n self.init_qubit_states(update=True)\n self.get_U_cb(update=True)\n else:\n try:\n self.state_product_ebeb\n except AttributeError:\n self.init_qubit_states()\n try:\n self.U_cb\n except AttributeError:\n self.get_U_cb()\n \n self.state_target_cb_0 = qt.basis(2 * self.ncut + 1, 0)\n self.state_target_cb_1 = qt.basis(2 * self.ncut + 1, 1)\n self.state_probe_eb_0 = self.eig_vectors_probe[0]\n self.state_probe_eb_1 = self.eig_vectors_probe[1]\n\n self.state_product_ebeb_00_ebcb = qt.tensor(self.state_probe_eb_0, self.state_target_cb_0)\n self.state_product_ebeb_01_ebcb = qt.tensor(self.state_probe_eb_0, self.state_target_cb_1)\n self.state_product_ebeb_10_ebcb = qt.tensor(self.state_probe_eb_1, self.state_target_cb_0)\n self.state_product_ebeb_11_ebcb = qt.tensor(self.state_probe_eb_1, self.state_target_cb_1)\n\n self.g_perp_cb = self.state_product_ebeb_11_ebcb.dag() * self.H_circuit * self.state_product_ebeb_01_ebcb - self.state_product_ebeb_10_ebcb.dag() * self.H_circuit * self.state_product_ebeb_00_ebcb\n self.g_perp_cb = float(np.real(self.g_perp_cb))\n\n return self.g_perp_cb ","repo_name":"balerat/Master-thesis---Superconducting-circuit-analysis","sub_path":"lib/circuit_cap_coupling.py","file_name":"circuit_cap_coupling.py","file_ext":"py","file_size_in_byte":19005,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35398604320","text":"from Crypto.PublicKey import RSA\nfrom Crypto.Random import get_random_bytes\nfrom cryptography.hazmat.primitives.asymmetric import padding\nfrom cryptography.hazmat.primitives import serialization, hashes\nfrom cryptography.fernet import Fernet\nimport os\n\n\ndef rsa_encrypt(data: bytes, public_key: bytes) -> bytes:\n key = serialization.load_pem_public_key(public_key)\n ciphertext = key.encrypt(\n data,\n padding.OAEP(\n mgf=padding.MGF1(algorithm=hashes.SHA256()),\n algorithm=hashes.SHA256(),\n label=None,\n ),\n )\n return ciphertext\n\ndef save_aes_key(aes_key, rsa_public_key):\n encrypted_aes_key = rsa_encrypt(aes_key, rsa_public_key)\n\n with open(\"secret.txt\", \"wb\") as file:\n file.write(encrypted_aes_key)\n\ndef generate_aes_key() -> bytes:\n return Fernet.generate_key()\n\ndef encrypt_file_with_aes(input_filename, aes_key):\n with open(input_filename, \"rb\") as file:\n file_data = file.read()\n cipher_suite = Fernet(aes_key)\n encrypted_data = cipher_suite.encrypt(file_data)\n\n with open(input_filename, \"wb\") as file:\n file.write(encrypted_data)\n\ndef encrypt(public_key: bytes, file_path: str) -> str:\n try:\n with open(file_path, \"rb\") as f:\n data = f.read()\n except FileNotFoundError:\n return \"File does not exist\"\n\n key = generate_aes_key() \n\n enc_data = encrypt_file_with_aes(file_path, key)\n save_aes_key(key, public_key)\n\n return \"Encrypted Successfully\"\n","repo_name":"pratikmpp22/AES-Encrypted-File-Transfer-over-Tor","sub_path":"encrypt.py","file_name":"encrypt.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2983577081","text":"# zomato_app/views.py\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\n\nmenu = {\n 1: {'name': 'Pizza', 'price': 10.99, 'availability': True},\n 2: {'name': 'Burger', 'price': 5.99, 'availability': True},\n 3: {'name': 'Pasta', 'price': 8.99, 'availability': False},\n # Add more menu items as needed\n}\n\norders = {}\n\nclass Order:\n def __init__(self, order_id, customer_name, dishes):\n self.order_id = order_id\n self.customer_name = customer_name\n self.dishes = dishes\n self.status = 'received'\n\n def update_status(self, new_status):\n self.status = new_status\n\n def check_dish_availability(self, dish_id):\n if dish_id in menu and menu[dish_id]['availability']:\n return True\n return False\n\ndef menu_view(request):\n return render(request, 'zomato_app/menu.html', {'menu': menu})\n\ndef place_order_view(request):\n if request.method == 'POST':\n customer_name = request.POST['customer_name']\n dish_ids = [int(dish_id) for dish_id in request.POST.getlist('dish')]\n \n available_dishes = [dish_id for dish_id in dish_ids if Order.check_dish_availability(Order, dish_id)]\n if len(available_dishes) == len(dish_ids):\n order_id = len(orders) + 1\n order = Order(order_id, customer_name, available_dishes)\n orders[order_id] = order\n return render(request, 'zomato_app/order_placed.html', {'order': order})\n else:\n unavailable_dishes = set(dish_ids) - set(available_dishes)\n return render(request, 'zomato_app/order_failed.html', {'unavailable_dishes': unavailable_dishes})\n \n return render(request, 'zomato_app/place_order.html', {'menu': menu})\n","repo_name":"mdShahbazUddin1/zomatochronicles","sub_path":"zomato_chronicles/zomato_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14295129221","text":"from __future__ import annotations\n\nimport asyncio\nimport itertools\nimport logging\nimport re\nimport urllib.parse\nfrom datetime import datetime\nfrom typing import (Any, Coroutine, Dict, List, Literal, Optional, Set,\n TypedDict)\n\nimport httpx\n\n\nclass Post(TypedDict):\n kind: Literal[\"t3\"]\n created_utc: int\n id: str\n num_comments: int\n over_18: bool\n permalink: str\n score: int\n selftext: str\n subreddit: str\n title: str\n url: str\n is_gallery: bool | None\n\n\nclass GalleryDataItem(TypedDict):\n media_id: str\n\n\nclass GalleryData(TypedDict):\n items: List[GalleryDataItem]\n\n\nclass MediaData(TypedDict):\n x: int\n y: int\n u: str\n\n\nclass MediaMetadata(TypedDict):\n s: MediaData\n p: List[MediaData]\n\n\nclass Gallery(TypedDict):\n title: str\n is_gallery: Literal[True]\n media_metadata: Dict[str, MediaMetadata]\n gallery_data: GalleryData\n\n\nclass Comment(TypedDict):\n kind: Literal[\"t1\"]\n author: str\n body: str\n created_utc: int\n id: str\n link_title: str\n link_url: str\n num_comments: str\n over_18: bool\n permalink: str\n score: int\n\n\ndef format_time_delta(delta_seconds: float) -> str:\n delta_seconds = int(delta_seconds)\n assert delta_seconds >= 0\n days = delta_seconds // (86400)\n hours = (delta_seconds % 86400) // 3600\n minutes = (delta_seconds % 3600) // 60\n seconds = delta_seconds % 60\n if days:\n return f\"{days}d {hours}h\"\n if hours:\n return f\"{hours}h {minutes}m\"\n if minutes:\n return f\"{minutes}m {seconds}s\"\n return f\"{seconds}s\"\n\n\ndef markdown_to_html(source: str) -> str:\n source = source.replace(\"&#x200B;\", \"\").replace(\"&nbsp;\", \" \")\n source = source.replace(\"<\", \"<\").replace(\">\", \">\")\n bold_md = r\"\\*\\*(.*?)\\*\\*\"\n bold_html = r\"\\1\"\n link_md = r\"\\[([^\\]\\[]*?)]\\((\\w[^\\s\\\"]*?)\\\\?\\\"?#?\\)\"\n link_html = r'\\1'\n source = re.sub(link_md, link_html, source)\n source = re.sub(bold_md, bold_html, source)\n return source\n\n\ndef formatted_post(post: Post) -> str:\n \"\"\"\n TODO: maybe show score and threshold, and subreddit in bold\n \"\"\"\n\n title = post[\"title\"].replace(\"<\", \"<\").replace(\">\", \">\")\n if post[\"over_18\"]:\n title += \" - NSFW\"\n\n time_ago = format_time_delta(datetime.now().timestamp() - post[\"created_utc\"])\n\n if len(post[\"selftext\"]) > 2100:\n post[\"selftext\"] = post[\"selftext\"][:2000] + \"...\"\n\n post[\"selftext\"] = markdown_to_html(post[\"selftext\"])\n if len(post[\"selftext\"]) > 3100:\n post[\"selftext\"] = post[\"selftext\"][:3000] + \"...\"\n\n template = (\n '{}: {} - '\n \"{}+ Comments - +{} in {}\\n\\n{}\"\n )\n return template.format(\n post[\"subreddit\"],\n urllib.parse.quote(post[\"url\"], safe=\"/:?=&#\"),\n title,\n post[\"permalink\"],\n post[\"num_comments\"],\n post[\"score\"],\n time_ago,\n post[\"selftext\"],\n )\n\n\ndef formatted_comment(comment: Comment) -> str:\n\n time_ago = format_time_delta(datetime.now().timestamp() - comment[\"created_utc\"])\n\n if len(comment[\"body\"]) > 2100:\n comment[\"body\"] = comment[\"body\"][:2000] + \"...\"\n\n template = (\n '{} on: {}'\n \"\\n\\n{}\\n\\n\"\n 'Context - +{} in {}'\n )\n\n return template.format(\n comment[\"author\"],\n urllib.parse.quote(comment[\"link_url\"], safe=\"/:?=&#\"),\n comment[\"link_title\"],\n markdown_to_html(comment[\"body\"]),\n comment[\"permalink\"],\n comment[\"score\"],\n time_ago,\n )\n\n\nclass SubredditBanned(Exception):\n pass\n\n\nclass SubredditPrivate(Exception):\n pass\n\n\nclass InvalidAnswerFromEndpoint(Exception):\n pass\n\n\nCLIENT_SESSION = httpx.AsyncClient()\n\n\nasync def get_posts_from_endpoint(\n endpoint: str, retry: bool = True\n) -> List[Post | Comment]:\n headers = {\"user-agent\": \"my-subreddits-bot-0.1\"}\n r_json = None\n response = None\n try:\n response = await CLIENT_SESSION.get(\n endpoint, headers=headers, timeout=60, follow_redirects=True\n )\n r_json = response.json()\n if not isinstance(r_json, dict):\n raise InvalidAnswerFromEndpoint()\n except Exception as e:\n if retry:\n logging.info(f\"{e!r} sleeping 60 seconds before retrying contacting reddit\")\n await asyncio.sleep(60)\n return await get_posts_from_endpoint(endpoint, retry=False)\n raise InvalidAnswerFromEndpoint(f\"{endpoint} returned invalid json {response}\")\n if \"data\" in r_json:\n children: Any = r_json[\"data\"][\"children\"]\n for child in children:\n child[\"data\"][\"kind\"] = child[\"kind\"]\n return [c[\"data\"] for c in children if c[\"kind\"] in (\"t1\", \"t3\")]\n if \"error\" in r_json and \"reason\" in r_json:\n if r_json[\"reason\"] == \"banned\" or r_json[\"reason\"] == \"quarantined\":\n raise SubredditBanned()\n if r_json[\"reason\"] == \"private\":\n raise SubredditPrivate()\n raise Exception(f\"{r_json} on {endpoint}\")\n\n\nBASE_URL = \"https://www.reddit.com\"\n\n\ndef is_subreddit(subscription: str) -> bool:\n if subscription[:2] not in (\"u/\", \"r/\"):\n raise ValueError(f\"Invalid subscription {subscription}\")\n return subscription.startswith(\"r/\")\n\n\nasync def hot_posts(subscription: str, limit: int = 30) -> List[Post | Comment]:\n endpoint = f\"{BASE_URL}/{subscription}/hot.json?limit={limit}\"\n return await get_posts_from_endpoint(endpoint)\n\n\nasync def new_posts(subscription: str, limit: int = 30) -> List[Post | Comment]:\n endpoint = f\"{BASE_URL}/{subscription}/new.json?limit={limit}\"\n return await get_posts_from_endpoint(endpoint)\n\n\nasync def get_top_posts(\n subscription: str, time_period: str, limit: int\n) -> List[Post | Comment]:\n if is_subreddit(subscription):\n endpoint = f\"{BASE_URL}/{subscription}/top.json?t={time_period}&limit={limit}\"\n else:\n subscription = subscription.replace(\"u/\", \"user/\")\n endpoint = (\n f\"{BASE_URL}/{subscription}.json?sort=top&t={time_period}&limit={limit}\"\n )\n return await get_posts_from_endpoint(endpoint)\n\n\nasync def get_posts(subscription: str, per_month: int) -> List[Post | Comment]:\n tasks: List[Coroutine[Any, Any, List[Post | Comment]]] = []\n if per_month < 99:\n tasks.append(get_top_posts(subscription, \"month\", per_month))\n if per_month // 4 < 99:\n limit = per_month // 4\n tasks.append(get_top_posts(subscription, \"week\", limit))\n if per_month // 31 < 99:\n limit = per_month // 31\n tasks.append(get_top_posts(subscription, \"day\", limit))\n if is_subreddit(subscription):\n tasks.append(hot_posts(subscription, min(per_month // 10, 99)))\n\n posts: List[Post | Comment] = list(\n itertools.chain.from_iterable(await asyncio.gather(*tasks))\n )\n\n def get_score(post: Post | Comment):\n return post[\"score\"]\n\n posts.sort(key=get_score, reverse=True)\n\n seen_ids: Set[str] = set()\n unique_posts: List[Post | Comment] = []\n for post in posts:\n if post[\"id\"] in seen_ids:\n continue\n seen_ids.add(post[\"id\"])\n unique_posts.append(post)\n return unique_posts\n\n\n# from https://github.com/reddit-archive/reddit/blob/753b17407e9a9dca09558526805922de24133d53/r2/r2/lib/validator/validator.py#L1570-L1571\nuser_rx = re.compile(r\"\\Au/[\\w-]{3,20}\\Z\", re.UNICODE)\n# from https://github.com/reddit-archive/reddit/blob/753b17407e9a9dca09558526805922de24133d53/r2/r2/models/subreddit.py#L114\nsubreddit_rx = re.compile(r\"\\Ar/[A-Za-z0-9][A-Za-z0-9_]{2,20}\\Z\")\n\n\ndef valid_subscription(text: str) -> bool:\n return bool(subreddit_rx.fullmatch(text) or user_rx.fullmatch(text))\n\n\nasync def get_posts_error(sub: str, monthly_rank: int) -> Optional[str]:\n if not valid_subscription(sub):\n return f\"{sub} is not a valid subreddit or user name\"\n try:\n posts = await get_posts(sub, monthly_rank)\n if posts and sum(post[\"over_18\"] for post in posts) / len(posts) >= 0.8:\n return f\"{sub} seems to be a porn subreddit, if that's not the case contact @recursing\"\n if not posts:\n return f\"{sub} does not exist or is empty or something\"\n except SubredditBanned:\n return f\"{sub} has been banned\"\n except SubredditPrivate:\n return f\"{sub} is private\"\n","repo_name":"Recursing/MySubredditsBot","sub_path":"reddit_adapter.py","file_name":"reddit_adapter.py","file_ext":"py","file_size_in_byte":8492,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"17127336006","text":"#Initial Template for Python 3\n# https://practice.geeksforgeeks.org/problems/stack-using-two-queues/1\n# Geek for Geek Stack Using queue problem\nimport atexit\nimport io\nimport sys\n#Contributed by : Nagendra Jha\n_INPUT_LINES = sys.stdin.read().splitlines()\ninput = iter(_INPUT_LINES).__next__\n_OUTPUT_BUFFER = io.StringIO()\nsys.stdout = _OUTPUT_BUFFER\n@atexit.register\ndef write():\n sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())\nqueue_1 = [] # first queue\nqueue_2 = [] # second queue\nif __name__ == '__main__':\n test_cases = int(input())\n for cases in range(test_cases) :\n n = int(input())\n a = list(map(int,input().strip().split()))\n i = 0\n while i 0)\r\n\r\n def test02ProperTitle(self):\r\n \"\"\"tests if the web page title is correct\"\"\"\r\n title = self.browser.title\r\n if not isinstance(title, str):\r\n title = title.decode()\r\n self.assertEqual(title, 'DnaAssembler')\r\n\r\n def test03StartPageTranslations(self):\r\n \"\"\"test 'start_page' page translations\"\"\"\r\n self.browser.reload()\r\n self.clickCssLink('#a_lang_en')\r\n self.assertEqual(len(self.browser.find_by_text(u'Welcome to DnaAssembler application')), 1)\r\n self.assertEqual(self.browser.find_by_id('loginAsGuestButton').first.text, u'Log in as guest')\r\n self.assertEqual(self.browser.find_by_id('loginAsGuestButton').first['title'], u\"Click to log in as guest\")\r\n self.assertEqual(self.browser.find_by_id('showLoginWindowButton').first.text, u'Log in')\r\n self.assertEqual(self.browser.find_by_id('showLoginWindowButton').first['title'], u\"Click to log in\")\r\n self.assertEqual(self.browser.find_by_id('showNewUserWindowButton').first.text, u'Create new user')\r\n self.assertEqual(self.browser.find_by_id('showNewUserWindowButton').first['title'], u\"Click to create new user\")\r\n self.assertEqual(self.browser.find_by_id('showHelpWindowButton').first.text, u'Help')\r\n self.assertEqual(self.browser.find_by_id('showHelpWindowButton').first['title'], u\"Click to view help page\")\r\n self.assertEqual(self.browser.find_by_id('a_lang_en').first['title'], u\"Click to change language to english\")\r\n self.assertEqual(self.browser.find_by_id('a_lang_pl').first['title'], u\"Click to change language to polish\")\r\n self.clickCssLink('#a_lang_pl')\r\n self.assertEqual(len(self.browser.find_by_text(u'Witaj w aplikacji DnaAssembler')), 1)\r\n self.assertEqual(self.browser.find_by_id('loginAsGuestButton').first.text, u'Zaloguj się jako gość')\r\n self.assertEqual(self.browser.find_by_id('loginAsGuestButton').first['title'], u\"Kliknij, aby zalogować się do aplikacji jako gość\")\r\n self.assertEqual(self.browser.find_by_id('showLoginWindowButton').first.text, u'Zaloguj się')\r\n self.assertEqual(self.browser.find_by_id('showLoginWindowButton').first['title'], u\"Kliknij, aby zalogować się do aplikacji\")\r\n self.assertEqual(self.browser.find_by_id('showNewUserWindowButton').first.text, u'Dodaj użytkownika')\r\n self.assertEqual(self.browser.find_by_id('showNewUserWindowButton').first['title'], u\"Kliknij, aby dodać nowego użytkownika\")\r\n self.assertEqual(self.browser.find_by_id('showHelpWindowButton').first.text, u'Pomoc')\r\n self.assertEqual(self.browser.find_by_id('showHelpWindowButton').first['title'], u\"Kliknij, aby zobaczyć pomoc dla aplikacji\")\r\n self.assertEqual(self.browser.find_by_id('a_lang_en').first['title'], u\"Kliknij, aby zmienić język na angielski\")\r\n self.assertEqual(self.browser.find_by_id('a_lang_pl').first['title'], u\"Kliknij, aby zmienić język na polski\")\r\n\r\nif __name__ == \"__main__\":\r\n www_browser = sys.argv[1] if len(sys.argv) >= 2 else 'chrome'\r\n www_addr = sys.argv[2] if len(sys.argv) >= 3 else '127.0.0.1'\r\n www_port = sys.argv[3] if len(sys.argv) >= 4 else '9000'\r\n admin_user = sys.argv[4] if len(sys.argv) >= 5 else ''\r\n admin_user_password = sys.argv[5] if len(sys.argv) >= 6 else ''\r\n\r\n browser = None\r\n\r\n try:\r\n if www_browser == 'firefox':\r\n caps = {}\r\n caps['acceptInsecureCerts'] = True\r\n browser = Browser('firefox', capabilities=caps)\r\n else:\r\n browser = Browser(www_browser)\r\n except DriverNotFoundError:\r\n print(\"ERROR: WebDriver for browser '\" + www_browser + \"' not found.\")\r\n\r\n browser.driver.maximize_window()\r\n\r\n print('http://' + www_addr + ':' + www_port)\r\n\r\n browser.visit('http://' + www_addr + ':' + www_port)\r\n\r\n TestFunctionalDnaasm.browser = browser\r\n TestFunctionalDnaasm.admin_user = admin_user\r\n TestFunctionalDnaasm.admin_user_password = admin_user_password\r\n\r\n suite = unittest.TestSuite()\r\n suite.addTest(unittest.makeSuite(TestFunctionalDnaasm))\r\n\r\n testToRun = 'all'\r\n\r\n if testToRun != 'all':\r\n anyTestWillBeRun = False\r\n\r\n for ts in suite:\r\n for t in ts:\r\n if testToRun not in t.id():\r\n setattr(t, 'setUp', lambda: t.skipTest('Not running this time'))\r\n else:\r\n anyTestWillBeRun = True\r\n if not anyTestWillBeRun:\r\n print('ERROR: Cannot run given test because it doesn\\'t exist: ' + testToRun)\r\n sys.exit()\r\n\r\n try:\r\n from xmlrunner import XMLTestRunner\r\n if not os.path.exists('./reports'):\r\n os.makedirs('./reports')\r\n with open('./reports/functional_output.xml', 'wb') as output:\r\n XMLTestRunner(output=output, verbosity=3).run(suite)\r\n\r\n except ImportError:\r\n print(\"Failed to import xmlrunner library. Using TextTestRunner instead...\\n\\n\")\r\n unittest.TextTestRunner(verbosity=3).run(suite)\r\n\r\n browser.quit()\r\n","repo_name":"wkusmirek/test-web-interface","sub_path":"functional_tests.py","file_name":"functional_tests.py","file_ext":"py","file_size_in_byte":7664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33138748631","text":"# ULTIMATE VER.\n#from MULT_Plurk_Stead_Data_smiling_face_with_open_mouth import * // this line doesn't work for some reason\n\n# BUT IT'S MULTITHREADING\n\nfrom selenium import webdriver\nfrom time import sleep\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.keys import Keys\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.action_chains import ActionChains\nimport requests\nimport json\nfrom selenium.common.exceptions import *\n\n#先把通知都關掉,不然後面會點不到按鈕\noptionla = Options();\noptionla.add_argument(\"disable-notifications\");\noptionla.add_argument('--headless') # don't render the webpage per se, but more difficult to debug\noptionla.add_argument('--disable-gpu') # prevent weird bug\n#driver = webdriver.Chrome(ChromeDriverManager().install(), options=optionla)\n#driver.get(\"https://www.plurk.com\")\n#那些個%F0啥小的其實是一個笑臉的表情符號的Coding!\n\n\n\"load face list\"\nimport pickle\nwith open(\"Face_list.pkl\", \"rb\") as f:\n face_list = pickle.load(f)\n f.close()\nassert len(face_list) == 70\n\n# file saving\nfrom pathlib import Path\nbasedir = Path(\"faces_exp\") # change to faces_experiment just in case the quality is weird?\n\n# FUCK\nif not basedir.is_dir():\n basedir.mkdir()\n\n\n# the crawler per se\n\n#自動化流程,跑這個就對了\ndef run_it(face_idx):\n\n emoji, filename = face_list[face_idx]\n\n # check if file exists or not\n if Path(basedir/(filename+\".json\")).is_file():\n print(f\"{filename} has been fetched, skip\")\n return\n\n # make driver local\n driver = webdriver.Chrome(ChromeDriverManager().install(), options=optionla)\n\n TAR_URL = f\"https://www.plurk.com/search?q={emoji}&date=2022-09\"\n driver.get(TAR_URL)\n\n # \"row to the bottom first\"\n # should change to while not bottom: scroll the darn thing?\n #for i in range(600):\n # driver.execute_script(\"window.scrollTo(0,Math.max(document.documentElement.scrollHeight,\" + \"document.body.scrollHeight,document.documentElement.clientHeight));\")\n # sleep(0.5)\n # \"SUCCEEDED\", while not at the buttom, scroll it!\n while len(driver.find_elements(By.XPATH, '//*[@id=\"result\"]//*[@class=\"status-holder\"]//*[@class=\"button\"]')) == 0:\n driver.execute_script(\"window.scrollTo(0,Math.max(document.documentElement.scrollHeight,\" + \"document.body.scrollHeight,document.documentElement.clientHeight));\")\n sleep(0.3)\n\n # \"then get the data\"\n # t = 0 # move this into the loop\n final = []\n for t, el in enumerate(driver.find_elements(By.CSS_SELECTOR,\"[class='plurk cboxAnchor divplurk bigplurk plink']\")):\n sleep(0.2)\n action = webdriver.common.action_chains.ActionChains(driver)\n action.move_to_element_with_offset(el, (el.size['width'])/2, 0)\n action.click()\n action.perform()\n sleep(0.2)\n try:\n testuser0 = driver.find_element(By.CSS_SELECTOR,\"[class='cbox_plurk_holder']\").find_element(By.CSS_SELECTOR,\"[class='user']\").text\n motherfucker = driver.find_elements(By.XPATH,\"//div[@data-type='response']\")\n testuser1 = motherfucker[0].find_element(By.XPATH,\".//div[@class='user']\").text\n testuser2 = motherfucker[1].find_element(By.XPATH,\".//div[@class='user']\").text\n # here? moved!\n if testuser0==testuser2 and testuser0!=testuser1:\n testtext0 = driver.find_element(By.CSS_SELECTOR,\"[class='cbox_plurk_holder']\").find_element(By.CSS_SELECTOR,\"[class='content']\").text\n testtext1 = motherfucker[0].find_element(By.CSS_SELECTOR,\"[class='content']\").text\n testtext2 = motherfucker[1].find_element(By.CSS_SELECTOR,\"[class='content']\").text\n TD = [[testuser0,testtext0],[testuser1,testtext1],[testuser2,testtext2]]\n print(TD) # we still want to load the text?\n final.append(TD)\n # move this to front so that we don't have to find the texts of invalid ones?\n # testtext0 = driver.find_element(By.CSS_SELECTOR,\"[class='cbox_plurk_holder']\").find_element(By.CSS_SELECTOR,\"[class='content']\").text\n # testtext1 = motherfucker[0].find_element(By.CSS_SELECTOR,\"[class='content']\").text\n # testtext2 = motherfucker[1].find_element(By.CSS_SELECTOR,\"[class='content']\").text\n # if testuser0==testuser2 and testuser0!=testuser1:\n # TD = [[testuser0,testtext0],[testuser1,testtext1],[testuser2,testtext2]]\n # print(TD)\n # final.append(TD)\n else:\n #print(\"可惜了\")\n pass\n except:\n #print(\"不合條件\")\n pass\n sleep(0.2)\n #\"add error handling\"\n try:\n driver.find_element(By.CSS_SELECTOR, \"[class='cbox_close pif-cancel']\").click()\n except ElementNotInteractableException:\n pass\n #print(t)\n with open(f\"{basedir/filename}.json\",'w', encoding = 'utf-8') as yyyyy:\n json.dump(final,yyyyy)\n yyyyy.close()\n\n # close the driver / browser after the task for this emoji is done\n driver.quit()\n\n\n# fetch ALL 70 POSTS\n# not tested\n# TODO\n# (done)add filename check: check if the file exists\n# (done)make driver a local variable, aka, put it in the function to run faster\n# (done)close the driver after done fetching on emoji\n\nif __name__ == \"__main__\":\n import multiprocessing\n import sys\n # instead of doing this, we should get all 70 files\n # and exclude the fetched ones\n # remember to exclude the ones from Sam as well?\n tar = [int(ele) for ele in sys.argv[1:] if ele.isnumeric() and len(ele) > 0]\n processes = []\n for face_idx in list(map(int, tar)):\n p = multiprocessing.Process(target=run_it, args=(face_idx,))\n processes.append(p)\n p.start()\n\n for process in processes:\n process.join()\n\n","repo_name":"Kelvinthedrugger/-AI-","sub_path":"PLURK/PLURK_EZ_GET/ultimate_fetch.py","file_name":"ultimate_fetch.py","file_ext":"py","file_size_in_byte":6104,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7953010308","text":"import torch\nfrom bindsnet.network import Network\nfrom bindsnet.network.nodes import Input, IFNodes, LIFNodes\nfrom bindsnet.network.topology import Connection\nfrom bindsnet.learning import PostPre\nfrom bindsnet.network.monitors import Monitor\n\nimport utils\n\nclass Net(Network):\n def __init__(self, inpt_shape=(1, 28, 28), neuron_shape=(10, 10),\n vrest=0.5, vreset=0.5, vth=1., lbound=0.,\n theta_w=1e-3, sigma=1., conn_strength=1.,\n sigma_lateral_exc=1., exc_strength=1.,\n sigma_lateral_inh=1., inh_strength=1.,\n refrac=5, tc_decay=50., tc_trace=20., dt=1.0,\n nu=(1e-4, 1e-2), reduction=None):\n super().__init__(dt=dt)\n\n self.inpt_shape = inpt_shape\n self.n_inpt = utils.shape2size(self.inpt_shape)\n self.neuron_shape = neuron_shape\n self.n_neurons = utils.shape2size(self.neuron_shape)\n self.dt = dt\n\n # Layers\n input = Input(n=self.n_inpt, shape=self.inpt_shape, traces=True, tc_trace=tc_trace)\n population = LIFNodes(shape=self.neuron_shape, traces=True, lbound=lbound, rest=vrest, reset=vreset, thresh=vth, refrac=refrac, tc_decay=tc_decay, tc_trace=tc_trace)\n inh = IFNodes(shape=self.neuron_shape, traces=True, lbound=0., rest=0., reset=0., thresh=0.99, refrac=0, tc_trace=tc_trace)\n\n # Coordinates\n self.coord_x = torch.rand(neuron_shape) * self.neuron_shape[1] / self.neuron_shape[0]\n self.coord_y = torch.rand(neuron_shape)\n self.coord_x_disc = (self.coord_x * self.inpt_shape[2]/(self.neuron_shape[1]/self.neuron_shape[0])).long()\n self.coord_y_disc = (self.coord_y * self.inpt_shape[1]).long()\n grid_x = (torch.arange(self.inpt_shape[2]).unsqueeze(0).float() + 0.5) * (self.neuron_shape[1] / self.neuron_shape[0]) / self.inpt_shape[2]\n grid_y = (torch.arange(self.inpt_shape[1]).unsqueeze(1).float() + 0.5) / self.inpt_shape[1]\n\n # Input-Neurons connections\n w = torch.abs(torch.randn(self.inpt_shape[1], self.inpt_shape[2], *self.neuron_shape))\n for k in range(neuron_shape[0]):\n for l in range(neuron_shape[1]):\n sq_dist = (grid_x - self.coord_x[k, l]) ** 2 + (grid_y - self.coord_y[k, l]) ** 2\n w[:, :, k, l] *= torch.exp(- sq_dist / (2 * sigma ** 2))\n w = w.view(self.n_inpt, self.n_neurons)\n input_mask = w < theta_w\n w[input_mask] = 0. # Drop connections smaller than threshold\n input_conn = Connection(source=input, target=population, w=w, update_rule=PostPre, nu=nu, reduction=reduction, wmin=0, norm=conn_strength)\n input_conn.normalize()\n\n # Excitatory self-connections\n w = torch.abs(torch.randn(*self.neuron_shape, *self.neuron_shape))\n for k in range(neuron_shape[0]):\n for l in range(neuron_shape[1]):\n sq_dist = (self.coord_x - self.coord_x[k, l]) ** 2 + (self.coord_y - self.coord_y[k, l]) ** 2\n w[:, :, k, l] *= torch.exp(- sq_dist / (2 * sigma_lateral_exc ** 2))\n w[k, l, k, l] = 0. # set connection from neuron to itself to zero\n w = w.view(self.n_neurons, self.n_neurons)\n exc_mask = w < theta_w\n w[exc_mask] = 0. # Drop connections smaller than threshold\n self_conn_exc = Connection(source=population, target=population, w=w, update_rule=PostPre, nu=nu, reduction=reduction, wmin=0, norm=exc_strength)\n self_conn_exc.normalize()\n\n # Inhibitory self-connection\n w = torch.eye(self.n_neurons)\n exc_inh = Connection(source=population, target=inh, w=w)\n w = -torch.abs(torch.randn(*self.neuron_shape, *self.neuron_shape))\n for k in range(neuron_shape[0]):\n for l in range(neuron_shape[1]):\n sq_dist = (self.coord_x - self.coord_x[k, l]) ** 2 + (self.coord_y - self.coord_y[k, l]) ** 2\n w[:, :, k, l] *= torch.exp(- sq_dist / (2 * sigma_lateral_inh ** 2))\n w[k, l, k, l] = 0. # set connection from neuron to itself to zero\n w = w.view(self.n_neurons, self.n_neurons)\n inh_mask = w > -theta_w\n w[inh_mask] = 0. # Drop connections smaller than threshold\n self_conn_inh = Connection(source=inh, target=population, w=w, update_rule=PostPre, nu=tuple(-a for a in nu), reduction=reduction, wmax=0, norm=inh_strength)\n self_conn_inh.normalize()\n\n # Add layers to network\n self.add_layer(input, name=\"X\")\n self.add_layer(population, name=\"Y\")\n self.add_layer(inh, name=\"Z\")\n\n # Add connections\n self.add_connection(input_conn, source=\"X\", target=\"Y\")\n self.add_connection(self_conn_exc, source=\"Y\", target=\"Y\")\n self.add_connection(exc_inh, source=\"Y\", target=\"Z\")\n self.add_connection(self_conn_inh, source=\"Z\", target=\"Y\")\n\n # Add weight masks to network\n self.masks = {}\n self.add_weight_mask(mask=input_mask, connection_id=(\"X\", \"Y\"))\n self.add_weight_mask(mask=exc_mask, connection_id=(\"Y\", \"Y\"))\n self.add_weight_mask(mask=inh_mask, connection_id=(\"Z\", \"Y\"))\n\n # Add monitors to record neuron spikes\n self.spike_monitor = Monitor(self.layers[\"Y\"], [\"s\"])\n self.add_monitor(self.spike_monitor, name=\"Spikes\")\n\n def add_weight_mask(self, mask, connection_id):\n self.masks[connection_id] = mask\n\n def run(self, inputs, time, one_step=False, **kwargs):\n super().run(inputs=inputs, time=time, one_step=one_step, masks=self.masks, **kwargs)\n\n def to_gpu(self):\n self.masks = {k: v.cuda() for k, v in self.masks.items()}\n return self.to(\"cuda\")\n\n","repo_name":"GabrieleLagani/SpikingGrid","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5677,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"43162622202","text":"import psutil\r\n\r\n\r\ndef secs2hours(secs):\r\n mm, ss = divmod(secs, 60)\r\n hh, mm = divmod(mm, 60)\r\n return hh, mm, ss\r\n\r\n\r\ndef battery_check():\r\n # gives the current battery and charging status of the system\r\n battery = psutil.sensors_battery()\r\n h, m, s = secs2hours(battery.secsleft)\r\n if battery.power_plugged:\r\n if battery.percent != 100:\r\n chrg_stat = \"charging\"\r\n else:\r\n chrg_stat = \"Fully charged\"\r\n desc = \".\"\r\n else:\r\n if battery.percent >= 30:\r\n chrg_stat = \"discharging\"\r\n else:\r\n chrg_stat = \"running on backup power, connect to a power source\"\r\n desc = \". Should last for \" + str(h) + \" hours \" + str(m) + \" minutes\"\r\n print(\"Power at \" + str(battery.percent) + \"% and \" + chrg_stat + desc)\r\n\r\n\r\nbattery_check()\r\n","repo_name":"PranavPutsa1006/System-battery","sub_path":"Battery.py","file_name":"Battery.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"39433520783","text":"import csv\n\nhouses = {\n \"gryff\": 0,\n \"huffle\": 0,\n \"raven\": 0,\n \"slyth\": 0,\n}\n\nwith open(\"hogwarts.csv\", \"r\") as file:\n # reader = csv.reader(file)\n reader = csv.DictReader(file)\n next(reader)\n for row in reader:\n house = row[\"House\"]\n # house = row[1]\n houses[house] += 1\n\nfor house in houses:\n count = houses[house]\n print(f\"{house}: {count}\")","repo_name":"kariscourey/CS50x-Coursework","sub_path":"Week6/hogwarts.py","file_name":"hogwarts.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"70949624467","text":"# Dependencies\n## stdlib\nimport argparse\nimport json\nimport logging\nfrom pathlib import Path\nfrom string import Template\nimport os\nimport subprocess\nimport sys\nimport time\n\n## proj\nimport utils\n\nCONFIG = utils.load_config()\nCONFIG_SRC = CONFIG[\"SRC\"]\nCONFIG_DST = CONFIG[\"DST\"]\n\n# Constants\nLOG_FMT = \"%(levelname)s %(asctime)-15s %(message)s\"\nCHUNK_SIZE = 5\n## rsync -avP --include='*.gz' --include='*/' --exclude='*' ~/honeyData/vz/root/100 ubuntu@130.245.169.240:/home/ubuntu/data\nRSYNC_TEMP = Template(\n f\"rsync -avP --include='*.gz' --include='*/' --exclude='*' {CONFIG_SRC['CTR_DIR']}/$ctr $host:$dir\"\n)\nGUNZIP_TEMP = Template(f\"gunzip -rf $dir/$ctr/var/log\") # ctr that has not yet been unzipped\nRM_CMD = \"sudo python3 filebeat_scrubber.py --remove --summary\"\nFIND_CMD = \"find data -type f -name '*.gz' | sort | head -n 1\"\n\nlogging.basicConfig(\n filename=f\"{CONFIG['LOCAL_DIR']}/{CONFIG['TRANSFER_LOG']}\", format=LOG_FMT, level=logging.DEBUG\n)\nlogger = logging.getLogger(\"transfer_containers\")\nlogger.addHandler(logging.StreamHandler(sys.stdout))\n\n# Utils\ndef get_rsync_cmd(ctr, dst, _dir):\n return RSYNC_TEMP.substitute(ctr=ctr, host=dst, dir=_dir)\n\n\ndef get_gunzip_cmd(ctr, _dir):\n return GUNZIP_TEMP.substitute(ctr=ctr, dir=_dir)\n\n\ndef get_rm_cmd():\n return RM_CMD\n\n\ndef get_find_cmd():\n return FIND_CMD\n\n\ndef get_next_ctr(dst_host):\n cmd = get_find_cmd()\n res = run_ssh(dst_host, cmd, output=True).strip()\n paths = res.split(\"/\")\n return int(paths[1])\n\n\ndef run_ssh(host, cmd, output=False, check=False):\n # stdout = sys.stdout if output else subprocess.DEVNULL\n proc = subprocess.run([\"ssh\", host, cmd], capture_output=output, check=check)\n if output:\n return proc.stdout.decode(\"utf-8\")\n else:\n return None\n\n\ndef rsync(src_host, dst_config, last_ctr, until, ctrs):\n dst_host = dst_config[\"HOST\"]\n dst_dir = dst_config[\"CTR_DIR\"]\n for idx, ctr in enumerate(ctrs):\n logger.debug(f\"rsync'ing ctr {ctr}...{len(ctrs)-idx-1} left\")\n rsync_cmd = get_rsync_cmd(ctr, dst_host, dst_dir)\n try:\n logger.debug(f\"\\t rsync'ing {ctr}: {rsync_cmd}\")\n run_ssh(src_host, rsync_cmd, output=False, check=False)\n except subprocess.CalledProcessError as e:\n logger.error(f\"\\t rsync err {ctr}: {e}\")\n continue\n # break\n\n\ndef filebeat_scrub(dst_host):\n rm_cmd = get_rm_cmd()\n logger.debug(f\"scrubbing {dst_host}: {rm_cmd}\")\n summary = run_ssh(dst_host, rm_cmd, output=True)\n logger.info(summary)\n\n\ndef unzip(dst_config, last_ctr, scrub, ctrs):\n dst_host = dst_config[\"HOST\"]\n dst_dir = dst_config[\"CTR_DIR\"]\n if last_ctr is None:\n next_ctr = get_next_ctr(dst_host)\n logger.debug(f\"host {dst_host} gunzip'ing from {next_ctr}\")\n ctrs = ctrs[ctrs.index(next_ctr) :]\n ctrs = ctrs[:CHUNK_SIZE]\n\n for idx, ctr in enumerate(ctrs):\n logger.debug(f\"guzip'ing ctr {ctr}...{len(ctrs)-idx-1} left\")\n gunzip_cmd = get_gunzip_cmd(ctr, dst_dir)\n try:\n logger.debug(f\"\\t gunzip'ing {ctr}: {gunzip_cmd}\")\n run_ssh(dst_host, gunzip_cmd, output=False, check=False)\n except subprocess.CalledProcessError as e:\n if e.returncode == 2:\n logger.warning(f\"\\t gunzip warning {ctr}: {e.returncode}\")\n else:\n logger.error(f\"\\t gunzip err {ctr}: {e}\")\n # break\n\n\ndef main(dst, last_ctr, transfer, until, scrub, gunzip):\n src_host = CONFIG_SRC[\"HOST\"]\n dst_config = CONFIG_DST[dst]\n dst_host = dst_config[\"HOST\"]\n dst_dir = dst_config[\"CTR_DIR\"]\n ctrs = list(utils.get_containers().keys())\n if last_ctr is not None and last_ctr != -1:\n ctrs = ctrs[ctrs.index(last_ctr) + 1 :]\n if until is not None:\n ctrs = ctrs[: ctrs.index(until) + 1]\n\n if transfer:\n rsync(src_host, dst_config, last_ctr, until, ctrs)\n\n if scrub:\n filebeat_scrub(dst_host)\n\n if gunzip:\n unzip(dst_config, last_ctr, scrub, ctrs)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Transfer container data.\")\n parser.add_argument(\"dst\", type=str)\n parser.add_argument(\"--last_ctr\", type=int)\n parser.add_argument(\"--until\", type=int)\n parser.add_argument(\"--transfer\", dest=\"transfer\", action=\"store_true\")\n parser.add_argument(\"--no-transfer\", dest=\"transfer\", action=\"store_false\")\n parser.add_argument(\"--scrub\", dest=\"scrub\", action=\"store_true\")\n parser.add_argument(\"--no-scrub\", dest=\"scrub\", action=\"store_false\")\n parser.add_argument(\"--gunzip\", dest=\"gunzip\", action=\"store_true\")\n parser.add_argument(\"--no-gunzip\", dest=\"gunzip\", action=\"store_false\")\n parser.set_defaults(transfer=False, scrub=True, gunzip=True)\n args = parser.parse_args()\n main(args.dst, args.last_ctr, args.transfer, args.until, args.scrub, args.gunzip)\n","repo_name":"jso123450/rt_expired","sub_path":"extract/transfer_containers.py","file_name":"transfer_containers.py","file_ext":"py","file_size_in_byte":4892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34964126207","text":"from typing import Any, List, Dict\nimport traceback\nfrom .Result import Result\nfrom itertools import compress\n\nimport unittest\n\n\nclass MonadicListOfResult():\n def __init__(\n self,\n value: List[Any],\n failed: bool = False,\n failure: Dict[str, Any] | None = None,\n ) -> None:\n if not isinstance(value, list):\n raise ValueError(\"value should be a list\")\n\n all_elements_result = all([\n type(x) is Result for x in value\n ])\n no_elements_result = all([\n type(x) is not Result for x in value\n ])\n\n if not (all_elements_result or no_elements_result):\n raise ValueError(\n \"List passed should contain either all elements of type Result\"\n \"or no elements of type Result, not a mixed list\"\n )\n\n if not all_elements_result:\n value = [Result(x) for x in value]\n\n self.value = value\n self.failed_indices = [v.failed for v in value]\n self.failed = True if failed else any(self.failed_indices)\n self.failure = failure\n\n # for iteration\n self.counter: int = 0\n self.iter_len: int = 0\n\n def __repr__(self) -> str:\n return (\n f\"MList({self.value}, is_failed={self.is_failed()}, \"\n f\"failure={self.failure})\"\n )\n\n def unwrap(self) -> List[Result]:\n return self.value\n\n def unwrap_all(self) -> List[Any]:\n return [v.unwrap() for v in self.unwrap()]\n\n def is_failed(self) -> bool:\n return self.failed\n\n def is_ok(self) -> bool:\n return not self.failed\n\n def bind(self, func, *args, **kwargs):\n if self.is_failed():\n return self\n\n try:\n return MonadicListOfResult(\n [v.bind(func, *args, **kwargs) for v in self.value]\n )\n except Exception as Err:\n failure = {\n \"trace\": traceback.format_exc(),\n \"exception\": Err,\n \"args\": args,\n \"kwargs\": kwargs,\n }\n return MonadicListOfResult(self.value, True, failure)\n\n def flatten(self):\n if self.is_failed():\n return self\n flattened = []\n\n try:\n for v in self.value:\n flattened.extend(v.flatten())\n return MonadicListOfResult(flattened)\n except Exception as Err:\n failure = {\n \"trace\": traceback.format_exc(),\n \"exception\": Err,\n \"args\": [],\n \"kwargs\": {},\n }\n return MonadicListOfResult(self.value, True, failure)\n\n def bind_and_flatten(\n self,\n func,\n *args,\n **kwargs,\n ):\n if self.is_failed():\n return self\n\n try:\n flattened = []\n for v in self.value:\n results = v.bind(func, *args, **kwargs).flatten()\n flattened.extend(results)\n return MonadicListOfResult(flattened)\n\n except Exception as Err:\n failure = {\n \"trace\": traceback.format_exc(),\n \"exception\": Err,\n \"args\": args,\n \"kwargs\": kwargs,\n }\n\n return MonadicListOfResult(self.value, True, failure)\n\n def filter(self, func, *args, **kwargs):\n if self.is_failed():\n return self\n\n try:\n filter_conds = [\n v.bind(func, *args, **kwargs).unwrap() for v in self.value\n ]\n return MonadicListOfResult(\n list(compress(self.value, filter_conds))\n )\n\n except Exception as Err:\n failure = {\n \"trace\": traceback.format_exc(),\n \"exception\": Err,\n \"args\": args,\n \"kwargs\": kwargs,\n }\n\n return MonadicListOfResult(self.value, True, failure)\n\n def __rshift__(self, func, *args, **kwargs):\n return self.bind_and_flatten(func, *args, **kwargs)\n\n def __eq__(self, __o: \"MonadicListOfResult\") -> bool:\n return self.unwrap() == __o.unwrap()\n\n def __iter__(self):\n self.counter = 0\n self.len_iter = len(self.value)\n return self\n\n def __next__(self):\n if self.counter < self.len_iter:\n obj = self.value[self.counter]\n self.counter += 1\n return obj\n else:\n raise StopIteration\n\nclass TestMonadicListClass(unittest.TestCase):\n\n def test_init_passing_result(self):\n my_l = MonadicListOfResult([Result(x) for x in [\"a\", \"b\", \"c\"]])\n self.assertFalse(my_l.is_failed())\n\n def test_init_passing_others(self):\n my_l = [1, 2, 3]\n my_ml = MonadicListOfResult(my_l)\n self.assertEqual(my_ml.unwrap(), [Result(x) for x in my_l])\n\n def test_list_mixed_types_with_result_should_fail(self):\n my_l = [1, Result(2), 3]\n with self.assertRaises(ValueError):\n MonadicListOfResult(my_l)\n\n def test_two_ways_creating(self):\n one = MonadicListOfResult([1, 2, 3])\n two = MonadicListOfResult([Result(x) for x in range(1, 4)])\n self.assertEqual(one, two)\n\n def test_bind(self):\n bind_result = MonadicListOfResult([1, 2, 3]).bind(lambda x: x ** 2)\n expected_result = MonadicListOfResult([1, 4, 9])\n self.assertEqual(bind_result, expected_result)\n\n def test_unwrapping(self):\n bind_result = MonadicListOfResult([1, 2, 3]).bind(lambda x: x ** 2)\n expected = [Result(v) for v in [1, 4, 9]]\n self.assertEqual(bind_result.unwrap(), expected)\n\n def test_unwrap_all(self):\n bind_result = MonadicListOfResult([1, 2, 3]).bind(lambda x: x ** 2)\n expected = [1, 4, 9]\n self.assertEqual(bind_result.unwrap_all(), expected)\n\n def test_flatten(self):\n flatten_result = (\n MonadicListOfResult([1, 2, 3])\n .bind(lambda x: [x, x ** 2])\n .flatten()\n )\n expected_result = MonadicListOfResult([1, 1, 2, 4, 3, 9])\n self.assertEqual(flatten_result, expected_result)\n\n def test_bind_flatten(self):\n flatten_result = (\n MonadicListOfResult([1, 2, 3])\n .bind_and_flatten(lambda x: [x, x ** 2])\n )\n expected_result = MonadicListOfResult([1, 1, 2, 4, 3, 9])\n self.assertEqual(flatten_result, expected_result)\n\n def test_filter(self):\n result = (\n MonadicListOfResult(list(range(10)))\n .filter(lambda x: x % 2 == 0)\n )\n expected = MonadicListOfResult([0, 2, 4, 6, 8])\n self.assertEqual(result, expected)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n # testing creation of MonadicListOfResult\n # should only take a list of all results or a list of no results\n # l_r = [Result(x) for x in range(3)]\n # l_no_r = [0, 1, 2]\n # l_mix_one = [0, Result(1), 2]\n\n # testing basic logic\n # print(l_r)\n # l_r_all_result = all([type(x) is Result for x in l_r])\n # l_r_no_result = all([type(x) is not Result for x in l_r])\n # print(l_r_all_result or l_r_no_result)\n\n # l_no_r_all_result = all([type(x) is Result for x in l_no_r])\n # l_no_r_no_result = all([type(x) is not Result for x in l_no_r])\n # print(l_no_r_all_result or l_no_r_no_result)\n\n # print(l_mix_one)\n # l_mix_r_all_result = all([type(x) is Result for x in l_mix_one])\n # print(l_mix_r_all_result)\n # l_mix_r_no_result = all([type(x) is not Result for x in l_mix_one])\n # print(l_mix_r_no_result)\n # print(l_mix_r_all_result or l_mix_r_no_result)\n\n # try:\n # l_one = MonadicListOfResult(l_r)\n # except Exception as Err:\n # print(Err)\n\n # try:\n # l_one = MonadicListOfResult(l_no_r)\n # except Exception as Err:\n # print(Err)\n\n # try:\n # l_one = MonadicListOfResult(l_mix_one)\n # except Exception as Err:\n # print(Err)\n\n # # testing filter\n # my_l = MonadicListOfResult(list(range(10)))\n # print(my_l)\n # print(my_l.bind(lambda x: x % 2 == 0))\n\n # # print(my_l)\n # print(my_l.filter(lambda x: x % 2 == 0))\n","repo_name":"ezeray/py_personal_helper","sub_path":"personal_helper/structs/MonadicListOfResult.py","file_name":"MonadicListOfResult.py","file_ext":"py","file_size_in_byte":8253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18161772814","text":"import os.path as osp\r\nimport pandas as pd\r\nimport torch\r\nimport torch.utils.data as data\r\nimport torch.nn as nn\r\nimport json\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.model_selection import train_test_split\r\nimport numpy as np\r\nfrom mpl_toolkits.axes_grid1 import host_subplot\r\nfrom sklearn.metrics import roc_auc_score\r\nfrom torch_geometric.data import Data, download_url, extract_gz\r\nimport torch_geometric.transforms as T\r\nfrom torch_geometric.datasets import Planetoid\r\nfrom torch_geometric.nn import GCNConv\r\nfrom torch_geometric.utils import negative_sampling\r\nfrom get_acc import tag_test,heat_map,heat_map_acc\r\nfrom net import *\r\nfrom sklearn.metrics import confusion_matrix\r\nfrom data_process import load_data\r\nimport time\r\nfrom plot_matrix import plot_acc_loss\r\nfrom data_process import get_fre_5\r\nfrom data_process import get_fre_3\r\n\r\ntime_start = time.time()\r\ndevice = torch.device(\"cuda:3\")\r\n# device = torch.device('cpu')\r\ntransform = T.Compose([\r\n T.NormalizeFeatures(),\r\n T.ToDevice(device),\r\n T.RandomLinkSplit(num_val=0.05, num_test=0.1, is_undirected=True,\r\n add_negative_train_samples=False),\r\n])\r\n\r\n\r\ndata_path = \"/home/cuiwentao/cwt/gene/GAE/tf_gene.csv\"\r\n# data_path = \"/home/cuiwentao/cwt/gene/model_multi_task/tf_gene_2424.csv\"\r\ndataset, gene_mapping = load_data(data_path)\r\nprint(\"Number of genes:\", len(gene_mapping))\r\n\r\ntrain_data, val_data, test_data = transform(dataset)\r\nprint(\"Train Data:\", train_data)\r\nprint(\"Validation Data:\", val_data)\r\nprint(\"Test Data:\", test_data)\r\n\r\n\r\ncriterion1 = torch.nn.BCEWithLogitsLoss().to(device)\r\ndef criterion2(a,b,fre):\r\n loss = torch.nn.SmoothL1Loss(reduction='mean').to(device)\r\n loss =loss(a,b)\r\n\r\n loss = loss * fre\r\n loss = torch.mean(loss)\r\n loss = torch.sqrt(loss)\r\n return loss\r\ncriterion3 = torch.nn.MSELoss().to(device)\r\n\r\n\r\neval_loss_list = []\r\neval_acc_list = []\r\n #8069\r\n# data1 = pd.read_csv(\"/home/cuiwentao/cwt/mode-feature102.csv\")\r\ndata1 = pd.read_csv('/home/cuiwentao/cwt/gene/tf_ko108.csv')\r\nfeature_ko = pd.read_csv('/home/cuiwentao/cwt/gene/feature_ko_623_108.csv')\r\nfeature_ko = feature_ko.values.T\r\ndata1 = data1.drop(['index'], axis=1) # 去除第一列索引)\r\n\r\nnum_gene = data1.shape[0]\r\nnum_gene_double = int((data1.shape[0])*2)\r\nnum_sample = data1.shape[1]\r\nnum_sample_c = int((data1.shape[1])/2)\r\n\r\ndata1 = np.log(data1 + 1)\r\n\r\ndata_c = data1.iloc[:, num_sample_c:].values.T\r\ndata_t = data1.iloc[:, :num_sample_c].values.T\r\n\r\ntarget_fre = get_fre_3(data_c,data_t)\r\n\r\ndata_c=np.concatenate((data_c,feature_ko),axis=1)\r\ndata_c=np.concatenate((data_c,target_fre),axis=1)\r\n\r\ntrain_c, test_c, train_t, test_t = train_test_split(data_c, data_t)\r\n\r\ndata_c_train = torch.tensor(train_c, dtype=torch.float32)\r\ndata_t_train = torch.tensor(train_t, dtype=torch.float32)\r\ndata_c_test = torch.tensor(test_c, dtype=torch.float32)\r\ndata_t_test = torch.tensor(test_t, dtype=torch.float32)\r\n\r\ndatac1 = data_c_train[:, 0:num_gene].to(device)\r\ndatac1 = torch.tensor(datac1, dtype=torch.float32)\r\n\r\ntorch_dataset = data.TensorDataset(data_c_train, data_t_train)\r\ntorch_dataset1 = data.TensorDataset(data_c_test, data_t_test)\r\n\r\nloader = data.DataLoader(\r\n dataset=torch_dataset,\r\n batch_size=512, # 每批提取的数量\r\n shuffle=True, # 要不要打乱数据(打乱比较好)\r\n num_workers=2 # 多少线程来读取数据\r\n)\r\nloader1 = data.DataLoader(\r\n dataset=torch_dataset1,\r\n batch_size=512, # 每批��取的数量\r\n shuffle=True, # 要不要打乱数据(打乱比较好)\r\n num_workers=2 # 多少线程来读取数据\r\n)\r\n\r\n\r\nmodel = NET(dataset.num_features, 256, 256,n_feature=num_gene_double, out=num_gene).to(device)\r\noptimizer = torch.optim.Adam(params=model.parameters(), lr=0.001)\r\n\r\ndef train(batch_x, batch_y):\r\n model.train()\r\n # print(batch_x.shape)\r\n batch_x = batch_x.to(device)\r\n batch_y = batch_y.to(device)\r\n\r\n z = model.encode(train_data.x, train_data.edge_index)\r\n # We perform a new round of negative sampling for every training epoch:\r\n\r\n neg_edge_index = negative_sampling(\r\n edge_index=train_data.edge_index, num_nodes=train_data.num_nodes,\r\n num_neg_samples=train_data.edge_label_index.size(1), method='sparse')\r\n\r\n edge_label_index = torch.cat(\r\n [train_data.edge_label_index, neg_edge_index],\r\n dim=-1,\r\n )\r\n edge_label = torch.cat([\r\n train_data.edge_label,\r\n train_data.edge_label.new_zeros(neg_edge_index.size(1))\r\n ], dim=0)\r\n\r\n # edge_label_index = train_data.edge_label_index\r\n # edge_label = train_data.edge_label\r\n # print(edge_label_index)\r\n out = model.decode(z, edge_label_index).view(-1)\r\n batchx = batch_x[:, 0:num_gene_double]\r\n fre = batch_x[:, num_gene_double:]\r\n # print(fre.shape)\r\n encode_vector, prediction = model.decode_re(batchx) # 用网络预测一下\r\n out2 = model.enco(z, encode_vector)\r\n loss1 = criterion1(out, edge_label)\r\n loss2 = criterion2(prediction, batch_y,fre)\r\n loss3 = criterion2(out2, datac1.t(),fre.t())\r\n # loss3 = criterion3(out2, datac1.t())\r\n loss = loss1 + loss2 + loss3\r\n print(f'loss: {loss:.4f}, Loss1: {loss1:.4f},loss2: {loss2:.4f}, '\r\n f'loss3: {loss3:.4f}')\r\n optimizer.zero_grad()\r\n loss.backward()\r\n optimizer.step()\r\n\r\n return loss\r\n\r\n@torch.no_grad()\r\ndef test(data):\r\n model.eval()\r\n z = model.encode(data.x, data.edge_index)\r\n out = model.decode(z, data.edge_label_index).view(-1).sigmoid()\r\n return roc_auc_score(data.edge_label.cpu().numpy(), out.cpu().numpy())\r\n\r\neval_loss_list = []\r\neval_acc_list = []\r\n\r\n\r\nfor epoch in range(1, 500):\r\n best_val_acc = final_test_acc = 0\r\n for batch_idx, (batch_x, batch_y) in enumerate(loader):\r\n loss = train(batch_x, batch_y)\r\n val_acc = test(val_data)\r\n test_acc = test(test_data)\r\n\r\n if val_acc > best_val_acc:\r\n best_val_acc = val_acc\r\n final_test_acc= test_acc\r\n eval_loss_list.append(loss)\r\n eval_acc_list.append(final_test_acc)\r\n\r\n if epoch%10 == 0:\r\n print(f'Epoch: {epoch:03d}, Loss: {loss:.4f},Val: {val_acc:.4f}, '\r\n f'Test: {test_acc:.4f}')\r\n # train_auc = test(train_data)\r\n\r\n\r\n\r\n@torch.no_grad()\r\ndef test1(loader1):\r\n best_val_auc = final_test_auc = 0\r\n model.eval()\r\n for step, (batchx, batchy) in enumerate(loader1):\r\n batchx = batchx.to(device)\r\n batchy = batchy.to(device)\r\n\r\n batchx1 = batchx[:, 0:num_gene_double]\r\n x1,x2 = model.decode_re(batchx1)\r\n res = tag_test(batchx1, x2, num_gene)\r\n res_cont = tag_test(batchx1, batchy, num_gene)\r\n val_auc = test(val_data)\r\n test_auc = test(test_data)\r\n if val_auc > best_val_auc:\r\n best_val_auc = val_auc\r\n final_test_auc = test_auc\r\n # eval_loss_list.append(loss)\r\n # eval_acc_list.append(test_auc)\r\n print(f'Epoch: {epoch:03d}, Val: {val_auc:.4f}, '\r\n f'Test: {test_auc:.4f}')\r\n\r\n y_true = res_cont.flatten()\r\n # print(true.shape)\r\n y_pred = res.flatten()\r\n cm = confusion_matrix(y_true, y_pred)\r\n # 计算混淆矩阵\r\n cm = np.zeros((5, 5))\r\n for i in range(len(y_true)):\r\n cm[y_true[i]][y_pred[i]] += 1\r\n print(cm)\r\n # 绘制混淆矩阵\r\n heat_map(cm)\r\n acc = np.zeros((5, 5))\r\n for i in range(5):\r\n for j in range(5):\r\n if cm[i, :].sum() == 0:\r\n acc[i] = 0\r\n else:\r\n acc[i, j] = cm[i, j] / cm[i, :].sum()\r\n heat_map_acc(acc)\r\n return acc\r\n\r\ntest1(loader1)\r\nplot_acc_loss(eval_loss_list,eval_acc_list)\r\nprint(f'Final Test: {final_test_acc:.4f}')\r\n\r\nz = model.encode(train_data.x, train_data.edge_index)\r\n\r\nfinal_edge_index = model.decode_all(z)\r\nprint(final_edge_index)\r\n\r\n\r\ntime_end = time.time()\r\nprint(\"Elapsed time: %.2f seconds\" % (time_end - time_start))\r\n\r\n","repo_name":"kdd-ucas/GeneKO_prediction","sub_path":"model/model_final.py","file_name":"model_final.py","file_ext":"py","file_size_in_byte":7921,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13631344760","text":"# David Richard Steinmetz\n# NYCDSA - Capstone Project\n\n\ndef search_yelp(secret_file, location, search_parameters):\n # Extract Yelp Data through the API\n import io\n import json\n from yelp.client import Client\n from yelp.oauth1_authenticator import Oauth1Authenticator\n\n # read API keys\n with io.open(secret_file) as cred: # Auth in file not shared on github\n creds = json.load(cred)\n auth = Oauth1Authenticator(**creds)\n client = Client(auth)\n\n # There are three ways to query the Search API: search, search_by_bounding_box, and\n # search_by_coordinates. For each of these methods, additional parameters are optional.\n # The full list of parameters can be found on the Search API Documentation.\n # https://github.com/Yelp/yelp-python\n\n # search_by_bounding_box takes a southwest latitude/longitude and a northeast\n # latitude/longitude as the location boundary\n response = client.search_by_bounding_box(\n location['sw_latitude'],\n location['sw_longitude'],\n location['ne_latitude'],\n location['ne_longitude'],\n **search_parameters\n )\n\n return response\n\n\n# Function to extract locations of search results\ndef get_response_coords(response):\n coord = []\n\n for i in range(len(response.businesses)):\n latitude = response.businesses[i].location.coordinate.latitude\n longitude = response.businesses[i].location.coordinate.longitude\n if latitude and longitude:\n coord.append((latitude, longitude))\n\n return coord\n\n\n# Write JSON object to a file\ndef write_resp_to_csv(resp_obj, file_name):\n import csv\n dicts_to_output = [\n {\n 'name': biz.name,\n 'id': biz.id,\n 'top_category': biz.categories[0].alias if biz.categories else '',\n 'rating': biz.rating,\n 'review_count': biz.review_count\n }\n for biz in resp_obj.businesses\n ]\n csv_keys = ['name', 'id', 'top_category', 'rating', 'review_count']\n with open(file_name, 'w') as output_file:\n dict_writer = csv.DictWriter(output_file, csv_keys, quoting=csv.QUOTE_NONNUMERIC)\n dict_writer.writeheader()\n dict_writer.writerows(dicts_to_output)\n\n\n# # Example use\n# secret = 'yelp_secret.json'\n# # Example yelp_secret.json\n# # {\n# # \"consumer_key\": \"my_key_here\",\n# # \"consumer_secret\": \"my_secret_here\",\n# # \"token\": \"my_token_here\",\n# # \"token_secret\": \"my_token_secret_here\"\n# # }\n# #\n# gps = {'sw_latitude': 37.900000,\n# 'sw_longitude': -122.500000,\n# 'ne_latitude': 37.788022,\n# 'ne_longitude': -122.399797}\n#\n# params = {\n# 'term': 'food',\n# 'lang': 'en'\n# }\n# #\n# resp = search_yelp(secret, gps, params)\n# get_response_coords(resp)\n# write_resp_to_csv(resp, 'businesses.csv')\n\n# Parse response documentation:\n# https://www.yelp.com/developers/documentation/v2/search_api\n# resp.businesses[0].name\n","repo_name":"nycdatasci/bootcamp006_project","sub_path":"Project5-Capstone/PC1/app/scripts/GetYelpData.py","file_name":"GetYelpData.py","file_ext":"py","file_size_in_byte":2940,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"48"} +{"seq_id":"24572831131","text":"import os\nimport unittest\nimport json\nfrom flask_sqlalchemy import SQLAlchemy\nfrom app import app\nfrom models import db, Movie, Actor\nfrom datetime import datetime\n\n\nclass CapstoneTestCase(unittest.TestCase):\n \"\"\"This class represents the trivia test case\"\"\"\n\n def setUp(self):\n \"\"\"Define test variables and initialize app.\"\"\"\n os.system('sh setup.sh')\n self.app = app()\n self.client = self.app.test_client\n self.database_path = os.environ.get('DATABASE_TEST_PATH')\n # setup_db(self.app, self.database_path)\n self.app.config[\"SQLALCHEMY_DATABASE_URI\"] = self.database_path\n self.app.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False\n db.app = self.app\n db.init_app(self.app)\n db.create_all()\n\n # binds the app to the current context\n with self.app.app_context():\n self.db = SQLAlchemy()\n self.db.init_app(self.app)\n # create all tables\n self.db.create_all()\n \n self.actor = {\n 'name': 'Leonardo Dicaprio',\n 'age': '46',\n 'gender': 'M'\n }\n\n self.updated_actor = {\n 'name': 'Leonardo Dicaprio',\n 'age': '47',\n 'gender': 'M'\n }\n\n self.movie = {\n 'title': 'Inception',\n 'release_date': datetime.now()\n }\n\n self.updated_movie = {\n 'title': 'Inception 2',\n 'release_date': datetime.now()\n }\n\n self.director_headers = {'Content-Type': 'application/json',\n 'Authorization': os.environ.get('DIRECTOR_TOKEN')}\n self.producer_headers = {'Content-Type': 'application/json',\n 'Authorization': os.environ.get('PRODUCER_TOKEN')}\n \n def tearDown(self):\n \"\"\"Executed after reach test\"\"\"\n pass\n\n def test_get_actors(self):\n \"\"\"\n This function tests retrieving actors successfully.\n \"\"\"\n res = self.client().get('/actors', headers=self.producer_headers)\n data = json.loads(res.data)\n self.assertEqual(res.status_code, 200)\n self.assertTrue(data['success'])\n self.assertTrue(len(data['actors']))\n\n def test_get_movies(self):\n \"\"\"\n This function tests retrieving movies successfully.\n \"\"\"\n res = self.client().get('/movies', headers=self.producer_headers)\n data = json.loads(res.data)\n self.assertEqual(res.status_code, 200)\n self.assertTrue(data['success'])\n self.assertTrue(len(data['actors'])) \n \n def test_404_delete_unavailable_actor(self):\n \"\"\"\n This function tests deleting an unavailable actor.\n \"\"\"\n res = self.client().delete(\"/actors/999\", headers=self.producer_headers)\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 404)\n self.assertFalse(data['success'])\n\n def test_404_delete_unavailable_movie(self):\n \"\"\"\n This function tests deleting an unavailable movie.\n \"\"\"\n res = self.client().delete(\"/movies/999\", headers=self.producer_headers)\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 404)\n self.assertFalse(data['success'])\n \n def test_add_actor(self):\n \"\"\"\n This function tests inserting a new actor successfully.\n \"\"\"\n res = self.client().post(\"/actors\", json=self.actor, headers=self.producer_headers)\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 200)\n self.assertTrue(data['success'])\n\n def test_add_movie(self):\n \"\"\"\n This function tests inserting a new movie successfully.\n \"\"\"\n res = self.client().post(\"/movies\", json=self.movie, headers=self.producer_headers)\n data = json.loads(res.data)\n\n # self.assertEqual(res.status_code, 200)\n # self.assertTrue(data['success'])\n\n def test_400_add_actor(self):\n \"\"\"\n This function tests inserting a actor with empty data.\n \"\"\"\n # test empty data\n res = self.client().post(\"/actors\", data=None, headers=self.producer_headers)\n data = json.loads(res.data)\n\n self.assertFalse(data['success'])\n self.assertEqual(res.status_code, 400)\n self.assertEqual(data['message'], 'bad request')\n\n\n def test_400_add_movie(self):\n \"\"\"\n This function tests inserting a movie with empty data.\n \"\"\"\n res = self.client().post(\"/movies\", data=None, headers=self.producer_headers)\n data = json.loads(res.data)\n\n self.assertFalse(data['success'])\n self.assertEqual(res.status_code, 400)\n self.assertEqual(data['message'], 'bad request')\n\n def test_patch_actor(self):\n \"\"\"\n This function tests updating an existing actor successfully.\n \"\"\"\n res = self.client().patch(\"/actors/1\", json=self.actor, headers=self.producer_headers)\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 200)\n self.assertTrue(data['success'])\n\n def test_patch_movie(self):\n \"\"\"\n This function tests updating an existing movie successfully.\n \"\"\"\n res = self.client().patch(\"/movies/2\", json=self.movie, headers=self.producer_headers)\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 200)\n self.assertTrue(data['success'])\n\n def test_delete_actor(self, actor_id=1):\n \"\"\"\n This function tests deleting a spicific actor successfully\n \"\"\"\n res = self.client().delete(f\"/actors/{actor_id}\", headers=self.producer_headers)\n data = json.loads(res.data)\n deleted_actor = Actor.query\\\n .filter(Actor.id == actor_id)\\\n .one_or_none()\n\n self.assertEqual(res.status_code, 200)\n self.assertTrue(data['success'])\n self.assertFalse(deleted_actor)\n\n def test_delete_movie(self, movie_id=2):\n \"\"\"\n This function tests deleting a spicific movie successfully\n \"\"\"\n res = self.client().delete(f\"/movies/{movie_id}\", headers=self.producer_headers)\n data = json.loads(res.data)\n deleted_movie = Movie.query\\\n .filter(Movie.id == movie_id)\\\n .one_or_none()\n\n self.assertEqual(res.status_code, 200)\n self.assertTrue(data['success'])\n self.assertFalse(deleted_movie)\n\n def test_404_patch_actor(self):\n \"\"\"\n This function tests updating a non-existing actor successfully.\n \"\"\"\n res = self.client().patch(\"/actors/999\", json=self.actor, headers=self.producer_headers)\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 404)\n self.assertFalse(data['success'])\n\n def test_404_patch_movie(self):\n \"\"\"\n This function tests updating a non-existing movie successfully.\n \"\"\"\n res = self.client().patch(\"/movies/999\", json=self.movie, headers=self.producer_headers)\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 404)\n self.assertFalse(data['success'])\n\n def test_403_add_movie(self):\n \"\"\"\n This function tests unauthorized insertion of a movie.\n \"\"\"\n res = self.client().post(\"/movies\", json={}, headers=self.director_headers)\n data = json.loads(res.data)\n\n self.assertFalse(data['success'])\n self.assertEqual(res.status_code, 403)\n self.assertEqual(data['message']['code'], 'unauthorized')\n \n def test_403_delete_movie(self):\n \"\"\"\n This function tests unauthorized deletion of a movie.\n \"\"\"\n res = self.client().delete(\"/movies/1\", json={}, headers=self.director_headers)\n data = json.loads(res.data)\n\n self.assertFalse(data['success'])\n self.assertEqual(res.status_code, 403)\n self.assertEqual(data['message']['code'], 'unauthorized')\n\n# Make the tests conveniently executable\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"Abdulrahman-97/fsnd-capstone","sub_path":"test_app.py","file_name":"test_app.py","file_ext":"py","file_size_in_byte":8141,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2345191518","text":"import sys\n\na, b = map(int, sys.stdin.readline().split())\ntemp = []\n# 반복문을 통해 b구간까지의 수열을 만든다.\nfor i in range(1, b + 1):\n for j in range(i):\n temp.append(i)\n\n# 만든 수열의 a부터 b구간까지 더한 값을 출력\nprint(sum(temp[a - 1:b]))\n","repo_name":"junjange/CodingTest","sub_path":"baekjoon/math/1292.py","file_name":"1292.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18201289066","text":"inputfile = open(\"inputfile.txt\")\noutputfile = open(\"DAT1.TXT\", \"w+\")\n\n#code to put 80 characters at the top\nfor x in range(8):\n for y in range(10):\n outputfile.write(str(y))\noutputfile.write(\"\\n\")\n\n#function to edit file with margins included\ndef edit_file(input_file, leftMargin, rightMargin):\n input_words = input_file.read().split();\n \n lmargin = \"\" #left margin shape\n fullline = \"\" #maximum 80 character line\n wordline = \"\" #line of words\n\n\n for m in range(leftMargin):\n for n in range(12):\n lmargin += \" \"\n lmargin = lmargin[:-1] #slices\n\n\n for rem_words in range(len(input_words)):\n if rem_words == 0:\n outputfile.write(lmargin)\n if (len(lmargin) + len(fullline) + 1 + len(input_words[rem_words])) > (80 - (12 * rightMargin)):\n outputfile.write('\\n')\n outputfile.write(lmargin)\n fullline = ''\n if rem_words != 0:\n if input_words[rem_words - 1].find('.')!= -1 or input_words[rem_words-1].find('?')!= -1 or input_words[rem_words - 1].find('!')!= -1:\n wordline = \" \" + \" \" + input_words[rem_words]\n else:\n wordline = \" \" + input_words[rem_words]\n fullline += wordline\n outputfile.write(wordline)\n outputfile.close()\n\nedit_file(inputfile, 2, 2);\n\nprint(open('DAT1.TXT').read())\n","repo_name":"serge404/Prog1","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29472039365","text":"import os\nimport sqlite3\nfrom flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash\n\n#application instance\napp = Flask(__name__)\napp.config.from_object(__name__) # load configs from flask_demo.py\napp.secret_key = 'development key'\ndef connect_db():\n \"\"\"Connects to the specific database.\"\"\"\n rv = sqlite3.connect('/Users/c100-60/Desktop/FLASK_DEMO/flask_demo/flask_demo/flask_demo.db')\n rv.row_factory = sqlite3.Row\n return rv\n\n\ndef get_db():\n \"\"\"Opens a new database connection if there is none yet for the\n current application context.\"\"\"\n if not hasattr(g, 'sqlite_db'):\n g.sqlite_db = connect_db()\n return g.sqlite_db\n\n@app.teardown_appcontext\ndef close_db(error):\n \"\"\"Closes the database again at the end of the request.\"\"\"\n if hasattr(g, 'sqlite_db'):\n g.sqlite_db.close()\n\ndef init_db():\n db = get_db()\n with app.open_resource('schema.sql', mode='r') as f:\n db.cursor().executescript(f.read())\n db.commit()\n\n@app.route('/')\ndef show_entries():\n if session.get('logged_in'):\n u = session['u_name']\n else:\n return redirect(url_for('add_std'))\n\n db = get_db()\n cur = db.execute('select id,title, text, u_name from fi')\n fi = cur.fetchall()\n \n return render_template('show_detail.html',fi=fi,u=u)\n\n\n@app.route('/add_std', methods=['GET', 'POST'])\ndef add_std():\n #print(request.method)\n try:\n #print(\"in try block\")\n name = request.form['name']\n username = request.form['uname']\n password = request.form['passw']\n cpassword = request.form['cpass'] \n email = request.form['email'] \n\n db = get_db()\n db.execute('insert into user (name,username,password,c_password,email) values (?,?,?,?,?)',(name,username,password,cpassword,email))\n db.commit()\n flash(\"Record successfully added\")\n session['reg']=True\n return redirect(url_for('login'))\n except:\n error = 'can not call the view'\n\n \n return render_template('register.html')\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n c = 0\n if not session.get('reg'):\n error = None\n if request.method == 'POST':\n db = get_db()\n cur = db.execute('select username,password from user')\n a = cur.fetchall()\n db.commit()\n print(a)\n #for i in a:\n #print(i['username'])\n #print(i['password'])\n\n for i in a:\n if(request.form['username']==i['username']):\n if(request.form['password']==i['password']):\n c=1\n\n if(c==1):\n session['logged_in'] = True\n session['u_name'] = request.form['username']\n u= session['u_name']\n flash('You were logged in')\n return redirect(url_for('add_entry'))\n \n #return render_template('login.html')\n return render_template('login.html')\n\n@app.route('/logout')\ndef logout():\n session.pop('logged_in', None)\n flash('You were logged out')\n return redirect(url_for('login'))\n\n\n@app.route('/add_entry', methods=['GET', 'POST'])\ndef add_entry():\n if not session.get('logged_in'):\n abort(401)\n if request.method == 'POST': \n u= session['u_name'] \n db = get_db()\n db.execute('insert into fi (title, text,u) values (?, ?, ?)',[request.form['title'], request.form['text'],u])\n db.commit()\n flash('New entry was successfully posted')\n return redirect(url_for('add_entry'))\n\n return render_template('list.html')\n\n@app.route('/edit//', methods=['GET', 'POST'])\ndef edit(a):\n print(\"helli\")\n print(a)\n print(\"hello\",session.get('logged_in'))\n if session.get('logged_in'):\n u = session['u_name']\n db = get_db()\n fi = db.execute('select * from fi where id=%s' % (a))\n return render_template('update.html',fi=fi,a=a)\n return redirect(url_for('show_entries'))\n\n@app.route('/update//',methods=['GET', 'POST'])\ndef update(a):\n if request.method == 'POST':\n print(a)\n print(request.form['title'])\n print(request.form['text'])\n db = get_db()\n db.execute('update fi set title=?,text=? where id=?',(request.form['title'],request.form['text'],a))\n db.commit()\n return redirect(url_for('show_entries'))\n return render_template('update.html',a=a)\n\n@app.route('/delete//',methods=['GET', 'POST'])\ndef delete(de):\n if session.get('logged_in'):\n print(de)\n db = get_db()\n db.execute('delete from fi where id=%s' %(de))\n db.commit()\n return redirect(url_for('show_entries'))\n\n return redirect(url_for('show_entries'))\n\n","repo_name":"karishmabardoliya/flask_demo","sub_path":"flask_demo/flask_demo/flask_demo.py","file_name":"flask_demo.py","file_ext":"py","file_size_in_byte":4724,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19854751217","text":"#!/usr/bin/env python\n\nimport sys\n\n# get top hits\n\ndef parse_top_hits(db, collisions):\n \"\"\"\n Sort collisions by expression level in db\n \"\"\"\n expression = {}\n\n with open(db) as fh:\n next(fh)\n for line in fh:\n line = line.strip().split('\\t')\n expression.update({line[0]: float(line[13])})\n\n collision_data = []\n with open(collisions) as fh:\n for line in fh:\n line = line.strip().split('\\t')\n host = line[0].split()[0]\n seq = line[4]\n hit = line[2]\n collision_data.append([host, seq, hit])\n\n for collision in collision_data:\n collision.append(expression[collision[0]])\n\n\n collision_data.sort(key = lambda x: x[3], reverse=True)\n\n top100 = collision_data[:100]\n\n with open(collisions + \"_top100.tsv\", 'w') as fh:\n fh.write(\"Host_Transcript\\tCollision_Sequence\\tCollision_Accession\\tHost_Expression_(Kallisto_TMM_Overall)\\n\")\n for hit in top100:\n hit = map(str, hit)\n fh.write(\"\\t\".join(hit) + '\\n')\n\n\n already_seen = []\n unique_collisions = []\n for collision in collision_data:\n if collision[0] not in already_seen:\n unique_collisions.append(collision)\n already_seen.append(collision[0])\n\n with open(collisions + \"_unique_top100.tsv\", 'w') as fh:\n fh.write(\"Host_Transcript\\tCollision_Sequence\\tCollision_Accession\\tHost_Expression_(Kallisto_TMM_Overall)\\n\")\n for hit in unique_collisions[:100]:\n hit = map(str, hit)\n fh.write(\"\\t\".join(hit) + '\\n')\n\nif __name__=='__main__':\n\n # first file is db with expression\n # second is bowtie file with collisions hits\n\n\n parse_top_hits(sys.argv[1], sys.argv[2])\n\n","repo_name":"fmaguire/eDicer","sub_path":"edicer/analysis_scripts/top_hits.py","file_name":"top_hits.py","file_ext":"py","file_size_in_byte":1760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7889719988","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 30 14:04:54 2019\n\n@author: 146790\n\"\"\"\n\n\nimport os\npath=\"D:\\Python\"\nfiles=os.listdir(path)\n\nimport glob\n\nprint(glob.glob('D:/Python/file sousa/*'))\n\nimport os\nos.chdir('D:/Python')\nos.rename('./file sousa/a.docx', './file sousa/a_000.docx')\n\nprint('{0:03d}, {1:04d},{2:05d}'.format(4, 6,9))\n\n\n# \n\nimport os\nimport glob\n\nfiles = glob.glob('D:/Python/dir/*')\n\nfor f in files:\n print(os.path.basename(f))\n \nfor f in files:\n print(os.path.join(path, 'img_' + os.path.basename(f)))\n \n\nfor f in files:\n os.rename(f, os.path.join(path, 'img_' + os.path.basename(f)))\n\n\nos.getcwd()\ndirpath_without_sep = './dir/d.docx'\n\nprint(os.path.splitext(dirpath_without_sep))\n\ntype(os.path.splitext(dirpath_without_sep))\n\nimport os\nos.getcwd()\npath = 'dir/f.docx'\n\nf = open(path)\n\nprint(type(f))\n# \n\nwith open(path) as f:\n s = f.read()\n print(type(s))\n print(s)\n \n\nf.close()\n\n\npath_w = 'dir/test_w.txt'\n\ns = 'New file'\n\nwith open(path_w, mode='w') as f:\n f.write(s)\n\nwith open(path_w) as f:\n print(f.read())\n \nwith open(path_w, mode='a') as f:\n f.write('\\nFour')\n\n\nwith open(path_w) as f:\n print(f.read())\n \n \npath = 'dir/test_w.txt'\n\n\nwith open(path) as f:\n lines = f.readlines()\n\nprint(lines)\n# ['XXX YYY ZZZ\\n', 'YYY\\n', 'aaa\\n', 'XXX\\n', 'ZZZ XXX\\n', 'xxx']\n\nprint(type(lines))\n\nlines_strip = [line.strip() for line in lines]\nprint(lines_strip)\n\nl_XXX_start = [line for line in lines_strip if line.startswith('XXX')]\nprint(l_XXX_start)\n\n","repo_name":"146790g/Spyder-","sub_path":"File Manipulation.py","file_name":"File Manipulation.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8705190865","text":"\"getting ccurrent working directory\"\n# import os\n# print(os.getcwd())\n\"making a new directory\"\n# os.mkdir(r\"C:\\kasi_king\")\n# os.mkdir(r\"C:\\kasipython\")\n\n\"changing currenet directory to some other directory\"\n# os.chdir(r\"C:\\Users\\Hp\\PycharmProjects\\python_training\\5.file handling\\normal_file_handling\\new\")\n# print(os.getcwd())\n\n# os.rmdir(r\"C:\\kasi_king\")\n# os.rmdir(r\"C:\\kasipython\")\n\n\"list directories\"\n# print(os.listdir(r\"D:\"))\n# print(os.listdir(r\"E:\"))\n\n# os.chdir(r\"D:\\PENDRIVE BACKUP\\SANDISK 64 GB\\CREATIVE STUDIO\\9-8-2020\\JULY DATA (15581)\\GIVEN TO VRDL STAFF\\9-8-2020\\MY FINAL\")\n# \"opening a file from python file\"\n# os.popen(r\"temp.csv\",'r')\n# file = open(\"madhuri.txt\",'w')\n# os.chdir(r\"C:\\Users\\Hp\\PycharmProjects\\python_training\\5.file handling\\normal_file_handling\")\n\n# \"counting the no of lines in the file\"\n\n# \"Counter class\"\n\nfrom collections import Counter\n# path = r\"C:\\Users\\Hp\\PycharmProjects\\python_training\\my_files\\text files\\sindhu.txt\"\n# with open(path) as file:\n# l = []\n# for line in file:\n# if line.strip():\n# list_ = line.split()\n# for word in list_:\n# l.append(word)\n#\n# word = Counter(l)\n# print(word)\n# print(Counter.most_common(word))\n# string_ = 'python is a language'\n# dict_count = Counter(string_)\n# for item in dict_count:\n# print(item, dict_count[item])\n\nfrom itertools import islice\n# string_ = \"python\"\n# print(*list(islice(string_,0,3)))\n\n\"print first n lines in file\"\n# path = r\"C:\\Users\\Hp\\PycharmProjects\\python_training\\my_files\\text files\\sindhu.txt\"\n# with open(path) as file:\n# res = islice(file, 2)\n# print(list(res))\n\n\"to print a particular series of lines\"\npath = r\"C:\\Users\\Hp\\PycharmProjects\\python_training\\my_files\\text files\\sindhu.txt\"\n# # with open(path) as file:\n# # res = islice(file, 3,5)\n# print(*list(res))\n\n\"to print last n lines\"\n# using islice\nn = 3\n# with open(path) as file:\n# for lineno,line in enumerate(file):\n# pass\n# file.seek(0)\n# print(lineno-2)\n# res = islice(file,lineno-2, lineno)\n# print(list(res))\n\n\"using deque\"\nfrom collections import deque\n# with open(path) as file:\n# res = deque(file, 3)\n# print(list(res))\n\n\"to print last 5 lines in a file\"\nn = 5\n# with open(path) as file:\n# res = deque(file, n)\n# print(list(res))\n\n\"to print first n linses\"\nn = 4\n# with open(path) as file:\n# res = islice(file, n)\n# print(*(list(res)))\n\n\"reading and writing into a file (using only single context manager)\"\npath_r = r\"C:\\Users\\Hp\\PycharmProjects\\python_training\\my_files\\text files\\sindhu.txt\"\npath_w = r\"C:\\Users\\Hp\\PycharmProjects\\python_training\\my_files\\text files\\sindhu12.txt\"\n# with open(path_r) as file_r, open(path_w, 'a') as file_w:\n# file_w.write(file_r.read())\n# # file_w.write(file_r.read())\n# file_w.writelines(file_r.readlines())\n\n\"csv file\"\nimport os\nimport csv\n# print(os.getcwd())\nwith open(\"bio.csv\",'w') as csv_file:\n write_obj = csv.writer(csv_file)\n write_obj.writerow({'name','gender','mobile'})\n write_obj.writerows({('mohanakasi','male','8886213059')}) # it takes int format also\n# os.popen(\"temp.csv\")\n# with open(\"bio.csv\") as csv_file:\n# read_obj = csv.reader(csv_file)\n# for row in read_obj:\n# print(row)\n\n# with open(\"bio.csv\") as csv_file:\n# read_obj = csv.DictReader(csv_file)\n# # print(next(read_obj))\n# for row in read_obj:\n# if row['gender'] == 'female':\n# print(row['name'])\n\nwith open(\"write.csv\",'w') as csv_file:\n write_obj = csv.DictWriter(csv_file,['x','y','z'])\n write_obj.writeheader()\n write_obj.writerow({'x':20, 'y':30, })\n","repo_name":"Mohanakasi/Mohana_SDET_moolya","sub_path":"Python/5.file handling/normal_file_handling/practice_1.py","file_name":"practice_1.py","file_ext":"py","file_size_in_byte":3654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25265309620","text":"def default_parser(widget_ner_query, datetime_from, datetime_to, parent_search):\n \"\"\"\n name_query_example = 'Пандемия Короновируса в Казахстане'\n ner_query_example = '1(|) AND 2(1(|||) $ 3(||||||) $ 4(|||||) $ 3(||||||||||||)) AND 2(||)'\n :param widget_ner_query:\n :param datetime_from:\n :param datetime_to:\n :param parent_search:\n :return:\n \"\"\"\n\n from elasticsearch_dsl import Search\n from nlpmonitor.settings import ES_INDEX_DOCUMENT, ES_CLIENT\n\n documents = Search(using=ES_CLIENT, index=ES_INDEX_DOCUMENT).filter('range', datetime={'gte': datetime_from}). \\\n filter('range', datetime={'lte': datetime_to}). \\\n source(['_id'])\n\n done_queries_list = list()\n for query in widget_ner_query.split(' AND '):\n done_queries_list.append(parse_query(query=query))\n\n q = parse_list_of_queries(q_list=done_queries_list, num=len(done_queries_list))\n\n s = apply_query(q=q,\n parent_search=parent_search,\n search_lvl=\"SEARCH_LVL_HARD\",\n documents=documents,\n cutoff='ABS_MAX_RESULTS_CUTOFF')\n\n return s\n\n\ndef apply_query(q, parent_search, search_lvl, documents, cutoff):\n from mainapp.constants import SEARCH_CUTOFF_CONFIG\n\n docs_with_applied_query = documents.query(q)\n new_query = docs_with_applied_query[:SEARCH_CUTOFF_CONFIG[search_lvl][cutoff]]\n executed_query = new_query.execute()\n search_ids = [d.meta.id for d in executed_query]\n new_search = parent_search.filter('terms', document_es_id=search_ids)\n\n return new_search\n\n\ndef create_elementary_query(words, num):\n from elasticsearch_dsl import Q\n number = isinstance_validator(num)\n return Q(\n 'bool',\n should=[Q(\"match_phrase\", text_lemmatized=k.strip()) for k in words.split(\"|\")] +\n [Q(\"match_phrase\", text=k.strip()) for k in words.split(\"|\")] +\n [Q(\"match_phrase\", title=k.strip()) for k in words.split(\"|\")],\n minimum_should_match=int(number)\n )\n\n\ndef parse_list_of_queries(q_list, num):\n from elasticsearch_dsl import Q\n number = isinstance_validator(num)\n return Q(\n 'bool',\n should=q_list,\n minimum_should_match=int(number)\n )\n\n\ndef parse_query(query):\n import re\n nums = re.findall('\\d(?![^(]*\\))', query)\n depth = True if re.findall('\\D', query)[:2].count('(') - 1 else False\n if len(nums) > 1:\n\n if depth:\n start_id = query.find('(') + 1 # скипаем начало строки где 2 скобки (re не обрабатывает такую скобку)\n parsed_text = re.findall('(?<=\\().+?(?=\\))', query[start_id:-1]) # получаем строку\n minimum_should_match_first = nums[0] # вытаскиваем первое число для query_list парсера\n del nums[0] # больше не нужно\n else:\n parsed_text = re.findall('(?<=\\().+?(?=\\))', query) # получаем строку\n minimum_should_match_first = len(nums)\n\n list_of_subqueries = list()\n assert len(nums) == len(parsed_text)\n for sub_text, num in zip(parsed_text, nums):\n list_of_subqueries.append(create_elementary_query(words=sub_text, num=num))\n\n return parse_list_of_queries(q_list=list_of_subqueries, num=minimum_should_match_first)\n\n parsed_text = isinstance_validator(re.findall('(?<=\\().+?(?=\\))', query))\n return create_elementary_query(words=parsed_text, num=nums)\n\n\ndef isinstance_validator(array):\n if isinstance(array, list):\n return array[0]\n else:\n return array\n\n\ndef location_buckets_parser(buckets, crit_type):\n from geo.models import Locality\n import random\n # {\"criterion__gte\": \"0\"}\n # {\"criterion__lt\": \"0\"}\n magnitude = list()\n radius = list()\n for bucket in buckets:\n radius.append(bucket.doc_count)\n if bucket.criterion_value_sum.value is not None:\n magnitude.append(bucket.criterion_value_sum.value)\n else:\n magnitude.append(0)\n scaled_data = scale(data=magnitude, scale_range=(1, 10))\n if crit_type == 'негатив':\n scaled_data = list(map(lambda x: abs(x - 10), scaled_data))\n scaled_radius = scale(data=radius, scale_range=(15, 30))\n coord_and_z = dict()\n loc_long_lat = {elem['name']: [elem['longitude'][:5] + str(int(random.random() * 100_000)),\n elem['latitude'][:5] + str(int(random.random() * 100_000))]\n for elem in Locality.objects.values()}\n assert len(buckets) == len(scaled_data) == len(scaled_radius)\n for i, bucket in enumerate(buckets):\n coord_and_z[bucket.key] = loc_long_lat[bucket.key] + [scaled_data[i]] + [scaled_radius[i]]\n coord_and_z = list(coord_and_z.values())\n\n return coord_and_z\n\n\ndef scale(data, scale_range):\n from sklearn.preprocessing import MinMaxScaler\n import numpy as np\n\n scaler = MinMaxScaler(feature_range=scale_range)\n scaled_data = list(map(lambda x: int(round(x)),\n scaler.fit_transform(np.array(data).reshape(-1, 1)).reshape(1, -1)[0]))\n return scaled_data\n\n\ndef criterion_map_parser(widget):\n from dashboard.criterions_meta import CRITERIONS_META\n crits = CRITERIONS_META[widget.criterion_id]['crits'] # TODO check on another criterions\n colormaps = CRITERIONS_META[widget.criterion_id]['colormap']\n params = widget.params_obj\n if not params:\n return None, None\n k = [key.split('__')[-1] for key in params.keys() if key.startswith('criterion')][0]\n return crits[k], colormaps[crits[k]]\n # TODO create all criterions parser, now only pos/neg\n","repo_name":"KindYAK/NLPMonitor","sub_path":"web/dashboard/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":5809,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"48"} +{"seq_id":"16895495729","text":"\"\"\"\r\nAdvantage Actor critic + rnd kind of works but not as good as dqn+rnd\r\nmostly because we are directly optimizing for better actions in the action space in the action space and this code doent use PPO.\r\nfor such simple discrete action space environments (off policy ) optimizes faster\r\nBut the agent can be clearly seen reinforcing actions that lead to unseen states , but takes lots of time to win\r\n\r\n\"\"\"\r\n\r\nimport tensorflow as tf\r\nimport numpy as np\r\nimport gym\r\n\r\n\r\n\r\n\r\nprediFILE=r\"C:\\\\Users\\\\Dell\\\\Desktop\\\\holidASY\\\\ac_predictor.h5\"\r\npolicyFILE=r\"C:\\\\Users\\\\Dell\\\\Desktop\\\\holidASY\\\\ac_rnd.h5\"\r\n\r\npolicy = tf.keras.models.Sequential()\r\npolicy.add(tf.keras.layers.Dense(units=4,input_dim=2, activation='relu'))\r\npolicy.add(tf.keras.layers.Dense(units=8,input_dim=2, activation='relu'))\r\n# output layer\r\npolicy.add(tf.keras.layers.Dense(units=3, activation='softmax'))\r\noptimizer=tf.keras.optimizers.Adam(lr=0.001,beta_1=0.9,epsilon=None,decay=0.00,amsgrad=False)\r\npolicy.compile(loss=\"categorical_crossentropy\", optimizer=optimizer, metrics=['accuracy'])\r\npolicy.summary()\r\n\r\nvalue = tf.keras.models.Sequential()\r\nvalue.add(tf.keras.layers.Dense(units=128,input_dim=2, activation='sigmoid'))\r\nvalue.add(tf.keras.layers.Dense(units=128, activation=\"relu\"))\r\nvalue.add(tf.keras.layers.Dense(units=1, activation=None))\r\noptimizer=tf.keras.optimizers.Adam(lr=0.01,beta_1=0.9,epsilon=None,decay=0.00,amsgrad=False)\r\nvalue.compile(loss=\"mse\", optimizer=\"RMSprop\", metrics=['accuracy'])\r\nvalue.summary()\r\n\r\ntarget = tf.keras.models.Sequential()\r\ntarget.add(tf.keras.layers.Dense(units=128,input_dim=2, activation='relu'))\r\ntarget.add(tf.keras.layers.Dense(units=1000, activation=\"sigmoid\"))\r\ntarget.summary()\r\ntarget.trainable=False\r\n\r\ntrainable= tf.keras.models.Sequential()\r\ntrainable.add(tf.keras.layers.Dense(units=128,input_dim=2, activation='relu'))\r\n#trainable.add(tf.keras.layers.Dense(units=6, activation='relu'))\r\ntrainable.add(tf.keras.layers.Dense(units=1000, activation=\"sigmoid\"))\r\n\r\noptimizer_1=tf.keras.optimizers.Adam(lr=0.01,beta_1=0.9,epsilon=None,decay=0.0,amsgrad=False)\r\ntrainable.compile(loss=\"mse\", optimizer=\"RMSprop\", metrics=['accuracy'])\r\ntrainable.summary()\r\n\r\n\r\n\r\n# to restore curiosity\r\ntf.keras.models.save_model(model=trainable,filepath=prediFILE,overwrite=True,include_optimizer=True)\r\n\r\n\r\nenv=gym.make('MountainCar-v0')\r\nenv=env.unwrapped#removes step restriction\r\nobservation = env.reset()\r\nrender =False\r\ndone =False\r\n# Hyperparameters\r\ngamma = 0.99\r\n\r\n\r\ntry:\r\n\tprint(\"loading\")\r\n\t#policy=tf.keras.models.load_model( policyFILE )\r\n\t\r\n\t#value=tf.keras.models.load_model( CriticFILE )\r\n\t#value.compile(loss=\"mse\", optimizer=optimizer, metrics=['accuracy'])\r\n\t#policy.compile(loss=\"categorical_crossentropy\", optimizer=optimizer, metrics=['accuracy'])\r\n\r\n\tprint(\"loaded\")\r\nexcept:\r\n\tprint(\"not loaded\")\t\r\nepisodes=1000000\r\np=1\r\nfor episode_nb in range(1,episodes):\r\n\tstep=0\r\n\r\n\tobservation = env.reset()#since game over brings back to default so cant relate end state(win) with\r\n\t# default start otherwise it wont be curious to learn to win (this env doent have exploration levels)\r\n\treward_sum = 0\r\n\tdone =False\r\n\tmax_far=0\r\n\trender=True\r\n\twhile not done:\r\n\t\tif render:\r\n\t\t\tenv.render()\r\n\t\t\r\n\t\tproba = policy.predict(np.array([observation]))\r\n\t\taction = np.random.choice(np.arange(proba.shape[1]), p=proba.ravel())\r\n\r\n\t\tact=action\r\n\t\tobservation_, reward, done, info = env.step(action)\r\n\t\t\r\n\t\tpredictor_target = target.predict(np.array([observation_]))\r\n\r\n\t\tintrinsic_reward=trainable.predict(np.array([observation_])) - predictor_target\r\n\t\tintrinsic_reward=np.sum(intrinsic_reward ,axis=1)**2\r\n\t\tintrinsic_reward*=10#some scaling, hardly makes any difference\r\n\r\n\r\n\t\t#adv(st,at) = {q(st,at)}-v(st) ==> {r(t+1) + v(st+1)} - v(st) \t\tII q(st,at)=r(t+1) + max(q(st+1,all)\r\n\t\t#in this env non episodic evaluation will disourage game over since it returns to same place\r\n\t\tif done == True:\r\n\t\t\ttargetQ=100 + 0*intrinsic_reward # no realtion to reset after game dones\r\n\t\telse:\t\r\n\t\t\ttargetQ=intrinsic_reward +\tgamma*(value.predict(np.array([observation_])).ravel()) \r\n\t\tadv = targetQ - value.predict(np.array([observation]))\r\n\t\t#print(adv)\r\n\t\t#print(\"targetQ:\"+str(targetQ))\r\n\t\t#print(\"val_state:\"+str(targetQ - adv )) \r\n\t\t#print(\"adv:\"+str(adv)) \r\n\t\t\r\n\t\t#print(\"episode:\"+str(episode_nb))\r\n\t\tif act==0:\r\n\t\t\ty_=np.array([1,0,0])\r\n\t\tif act==1:\r\n\t\t\ty_=np.array([0,1,0])\t\r\n\t\tif act==2:\r\n\t\t\ty_=np.array([0,0,1])\r\n\t\tyy=adv*y_\r\n\t\t#if adv.ravel()>0:\r\n\t\t\t#print(\"+ \"+str(act))\r\n\r\n\t\t#if adv.ravel()<0:\r\n\t\t\t#print(\"- \"+str(act))\t\r\n\t\t#print(\"action*adv:\"+str(yy))\r\n\t\t# do one step in our environment\r\n\t\tvalue.fit(x=np.array([observation]), y=targetQ, epochs=1,verbose=0)\r\n\t\t\r\n\t\tpolicy.fit(x=np.array([observation]), y=yy, epochs=1,verbose=0)\r\n\t\tif step % 5==0:\r\n\t\t\ttrainable.fit(x=np.array([observation_]), y=predictor_target, epochs=1,verbose=0)\r\n\r\n\r\n\t\tobservation=observation_\r\n\t\tstep+=1\r\n\t\tif step == 30000:\r\n\t\t\tprint(\"useless!!!\")\r\n\t\t\t#break\r\n\r\n\tprint('At the end of episode', episode_nb, 'the total steps was :', step)\r\n\t#value=value_t\r\n\r\n\r\n\t# Reinitialization\r\n\tif episode_nb> 50:\r\n\t\trender=True\r\n\t\r\n\tif episode_nb%4==0:\r\n\t\t# restore creativity since after lots of same game it wil loose creativity \r\n\t\ttrainable=tf.keras.models.load_model( prediFILE )\r\n\t\ttrainable.compile(loss=\"mse\", optimizer=optimizer_1, metrics=['accuracy'])\r\n\t\r\n\t\ttf.keras.models.save_model(model=policy,filepath= policyFILE ,overwrite=True,include_optimizer=True)\r\n\t\t#tf.keras.models.save_model(model=value,filepath=CriticFILE,overwrite=True,include_optimizer=True)\r\n\t\tprint(\"saved\")\t\r\n","repo_name":"rootAkash/reinforcement_learning","sub_path":"A2C+RND_tf.keras/ac_rnd.py","file_name":"ac_rnd.py","file_ext":"py","file_size_in_byte":5587,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"37927572771","text":"\"\"\"Constants used as a reference by different scripts\"\"\"\n\n# define target column\nTARGET = [\"default_payment_next_month\"]\n\n# define categorical feature columns\nCATEGORICAL_FEATURES = [\n \"sex\",\n \"education\",\n \"marriage\",\n \"repayment_status_1\",\n \"repayment_status_2\",\n \"repayment_status_3\",\n \"repayment_status_4\",\n \"repayment_status_5\",\n \"repayment_status_6\",\n]\n\n# define numeric feature columns\nNUMERIC_FEATURES = [\n \"credit_limit\",\n \"age\",\n \"bill_amount_1\",\n \"bill_amount_2\",\n \"bill_amount_3\",\n \"bill_amount_4\",\n \"bill_amount_5\",\n \"bill_amount_6\",\n \"payment_amount_1\",\n \"payment_amount_2\",\n \"payment_amount_3\",\n \"payment_amount_4\",\n \"payment_amount_5\",\n \"payment_amount_6\",\n]\n\n# define all features\nFEATURES = CATEGORICAL_FEATURES + NUMERIC_FEATURES\n\n# define sample data for inference\nINPUT_SAMPLE = [\n {\n \"sex\": \"male\",\n \"education\": \"university\",\n \"marriage\": \"married\",\n \"repayment_status_1\": \"duly_paid\",\n \"repayment_status_2\": \"duly_paid\",\n \"repayment_status_3\": \"duly_paid\",\n \"repayment_status_4\": \"duly_paid\",\n \"repayment_status_5\": \"no_delay\",\n \"repayment_status_6\": \"no_delay\",\n \"credit_limit\": 18000.0,\n \"age\": 33.0,\n \"bill_amount_1\": 764.95,\n \"bill_amount_2\": 2221.95,\n \"bill_amount_3\": 1131.85,\n \"bill_amount_4\": 5074.85,\n \"bill_amount_5\": 3448.0,\n \"bill_amount_6\": 1419.95,\n \"payment_amount_1\": 2236.5,\n \"payment_amount_2\": 1137.55,\n \"payment_amount_3\": 5084.55,\n \"payment_amount_4\": 111.65,\n \"payment_amount_5\": 306.9,\n \"payment_amount_6\": 805.65,\n }\n]\n\n# define sample response for inference\nOUTPUT_SAMPLE = {\"predictions\": [0.02]}\n","repo_name":"nfmoore/azureml-mlops-example-scenarios","sub_path":"core/src/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1783,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"48"} +{"seq_id":"13218007571","text":"import unittest\n\nimport numpy as np\nfrom sklearn.ensemble import RandomForestClassifier\n\nfrom kaogexp.data.loader import ColunaYSingleton\nfrom kaogexp.model.RandomForestModel import RandomForestModel\nfrom util import Data\n\n\nclass RandomForestModelTest(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls) -> None:\n ColunaYSingleton().NOME_COLUNA_Y = 'target'\n\n def test_predict_dataset(self):\n model, x = self._prepare_data()\n\n expected_shape = (x.shape[0],)\n predict = model.predict(x)\n self.assertEqual(expected_shape, predict.shape)\n\n def test_predict_series(self):\n model, x = self._prepare_data()\n\n x = x.sample(n=1).iloc[0]\n predict = model.predict(x)\n self.assertIsInstance(predict, np.number)\n\n def test_create_from_dataset(self):\n dataset = Data.create_new_instance_adult()\n model = RandomForestModel.from_dataset(dataset)\n self.assertIsInstance(model, RandomForestModel)\n self.assertIsInstance(model.raw_model, RandomForestClassifier)\n\n ################\n # Util methods #\n ################\n\n def _prepare_data(self):\n data = Data.iris_dataset()\n target_col = 'target'\n x = data.drop(target_col, axis=1)\n y = data[target_col]\n model = RandomForestModel(x, y, None)\n return model, x\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"Anakin86708/kaogexp","sub_path":"test/test_RandomForestModel.py","file_name":"test_RandomForestModel.py","file_ext":"py","file_size_in_byte":1403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29226536369","text":"\"\"\"\nBy counting carefully it can be seen that a rectangular\ngrid measuring 3 by 2 contains eighteen rectangles:\n\n\nAlthough there exists no rectangular grid that contains \nexactly two million rectangles, find the area of the grid \nwith the nearest solution.\n\"\"\"\n\nsubgrids = []\n\nfor a in range(1,10000):\n for b in range(1,1000):\n\n # the number of subgrids is given by\n # a*(a+1)*b*(b+1)//4\n res = abs(a*(a+1)*b*(b+1)//4 - 2*10**6)\n\n subgrids.append((a,b,res))\n\n#print(results)\n\nfound = subgrids[0]\n\n\nfor res in subgrids:\n if subgrids[2] < found[2]:\n found = res\n\nprint(found)\n","repo_name":"mccornet/project_euler_2014","sub_path":"problem_085.py","file_name":"problem_085.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37330285171","text":"#!/usr/bin/python3\nfrom KerberosClient import KerberosClient\n\nkrb = KerberosClient(\"host@kdc.insat.tn\")\nSERVER_URL = 'http://kdc.insat.tn:5000'\nRED = \"\\033[31m\"\nRESET = \"\\033[0m\"\n\n\ndef output_in_red(msg):\n print(RED + msg + RESET)\n\n\ndef handle_response(response):\n if response is None:\n output_in_red(\n \"Something went wrong, please check your kerberos ticket!\")\n elif response.status_code == 200:\n output_in_red(response.content.decode(\"utf-8\"))\n else:\n print(\n f'Error {response.status_code}: {response.content.decode(\"utf-8\")}')\n\n\ndef menu():\n \"\"\"Display a menu to the user and get their choice.\"\"\"\n print('1. List content of a directory')\n print('2. Read a file')\n print('3. Upload a file')\n print('4. Quit')\n choice = input('Enter your choice (1/2/3/4): ')\n return choice\n\n\ndef list_directory_content():\n \"\"\"List the content of a directory on the Flask server.\"\"\"\n directory_path = input('Enter the directory path: ')\n data = {\"path\": directory_path}\n response = krb.post(\n f\"{SERVER_URL}/directory\", data)\n handle_response(response)\n\n\ndef read_file():\n \"\"\"Read a file on the Flask server.\"\"\"\n file_path = input('Enter the file path: ')\n data = {\"file_path\": file_path}\n response = krb.post(\n f\"{SERVER_URL}/read_file\", data)\n handle_response(response)\n\n\ndef upload_file():\n \"\"\"Upload a file to the Flask server.\"\"\"\n file_path = input('Enter the file path to upload: ')\n destination_path = input('Enter the destination path: ')\n response = krb.upload_file(\n f'{SERVER_URL}/upload', file_path, destination_path)\n handle_response(response)\n\n\ndef main():\n while True:\n choice = menu()\n if choice == '1':\n list_directory_content()\n elif choice == '2':\n read_file()\n elif choice == '3':\n upload_file()\n elif choice == '4':\n break\n else:\n print('Invalid choice. Please try again.')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"alabenhamouda/kerberos-auth-example","sub_path":"client/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2063,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14282908635","text":"MENU = {\r\n \"espresso\": {\r\n \"ingredients\": {\r\n \"water\": 50,\r\n \"milk\": 0,\r\n \"coffee\": 18,\r\n },\r\n \"cost\": 350,\r\n },\r\n \"latte\": {\r\n \"ingredients\": {\r\n \"water\": 200,\r\n \"milk\": 150,\r\n \"coffee\": 24,\r\n },\r\n \"cost\": 250,\r\n },\r\n \"cappuccino\": {\r\n \"ingredients\": {\r\n \"water\": 250,\r\n \"milk\": 100,\r\n \"coffee\": 24,\r\n },\r\n \"cost\": 450,\r\n }\r\n}\r\nresources = {\r\n \"water\": 300,\r\n \"milk\": 200,\r\n \"coffee\": 100,\r\n}\r\nmoney = 0\r\ndef resource_check(sufficient):\r\n for items in sufficient:\r\n if sufficient[items] >= resources[items]:\r\n print(f\"Sorry {items} is'nt enough!\")\r\n return False\r\n return True\r\n\r\ndef transaction_check(money_recieved , cost_of_item):\r\n if money_recieved >= cost_of_item:\r\n change = round(money_recieved - cost_of_item , 2)\r\n print(f\"Here is Your Change {change}\")\r\n return True \r\n else:\r\n print(\"Sorry Your Money is'nt sufficient, it is Refunded\")\r\n return False\r\ndef make_coffee(drink_name , order_resources):\r\n for item in order_resources:\r\n resources[item] -= order_resources[item]\r\n print(f\"Here is your drink name {drink_name}\")\r\n \r\nis_on = True\r\nwhile is_on:\r\n user_input = input(\"What do you want to order (Espresso/Latte/Cappuccino) : \").lower()\r\n if user_input == 'off':\r\n is_on = False\r\n elif user_input == 'report':\r\n print(f'''\r\n Water : {resources[\"water\"]}\r\n Milk : {resources[\"water\"]}\r\n Coffee : {resources[\"coffee\"]}\r\n ''')\r\n else:\r\n drink = MENU[user_input]\r\n if resource_check(drink['ingredients']):\r\n user_topup = int(input(\"Topup your account by adding money : \"))\r\n if transaction_check(user_topup , drink['cost']):\r\n money = user_topup\r\n make_coffee(user_input , drink['ingredients'])\r\n \r\n \r\n ","repo_name":"callmenani/Python_programming","sub_path":"Coffee_Machine/Coffee_Machine.py","file_name":"Coffee_Machine.py","file_ext":"py","file_size_in_byte":2032,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"31966078162","text":"class Solution:\n def sortString(self, s):\n l = list(s)\n l.sort()\n s = \"\".join(l)\n return s\n def string2dict(self, s):\n dict = {}\n for c in s:\n dict.setdefault(c, 0)\n dict[c] = dict[c] + 1\n return dict\n\n def canConstruct(self, ransomNote, magazine):\n dict_r = self.string2dict(ransomNote)\n dict_m = self.string2dict(magazine)\n for r_key in dict_r.keys():\n if r_key in dict_m.keys() and dict_m[r_key] >= dict_r[r_key]:\n continue\n else:\n return False\n return True\n\nsolution = Solution()\nresult = solution.canConstruct(\"bg\",\"efjbdfbdgfjhhaiigfhbaejahgfbbgbjagbddfgdiaigdadhcfcj\")\nprint(result)","repo_name":"boyjared/leetcode","sub_path":"383. Ransom Note.py","file_name":"383. Ransom Note.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"3529724953","text":"import sys\nimport logging\nimport warnings\n\n# Biopython (used by varcode) throws a warning when sequences are compared.\nwarnings.filterwarnings(\"ignore\", message=\"Biopython Seq objects\")\n\ndef configure_logging(args=None):\n if args is not None and args.verbose:\n level = logging.DEBUG\n else:\n level = logging.INFO\n\n logging.basicConfig(\n format=\"%(asctime)s.%(msecs)d %(levelname)s %(module)s - %(funcName)s:\"\n \" %(message)s\",\n datefmt=\"%Y-%m-%d %H:%M:%S\",\n stream=sys.stderr,\n level=level)\n\n","repo_name":"openvax/varlens","sub_path":"varlens/commands/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"48"} +{"seq_id":"18128726171","text":"import pygame\n\npygame.init()\n\npygame.font.init()\n\nwin_w, win_h = 1000, 1000\n\n\nwin = pygame.display.set_mode((win_w, win_h))\npygame.display.set_caption(\"First Game\")\n\nclass Rope:\n def __init__(self, x, y, width, height, color):\n self.x = x\n self.y = y\n self.width = width\n self.height = height\n self.color = color\n self.line_offset = 0\n\nclass Elevator():\n def __init__(self, x, y, width, height, color):\n self.x = x\n self.y = y\n self.width = width\n self.height = height\n self.color = color\n\n def switch_ropes(self, end_rope):\n self.x = end_rope.x - (self.width / 2)\n\naltfont = pygame.font.SysFont('Comic Sans MS', 30)\naltitude = 0.4 * win_h\n\nrun = True\ngameover = False\nwon = False\n\nA = Rope(0.25 * win_w, 0, 0.02 * win_w, win_h, \"green\")\nB = Rope(0.75 * win_w, 0, 0.02 * win_w, win_h, \"yellow\")\nElev = Elevator(A.x - (0.3 * win_w / 2), altitude, 0.3 * win_w, 0.2 * win_h, \"blue\")\n\ninefficiency = 0.05\n\nwhile run:\n pygame.time.delay(100)\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n\n if altitude >= win_h:\n gameover = True\n won = False\n elif altitude <= 0:\n gameover = True\n won = True\n\n if gameover:\n donefont = pygame.font.SysFont('Comic Sans MS', 50)\n displaytext = \"You won!\" if won else \"You lost :(\"\n done_surf = donefont.render(displaytext, False, (0, 0, 0))\n\n win.blit(done_surf, (0.5 * win_w, 0.5 * win_h))\n pygame.display.update()\n continue\n\n win.fill((255, 255, 255))\n keys = pygame.key.get_pressed()\n\n if keys[pygame.K_UP]:\n Elev.switch_ropes(B)\n altitude += inefficiency * altitude\n Elev.y = altitude\n\n B.line_offset = (B.line_offset - 5) % 50\n\n altitude -= 0.1\n print(altitude)\n Elev.y = altitude\n\n if keys[pygame.K_DOWN]:\n if Elev.x != A.x - (Elev.width / 2):\n Elev.switch_ropes(A)\n altitude += inefficiency * altitude\n Elev.y = altitude\n\n B.line_offset = (B.line_offset + 5) % 50\n\n\n # if keys[pygame.K_DOWN]:\n # Elev.switch_ropes(A)\n\n for obj in [A, B, Elev]:\n pygame.draw.rect(win, obj.color, (obj.x, obj.y, obj.width, obj.height))\n\n for rope in [A, B]:\n for i in range(20):\n pygame.draw.line(win, \"black\", (rope.x, rope.line_offset + i * 50),(rope.x + rope.width, rope.line_offset + 20 + i * 50))\n\n alt_surf = altfont.render('Alt: {}'.format(win_h - altitude), False, (0, 0, 0))\n win.blit(alt_surf,(0.85 * win_w,0))\n pygame.display.update()\n\npygame.quit()","repo_name":"BK-Modding/learning","sub_path":"game_development/pygame/firstGame.py","file_name":"firstGame.py","file_ext":"py","file_size_in_byte":2661,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23386062229","text":"import time\n\n\n# Standard Sieve of Eratosthenes to find the number of primes up to n\ndef standard_sieve(n):\n # Create a boolean array \"prime[0..n]\" and initialize all entries as true\n # A value in prime[i] will finally be false if i is Not a prime, otherwise true\n prime = [True for _ in range(n+1)]\n p = 2\n while p * p <= n:\n # If prime[p] is not changed, then it is a prime\n if prime[p]:\n # Update all multiples of p\n for i in range(p * p, n + 1, p):\n prime[i] = False\n p += 1\n \n # Count and return the number of prime numbers\n return len([x for x in range(2, n+1) if prime[x]])\n\n# Further optimized Sieve of Eratosthenes to strictly follow the form 6n +/- 1\ndef altered_sieve(n):\n # Create a boolean array \"prime[0..n]\" and initialize all entries as true.\n # A value in prime[i] will finally be false if i is Not a prime, otherwise true.\n prime = [True for _ in range(n+1)]\n \n # Manually set multiples of 2 and 3 as not prime\n for i in range(2, int(n / 2) + 1):\n prime[2 * i] = False\n for i in range(2, int(n / 3) + 1):\n prime[3 * i] = False\n \n # Start the sieve\n p = 5 # Starting from the next prime after 3\n w = 2 # The wheel to cycle through 6n - 1 and 6n + 1\n while p * p <= n:\n if prime[p]:\n # Update all multiples of p\n for i in range(p * p, n + 1, p):\n prime[i] = False\n \n # Increment by w to skip multiples of 2 and 3\n # and cycle through 6n - 1 and 6n + 1\n p += w\n w = 6 - w\n \n # Count and return the number of prime numbers\n # Adding 2 for the primes 2 and 3\n return len([x for x in range(5, n+1) if prime[x]]) + 2\n\n# Implementing the \"Multiples of Consequence\" algorithm to find prime numbers\ndef multiples_of_consequence(n):\n # Initialize a list to keep track of potential primes\n # We'll mark the indices corresponding to non-primes as False\n is_prime = [True] * (n + 1)\n \n # Manually handle the cases for 2 and 3\n is_prime[0] = is_prime[1] = False\n for i in range(4, n + 1, 2):\n is_prime[i] = False\n for i in range(6, n + 1, 3):\n is_prime[i] = False\n \n # Start with a count of 2 for the primes 2 and 3\n prime_count = 2\n \n # Loop through potential primes (p) starting from 5\n for p in range(5, n + 1, 6):\n # Iterate over p and p + 2 (to cover both 6n - 1 and 6n + 1 forms)\n for base in [p, p + 2]:\n if base > n:\n break\n \n if not is_prime[base]:\n continue\n \n # Increment the prime count for base\n prime_count += 1\n \n # Calculate \"Multiples of Consequence\" for the current base\n for k in range(1, (n // base) + 1):\n for offset in [6 * k - 2, 6 * k]:\n multiple = base + base * offset\n if multiple > n:\n break\n is_prime[multiple] = False\n \n return prime_count\n\nstart_time = time.time()\nprint(standard_sieve(10000000)) # Should print 9592 for 10k\nprint('Time for standard Eratosthenes: ', time.time() - start_time)\n\n# start_time = time.time()\n# print(altered_sieve(10000)) # Should print 9592 for 10k\n# print('Time for altered sieve: ', time.time() - start_time)\n\nstart_time = time.time()\nprint(multiples_of_consequence(10000000)) # Should print 9592 for 10k\nprint('Time for multiples of consequence: ', time.time() - start_time)\n\n# start_time = time.time()\n# print(multiples_of_consequence(100000)) # Should print 9592 for 10k\n# print('Time for multiples of consequence numpy: ', time.time() - start_time)","repo_name":"dennissmith0/Prime_Counting","sub_path":"algorithms/play.py","file_name":"play.py","file_ext":"py","file_size_in_byte":3745,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"38788329663","text":"\"\"\"\nListing 3.68\n\nCallbacks offer a convenient way to clearly define cleanup logic without\nthe overhead of creating a new context manager class. To improve code\nreadability, that logic can be encapsulated in an inline function, and\ncallback() can be used as a decorator\n\nThere is no way to specify the arguments for functions registered using\nthe decorator form of callback(). However, if the cleanup callback is\ndefined inline, scope rules give it access to variables defined in the\ncalling code\n\"\"\"\nimport contextlib\n\n\ndef main():\n with contextlib.ExitStack() as stack:\n\n @stack.callback\n def inline_cleanup():\n print(\"inline_cleanup()\")\n print(f\"local_resource = {local_resource!r}\")\n\n local_resource = \"resource created in context\"\n print(\"within the context\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"8563a236e65cede7b14220e65c70ad5718144a3/python3-standard-library-solutions","sub_path":"Chapter03/0068_contextlib_exitstack_callbacks_decorator.py","file_name":"0068_contextlib_exitstack_callbacks_decorator.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"34887321402","text":"# Write a program that will display successive results for the factorial of the natural number N\n# (User-specified N, but not greater than 8).\nprint('Program returns result of factorial for given natural \"n\" not grater than 8.')\nnat = int(input('Type natural number in range from 1 to 8:'))\nif nat > 8:\n print('You give too big number.')\n nat = int(input('Type natural number in range from 1 to 8:'))\ni = 1\ns = 1\nif nat == 0:\n print(f'{nat}! = 1')\nelif nat == 1:\n print(f'{nat}! = 1')\nelse:\n print(f'{nat}! =')\nfor n in range(1, nat):\n print(n, end=' * ')\nwhile i <= nat:\n s *= i\n i += 1\nprint(nat, '=', s)\nprint(f'Factorial of {nat} is equal {s}')\n","repo_name":"Adam-Kolowrocki/New_beginning","sub_path":"03_instructions/for_04.py","file_name":"for_04.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20256852567","text":"from flask import Flask, jsonify, request\nimport json\n\napp = Flask(__name__)\n\n@app.route('/api', methods=['GET'])\ndef get_data():\n with open('./data.json', 'r') as f:\n data = json.load(f)\n return jsonify(data)\n\n@app.route('/api/', methods=['GET'])\ndef get_data_by_id(id):\n with open('data.json', 'r') as f:\n data = json.load(f)\n filtered_data = [item for item in data if item['id'] == id]\n return jsonify(filtered_data)\n\nif __name__ == '__main__':\n app.run()\n","repo_name":"daniel-sbarros/simple-api-python3","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42437637614","text":"# -*- coding: UTF-8 -*-\n\nimport argparse\nimport json\nimport logging\nimport os\n\nimport face_recognition\n\nlogging.basicConfig(\n format='',\n level=logging.INFO\n)\n\n\ndef split_video(args):\n n = args.index\n logging.info(\"Number of index: {}\".format(n))\n os.system('mkdir -p /tmp/liu_jin_sui_yue/images/{}'.format(n))\n cmd = 'ffmpeg -i /tmp/liu_jin_sui_yue/videos/result-{}.mp4 -r 1 /tmp/liu_jin_sui_yue/images/{}/%d.png'.format(n, n)\n os.system(cmd)\n\n\ndef glance_for_one(lss_encodings, path):\n if not os.path.exists(path):\n return False\n unknow = face_recognition.load_image_file(path)\n try:\n unknow_encoding = face_recognition.face_encodings(unknow)[0]\n except:\n return False\n\n results = face_recognition.compare_faces(lss_encodings, unknow_encoding, tolerance=0.3)\n if results[0]:\n return True\n else:\n return False\n\n\ndef glance(args):\n n = int(args.index)\n lss_encodings = []\n for _ in os.listdir('lss'):\n lss = face_recognition.load_image_file(\"lss/{}\".format(_))\n lss_encoding = face_recognition.face_encodings(lss)[0]\n lss_encodings.append(lss_encoding)\n\n base_dir = '/tmp/liu_jin_sui_yue/images/{}'.format(n)\n result_list = []\n index = 0\n for _ in os.listdir(base_dir):\n index = index + 1\n logging.info(\"Current index {} -------\".format(index))\n p = os.path.join(base_dir, _)\n flag = glance_for_one(lss_encodings, p)\n if flag:\n logging.info(\"Match success {}\".format(p))\n result_list.append(p)\n\n with open('result/{}.json'.format(n), 'w') as f:\n json.dump(result_list, f)\n\n\ndef number_to_date(n):\n m = int(n / 60)\n diff = n - m * 60\n return '00:{}:{}'.format(str(m).zfill(2), diff)\n\n\ndef merge(args):\n n = int(args.index)\n with open('result/{}.json'.format(n), 'r') as f:\n d = json.load(f)\n indexs = []\n for _ in d:\n indexs.append(int(_.split('/')[-1].split('.')[0]))\n indexs = sorted(indexs)\n result = []\n arr = []\n for i in range(len(indexs) - 1):\n if indexs[i + 1] - 30 > indexs[i]:\n if arr and len(arr) != 1:\n result.append(arr)\n arr = []\n continue\n arr.append(indexs[i])\n index = 1\n os.chdir('/tmp/liu_jin_sui_yue/videos')\n for _ in result:\n ss = number_to_date(_[0] - 10)\n to = number_to_date(_[-1] + 10)\n tmp_name = '{}-{}.mp4'.format(n, index)\n cmd = 'ffmpeg -i result-{}.mp4 -ss {} -to {} -vcodec copy -acodec copy {} -y'.format(n, ss, to, tmp_name)\n index = index + 1\n os.system(cmd)\n add_subtitle(tmp_name)\n\n\nall_mp4 = []\n\n\ndef add_subtitle(file_name):\n result_file = file_name.split('/')[-1]\n arr = result_file.split('-')\n parmas = [\n 'crop=\"800:650\"',\n 'scale=1080:-1',\n 'pad=1080:1920:0:550',\n \"delogo=x=1000:y=580:w=79:h=50\",\n 'drawtext=text=\"流金岁月\":fontfile=/Users/beer/beer/liu_jin_sui_yue/ttf/fan.ttf:x=210:y=230:fontsize=180:fontcolor=red',\n 'drawtext=text=\"beer\":fontfile=/Users/beer/beer/liu_jin_sui_yue/ttf/kai.ttf:x=900:y=500:fontsize=50:fontcolor=yellow',\n ]\n\n tang = datas[(int(arr[0]) - 1) * 5 + int(arr[1].split('.')[0])]\n paragraphs = tang.get('paragraphs')\n paragraphs = paragraphs[0:min(len(paragraphs), 6)]\n s = 'drawtext=text=\"{}\":fontfile=/Users/beer/beer/liu_jin_sui_yue/ttf/kai.ttf:x=(w-text_w)/2:y={}:fontsize=50:fontcolor=white'\n y = 1480\n for _ in paragraphs:\n parmas.append(s.format(_, y))\n y = y + 80\n\n cmd = 'ffmpeg -i {} -vf \"{}\" -preset superfast -acodec copy final_{} -y'.format(file_name, ','.join(parmas), result_file)\n print(cmd)\n os.system(cmd)\n\n\ndef main(args):\n if args.mode == 'split':\n split_video(args)\n elif args.mode == 'glance':\n glance(args)\n elif args.mode == 'merge':\n merge(args)\n else:\n pass\n\n\ndatas = []\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='god eye project')\n parser.add_argument('-m', '--mode', type=str, required=True, choices=['split', 'glance', 'merge'])\n parser.add_argument('-n', '--index', type=str, required=True, help='the number of index')\n args = parser.parse_args()\n\n with open('poet.song.0.json', 'r', encoding='utf8') as f:\n datas = json.load(f)\n\n main(args)\n","repo_name":"yangyang5214/douyin","sub_path":"liu_jin_sui_yue/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4394,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"25533607589","text":"from __future__ import annotations\n\nimport contextlib\nimport inspect\nfrom enum import Enum\nfrom enum import auto\nfrom functools import wraps\nfrom typing import Any, Optional, Callable, Dict, _GenericAlias\nfrom typing import Sequence, List, Union, Protocol\n\nimport jpy\nimport numba\nimport numpy as np\n\nfrom deephaven import DHError\nfrom deephaven import dtypes\nfrom deephaven._jpy import strict_cast\nfrom deephaven._wrapper import JObjectWrapper\nfrom deephaven._wrapper import unwrap\nfrom deephaven.agg import Aggregation\nfrom deephaven.column import Column, ColumnType\nfrom deephaven.filters import Filter, and_, or_\nfrom deephaven.jcompat import j_unary_operator, j_binary_operator, j_map_to_dict, j_hashmap\nfrom deephaven.jcompat import to_sequence, j_array_list\nfrom deephaven.update_graph import auto_locking_ctx, UpdateGraph\nfrom deephaven.updateby import UpdateByOperation\nfrom deephaven.dtypes import _BUILDABLE_ARRAY_DTYPE_MAP, _scalar, _np_dtype_char, \\\n _component_np_dtype_char\n\n# Table\n_J_Table = jpy.get_type(\"io.deephaven.engine.table.Table\")\n_JAttributeMap = jpy.get_type(\"io.deephaven.engine.table.AttributeMap\")\n_JTableTools = jpy.get_type(\"io.deephaven.engine.util.TableTools\")\n_JColumnName = jpy.get_type(\"io.deephaven.api.ColumnName\")\n_JSortColumn = jpy.get_type(\"io.deephaven.api.SortColumn\")\n_JFilter = jpy.get_type(\"io.deephaven.api.filter.Filter\")\n_JFilterOr = jpy.get_type(\"io.deephaven.api.filter.FilterOr\")\n_JPair = jpy.get_type(\"io.deephaven.api.Pair\")\n_JLayoutHintBuilder = jpy.get_type(\"io.deephaven.engine.util.LayoutHintBuilder\")\n_JSearchDisplayMode = jpy.get_type(\"io.deephaven.engine.util.LayoutHintBuilder$SearchDisplayModes\")\n_JSnapshotWhenOptions = jpy.get_type(\"io.deephaven.api.snapshot.SnapshotWhenOptions\")\n_JBlinkTableTools = jpy.get_type(\"io.deephaven.engine.table.impl.BlinkTableTools\")\n\n# PartitionedTable\n_JPartitionedTable = jpy.get_type(\"io.deephaven.engine.table.PartitionedTable\")\n_JPartitionedTableFactory = jpy.get_type(\"io.deephaven.engine.table.PartitionedTableFactory\")\n_JTableDefinition = jpy.get_type(\"io.deephaven.engine.table.TableDefinition\")\n_JPartitionedTableProxy = jpy.get_type(\"io.deephaven.engine.table.PartitionedTable$Proxy\")\n_JJoinMatch = jpy.get_type(\"io.deephaven.api.JoinMatch\")\n_JJoinAddition = jpy.get_type(\"io.deephaven.api.JoinAddition\")\n_JAsOfJoinRule = jpy.get_type(\"io.deephaven.api.AsOfJoinRule\")\n_JTableOperations = jpy.get_type(\"io.deephaven.api.TableOperations\")\n\n# Dynamic Query Scope\n_JExecutionContext = jpy.get_type(\"io.deephaven.engine.context.ExecutionContext\")\n_JScriptSessionQueryScope = jpy.get_type(\"io.deephaven.engine.util.AbstractScriptSession$ScriptSessionQueryScope\")\n_JPythonScriptSession = jpy.get_type(\"io.deephaven.integrations.python.PythonDeephavenSession\")\n\n# Rollup Table and Tree Table\n_JRollupTable = jpy.get_type(\"io.deephaven.engine.table.hierarchical.RollupTable\")\n_JTreeTable = jpy.get_type(\"io.deephaven.engine.table.hierarchical.TreeTable\")\n_JRollupTableNodeOperationsRecorder = jpy.get_type(\n \"io.deephaven.engine.table.hierarchical.RollupTable$NodeOperationsRecorder\")\n_JTreeTableNodeOperationsRecorder = jpy.get_type(\n \"io.deephaven.engine.table.hierarchical.TreeTable$NodeOperationsRecorder\")\n_JNodeType = jpy.get_type(\"io.deephaven.engine.table.hierarchical.RollupTable$NodeType\")\n_JFormatOperationsRecorder = jpy.get_type(\"io.deephaven.engine.table.hierarchical.FormatOperationsRecorder\")\n_JSortOperationsRecorder = jpy.get_type(\"io.deephaven.engine.table.hierarchical.SortOperationsRecorder\")\n_JFilterOperationsRecorder = jpy.get_type(\"io.deephaven.engine.table.hierarchical.FilterOperationsRecorder\")\n\n# MultiJoin Table and input\n_JMultiJoinInput = jpy.get_type(\"io.deephaven.engine.table.MultiJoinInput\")\n_JMultiJoinTable = jpy.get_type(\"io.deephaven.engine.table.MultiJoinTable\")\n_JMultiJoinFactory = jpy.get_type(\"io.deephaven.engine.table.MultiJoinFactory\")\n\n# For unittest vectorization\n_test_vectorization = False\n_vectorized_count = 0\n\n\nclass NodeType(Enum):\n \"\"\"An enum of node types for RollupTable\"\"\"\n AGGREGATED = _JNodeType.Aggregated\n \"\"\"Nodes at an aggregated (rolled up) level in the RollupTable. An aggregated level is above the constituent (\n leaf) level. These nodes have column names and types that result from applying aggregations on the source table \n of the RollupTable. \"\"\"\n CONSTITUENT = _JNodeType.Constituent\n \"\"\"Nodes at the leaf level when :meth:`~deephaven.table.Table.rollup` method is called with \n include_constituent=True. The constituent level is the lowest in a rollup table. These nodes have column names \n and types from the source table of the RollupTable. \"\"\"\n\n\nclass SearchDisplayMode(Enum):\n \"\"\"An enum of search display modes for layout hints\"\"\"\n DEFAULT = _JSearchDisplayMode.Default\n \"\"\"Use the system default. This may depend on your user and/or system settings.\"\"\"\n SHOW = _JSearchDisplayMode.Show\n \"\"\"Permit the search bar to be displayed, regardless of user or system settings.\"\"\"\n HIDE = _JSearchDisplayMode.Hide\n \"\"\"Hide the search bar, regardless of user or system settings.\"\"\"\n\n\nclass _FormatOperationsRecorder(Protocol):\n \"\"\"A mixin for creating format operations to be applied to individual nodes of either RollupTable or TreeTable.\"\"\"\n\n def format_column(self, formulas: Union[str, List[str]]):\n \"\"\"Returns a new recorder with the :meth:`~deephaven.table.Table.format_columns` operation applied to nodes.\"\"\"\n formulas = to_sequence(formulas)\n j_format_ops_recorder = jpy.cast(self.j_node_ops_recorder, _JFormatOperationsRecorder)\n return self.__class__(j_format_ops_recorder.formatColumns(formulas))\n\n def format_row_where(self, cond: str, formula: str):\n \"\"\"Returns a new recorder with the :meth:`~deephaven.table.Table.format_row_where` operation applied to\n nodes.\"\"\"\n j_format_ops_recorder = jpy.cast(self.j_node_ops_recorder, _JFormatOperationsRecorder)\n return self.__class__(j_format_ops_recorder.formatRowWhere(cond, formula))\n\n def format_column_where(self, col: str, cond: str, formula: str):\n \"\"\"Returns a new recorder with the :meth:`~deephaven.table.Table.format_column_where` operation applied to\n nodes.\"\"\"\n j_format_ops_recorder = jpy.cast(self.j_node_ops_recorder, _JFormatOperationsRecorder)\n return self.__class__(j_format_ops_recorder.formatColumnWhere(col, cond, formula))\n\n\nclass _SortOperationsRecorder(Protocol):\n \"\"\"A mixin for creating sort operations to be applied to individual nodes of either RollupTable or\n TreeTable.\"\"\"\n\n def sort(self, order_by: Union[str, Sequence[str]]):\n \"\"\"Returns a new recorder with the :meth:`~deephaven.table.Table.sort` operation applied to nodes.\"\"\"\n order_by = to_sequence(order_by)\n j_sort_ops_recorder = jpy.cast(self.j_node_ops_recorder, _JSortOperationsRecorder)\n return self.__class__(j_sort_ops_recorder.sort(order_by))\n\n def sort_descending(self, order_by: Union[str, Sequence[str]]):\n \"\"\"Returns a new recorder with the :meth:`~deephaven.table.Table.sort_descending` applied to nodes.\"\"\"\n order_by = to_sequence(order_by)\n j_sort_ops_recorder = jpy.cast(self.j_node_ops_recorder, _JSortOperationsRecorder)\n return self.__class__(j_sort_ops_recorder.sortDescending(order_by))\n\n\nclass _FilterOperationsRecorder(Protocol):\n \"\"\"A mixin for creating filter operations to be applied to individual nodes of either RollupTable or\n TreeTable.\"\"\"\n\n def where(self, filters: Union[str, Filter, Sequence[str], Sequence[Filter]]):\n \"\"\"Returns a new recorder with the :meth:`~deephaven.table.Table.where` operation applied to nodes.\"\"\"\n j_filter_ops_recorder = jpy.cast(self.j_node_ops_recorder, _JFilterOperationsRecorder)\n return self.__class__(j_filter_ops_recorder.where(and_(filters).j_filter))\n\n\nclass RollupNodeOperationsRecorder(JObjectWrapper, _FormatOperationsRecorder,\n _SortOperationsRecorder):\n \"\"\"Recorder for node-level operations to be applied when gathering snapshots of RollupTable. Supported operations\n include column formatting and sorting.\n\n Note: It should not be instantiated directly. User code must call :meth:`~RollupTable.node_operation_recorder` to\n create an instance of the recorder.\n \"\"\"\n\n j_object_type = _JRollupTableNodeOperationsRecorder\n\n @property\n def j_object(self) -> jpy.JType:\n return self.j_node_ops_recorder\n\n def __init__(self, j_node_ops_recorder: jpy.JType):\n self.j_node_ops_recorder = j_node_ops_recorder\n\n\nclass RollupTable(JObjectWrapper):\n \"\"\" A RollupTable is generated as a result of applying the :meth:`~deephaven.table.Table.rollup` operation on a\n :class:`~deephaven.table.Table`.\n\n A RollupTable aggregates by the grouping columns, and then creates a hierarchical table which re-aggregates\n using one less grouping column on each level.\n\n Note: RollupTable should not be instantiated directly by user code.\n \"\"\"\n j_object_type = _JRollupTable\n\n @property\n def j_object(self) -> jpy.JType:\n return self.j_rollup_table\n\n def __init__(self, j_rollup_table: jpy.JType, aggs: Sequence[Aggregation], include_constituents: bool,\n by: Sequence[str]):\n self.j_rollup_table = j_rollup_table\n self.aggs = aggs\n self.include_constituents = include_constituents\n self.by = by\n\n def node_operation_recorder(self, node_type: NodeType) -> RollupNodeOperationsRecorder:\n \"\"\"Creates a RollupNodeOperationsRecorder for per-node operations to apply during Deephaven UI driven\n snapshotting of this RollupTable. The recorded node operations will be applied only to the node of the\n provided NodeType. See :class:`NodeType` for details.\n\n Args:\n node_type (NodeType): the type of node tables that the recorded operations will be applied to; if it is\n :attr:`NodeType.CONSTITUENT`, the RollupTable must be created with include_constituents=True.\n\n Returns:\n a RollupNodeOperationsRecorder\n\n Raises:\n DHError\n \"\"\"\n try:\n return RollupNodeOperationsRecorder(j_node_ops_recorder=self.j_rollup_table.makeNodeOperationsRecorder(\n node_type.value))\n except Exception as e:\n raise DHError(e, \"failed to create a RollupNodeOperationsRecorder.\") from e\n\n def with_node_operations(self, recorders: List[RollupNodeOperationsRecorder]) -> RollupTable:\n \"\"\"Returns a new RollupTable that will apply the recorded node operations to nodes when gathering\n snapshots requested by the Deephaven UI.\n\n Args:\n recorders (List[RollupNodeOperationsRecorder]): a list of RollupNodeOperationsRecorder containing\n the node operations to be applied, they must be ones created by calling the 'node_operation_recorder'\n method on the same table.\n\n Returns:\n a new RollupTable\n\n Raises:\n DHError\n \"\"\"\n try:\n return RollupTable(\n j_rollup_table=self.j_rollup_table.withNodeOperations(\n [op.j_node_ops_recorder for op in recorders]),\n include_constituents=self.include_constituents, aggs=self.aggs, by=self.by)\n except Exception as e:\n raise DHError(e, \"with_node_operations on RollupTable failed.\") from e\n\n def with_filters(self, filters: Union[str, Filter, Sequence[str], Sequence[Filter]]) -> RollupTable:\n \"\"\"Returns a new RollupTable by applying the given set of filters to the group-by columns of this RollupTable.\n\n Args:\n filters (Union[str, Filter, Sequence[str], Sequence[Filter]], optional): the filter condition\n expression(s) or Filter object(s)\n\n Returns:\n a new RollupTable\n\n Raises:\n DHError\n \"\"\"\n try:\n return RollupTable(j_rollup_table=self.j_rollup_table.withFilter(and_(filters).j_filter),\n include_constituents=self.include_constituents, aggs=self.aggs, by=self.by)\n except Exception as e:\n raise DHError(e, \"with_filters operation on RollupTable failed.\") from e\n\n\nclass TreeNodeOperationsRecorder(JObjectWrapper, _FormatOperationsRecorder,\n _SortOperationsRecorder, _FilterOperationsRecorder):\n \"\"\"Recorder for node-level operations to be applied when gathering snapshots of TreeTable. Supported operations\n include column formatting, sorting, and filtering.\n\n Note: It should not be instantiated directly. User code must call :meth:`~TreeTable.node_operation_recorder` to\n create an instance of the recorder.\n \"\"\"\n\n j_object_type = _JTreeTableNodeOperationsRecorder\n\n @property\n def j_object(self) -> jpy.JType:\n return self.j_node_ops_recorder\n\n def __init__(self, j_node_ops_recorder: jpy.JType):\n self.j_node_ops_recorder = j_node_ops_recorder\n\n\nclass TreeTable(JObjectWrapper):\n \"\"\" A TreeTable is generated as a result of applying the :meth:`~Table.tree` method on a\n :class:`~deephaven.table.Table`.\n\n A TreeTable presents a hierarchically structured \"tree\" view of a table where parent-child relationships are expressed\n by an \"id\" and a \"parent\" column. The id column should represent a unique identifier for a given row, and the parent\n column indicates which row is the parent for a given row.\n\n Note: TreeTable should not be instantiated directly by user code.\n \"\"\"\n j_object_type = _JTreeTable\n\n @property\n def j_object(self) -> jpy.JType:\n return self.j_tree_table\n\n def __init__(self, j_tree_table: jpy.JType, id_col: str, parent_col: str):\n self.j_tree_table = j_tree_table\n self.id_col = id_col\n self.parent_col = parent_col\n\n def node_operation_recorder(self) -> TreeNodeOperationsRecorder:\n \"\"\"Creates a TreepNodeOperationsRecorder for per-node operations to apply during Deephaven UI driven\n snapshotting of this TreeTable.\n\n Returns:\n a TreeNodeOperationsRecorder\n \"\"\"\n return TreeNodeOperationsRecorder(j_node_ops_recorder=self.j_tree_table.makeNodeOperationsRecorder())\n\n def with_node_operations(self, recorder: TreeNodeOperationsRecorder) -> TreeTable:\n \"\"\"Returns a new TreeTable that will apply the recorded node operations to nodes when gathering snapshots\n requested by the Deephaven UI.\n\n Args:\n recorder (TreeNodeOperationsRecorder): the TreeNodeOperationsRecorder containing the node operations to be\n applied, it must be created by calling the 'node_operation_recorder' method on the same table.\n\n Returns:\n a new TreeTable\n\n Raises:\n DHError\n \"\"\"\n\n try:\n return TreeTable(\n j_tree_table=self.j_tree_table.withNodeOperations(recorder.j_node_ops_recorder),\n id_col=self.id_col, parent_col=self.parent_col)\n except Exception as e:\n raise DHError(e, \"with_node_operations on TreeTable failed.\") from e\n\n def with_filters(self, filters: Union[str, Filter, Sequence[str], Sequence[Filter]]) -> TreeTable:\n \"\"\"Returns a new TreeTable by applying the given set of filters to the columns of this TreeTable.\n\n Args:\n filters (Union[str, Filter, Sequence[str], Sequence[Filter]], optional): the filter condition\n expression(s) or Filter object(s)\n\n Returns:\n a new TreeTable\n\n Raises:\n DHError\n \"\"\"\n\n try:\n return TreeTable(j_tree_table=self.j_tree_table.withFilter(and_(filters).j_filter), id_col=self.id_col,\n parent_col=self.parent_col)\n except Exception as e:\n raise DHError(e, \"with_filters operation on TreeTable failed.\") from e\n\n\ndef _j_py_script_session() -> _JPythonScriptSession:\n j_execution_context = _JExecutionContext.getContext()\n j_query_scope = j_execution_context.getQueryScope()\n try:\n j_script_session_query_scope = strict_cast(j_query_scope, _JScriptSessionQueryScope)\n return strict_cast(j_script_session_query_scope.scriptSession(), _JPythonScriptSession)\n except DHError:\n return None\n\n\n_SUPPORTED_NP_TYPE_CODES = [\"i\", \"l\", \"h\", \"f\", \"d\", \"b\", \"?\", \"U\", \"M\", \"O\"]\n\n\ndef _parse_annotation(annotation: Any) -> Any:\n \"\"\"Parse a Python annotation, for now mostly to extract the non-None type from an Optional(Union) annotation,\n otherwise return the original annotation. \"\"\"\n if isinstance(annotation, _GenericAlias) and annotation.__origin__ == Union and len(annotation.__args__) == 2:\n if annotation.__args__[1] == type(None): # noqa: E721\n return annotation.__args__[0]\n elif annotation.__args__[0] == type(None): # noqa: E721\n return annotation.__args__[1]\n else:\n return annotation\n else:\n return annotation\n\n\ndef _encode_signature(fn: Callable) -> str:\n \"\"\"Encode the signature of a Python function by mapping the annotations of the parameter types and the return\n type to numpy dtype chars (i,l,h,f,d,b,?,U,M,O), and pack them into a string with parameter type chars first,\n in their original order, followed by the delimiter string '->', then the return type_char.\n\n If a parameter or the return of the function is not annotated, the default 'O' - object type, will be used.\n \"\"\"\n try:\n sig = inspect.signature(fn)\n except:\n # in case inspect.signature() fails, we'll just use the default 'O' - object type.\n # numpy ufuncs actually have signature encoded in their 'types' attribute, we want to better support\n # them in the future (https://github.com/deephaven/deephaven-core/issues/4762)\n if type(fn) == np.ufunc:\n return \"O\"*fn.nin + \"->\" + \"O\"\n return \"->O\"\n\n np_type_codes = []\n for n, p in sig.parameters.items():\n p_annotation = _parse_annotation(p.annotation)\n np_type_codes.append(_np_dtype_char(p_annotation))\n\n return_annotation = _parse_annotation(sig.return_annotation)\n return_type_code = _np_dtype_char(return_annotation)\n np_type_codes = [c if c in _SUPPORTED_NP_TYPE_CODES else \"O\" for c in np_type_codes]\n return_type_code = return_type_code if return_type_code in _SUPPORTED_NP_TYPE_CODES else \"O\"\n\n np_type_codes.extend([\"-\", \">\", return_type_code])\n return \"\".join(np_type_codes)\n\n\ndef _udf_return_dtype(fn):\n if isinstance(fn, (numba.np.ufunc.dufunc.DUFunc, numba.np.ufunc.gufunc.GUFunc)) and hasattr(fn, \"types\"):\n return dtypes.from_np_dtype(np.dtype(fn.types[0][-1]))\n else:\n return dtypes.from_np_dtype(np.dtype(_encode_signature(fn)[-1]))\n\n\ndef _py_udf(fn: Callable):\n \"\"\"A decorator that acts as a transparent translator for Python UDFs used in Deephaven query formulas between\n Python and Java. This decorator is intended for use by the Deephaven query engine and should not be used by\n users.\n\n For now, this decorator is only capable of converting Python function return values to Java values. It\n does not yet convert Java values in arguments to usable Python object (e.g. numpy arrays) or properly translate\n Deephaven primitive null values.\n\n For properly annotated functions, including numba vectorized and guvectorized ones, this decorator inspects the\n signature of the function and determines its return type, including supported primitive types and arrays of\n the supported primitive types. It then converts the return value of the function to the corresponding Java value\n of the same type. For unsupported types, the decorator returns the original Python value which appears as\n org.jpy.PyObject in Java.\n \"\"\"\n\n if hasattr(fn, \"return_type\"):\n return fn\n ret_dtype = _udf_return_dtype(fn)\n\n return_array = False\n # If the function is a numba guvectorized function, examine the signature of the function to determine if it\n # returns an array.\n if isinstance(fn, numba.np.ufunc.gufunc.GUFunc):\n sig = fn.signature\n rtype = sig.split(\"->\")[-1].strip(\"()\")\n if rtype:\n return_array = True\n else:\n try:\n return_annotation = _parse_annotation(inspect.signature(fn).return_annotation)\n except ValueError:\n # the function has no return annotation, and since we can't know what the exact type is, the return type\n # defaults to the generic object type therefore it is not an array of a specific type,\n # but see (https://github.com/deephaven/deephaven-core/issues/4762) for future imporvement to better support\n # numpy ufuncs.\n pass\n else:\n component_type = _component_np_dtype_char(return_annotation)\n if component_type:\n ret_dtype = dtypes.from_np_dtype(np.dtype(component_type))\n if ret_dtype in _BUILDABLE_ARRAY_DTYPE_MAP:\n return_array = True\n\n @wraps(fn)\n def wrapper(*args, **kwargs):\n ret = fn(*args, **kwargs)\n if return_array:\n return dtypes.array(ret_dtype, ret)\n elif ret_dtype == dtypes.PyObject:\n return ret\n else:\n return _scalar(ret, ret_dtype)\n\n wrapper.j_name = ret_dtype.j_name\n real_ret_dtype = _BUILDABLE_ARRAY_DTYPE_MAP.get(ret_dtype) if return_array else ret_dtype\n\n if hasattr(ret_dtype.j_type, 'jclass'):\n j_class = real_ret_dtype.j_type.jclass\n else:\n j_class = real_ret_dtype.qst_type.clazz()\n\n wrapper.return_type = j_class\n\n return wrapper\n\n\ndef dh_vectorize(fn):\n \"\"\"A decorator to vectorize a Python function used in Deephaven query formulas and invoked on a row basis.\n\n If this annotation is not used on a query function, the Deephaven query engine will make an effort to vectorize\n the function. If vectorization is not possible, the query engine will use the original, non-vectorized function.\n If this annotation is used on a function, the Deephaven query engine will use the vectorized function in a query,\n or an error will result if the function can not be vectorized.\n\n When this decorator is used on a function, the number and type of input and output arguments are changed.\n These changes are only intended for use by the Deephaven query engine. Users are discouraged from using\n vectorized functions in non-query code, since the function signature may change in future versions.\n \n The current vectorized function signature includes (1) the size of the input arrays, (2) the output array,\n and (3) the input arrays.\n \"\"\"\n signature = _encode_signature(fn)\n ret_dtype = _udf_return_dtype(fn)\n\n @wraps(fn)\n def wrapper(*args):\n if len(args) != len(signature) - len(\"->?\") + 2:\n raise ValueError(\n f\"The number of arguments doesn't match the function signature. {len(args) - 2}, {signature}\")\n if args[0] <= 0:\n raise ValueError(f\"The chunk size argument must be a positive integer. {args[0]}\")\n\n chunk_size = args[0]\n chunk_result = args[1]\n if args[2:]:\n vectorized_args = zip(*args[2:])\n for i in range(chunk_size):\n scalar_args = next(vectorized_args)\n chunk_result[i] = _scalar(fn(*scalar_args), ret_dtype)\n else:\n for i in range(chunk_size):\n chunk_result[i] = _scalar(fn(), ret_dtype)\n\n return chunk_result\n\n wrapper.callable = fn\n wrapper.signature = signature\n wrapper.dh_vectorized = True\n\n if _test_vectorization:\n global _vectorized_count\n _vectorized_count += 1\n\n return wrapper\n\n\n@contextlib.contextmanager\ndef _query_scope_ctx():\n \"\"\"A context manager to set/unset query scope based on the scope of the most immediate caller code that invokes\n Table operations.\"\"\"\n\n # locate the innermost Deephaven frame (i.e. any of the table operation methods that use this context manager)\n outer_frames = inspect.getouterframes(inspect.currentframe())[1:]\n for i, (frame, filename, *_) in enumerate(outer_frames):\n if filename and filename == __file__:\n break\n\n # combine the immediate caller's globals and locals into a single dict and use it as the query scope\n caller_frame = outer_frames[i + 1].frame\n function = outer_frames[i + 1].function\n j_py_script_session = _j_py_script_session()\n if j_py_script_session and (len(outer_frames) > i + 2 or function != \"\"):\n scope_dict = caller_frame.f_globals.copy()\n scope_dict.update(caller_frame.f_locals)\n j_py_script_session.pushScope(scope_dict)\n try:\n yield\n finally:\n j_py_script_session.popScope()\n else:\n # in the __main__ module, use the default main global scope\n yield\n\n\ndef _query_scope_agg_ctx(aggs: Sequence[Aggregation]) -> contextlib.AbstractContextManager:\n has_agg_formula = any([agg.is_formula for agg in aggs])\n if has_agg_formula:\n cm = _query_scope_ctx()\n else:\n cm = contextlib.nullcontext()\n return cm\n\n\nclass SortDirection(Enum):\n \"\"\"An enum defining the sorting orders.\"\"\"\n DESCENDING = auto()\n \"\"\"\"\"\"\n ASCENDING = auto()\n \"\"\"\"\"\"\n\n\ndef _sort_column(col, dir_):\n return (_JSortColumn.desc(_JColumnName.of(col)) if dir_ == SortDirection.DESCENDING else _JSortColumn.asc(\n _JColumnName.of(col)))\n\n\ndef _td_to_columns(table_definition):\n cols = []\n j_cols = table_definition.getColumnsArray()\n for j_col in j_cols:\n cols.append(\n Column(\n name=j_col.getName(),\n data_type=dtypes.from_jtype(j_col.getDataType()),\n component_type=dtypes.from_jtype(j_col.getComponentType()),\n column_type=ColumnType(j_col.getColumnType()),\n )\n )\n return cols\n\n\nclass Table(JObjectWrapper):\n \"\"\"A Table represents a Deephaven table. It allows applications to perform powerful Deephaven table operations.\n\n Note: It should not be instantiated directly by user code. Tables are mostly created by factory methods,\n data ingestion operations, queries, aggregations, joins, etc.\n\n \"\"\"\n j_object_type = _J_Table\n\n def __init__(self, j_table: jpy.JType):\n self.j_table = jpy.cast(j_table, self.j_object_type)\n if self.j_table is None:\n raise DHError(\"j_table type is not io.deephaven.engine.table.Table\")\n self._definition = self.j_table.getDefinition()\n self._schema = None\n self._is_refreshing = None\n self._update_graph = None\n self._is_flat = None\n\n def __repr__(self):\n default_repr = super().__repr__()\n # default_repr is in a format like so:\n # deephaven.table.Table(io.deephaven.engine.table.Table(objectRef=0x7f07e4890518))\n # We take the last two brackets off, add a few more details about the table, then add the necessary brackets back\n column_dict = {col.name: col.data_type for col in self.columns[:10]}\n repr_str = (\n f\"{default_repr[:-2]}, num_rows = {self.size}, columns = {column_dict}\"\n )\n # We need to add the two brackets back, and also truncate it to be 120 char total (118 + two brackets)\n repr_str = repr_str[:114] + \"...}))\" if len(repr_str) > 118 else repr_str + \"))\"\n return repr_str\n\n def __str__(self):\n return repr(self)\n\n @property\n def size(self) -> int:\n \"\"\"The current number of rows in the table.\"\"\"\n return self.j_table.size()\n\n @property\n def is_refreshing(self) -> bool:\n \"\"\"Whether this table is refreshing.\"\"\"\n if self._is_refreshing is None:\n self._is_refreshing = self.j_table.isRefreshing()\n return self._is_refreshing\n\n @property\n def is_blink(self) -> bool:\n \"\"\"Whether this table is a blink table.\"\"\"\n return _JBlinkTableTools.isBlink(self.j_table)\n\n @property\n def update_graph(self) -> UpdateGraph:\n \"\"\"The update graph of the table.\"\"\"\n if self._update_graph is None:\n self._update_graph = UpdateGraph(self.j_table.getUpdateGraph())\n return self._update_graph\n\n @property\n def is_flat(self) -> bool:\n \"\"\"Whether this table is guaranteed to be flat, i.e. its row set will be from 0 to number of rows - 1.\"\"\"\n if self._is_flat is None:\n self._is_flat = self.j_table.isFlat()\n return self._is_flat\n\n @property\n def columns(self) -> List[Column]:\n \"\"\"The column definitions of the table.\"\"\"\n if self._schema:\n return self._schema\n\n self._schema = _td_to_columns(self._definition)\n return self._schema\n\n @property\n def meta_table(self) -> Table:\n \"\"\"The column definitions of the table in a Table form. \"\"\"\n return Table(j_table=self.j_table.meta())\n\n @property\n def j_object(self) -> jpy.JType:\n return self.j_table\n\n def has_columns(self, cols: Union[str, Sequence[str]]):\n \"\"\"Whether this table contains a column for each of the provided names, return False if any of the columns is\n not in the table.\n\n Args:\n cols (Union[str, Sequence[str]]): the column name(s)\n\n Returns:\n bool\n \"\"\"\n cols = to_sequence(cols)\n return self.j_table.hasColumns(cols)\n\n def attributes(self) -> Dict[str, Any]:\n \"\"\"Returns all the attributes defined on the table.\"\"\"\n j_map = jpy.cast(self.j_table, _JAttributeMap).getAttributes()\n return j_map_to_dict(j_map)\n\n def with_attributes(self, attrs: Dict[str, Any]) -> Table:\n \"\"\"Returns a new Table that has the provided attributes defined on it and shares the underlying data and schema\n with this table.\n\n Note, the table attributes are immutable once defined, and are mostly used internally by the Deephaven\n engine. For advanced users, certain predefined plug-in attributes provide a way to extend Deephaven with\n custom-built plug-ins.\n\n Args:\n attrs (Dict[str, Any]): a dict of table attribute names and their values\n\n Returns:\n a new Table\n\n Raises:\n DHError\n \"\"\"\n try:\n j_map = j_hashmap(attrs)\n return Table(j_table=jpy.cast(self.j_table, _JAttributeMap).withAttributes(j_map))\n except Exception as e:\n raise DHError(e, \"failed to create a table with attributes.\") from e\n\n def without_attributes(self, attrs: Union[str, Sequence[str]]) -> Table:\n \"\"\"Returns a new Table that shares the underlying data and schema with this table but with the specified\n attributes removed.\n\n Args:\n attrs (Union[str, Sequence[str]]): the attribute name(s) to be removed\n\n Returns:\n a new Table\n\n Raises:\n DHError\n \"\"\"\n try:\n attrs = j_array_list(to_sequence(attrs))\n return Table(j_table=jpy.cast(self.j_table, _JAttributeMap).withoutAttributes(attrs))\n except Exception as e:\n raise DHError(e, \"failed to create a table without attributes.\") from e\n\n def to_string(self, num_rows: int = 10, cols: Union[str, Sequence[str]] = None) -> str:\n \"\"\"Returns the first few rows of a table as a pipe-delimited string.\n\n Args:\n num_rows (int): the number of rows at the beginning of the table\n cols (Union[str, Sequence[str]]): the column name(s), default is None\n\n Returns:\n string\n\n Raises:\n DHError\n \"\"\"\n try:\n cols = to_sequence(cols)\n return _JTableTools.string(self.j_table, num_rows, *cols)\n except Exception as e:\n raise DHError(e, \"table to_string failed\") from e\n\n def coalesce(self) -> Table:\n \"\"\"Returns a coalesced child table.\"\"\"\n return Table(j_table=self.j_table.coalesce())\n\n def flatten(self) -> Table:\n \"\"\"Returns a new version of this table with a flat row set, i.e. from 0 to number of rows - 1.\"\"\"\n return Table(j_table=self.j_table.flatten())\n\n def snapshot(self) -> Table:\n \"\"\"Returns a static snapshot table.\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n with auto_locking_ctx(self):\n return Table(j_table=self.j_table.snapshot())\n except Exception as e:\n raise DHError(message=\"failed to create a snapshot.\") from e\n\n def snapshot_when(self, trigger_table: Table, stamp_cols: Union[str, List[str]] = None, initial: bool = False,\n incremental: bool = False, history: bool = False) -> Table:\n \"\"\"Returns a table that captures a snapshot of this table whenever trigger_table updates.\n\n When trigger_table updates, a snapshot of this table and the \"stamp key\" from trigger_table form the resulting\n table. The \"stamp key\" is the last row of the trigger_table, limited by the stamp_cols. If trigger_table is\n empty, the \"stamp key\" will be represented by NULL values.\n\n Args:\n trigger_table (Table): the trigger table\n stamp_cols (Union[str, Sequence[str]): The columns from trigger_table that form the \"stamp key\", may be\n renames. None, or empty, means that all columns from trigger_table form the \"stamp key\".\n initial (bool): Whether to take an initial snapshot upon construction, default is False. When False, the\n resulting table will remain empty until trigger_table first updates.\n incremental (bool): Whether the resulting table should be incremental, default is False. When False, all\n rows of this table will have the latest \"stamp key\". When True, only the rows of this table that have\n been added or updated will have the latest \"stamp key\".\n history (bool): Whether the resulting table should keep history, default is False. A history table appends a\n full snapshot of this table and the \"stamp key\" as opposed to updating existing rows. The history flag\n is currently incompatible with initial and incremental: when history is True, incremental and initial\n must be False.\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n options = _JSnapshotWhenOptions.of(initial, incremental, history, to_sequence(stamp_cols))\n with auto_locking_ctx(self, trigger_table):\n return Table(j_table=self.j_table.snapshotWhen(trigger_table.j_table, options))\n except Exception as e:\n raise DHError(message=\"failed to create a snapshot_when table.\") from e\n\n #\n # Table operation category: Select\n #\n # region Select\n def drop_columns(self, cols: Union[str, Sequence[str]]) -> Table:\n \"\"\"The drop_columns method creates a new table with the same size as this table but omits any of specified\n columns.\n\n Args:\n cols (Union[str, Sequence[str]): the column name(s)\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n cols = to_sequence(cols)\n return Table(j_table=self.j_table.dropColumns(*cols))\n except Exception as e:\n raise DHError(e, \"table drop_columns operation failed.\") from e\n\n def move_columns(self, idx: int, cols: Union[str, Sequence[str]]) -> Table:\n \"\"\"The move_columns method creates a new table with specified columns moved to a specific column index value.\n\n Args:\n idx (int): the column index where the specified columns will be moved in the new table.\n cols (Union[str, Sequence[str]]) : the column name(s)\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n cols = to_sequence(cols)\n return Table(j_table=self.j_table.moveColumns(idx, *cols))\n except Exception as e:\n raise DHError(e, \"table move_columns operation failed.\") from e\n\n def move_columns_down(self, cols: Union[str, Sequence[str]]) -> Table:\n \"\"\"The move_columns_down method creates a new table with specified columns appearing last in order, to the far\n right.\n\n Args:\n cols (Union[str, Sequence[str]]) : the column name(s)\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n cols = to_sequence(cols)\n return Table(j_table=self.j_table.moveColumnsDown(*cols))\n except Exception as e:\n raise DHError(e, \"table move_columns_down operation failed.\") from e\n\n def move_columns_up(self, cols: Union[str, Sequence[str]]) -> Table:\n \"\"\"The move_columns_up method creates a new table with specified columns appearing first in order, to the far\n left.\n\n Args:\n cols (Union[str, Sequence[str]]) : the column name(s)\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n cols = to_sequence(cols)\n return Table(j_table=self.j_table.moveColumnsUp(*cols))\n except Exception as e:\n raise DHError(e, \"table move_columns_up operation failed.\") from e\n\n def rename_columns(self, cols: Union[str, Sequence[str]]) -> Table:\n \"\"\"The rename_columns method creates a new table with the specified columns renamed.\n\n Args:\n cols (Union[str, Sequence[str]]) : the column rename expr(s) as \"X = Y\"\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n cols = to_sequence(cols)\n with auto_locking_ctx(self):\n return Table(j_table=self.j_table.renameColumns(*cols))\n except Exception as e:\n raise DHError(e, \"table rename_columns operation failed.\") from e\n\n def update(self, formulas: Union[str, Sequence[str]]) -> Table:\n \"\"\"The update method creates a new table containing a new, in-memory column for each formula.\n\n Args:\n formulas (Union[str, Sequence[str]]): the column formula(s)\n\n Returns:\n A new table\n\n Raises:\n DHError\n \"\"\"\n try:\n formulas = to_sequence(formulas)\n with _query_scope_ctx(), auto_locking_ctx(self):\n return Table(j_table=self.j_table.update(*formulas))\n except Exception as e:\n raise DHError(e, \"table update operation failed.\") from e\n\n def lazy_update(self, formulas: Union[str, Sequence[str]]) -> Table:\n \"\"\"The lazy_update method creates a new table containing a new, cached, formula column for each formula.\n\n Args:\n formulas (Union[str, Sequence[str]]): the column formula(s)\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n formulas = to_sequence(formulas)\n with _query_scope_ctx(), auto_locking_ctx(self):\n return Table(j_table=self.j_table.lazyUpdate(*formulas))\n except Exception as e:\n raise DHError(e, \"table lazy_update operation failed.\") from e\n\n def view(self, formulas: Union[str, Sequence[str]]) -> Table:\n \"\"\"The view method creates a new formula table that includes one column for each formula.\n\n Args:\n formulas (Union[str, Sequence[str]]): the column formula(s)\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n formulas = to_sequence(formulas)\n with _query_scope_ctx():\n return Table(j_table=self.j_table.view(*formulas))\n except Exception as e:\n raise DHError(e, \"table view operation failed.\") from e\n\n def update_view(self, formulas: Union[str, Sequence[str]]) -> Table:\n \"\"\"The update_view method creates a new table containing a new, formula column for each formula.\n\n Args:\n formulas (Union[str, Sequence[str]]): the column formula(s)\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n formulas = to_sequence(formulas)\n with _query_scope_ctx():\n return Table(j_table=self.j_table.updateView(*formulas))\n except Exception as e:\n raise DHError(e, \"table update_view operation failed.\") from e\n\n def select(self, formulas: Union[str, Sequence[str]] = None) -> Table:\n \"\"\"The select method creates a new in-memory table that includes one column for each formula. If no formula\n is specified, all columns will be included.\n\n Args:\n formulas (Union[str, Sequence[str]], optional): the column formula(s), default is None\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n with _query_scope_ctx(), auto_locking_ctx(self):\n if not formulas:\n return Table(j_table=self.j_table.select())\n formulas = to_sequence(formulas)\n return Table(j_table=self.j_table.select(*formulas))\n except Exception as e:\n raise DHError(e, \"table select operation failed.\") from e\n\n def select_distinct(self, formulas: Union[str, Sequence[str]] = None) -> Table:\n \"\"\"The select_distinct method creates a new table containing all the unique values for a set of key\n columns. When the selectDistinct method is used on multiple columns, it looks for distinct sets of values in\n the selected columns.\n\n Args:\n formulas (Union[str, Sequence[str]], optional): the column name(s), default is None\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n formulas = to_sequence(formulas)\n with _query_scope_ctx():\n return Table(j_table=self.j_table.selectDistinct(*formulas))\n except Exception as e:\n raise DHError(e, \"table select_distinct operation failed.\") from e\n\n # endregion\n\n #\n # Table operation category: Filter\n #\n # region Filter\n\n def where(self, filters: Union[str, Filter, Sequence[str], Sequence[Filter]] = None) -> Table:\n \"\"\"The where method creates a new table with only the rows meeting the filter criteria in the column(s) of\n the table.\n\n Args:\n filters (Union[str, Filter, Sequence[str], Sequence[Filter]], optional): the filter condition\n expression(s) or Filter object(s), default is None\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n filters = to_sequence(filters)\n with _query_scope_ctx():\n return Table(j_table=self.j_table.where(and_(filters).j_filter))\n except Exception as e:\n raise DHError(e, \"table where operation failed.\") from e\n\n def where_in(self, filter_table: Table, cols: Union[str, Sequence[str]]) -> Table:\n \"\"\"The where_in method creates a new table containing rows from the source table, where the rows match\n values in the filter table. The filter is updated whenever either table changes.\n\n Args:\n filter_table (Table): the table containing the set of values to filter on\n cols (Union[str, Sequence[str]]): the column name(s)\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n cols = to_sequence(cols)\n with auto_locking_ctx(self, filter_table):\n return Table(j_table=self.j_table.whereIn(filter_table.j_table, *cols))\n except Exception as e:\n raise DHError(e, \"table where_in operation failed.\") from e\n\n def where_not_in(self, filter_table: Table, cols: Union[str, Sequence[str]]) -> Table:\n \"\"\"The where_not_in method creates a new table containing rows from the source table, where the rows do not\n match values in the filter table.\n\n Args:\n filter_table (Table): the table containing the set of values to filter on\n cols (Union[str, Sequence[str]]): the column name(s)\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n cols = to_sequence(cols)\n with auto_locking_ctx(self, filter_table):\n return Table(j_table=self.j_table.whereNotIn(filter_table.j_table, *cols))\n except Exception as e:\n raise DHError(e, \"table where_not_in operation failed.\") from e\n\n def where_one_of(self, filters: Union[str, Filter, Sequence[str], Sequence[Filter]] = None) -> Table:\n \"\"\"The where_one_of method creates a new table containing rows from the source table, where the rows match at\n least one filter.\n\n Args:\n filters (Union[str, Filter, Sequence[str], Sequence[Filter]], optional): the filter condition expression(s), default is None\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n filters = to_sequence(filters)\n with _query_scope_ctx():\n return Table(j_table=self.j_table.where(or_(filters).j_filter))\n except Exception as e:\n raise DHError(e, \"table where_one_of operation failed.\") from e\n\n def head(self, num_rows: int) -> Table:\n \"\"\"The head method creates a new table with a specific number of rows from the beginning of the table.\n\n Args:\n num_rows (int): the number of rows at the head of table\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n return Table(j_table=self.j_table.head(num_rows))\n except Exception as e:\n raise DHError(e, \"table head operation failed.\") from e\n\n def head_pct(self, pct: float) -> Table:\n \"\"\"The head_pct method creates a new table with a specific percentage of rows from the beginning of the table.\n\n Args:\n pct (float): the percentage of rows to return as a value from 0 (0%) to 1 (100%).\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n return Table(j_table=self.j_table.headPct(pct))\n except Exception as e:\n raise DHError(e, \"table head_pct operation failed.\") from e\n\n def tail(self, num_rows: int) -> Table:\n \"\"\"The tail method creates a new table with a specific number of rows from the end of the table.\n\n Args:\n num_rows (int): the number of rows at the end of table\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n return Table(j_table=self.j_table.tail(num_rows))\n except Exception as e:\n raise DHError(e, \"table tail operation failed.\") from e\n\n def tail_pct(self, pct: float) -> Table:\n \"\"\"The tail_pct method creates a new table with a specific percentage of rows from the end of the table.\n\n Args:\n pct (float): the percentage of rows to return as a value from 0 (0%) to 1 (100%).\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n return Table(j_table=self.j_table.tailPct(pct))\n except Exception as e:\n raise DHError(e, \"table tail_pct operation failed.\") from e\n\n # endregion\n\n #\n # Table operation category: Sort\n #\n # region Sort\n def restrict_sort_to(self, cols: Union[str, Sequence[str]]):\n \"\"\"The restrict_sort_to method adjusts the input table to produce an output table that only allows sorting on\n specified table columns. This can be useful to prevent users from accidentally performing expensive sort\n operations as they interact with tables in the UI.\n\n Args:\n cols (Union[str, Sequence[str]]): the column name(s)\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n cols = to_sequence(cols)\n return Table(self.j_table.restrictSortTo(*cols))\n except Exception as e:\n raise DHError(e, \"table restrict_sort_to operation failed.\") from e\n\n def sort_descending(self, order_by: Union[str, Sequence[str]]) -> Table:\n \"\"\"The sort_descending method creates a new table where rows in a table are sorted in descending order based on\n the order_by column(s).\n\n Args:\n order_by (Union[str, Sequence[str]], optional): the column name(s)\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n order_by = to_sequence(order_by)\n return Table(j_table=self.j_table.sortDescending(*order_by))\n except Exception as e:\n raise DHError(e, \"table sort_descending operation failed.\") from e\n\n def reverse(self) -> Table:\n \"\"\"The reverse method creates a new table with all of the rows from this table in reverse order.\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n return Table(j_table=self.j_table.reverse())\n except Exception as e:\n raise DHError(e, \"table reverse operation failed.\") from e\n\n def sort(self, order_by: Union[str, Sequence[str]],\n order: Union[SortDirection, Sequence[SortDirection]] = None) -> Table:\n \"\"\"The sort method creates a new table where the rows are ordered based on values in a specified set of columns.\n\n Args:\n order_by (Union[str, Sequence[str]]): the column(s) to be sorted on\n order (Union[SortDirection, Sequence[SortDirection], optional): the corresponding sort directions for\n each sort column, default is None, meaning ascending order for all the sort columns.\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n\n try:\n order_by = to_sequence(order_by)\n if not order:\n order = (SortDirection.ASCENDING,) * len(order_by)\n order = to_sequence(order)\n if len(order_by) != len(order):\n raise DHError(message=\"The number of sort columns must be the same as the number of sort directions.\")\n\n sort_columns = [_sort_column(col, dir_) for col, dir_ in zip(order_by, order)]\n j_sc_list = j_array_list(sort_columns)\n return Table(j_table=self.j_table.sort(j_sc_list))\n except Exception as e:\n raise DHError(e, \"table sort operation failed.\") from e\n\n # endregion\n\n #\n # Table operation category: Join\n #\n # region Join\n\n def natural_join(self, table: Table, on: Union[str, Sequence[str]],\n joins: Union[str, Sequence[str]] = None) -> Table:\n \"\"\"The natural_join method creates a new table containing all the rows and columns of this table,\n plus additional columns containing data from the right table. For columns appended to the left table (joins),\n row values equal the row values from the right table where the key values in the left and right tables are\n equal. If there is no matching key in the right table, appended row values are NULL.\n\n Args:\n table (Table): the right-table of the join\n on (Union[str, Sequence[str]]): the column(s) to match, can be a common name or an equal expression,\n i.e. \"col_a = col_b\" for different column names\n joins (Union[str, Sequence[str]], optional): the column(s) to be added from the right table to the result\n table, can be renaming expressions, i.e. \"new_col = col\"; default is None\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n on = to_sequence(on)\n joins = to_sequence(joins)\n with auto_locking_ctx(self, table):\n if joins:\n return Table(\n j_table=self.j_table.naturalJoin(\n table.j_table, \",\".join(on), \",\".join(joins)\n )\n )\n else:\n return Table(\n j_table=self.j_table.naturalJoin(table.j_table, \",\".join(on))\n )\n except Exception as e:\n raise DHError(e, \"table natural_join operation failed.\") from e\n\n def exact_join(self, table: Table, on: Union[str, Sequence[str]], joins: Union[str, Sequence[str]] = None) -> Table:\n \"\"\"The exact_join method creates a new table containing all the rows and columns of this table plus\n additional columns containing data from the right table. For columns appended to the left table (joins),\n row values equal the row values from the right table where the key values in the left and right tables are\n equal.\n\n Args:\n table (Table): the right-table of the join\n on (Union[str, Sequence[str]]): the column(s) to match, can be a common name or an equal expression,\n i.e. \"col_a = col_b\" for different column names\n joins (Union[str, Sequence[str]], optional): the column(s) to be added from the right table to the result\n table, can be renaming expressions, i.e. \"new_col = col\"; default is None\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n on = to_sequence(on)\n joins = to_sequence(joins)\n with auto_locking_ctx(self, table):\n if joins:\n return Table(\n j_table=self.j_table.exactJoin(\n table.j_table, \",\".join(on), \",\".join(joins)\n )\n )\n else:\n return Table(\n j_table=self.j_table.exactJoin(table.j_table, \",\".join(on))\n )\n except Exception as e:\n raise DHError(e, \"table exact_join operation failed.\") from e\n\n def join(self, table: Table, on: Union[str, Sequence[str]] = None,\n joins: Union[str, Sequence[str]] = None) -> Table:\n \"\"\"The join method creates a new table containing rows that have matching values in both tables. Rows that\n do not have matching criteria will not be included in the result. If there are multiple matches between a row\n from the left table and rows from the right table, all matching combinations will be included. If no columns\n to match (on) are specified, every combination of left and right table rows is included.\n\n Args:\n table (Table): the right-table of the join\n on (Union[str, Sequence[str]]): the column(s) to match, can be a common name or an equal expression,\n i.e. \"col_a = col_b\" for different column names; default is None\n joins (Union[str, Sequence[str]], optional): the column(s) to be added from the right table to the result\n table, can be renaming expressions, i.e. \"new_col = col\"; default is None\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n on = to_sequence(on)\n joins = to_sequence(joins)\n with auto_locking_ctx(self, table):\n if joins:\n return Table(\n j_table=self.j_table.join(\n table.j_table, \",\".join(on), \",\".join(joins)\n )\n )\n else:\n return Table(j_table=self.j_table.join(table.j_table, \",\".join(on)))\n except Exception as e:\n raise DHError(e, \"table join operation failed.\") from e\n\n def aj(self, table: Table, on: Union[str, Sequence[str]], joins: Union[str, Sequence[str]] = None) -> Table:\n \"\"\"The aj (as-of join) method creates a new table containing all the rows and columns of the left table,\n plus additional columns containing data from the right table. For columns appended to the left table (joins),\n row values equal the row values from the right table where the keys from the left table most closely match\n the keys from the right table without going over. If there is no matching key in the right table, appended row\n values are NULL.\n\n Args:\n table (Table): the right-table of the join\n on (Union[str, Sequence[str]]): the column(s) to match, can be a common name or a match condition of two\n columns, e.g. 'col_a = col_b'. The first 'N-1' matches are exact matches. The final match is an inexact\n match. The inexact match can use either '>' or '>='. If a common name is used for the inexact match,\n '>=' is used for the comparison.\n joins (Union[str, Sequence[str]], optional): the column(s) to be added from the right table to the result\n table, can be renaming expressions, i.e. \"new_col = col\"; default is None\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n on = \",\".join(to_sequence(on))\n joins = \",\".join(to_sequence(joins))\n table_op = jpy.cast(self.j_object, _JTableOperations)\n with auto_locking_ctx(self, table):\n return Table(j_table=table_op.aj(table.j_table, on, joins))\n except Exception as e:\n raise DHError(e, \"table as-of join operation failed.\") from e\n\n def raj(self, table: Table, on: Union[str, Sequence[str]], joins: Union[str, Sequence[str]] = None) -> Table:\n \"\"\"The reverse-as-of join method creates a new table containing all the rows and columns of the left table,\n plus additional columns containing data from the right table. For columns appended to the left table (joins),\n row values equal the row values from the right table where the keys from the left table most closely match\n the keys from the right table without going under. If there is no matching key in the right table, appended row\n values are NULL.\n\n Args:\n table (Table): the right-table of the join\n on (Union[str, Sequence[str]]): the column(s) to match, can be a common name or a match condition of two\n columns, e.g. 'col_a = col_b'. The first 'N-1' matches are exact matches. The final match is an inexact\n match. The inexact match can use either '<' or '<='. If a common name is used for the inexact match,\n '<=' is used for the comparison.\n joins (Union[str, Sequence[str]], optional): the column(s) to be added from the right table to the result\n table, can be renaming expressions, i.e. \"new_col = col\"; default is None\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n on = \",\".join(to_sequence(on))\n joins = \",\".join(to_sequence(joins))\n table_op = jpy.cast(self.j_object, _JTableOperations)\n with auto_locking_ctx(self, table):\n return Table(j_table=table_op.raj(table.j_table, on, joins))\n except Exception as e:\n raise DHError(e, \"table reverse-as-of join operation failed.\") from e\n\n def range_join(self, table: Table, on: Union[str, List[str]], aggs: Union[Aggregation, List[Aggregation]]) -> Table:\n \"\"\"The range_join method creates a new table containing all the rows and columns of the left table,\n plus additional columns containing aggregated data from the right table. For columns appended to the\n left table (joins), cell values equal aggregations over vectors of values from the right table.\n These vectors are formed from all values in the right table where the right table keys fall within the\n ranges of keys defined by the left table (responsive ranges).\n\n range_join is a join plus aggregation that (1) joins arrays of data from the right table onto the left table,\n and then (2) aggregates over the joined data. Oftentimes this is used to join data for a particular time range\n from the right table onto the left table.\n\n Rows from the right table with null or NaN key values are discarded; that is, they are never included in the\n vectors used for aggregation. For all rows that are not discarded, the right table must be sorted according\n to the right range column for all rows within a group.\n\n Join key ranges, specified by the 'on' argument, are defined by zero-or-more exact join matches and a single\n range join match. The range join match must be the last match in the list.\n\n The exact match expressions are parsed as in other join operations. That is, they are either a column name\n common to both tables or a column name from the left table followed by an equals sign followed by a column\n name from the right table.\n Examples:\n Match on the same column name in both tables:\n \"common_column\"\n Match on different column names in each table:\n \"left_column = right_column\"\n or\n \"left_column == right_column\"\n\n The range match expression is expressed as a ternary logical expression, expressing the relationship between\n the left start column, the right range column, and the left end column. Each column name pair is separated by\n a logical operator, either < or <=. Additionally, the entire expression may be preceded by a left arrow <-\n and/or followed by a right arrow ->. The arrows indicate that range match can 'allow preceding' or 'allow\n following' to match values outside the explicit range. 'Allow preceding' means that if no matching right\n range column value is equal to the left start column value, the immediately preceding matching right row\n should be included in the aggregation if such a row exists. 'Allow following' means that if no matching right\n range column value is equal to the left end column value, the immediately following matching right row should\n be included in the aggregation if such a row exists.\n Examples:\n For less than paired with greater than:\n \"left_start_column < right_range_column < left_end_column\"\n For less than or equal paired with greater than or equal:\n \"left_start_column <= right_range_column <= left_end_column\"\n For less than or equal (allow preceding) paired with greater than or equal (allow following):\n \"<- left_start_column <= right_range_column <= left_end_column ->\"\n\n Special Cases\n In order to produce aggregated output, range match expressions must define a range of values to aggregate\n over. There are a few noteworthy special cases of ranges.\n\n Empty Range\n An empty range occurs for any left row with no matching right rows. That is, no non-null, non-NaN right\n rows were found using the exact join matches, or none were in range according to the range join match.\n\n Single-value Ranges\n A single-value range is a range where the left row's values for the left start column and left end\n column are equal and both relative matches are inclusive (<= and >=, respectively). For a single-value\n range, only rows within the bucket where the right range column matches the single value are included in\n the output aggregations.\n\n Invalid Ranges\n An invalid range occurs in two scenarios:\n (1) When the range is inverted, i.e., when the value of the left start column is greater than the value\n of the left end column.\n (2) When either relative-match is exclusive (< or >) and the value in the left start column is equal to\n the value in the left end column.\n For invalid ranges, the result row will be null for all aggregation output columns.\n\n Undefined Ranges\n An undefined range occurs when either the left start column or the left end column is NaN. For rows with an\n undefined range, the corresponding output values will be null (as with invalid ranges).\n\n Unbounded Ranges\n A partially or fully unbounded range occurs when either the left start column or the left end column is\n null. If the left start column value is null and the left end column value is non-null, the range is\n unbounded at the beginning, and only the left end column subexpression will be used for the match. If the\n left start column value is non-null and the left end column value is null, the range is unbounded at the\n end, and only the left start column subexpression will be used for the match. If the left start column\n and left end column values are null, the range is unbounded, and all rows will be included.\n\n Note: At this time, implementations only support static tables. This operation remains under active development.\n\n Args:\n table (Table): the right table of the join\n on (Union[str, List[str]]): the match expression(s) that must include zero-or-more exact match expression,\n and exactly one range match expression as described above\n aggs (Union[Aggregation, List[Aggregation]]): the aggregation(s) to perform over the responsive ranges from\n the right table for each row from this Table\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n on = to_sequence(on)\n aggs = to_sequence(aggs)\n j_agg_list = j_array_list([agg.j_aggregation for agg in aggs])\n return Table(j_table=self.j_table.rangeJoin(table.j_table, j_array_list(on), j_agg_list))\n except Exception as e:\n raise DHError(e, message=\"table range_join operation failed.\") from e\n\n # endregion\n\n #\n # Table operation category: Aggregation\n # region Aggregation\n\n def head_by(self, num_rows: int, by: Union[str, Sequence[str]] = None) -> Table:\n \"\"\"The head_by method creates a new table containing the first number of rows for each group.\n\n Args:\n num_rows (int): the number of rows at the beginning of each group\n by (Union[str, Sequence[str]]): the group-by column name(s), default is None\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n by = to_sequence(by)\n with auto_locking_ctx(self):\n return Table(j_table=self.j_table.headBy(num_rows, *by))\n except Exception as e:\n raise DHError(e, \"table head_by operation failed.\") from e\n\n def tail_by(self, num_rows: int, by: Union[str, Sequence[str]] = None) -> Table:\n \"\"\"The tail_by method creates a new table containing the last number of rows for each group.\n\n Args:\n num_rows (int): the number of rows at the end of each group\n by (Union[str, Sequence[str]]): the group-by column name(s), default is None\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n by = to_sequence(by)\n with auto_locking_ctx(self):\n return Table(j_table=self.j_table.tailBy(num_rows, *by))\n except Exception as e:\n raise DHError(e, \"table tail_by operation failed.\") from e\n\n def group_by(self, by: Union[str, Sequence[str]] = None) -> Table:\n \"\"\"The group_by method creates a new table containing grouping columns and grouped data, column content is\n grouped into vectors.\n\n Args:\n by (Union[str, Sequence[str]], optional): the group-by column name(s), default is None\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n by = to_sequence(by)\n if by:\n return Table(j_table=self.j_table.groupBy(*by))\n else:\n return Table(j_table=self.j_table.groupBy())\n except Exception as e:\n raise DHError(e, \"table group-by operation failed.\") from e\n\n def ungroup(self, cols: Union[str, Sequence[str]] = None) -> Table:\n \"\"\"The ungroup method creates a new table in which array columns from the source table are unwrapped into\n separate rows.\n\n Args:\n cols (Union[str, Sequence[str]], optional): the name(s) of the array column(s), if None, all array columns\n will be ungrouped, default is None\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n cols = to_sequence(cols)\n with auto_locking_ctx(self):\n if cols:\n return Table(j_table=self.j_table.ungroup(*cols))\n else:\n return Table(j_table=self.j_table.ungroup())\n except Exception as e:\n raise DHError(e, \"table ungroup operation failed.\") from e\n\n def first_by(self, by: Union[str, Sequence[str]] = None) -> Table:\n \"\"\"The first_by method creates a new table containing the first row for each group.\n\n Args:\n by (Union[str, Sequence[str]], optional): the group-by column name(s), default is None\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n by = to_sequence(by)\n if by:\n return Table(j_table=self.j_table.firstBy(*by))\n else:\n return Table(j_table=self.j_table.firstBy())\n except Exception as e:\n raise DHError(e, \"table first_by operation failed.\") from e\n\n def last_by(self, by: Union[str, Sequence[str]] = None) -> Table:\n \"\"\"The last_by method creates a new table containing the last row for each group.\n\n Args:\n by (Union[str, Sequence[str]], optional): the group-by column name(s), default is None\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n by = to_sequence(by)\n if by:\n return Table(j_table=self.j_table.lastBy(*by))\n else:\n return Table(j_table=self.j_table.lastBy())\n except Exception as e:\n raise DHError(e, \"table last_by operation failed.\") from e\n\n def sum_by(self, by: Union[str, Sequence[str]] = None) -> Table:\n \"\"\"The sum_by method creates a new table containing the sum for each group.\n\n Args:\n by (Union[str, Sequence[str]], optional): the group-by column name(s), default is None\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n by = to_sequence(by)\n if by:\n return Table(j_table=self.j_table.sumBy(*by))\n else:\n return Table(j_table=self.j_table.sumBy())\n except Exception as e:\n raise DHError(e, \"table sum_by operation failed.\") from e\n\n def abs_sum_by(self, by: Union[str, Sequence[str]] = None) -> Table:\n \"\"\"The abs_sum_by method creates a new table containing the absolute sum for each group.\n\n Args:\n by (Union[str, Sequence[str]], optional): the group-by column name(s), default is None\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n by = to_sequence(by)\n if by:\n return Table(j_table=self.j_table.absSumBy(*by))\n else:\n return Table(j_table=self.j_table.absSumBy())\n except Exception as e:\n raise DHError(e, \"table asb_sum_by operation failed.\") from e\n\n def weighted_sum_by(self, wcol: str, by: Union[str, Sequence[str]] = None) -> Table:\n \"\"\"The weighted_sum_by method creates a new table containing the weighted sum for each group.\n\n Args:\n wcol (str): the name of the weight column\n by (Union[str, Sequence[str]], optional): the group-by column name(s), default is None\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n by = to_sequence(by)\n if by:\n return Table(j_table=self.j_table.wsumBy(wcol, *by))\n else:\n return Table(j_table=self.j_table.wsumBy(wcol))\n except Exception as e:\n raise DHError(e, \"table weighted_sum_by operation failed.\") from e\n\n def avg_by(self, by: Union[str, Sequence[str]] = None) -> Table:\n \"\"\"The avg_by method creates a new table containing the average for each group.\n\n Args:\n by (Union[str, Sequence[str]], optional): the group-by column name(s), default is None\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n by = to_sequence(by)\n if by:\n return Table(j_table=self.j_table.avgBy(*by))\n else:\n return Table(j_table=self.j_table.avgBy())\n except Exception as e:\n raise DHError(e, \"table avg_by operation failed.\") from e\n\n def weighted_avg_by(self, wcol: str, by: Union[str, Sequence[str]] = None) -> Table:\n \"\"\"The weighted_avg_by method creates a new table containing the weighted average for each group.\n\n Args:\n wcol (str): the name of the weight column\n by (Union[str, Sequence[str]], optional): the group-by column name(s), default is None\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n by = to_sequence(by)\n if by:\n return Table(j_table=self.j_table.wavgBy(wcol, *by))\n else:\n return Table(j_table=self.j_table.wavgBy(wcol))\n except Exception as e:\n raise DHError(e, \"table avg_by operation failed.\") from e\n\n def std_by(self, by: Union[str, Sequence[str]] = None) -> Table:\n \"\"\"The std_by method creates a new table containing the sample standard deviation for each group.\n\n Sample standard deviation is computed using `Bessel's correction `_,\n which ensures that the sample variance will be an unbiased estimator of population variance.\n\n Args:\n by (Union[str, Sequence[str]], optional): the group-by column name(s), default is None\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n by = to_sequence(by)\n if by:\n return Table(j_table=self.j_table.stdBy(*by))\n else:\n return Table(j_table=self.j_table.stdBy())\n except Exception as e:\n raise DHError(e, \"table std_by operation failed.\") from e\n\n def var_by(self, by: Union[str, Sequence[str]] = None) -> Table:\n \"\"\"The var_by method creates a new table containing the sample variance for each group.\n\n Sample variance is computed using `Bessel's correction `_,\n which ensures that the sample variance will be an unbiased estimator of population variance.\n\n Args:\n by (Union[str, Sequence[str]], optional): the group-by column name(s), default is None\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n by = to_sequence(by)\n if by:\n return Table(j_table=self.j_table.varBy(*by))\n else:\n return Table(j_table=self.j_table.varBy())\n except Exception as e:\n raise DHError(e, \"table var_by operation failed.\") from e\n\n def median_by(self, by: Union[str, Sequence[str]] = None) -> Table:\n \"\"\"The median_by method creates a new table containing the median for each group.\n\n Args:\n by (Union[str, Sequence[str]], optional): the group-by column name(s), default is None\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n by = to_sequence(by)\n if by:\n return Table(j_table=self.j_table.medianBy(*by))\n else:\n return Table(j_table=self.j_table.medianBy())\n except Exception as e:\n raise DHError(e, \"table median_by operation failed.\") from e\n\n def min_by(self, by: Union[str, Sequence[str]] = None) -> Table:\n \"\"\"The min_by method creates a new table containing the minimum value for each group.\n\n Args:\n by (Union[str, Sequence[str]], optional): the group-by column name(s), default is None\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n by = to_sequence(by)\n if by:\n return Table(j_table=self.j_table.minBy(*by))\n else:\n return Table(j_table=self.j_table.minBy())\n except Exception as e:\n raise DHError(e, \"table min_by operation failed.\") from e\n\n def max_by(self, by: Union[str, Sequence[str]] = None) -> Table:\n \"\"\"The max_by method creates a new table containing the maximum value for each group.\n\n Args:\n by (Union[str, Sequence[str]], optional): the group-by column name(s), default is None\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n by = to_sequence(by)\n if by:\n return Table(j_table=self.j_table.maxBy(*by))\n else:\n return Table(j_table=self.j_table.maxBy())\n except Exception as e:\n raise DHError(e, \"table max_by operation failed.\") from e\n\n def count_by(self, col: str, by: Union[str, Sequence[str]] = None) -> Table:\n \"\"\"The count_by method creates a new table containing the number of rows for each group.\n\n Args:\n col (str): the name of the column to store the counts\n by (Union[str, Sequence[str]], optional): the group-by column name(s), default is None\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n by = to_sequence(by)\n if by:\n return Table(j_table=self.j_table.countBy(col, *by))\n else:\n return Table(j_table=self.j_table.countBy(col))\n except Exception as e:\n raise DHError(e, \"table count_by operation failed.\") from e\n\n def agg_by(self, aggs: Union[Aggregation, Sequence[Aggregation]], by: Union[str, Sequence[str]] = None,\n preserve_empty: bool = False, initial_groups: Table = None) -> Table:\n \"\"\"The agg_by method creates a new table containing grouping columns and grouped data. The resulting\n grouped data is defined by the aggregations specified.\n\n Args:\n aggs (Union[Aggregation, Sequence[Aggregation]]): the aggregation(s)\n by (Union[str, Sequence[str]]): the group-by column name(s), if not provided, all rows from this table are\n grouped into a single group of rows before the aggregations are applied to the result, default is None.\n preserve_empty (bool): whether to keep result rows for groups that are initially empty or become empty as\n a result of updates. Each aggregation operator defines its own value for empty groups. Default is False.\n initial_groups (Table): a table whose distinct combinations of values for the group-by column(s)\n should be used to create an initial set of aggregation groups. All other columns are ignored. This is\n useful in combination with preserve_empty=True to ensure that particular groups appear in the result\n table, or with preserve_empty=False to control the encounter order for a collection of groups and\n thus their relative order in the result. Changes to this table are not expected or handled; if this\n table is a refreshing table, only its contents at instantiation time will be used. Default is None,\n the result will be the same as if a table is provided but no rows were supplied. When it is provided,\n the 'by' argument must be provided to explicitly specify the grouping columns.\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n aggs = to_sequence(aggs)\n by = to_sequence(by)\n if not by and initial_groups:\n raise ValueError(\"missing group-by column names when initial_groups is provided.\")\n j_agg_list = j_array_list([agg.j_aggregation for agg in aggs])\n\n cm = _query_scope_agg_ctx(aggs)\n with cm:\n if not by:\n return Table(j_table=self.j_table.aggBy(j_agg_list, preserve_empty))\n else:\n j_column_name_list = j_array_list([_JColumnName.of(col) for col in by])\n initial_groups = unwrap(initial_groups)\n return Table(\n j_table=self.j_table.aggBy(j_agg_list, preserve_empty, initial_groups, j_column_name_list))\n except Exception as e:\n raise DHError(e, \"table agg_by operation failed.\") from e\n\n def partitioned_agg_by(self, aggs: Union[Aggregation, Sequence[Aggregation]],\n by: Union[str, Sequence[str]] = None, preserve_empty: bool = False,\n initial_groups: Table = None) -> PartitionedTable:\n \"\"\"The partitioned_agg_by method is a convenience method that performs an agg_by operation on this table and\n wraps the result in a PartitionedTable. If the argument 'aggs' does not include a partition aggregation\n created by calling :py:func:`agg.partition`, one will be added automatically with the default constituent column\n name __CONSTITUENT__.\n\n Args:\n aggs (Union[Aggregation, Sequence[Aggregation]]): the aggregation(s)\n by (Union[str, Sequence[str]]): the group-by column name(s), default is None\n preserve_empty (bool): whether to keep result rows for groups that are initially empty or become empty as\n a result of updates. Each aggregation operator defines its own value for empty groups. Default is False.\n initial_groups (Table): a table whose distinct combinations of values for the group-by column(s)\n should be used to create an initial set of aggregation groups. All other columns are ignored. This is\n useful in combination with preserve_empty=True to ensure that particular groups appear in the result\n table, or with preserve_empty=False to control the encounter order for a collection of groups and\n thus their relative order in the result. Changes to this table are not expected or handled; if this\n table is a refreshing table, only its contents at instantiation time will be used. Default is None,\n the result will be the same as if a table is provided but no rows were supplied. When it is provided,\n the 'by' argument must be provided to explicitly specify the grouping columns.\n\n Returns:\n a PartitionedTable\n\n Raises:\n DHError\n \"\"\"\n try:\n aggs = to_sequence(aggs)\n by = to_sequence(by)\n j_agg_list = j_array_list([agg.j_aggregation for agg in aggs])\n initial_groups = unwrap(initial_groups)\n\n cm = _query_scope_agg_ctx(aggs)\n with cm:\n return PartitionedTable(\n j_partitioned_table=self.j_table.partitionedAggBy(j_agg_list, preserve_empty, initial_groups, *by))\n except Exception as e:\n raise DHError(e, \"table partitioned_agg_by operation failed.\") from e\n\n def agg_all_by(self, agg: Aggregation, by: Union[str, Sequence[str]] = None) -> Table:\n \"\"\"The agg_all_by method creates a new table containing grouping columns and grouped data. The resulting\n grouped data is defined by the aggregation specified.\n\n Note, because agg_all_by applies the aggregation to all the columns of the table, it will ignore\n any column names specified for the aggregation.\n\n Args:\n agg (Aggregation): the aggregation\n by (Union[str, Sequence[str]], optional): the group-by column name(s), default is None\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n by = to_sequence(by)\n cm = _query_scope_agg_ctx([agg])\n with cm:\n return Table(j_table=self.j_table.aggAllBy(agg.j_agg_spec, *by))\n except Exception as e:\n raise DHError(e, \"table agg_all_by operation failed.\") from e\n\n # endregion\n\n def format_columns(self, formulas: Union[str, List[str]]) -> Table:\n \"\"\" Applies color formatting to the columns of the table.\n\n Args:\n formulas (Union[str, List[str]]): formatting string(s) in the form of \"column=color_expression\"\n where color_expression can be a color name or a Java ternary expression that results in a color.\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n formulas = to_sequence(formulas)\n return Table(j_table=self.j_table.formatColumns(formulas))\n except Exception as e:\n raise DHError(e, \"failed to color format columns.\") from e\n\n def format_column_where(self, col: str, cond: str, formula: str) -> Table:\n \"\"\" Applies color formatting to a column of the table conditionally.\n\n Args:\n col (str): the column name\n cond (str): the condition expression\n formula (str): the formatting string in the form of assignment expression \"column=color expression\"\n where color_expression can be a color name or a Java ternary expression that results in a color.\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n return Table(j_table=self.j_table.formatColumnWhere(col, cond, formula))\n except Exception as e:\n raise DHError(e, \"failed to color format column conditionally.\") from e\n\n def format_row_where(self, cond: str, formula: str) -> Table:\n \"\"\" Applies color formatting to rows of the table conditionally.\n\n Args:\n cond (str): the condition expression\n formula (str): the formatting string in the form of assignment expression \"column=color expression\"\n where color_expression can be a color name or a Java ternary expression that results in a color.\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n return Table(j_table=self.j_table.formatRowWhere(cond, formula))\n except Exception as e:\n raise DHError(e, \"failed to color format rows conditionally.\") from e\n\n def layout_hints(self, front: Union[str, List[str]] = None, back: Union[str, List[str]] = None,\n freeze: Union[str, List[str]] = None, hide: Union[str, List[str]] = None,\n column_groups: List[dict] = None, search_display_mode: SearchDisplayMode = None) -> Table:\n \"\"\" Sets layout hints on the Table\n\n Args:\n front (Union[str, List[str]]): the columns to show at the front.\n back (Union[str, List[str]]): the columns to show at the back.\n freeze (Union[str, List[str]]): the columns to freeze to the front.\n These will not be affected by horizontal scrolling.\n hide (Union[str, List[str]]): the columns to hide.\n column_groups (List[Dict]): A list of dicts specifying which columns should be grouped in the UI.\n The dicts can specify the following:\n\n * name (str): The group name\n * children (List[str]): The column names in the group\n * color (Optional[str]): The hex color string or Deephaven color name\n search_display_mode (SearchDisplayMode): set the search bar to explicitly be accessible or inaccessible,\n or use the system default. :attr:`SearchDisplayMode.SHOW` will show the search bar,\n :attr:`SearchDisplayMode.HIDE` will hide the search bar, and :attr:`SearchDisplayMode.DEFAULT` will\n use the default value configured by the user and system settings.\n\n Returns:\n a new table with the layout hints set\n\n Raises:\n DHError\n \"\"\"\n try:\n _j_layout_hint_builder = _JLayoutHintBuilder.get()\n\n if front is not None:\n _j_layout_hint_builder.atFront(to_sequence(front))\n\n if back is not None:\n _j_layout_hint_builder.atBack(to_sequence(back))\n\n if freeze is not None:\n _j_layout_hint_builder.freeze(to_sequence(freeze))\n\n if hide is not None:\n _j_layout_hint_builder.hide(to_sequence(hide))\n\n if column_groups is not None:\n for group in column_groups:\n _j_layout_hint_builder.columnGroup(group.get(\"name\"), j_array_list(group.get(\"children\")),\n group.get(\"color\", \"\"))\n\n if search_display_mode is not None:\n _j_layout_hint_builder.setSearchBarAccess(search_display_mode.value)\n\n except Exception as e:\n raise DHError(e, \"failed to create layout hints\") from e\n\n try:\n return Table(j_table=self.j_table.setLayoutHints(_j_layout_hint_builder.build()))\n except Exception as e:\n raise DHError(e, \"failed to set layout hints on table\") from e\n\n def partition_by(self, by: Union[str, Sequence[str]], drop_keys: bool = False) -> PartitionedTable:\n \"\"\" Creates a PartitionedTable from this table, partitioned according to the specified key columns.\n\n Args:\n by (Union[str, Sequence[str]]): the column(s) by which to group data\n drop_keys (bool): whether to drop key columns in the constituent tables, default is False\n\n Returns:\n A PartitionedTable containing a sub-table for each group\n\n Raises:\n DHError\n \"\"\"\n try:\n by = to_sequence(by)\n return PartitionedTable(j_partitioned_table=self.j_table.partitionBy(drop_keys, *by))\n except Exception as e:\n raise DHError(e, \"failed to create a partitioned table.\") from e\n\n def update_by(self, ops: Union[UpdateByOperation, List[UpdateByOperation]],\n by: Union[str, List[str]] = None) -> Table:\n \"\"\"Creates a table with additional columns calculated from window-based aggregations of columns in this table.\n The aggregations are defined by the provided operations, which support incremental aggregations over the\n corresponding rows in the table. The aggregations will apply position or time-based windowing and\n compute the results over the entire table or each row group as identified by the provided key columns.\n\n Args:\n ops (Union[UpdateByOperation, List[UpdateByOperation]]): the update-by operation definition(s)\n by (Union[str, List[str]]): the key column name(s) to group the rows of the table\n\n Returns:\n a new Table\n\n Raises:\n DHError\n \"\"\"\n try:\n ops = to_sequence(ops)\n by = to_sequence(by)\n with auto_locking_ctx(self):\n return Table(j_table=self.j_table.updateBy(j_array_list(ops), *by))\n except Exception as e:\n raise DHError(e, \"table update-by operation failed.\") from e\n\n def slice(self, start: int, stop: int) -> Table:\n \"\"\"Extracts a subset of a table by row positions into a new Table.\n\n If both the start and the stop are positive, then both are counted from the beginning of the table.\n The start is inclusive, and the stop is exclusive. slice(0, N) is equivalent to :meth:`~Table.head` (N)\n The start must be less than or equal to the stop.\n\n If the start is positive and the stop is negative, then the start is counted from the beginning of the\n table, inclusively. The stop is counted from the end of the table. For example, slice(1, -1) includes all\n rows but the first and last. If the stop is before the start, the result is an empty table.\n\n If the start is negative, and the stop is zero, then the start is counted from the end of the table,\n and the end of the slice is the size of the table. slice(-N, 0) is equivalent to :meth:`~Table.tail` (N).\n\n If the start is negative and the stop is negative, they are both counted from the end of the\n table. For example, slice(-2, -1) returns the second to last row of the table.\n\n Args:\n start (int): the first row position to include in the result\n stop (int): the last row position to include in the result\n\n Returns:\n a new Table\n\n Raises:\n DHError\n \"\"\"\n try:\n return Table(j_table=self.j_table.slice(start, stop))\n except Exception as e:\n raise DHError(e, \"table slice operation failed.\") from e\n\n def slice_pct(self, start_pct: float, end_pct: float) -> Table:\n \"\"\"Extracts a subset of a table by row percentages.\n\n Returns a subset of table in the range [floor(start_pct * size_of_table), floor(end_pct * size_of_table)).\n For example, for a table of size 10, slice_pct(0.1, 0.7) will return a subset from the second row to the seventh\n row. Similarly, slice_pct(0, 1) would return the entire table (because row positions run from 0 to size - 1).\n The percentage arguments must be in range [0, 1], otherwise the function returns an error.\n\n Args:\n start_pct (float): the starting percentage point (inclusive) for rows to include in the result, range [0, 1]\n end_pct (float): the ending percentage point (exclusive) for rows to include in the result, range [0, 1]\n\n Returns:\n a new table\n\n Raises:\n DHError\n \"\"\"\n try:\n return Table(j_table=self.j_table.slicePct(start_pct, end_pct))\n except Exception as e:\n raise DHError(e, \"table slice_pct operation failed.\") from e\n\n def rollup(self, aggs: Union[Aggregation, Sequence[Aggregation]], by: Union[str, Sequence[str]] = None,\n include_constituents: bool = False) -> RollupTable:\n \"\"\"Creates a rollup table.\n\n A rollup table aggregates by the specified columns, and then creates a hierarchical table which re-aggregates\n using one less by column on each level. The column that is no longer part of the aggregation key is\n replaced with null on each level.\n\n Note some aggregations can not be used in creating a rollup tables, these include: group, partition, median,\n pct, weighted_avg\n\n Args:\n aggs (Union[Aggregation, Sequence[Aggregation]]): the aggregation(s)\n by (Union[str, Sequence[str]]): the group-by column name(s), default is None\n include_constituents (bool): whether to include the constituent rows at the leaf level, default is False\n\n Returns:\n a new RollupTable\n\n Raises:\n DHError\n \"\"\"\n try:\n aggs = to_sequence(aggs)\n by = to_sequence(by)\n j_agg_list = j_array_list([agg.j_aggregation for agg in aggs])\n\n cm = _query_scope_agg_ctx(aggs)\n with cm:\n if not by:\n return RollupTable(j_rollup_table=self.j_table.rollup(j_agg_list, include_constituents), aggs=aggs,\n include_constituents=include_constituents, by=by)\n else:\n return RollupTable(j_rollup_table=self.j_table.rollup(j_agg_list, include_constituents, by),\n aggs=aggs, include_constituents=include_constituents, by=by)\n except Exception as e:\n raise DHError(e, \"table rollup operation failed.\") from e\n\n def tree(self, id_col: str, parent_col: str, promote_orphans: bool = False) -> TreeTable:\n \"\"\"Creates a hierarchical tree table.\n\n The structure of the table is encoded by an \"id\" and a \"parent\" column. The id column should represent a unique\n identifier for a given row, and the parent column indicates which row is the parent for a given row. Rows that\n have a None parent are part of the \"root\" table.\n\n It is possible for rows to be \"orphaned\" if their parent is non-None and does not exist in the table. These\n rows will not be present in the resulting tree. If this is not desirable, they could be promoted to become\n children of the root table by setting 'promote_orphans' argument to True.\n\n Args:\n id_col (str): the name of a column containing a unique identifier for a particular row in the table\n parent_col (str): the name of a column containing the parent's identifier, {@code null} for rows that are\n part of the root table\n promote_orphans (bool): whether to promote node tables whose parents don't exist to be children of the\n root node, default is False\n\n Returns:\n a new TreeTable organized according to the parent-child relationships expressed by id_col and parent_col\n\n Raises:\n DHError\n \"\"\"\n try:\n if promote_orphans:\n with auto_locking_ctx(self):\n j_table = _JTreeTable.promoteOrphans(self.j_table, id_col, parent_col)\n else:\n j_table = self.j_table\n\n return TreeTable(j_tree_table=j_table.tree(id_col, parent_col), id_col=id_col, parent_col=parent_col)\n except Exception as e:\n raise DHError(e, \"table tree operation failed.\") from e\n\n def await_update(self, timeout: int = None) -> bool:\n \"\"\"Waits until either this refreshing Table is updated or the timeout elapses if provided.\n\n Args:\n timeout (int): the maximum time to wait in milliseconds, default is None, meaning no timeout\n\n Returns:\n True when the table is updated or False when the timeout has been reached.\n\n Raises:\n DHError\n \"\"\"\n if not self.is_refreshing:\n raise DHError(message=\"await_update can only be called on refreshing tables.\")\n\n updated = True\n try:\n if timeout is not None:\n updated = self.j_table.awaitUpdate(timeout)\n else:\n self.j_table.awaitUpdate()\n except Exception as e:\n raise DHError(e, \"await_update was interrupted.\") from e\n else:\n return updated\n\n\nclass PartitionedTable(JObjectWrapper):\n \"\"\"A partitioned table is a table containing tables, known as constituent tables.\n Each constituent table has the same schema.\n\n The partitioned table contains:\n 1. one column containing constituent tables\n 2. key columns (optional)\n 3. non-key columns (optional)\n\n Key values can be used to retrieve constituent tables from the partitioned table and\n can be used to perform operations with other like-keyed partitioned tables.\n \"\"\"\n\n j_object_type = _JPartitionedTable\n\n @property\n def j_object(self) -> jpy.JType:\n return self.j_partitioned_table\n\n def __init__(self, j_partitioned_table):\n self.j_partitioned_table = j_partitioned_table\n self._schema = None\n self._table = None\n self._key_columns = None\n self._unique_keys = None\n self._constituent_column = None\n self._constituent_changes_permitted = None\n self._is_refreshing = None\n\n @classmethod\n def from_partitioned_table(cls,\n table: Table,\n key_cols: Union[str, List[str]] = None,\n unique_keys: bool = None,\n constituent_column: str = None,\n constituent_table_columns: List[Column] = None,\n constituent_changes_permitted: bool = None) -> PartitionedTable:\n \"\"\"Creates a PartitionedTable from the provided underlying partitioned Table.\n\n Note: key_cols, unique_keys, constituent_column, constituent_table_columns,\n constituent_changes_permitted must either be all None or all have values. When they are None, their values will\n be inferred as follows:\n\n | * key_cols: the names of all columns with a non-Table data type\n | * unique_keys: False\n | * constituent_column: the name of the first column with a Table data type\n | * constituent_table_columns: the column definitions of the first cell (constituent table) in the constituent\n column. Consequently, the constituent column can't be empty.\n | * constituent_changes_permitted: the value of table.is_refreshing\n\n\n Args:\n table (Table): the underlying partitioned table\n key_cols (Union[str, List[str]]): the key column name(s) of 'table'\n unique_keys (bool): whether the keys in 'table' are guaranteed to be unique\n constituent_column (str): the constituent column name in 'table'\n constituent_table_columns (List[Column]): the column definitions of the constituent table\n constituent_changes_permitted (bool): whether the values of the constituent column can change\n\n Returns:\n a PartitionedTable\n\n Raise:\n DHError\n \"\"\"\n none_args = [key_cols, unique_keys, constituent_column, constituent_table_columns,\n constituent_changes_permitted]\n\n try:\n if all([arg is None for arg in none_args]):\n return PartitionedTable(j_partitioned_table=_JPartitionedTableFactory.of(table.j_table))\n\n if all([arg is not None for arg in none_args]):\n table_def = _JTableDefinition.of([col.j_column_definition for col in constituent_table_columns])\n j_partitioned_table = _JPartitionedTableFactory.of(table.j_table,\n j_array_list(to_sequence(key_cols)),\n unique_keys,\n constituent_column,\n table_def,\n constituent_changes_permitted)\n return PartitionedTable(j_partitioned_table=j_partitioned_table)\n except Exception as e:\n raise DHError(e, \"failed to build a PartitionedTable.\") from e\n\n missing_value_args = [arg for arg in none_args if arg is None]\n raise DHError(message=f\"invalid argument values, must specify non-None values for {missing_value_args}.\")\n\n @classmethod\n def from_constituent_tables(cls,\n tables: List[Table],\n constituent_table_columns: List[Column] = None) -> PartitionedTable:\n \"\"\"Creates a PartitionedTable with a single column named '__CONSTITUENT__' containing the provided constituent\n tables.\n\n The result PartitionedTable has no key columns, and both its unique_keys and constituent_changes_permitted\n properties are set to False. When constituent_table_columns isn't provided, it will be set to the column\n definitions of the first table in the provided constituent tables.\n\n Args:\n tables (List[Table]): the constituent tables\n constituent_table_columns (List[Column]): a list of column definitions compatible with all the constituent\n tables, default is None\n\n Returns:\n a PartitionedTable\n\n Raises:\n DHError\n \"\"\"\n try:\n if not constituent_table_columns:\n return PartitionedTable(j_partitioned_table=_JPartitionedTableFactory.ofTables(to_sequence(tables)))\n else:\n table_def = _JTableDefinition.of([col.j_column_definition for col in constituent_table_columns])\n return PartitionedTable(j_partitioned_table=_JPartitionedTableFactory.ofTables(table_def,\n to_sequence(tables)))\n except Exception as e:\n raise DHError(e, \"failed to create a PartitionedTable from constituent tables.\") from e\n\n @property\n def table(self) -> Table:\n \"\"\"The underlying partitioned table.\"\"\"\n if self._table is None:\n self._table = Table(j_table=self.j_partitioned_table.table())\n return self._table\n\n @property\n def update_graph(self) -> UpdateGraph:\n \"\"\"The underlying partitioned table's update graph.\"\"\"\n return self.table.update_graph\n\n @property\n def is_refreshing(self) -> bool:\n \"\"\"Whether the underlying partitioned table is refreshing.\"\"\"\n if self._is_refreshing is None:\n self._is_refreshing = self.table.is_refreshing\n return self._is_refreshing\n\n @property\n def key_columns(self) -> List[str]:\n \"\"\"The partition key column names.\"\"\"\n if self._key_columns is None:\n self._key_columns = list(self.j_partitioned_table.keyColumnNames().toArray())\n return self._key_columns\n\n def keys(self) -> Table:\n \"\"\"Returns a Table containing all the keys of the underlying partitioned table.\"\"\"\n if self.unique_keys:\n return self.table.view(self.key_columns)\n else:\n return self.table.select_distinct(self.key_columns)\n\n @property\n def unique_keys(self) -> bool:\n \"\"\"Whether the keys in the underlying table must always be unique. If keys must be unique, one can expect\n that self.table.select_distinct(self.key_columns) and self.table.view(self.key_columns) operations always\n produce equivalent tables.\"\"\"\n if self._unique_keys is None:\n self._unique_keys = self.j_partitioned_table.uniqueKeys()\n return self._unique_keys\n\n @property\n def constituent_column(self) -> str:\n \"\"\"The name of the column containing constituent tables.\"\"\"\n if self._constituent_column is None:\n self._constituent_column = self.j_partitioned_table.constituentColumnName()\n return self._constituent_column\n\n @property\n def constituent_table_columns(self) -> List[Column]:\n \"\"\"The column definitions for constituent tables. All constituent tables in a partitioned table have the\n same column definitions.\"\"\"\n if not self._schema:\n self._schema = _td_to_columns(self.j_partitioned_table.constituentDefinition())\n\n return self._schema\n\n @property\n def constituent_changes_permitted(self) -> bool:\n \"\"\"Can the constituents of the underlying partitioned table change? Specifically, can the values of the\n constituent column change?\n\n If constituent changes are not permitted, the underlying partitioned table:\n 1. has no adds\n 2. has no removes\n 3. has no shifts\n 4. has no modifies that include the constituent column\n\n Note, it is possible for constituent changes to not be permitted even if constituent tables are refreshing or\n if the underlying partitioned table is refreshing. Also note that the underlying partitioned table must be\n refreshing if it contains any refreshing constituents.\n \"\"\"\n if self._constituent_changes_permitted is None:\n self._constituent_changes_permitted = self.j_partitioned_table.constituentChangesPermitted()\n return self._constituent_changes_permitted\n\n def merge(self) -> Table:\n \"\"\"Makes a new Table that contains all the rows from all the constituent tables. In the merged result,\n data from a constituent table is contiguous, and data from constituent tables appears in the same order the\n constituent table appears in the PartitionedTable. Basically, merge stacks constituent tables on top of each\n other in the same relative order as the partitioned table.\n\n Returns:\n a Table\n\n Raises:\n DHError\n \"\"\"\n try:\n with auto_locking_ctx(self):\n return Table(j_table=self.j_partitioned_table.merge())\n except Exception as e:\n raise DHError(e, \"failed to merge all the constituent tables.\")\n\n def filter(self, filters: Union[str, Filter, Sequence[str], Sequence[Filter]]) -> PartitionedTable:\n \"\"\"The filter method creates a new partitioned table containing only the rows meeting the filter criteria.\n Filters can not use the constituent column.\n\n Args:\n filters (Union[str, Filter, Sequence[str], Sequence[Filter]]): the filter condition expression(s) or\n Filter object(s)\n\n Returns:\n a PartitionedTable\n\n Raises:\n DHError\n \"\"\"\n filters = to_sequence(filters)\n if isinstance(filters[0], str):\n filters = Filter.from_(filters)\n filters = to_sequence(filters)\n try:\n return PartitionedTable(j_partitioned_table=self.j_partitioned_table.filter(j_array_list(filters)))\n except Exception as e:\n raise DHError(e, \"failed to apply filters to the partitioned table.\") from e\n\n def sort(self, order_by: Union[str, Sequence[str]],\n order: Union[SortDirection, Sequence[SortDirection]] = None) -> PartitionedTable:\n \"\"\"The sort method creates a new partitioned table where the rows are ordered based on values in a specified\n set of columns. Sort can not use the constituent column.\n\n Args:\n order_by (Union[str, Sequence[str]]): the column(s) to be sorted on. Can't include the constituent column.\n order (Union[SortDirection, Sequence[SortDirection], optional): the corresponding sort directions for\n each sort column, default is None, meaning ascending order for all the sort columns.\n\n Returns:\n a new PartitionedTable\n\n Raises:\n DHError\n \"\"\"\n\n try:\n order_by = to_sequence(order_by)\n if not order:\n order = (SortDirection.ASCENDING,) * len(order_by)\n order = to_sequence(order)\n if len(order_by) != len(order):\n raise DHError(message=\"The number of sort columns must be the same as the number of sort directions.\")\n\n sort_columns = [_sort_column(col, dir_) for col, dir_ in zip(order_by, order)]\n j_sc_list = j_array_list(sort_columns)\n return PartitionedTable(j_partitioned_table=self.j_partitioned_table.sort(j_sc_list))\n except Exception as e:\n raise DHError(e, \"failed to sort the partitioned table.\") from e\n\n def get_constituent(self, key_values: Union[Any, Sequence[Any]]) -> Optional[Table]:\n \"\"\"Gets a single constituent table by its corresponding key column value(s).\n If there are no matching rows, the result is None. If there are multiple matching rows, a DHError is thrown.\n\n Args:\n key_values (Union[Any, Sequence[Any]]): the value(s) of the key column(s)\n\n Returns:\n a Table or None\n\n Raises:\n DHError\n \"\"\"\n try:\n key_values = to_sequence(key_values)\n j_table = self.j_partitioned_table.constituentFor(key_values)\n if j_table:\n return Table(j_table=j_table)\n else:\n return None\n except Exception as e:\n raise DHError(e, \"unable to get constituent table.\") from e\n\n @property\n def constituent_tables(self) -> List[Table]:\n \"\"\"Returns all the current constituent tables.\"\"\"\n return list(map(Table, self.j_partitioned_table.constituents()))\n\n def transform(self, func: Callable[[Table], Table]) -> PartitionedTable:\n \"\"\"Apply the provided function to all constituent Tables and produce a new PartitionedTable with the results\n as its constituents, with the same data for all other columns in the underlying partitioned Table. Note that\n if the Table underlying this PartitionedTable changes, a corresponding change will propagate to the result.\n\n Args:\n func (Callable[[Table], Table]): a function which takes a Table as input and returns a new Table\n\n Returns:\n a PartitionedTable\n\n Raises:\n DHError\n \"\"\"\n try:\n j_operator = j_unary_operator(func, dtypes.from_jtype(Table.j_object_type.jclass))\n with auto_locking_ctx(self):\n j_pt = self.j_partitioned_table.transform(j_operator)\n return PartitionedTable(j_partitioned_table=j_pt)\n except Exception as e:\n raise DHError(e, \"failed to transform the PartitionedTable.\") from e\n\n def partitioned_transform(self, other: PartitionedTable, func: Callable[[Table, Table], Table]) -> PartitionedTable:\n \"\"\"Join the underlying partitioned Tables from this PartitionedTable and other on the key columns, then apply\n the provided function to all pairs of constituent Tables with the same keys in order to produce a new\n PartitionedTable with the results as its constituents, with the same data for all other columns in the\n underlying partitioned Table from this.\n\n Note that if the Tables underlying this PartitionedTable or other change, a corresponding change will propagate\n to the result.\n\n Args:\n other (PartitionedTable): the other Partitioned table whose constituent tables will be passed in as the 2nd\n argument to the provided function\n func (Callable[[Table, Table], Table]): a function which takes two Tables as input and returns a new Table\n\n Returns:\n a PartitionedTable\n\n Raises:\n DHError\n \"\"\"\n try:\n j_operator = j_binary_operator(func, dtypes.from_jtype(Table.j_object_type.jclass))\n with auto_locking_ctx(self, other):\n j_pt = self.j_partitioned_table.partitionedTransform(other.j_partitioned_table, j_operator)\n return PartitionedTable(j_partitioned_table=j_pt)\n except Exception as e:\n raise DHError(e, \"failed to transform the PartitionedTable with another PartitionedTable.\") from e\n\n def proxy(self, require_matching_keys: bool = True, sanity_check_joins: bool = True) -> PartitionedTableProxy:\n \"\"\"Makes a proxy that allows table operations to be applied to the constituent tables of this\n PartitionedTable.\n\n Args:\n require_matching_keys (bool): whether to ensure that both partitioned tables have all the same keys\n present when an operation uses this PartitionedTable and another PartitionedTable as inputs for a\n :meth:`~PartitionedTable.partitioned_transform`, default is True\n sanity_check_joins (bool): whether to check that for proxied join operations, a given join key only occurs\n in exactly one constituent table of the underlying partitioned table. If the other table argument is also a\n PartitionedTableProxy, its constituents will also be subjected to this constraint.\n \"\"\"\n return PartitionedTableProxy(\n j_pt_proxy=self.j_partitioned_table.proxy(require_matching_keys, sanity_check_joins))\n\n\nclass PartitionedTableProxy(JObjectWrapper):\n \"\"\"A PartitionedTableProxy is a table operation proxy for the underlying partitioned table. It provides methods\n that apply table operations to the constituent tables of the underlying partitioned table, produce a new\n partitioned table from the resulting constituent tables, and return a proxy of it.\n\n Attributes:\n target (PartitionedTable): the underlying partitioned table of the proxy\n require_matching_keys (bool): whether to ensure that both partitioned tables have all the same keys\n present when an operation uses this PartitionedTable and another PartitionedTable as inputs for a\n :meth:`~PartitionedTable.partitioned_transform`, default is True\n sanity_check_joins (bool): whether to check that for proxied join operations, a given join key only occurs\n in exactly one constituent table of the underlying partitioned table. If the other table argument is also a\n PartitionedTableProxy, its constituents will also be subjected to this constraint.\n \"\"\"\n j_object_type = _JPartitionedTableProxy\n\n @property\n def j_object(self) -> jpy.JType:\n return self.j_pt_proxy\n\n @property\n def is_refreshing(self) -> bool:\n \"\"\"Whether this proxy represents a refreshing partitioned table.\"\"\"\n return self.target.is_refreshing\n\n @property\n def update_graph(self) -> UpdateGraph:\n \"\"\"The underlying partitioned table proxy's update graph.\"\"\"\n return self.target.update_graph\n\n def __init__(self, j_pt_proxy):\n self.j_pt_proxy = jpy.cast(j_pt_proxy, _JPartitionedTableProxy)\n self.require_matching_keys = self.j_pt_proxy.requiresMatchingKeys()\n self.sanity_check_joins = self.j_pt_proxy.sanityChecksJoins()\n self.target = PartitionedTable(j_partitioned_table=self.j_pt_proxy.target())\n\n def head(self, num_rows: int) -> PartitionedTableProxy:\n \"\"\"Applies the :meth:`~Table.head` table operation to all constituent tables of the underlying partitioned\n table, and produces a new PartitionedTableProxy with the result tables as the constituents of its underlying\n partitioned table.\n\n Args:\n num_rows (int): the number of rows at the head of the constituent tables\n\n Returns:\n a new PartitionedTableProxy\n\n Raises:\n DHError\n \"\"\"\n try:\n with auto_locking_ctx(self):\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.head(num_rows))\n except Exception as e:\n raise DHError(e, \"head operation on the PartitionedTableProxy failed.\") from e\n\n def tail(self, num_rows: int) -> PartitionedTableProxy:\n \"\"\"Applies the :meth:`~Table.tail` table operation to all constituent tables of the underlying partitioned\n table, and produces a new PartitionedTableProxy with the result tables as the constituents of its underlying\n partitioned table.\n\n Args:\n num_rows (int): the number of rows at the end of the constituent tables\n\n Returns:\n a new PartitionedTableProxy\n\n Raises:\n DHError\n \"\"\"\n try:\n with auto_locking_ctx(self):\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.tail(num_rows))\n except Exception as e:\n raise DHError(e, \"tail operation on the PartitionedTableProxy failed.\") from e\n\n def reverse(self) -> PartitionedTableProxy:\n \"\"\"Applies the :meth:`~Table.reverse` table operation to all constituent tables of the underlying partitioned\n table, and produces a new PartitionedTableProxy with the result tables as the constituents of its underlying\n partitioned table.\n\n Returns:\n a new PartitionedTableProxy\n\n Raises:\n DHError\n \"\"\"\n try:\n with auto_locking_ctx(self):\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.reverse())\n except Exception as e:\n raise DHError(e, \"reverse operation on the PartitionedTableProxy failed.\") from e\n\n def snapshot(self) -> PartitionedTableProxy:\n \"\"\"Applies the :meth:`~Table.snapshot` table operation to all constituent tables of the underlying partitioned\n table, and produces a new PartitionedTableProxy with the result tables as the constituents of its underlying\n partitioned table.\n\n Returns:\n a new PartitionedTableProxy\n\n Raises:\n DHError\n \"\"\"\n try:\n with auto_locking_ctx(self):\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.snapshot())\n except Exception as e:\n raise DHError(e, \"snapshot operation on the PartitionedTableProxy failed.\") from e\n\n def snapshot_when(self, trigger_table: Union[Table, PartitionedTableProxy],\n stamp_cols: Union[str, List[str]] = None, initial: bool = False, incremental: bool = False,\n history: bool = False) -> PartitionedTableProxy:\n \"\"\"Applies the :meth:`~Table.snapshot_when` table operation to all constituent tables of the underlying\n partitioned table with the provided trigger table or PartitionedTableProxy, and produces a new\n PartitionedTableProxy with the result tables as the constituents of its underlying partitioned table.\n\n In the case of the trigger table being another PartitionedTableProxy, the :meth:`~Table.snapshot_when` table\n operation is applied to the matching pairs of the constituent tables from both underlying partitioned tables.\n\n Args:\n trigger_table (Union[Table, PartitionedTableProxy]): the trigger Table or PartitionedTableProxy\n stamp_cols (Union[str, Sequence[str]): The columns from trigger_table that form the \"stamp key\", may be\n renames. None, or empty, means that all columns from trigger_table form the \"stamp key\".\n initial (bool): Whether to take an initial snapshot upon construction, default is False. When False, the\n resulting table will remain empty until trigger_table first updates.\n incremental (bool): Whether the resulting table should be incremental, default is False. When False, all\n rows of this table will have the latest \"stamp key\". When True, only the rows of this table that have\n been added or updated will have the latest \"stamp key\".\n history (bool): Whether the resulting table should keep history, default is False. A history table appends a\n full snapshot of this table and the \"stamp key\" as opposed to updating existing rows. The history flag\n is currently incompatible with initial and incremental: when history is True, incremental and initial\n must be False.\n Returns:\n a new PartitionedTableProxy\n\n Raises:\n DHError\n \"\"\"\n try:\n options = _JSnapshotWhenOptions.of(initial, incremental, history, to_sequence(stamp_cols))\n with auto_locking_ctx(self, trigger_table):\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.snapshotWhen(trigger_table.j_object, options))\n except Exception as e:\n raise DHError(e, \"snapshot_when operation on the PartitionedTableProxy failed.\") from e\n\n def sort(self, order_by: Union[str, Sequence[str]],\n order: Union[SortDirection, Sequence[SortDirection]] = None) -> PartitionedTableProxy:\n \"\"\"Applies the :meth:`~Table.sort` table operation to all constituent tables of the underlying partitioned\n table, and produces a new PartitionedTableProxy with the result tables as the constituents of its underlying\n partitioned table.\n\n Args:\n order_by (Union[str, Sequence[str]]): the column(s) to be sorted on\n order (Union[SortDirection, Sequence[SortDirection], optional): the corresponding sort directions for\n each sort column, default is None, meaning ascending order for all the sort columns.\n\n Returns:\n a new PartitionedTableProxy\n\n Raises:\n DHError\n \"\"\"\n try:\n order_by = to_sequence(order_by)\n if not order:\n order = (SortDirection.ASCENDING,) * len(order_by)\n order = to_sequence(order)\n if len(order_by) != len(order):\n raise ValueError(\"The number of sort columns must be the same as the number of sort directions.\")\n\n sort_columns = [_sort_column(col, dir_) for col, dir_ in zip(order_by, order)]\n j_sc_list = j_array_list(sort_columns)\n with auto_locking_ctx(self):\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.sort(j_sc_list))\n except Exception as e:\n raise DHError(e, \"sort operation on the PartitionedTableProxy failed.\") from e\n\n def sort_descending(self, order_by: Union[str, Sequence[str]]) -> PartitionedTableProxy:\n \"\"\"Applies the :meth:`~Table.sort_descending` table operation to all constituent tables of the underlying\n partitioned table, and produces a new PartitionedTableProxy with the result tables as the constituents of its\n underlying partitioned table.\n\n Args:\n order_by (Union[str, Sequence[str]]): the column(s) to be sorted on\n\n Returns:\n a new PartitionedTableProxy\n\n Raises:\n DHError\n \"\"\"\n try:\n order_by = to_sequence(order_by)\n with auto_locking_ctx(self):\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.sortDescending(*order_by))\n except Exception as e:\n raise DHError(e, \"sort_descending operation on the PartitionedTableProxy failed.\") from e\n\n def where(self, filters: Union[str, Filter, Sequence[str], Sequence[Filter]] = None) -> PartitionedTableProxy:\n \"\"\"Applies the :meth:`~Table.where` table operation to all constituent tables of the underlying partitioned\n table, and produces a new PartitionedTableProxy with the result tables as the constituents of its underlying\n partitioned table.\n\n Args:\n filters (Union[str, Filter, Sequence[str], Sequence[Filter]], optional): the filter condition\n expression(s) or Filter object(s), default is None\n\n Returns:\n a new PartitionedTableProxy\n\n Raises:\n DHError\n \"\"\"\n try:\n filters = to_sequence(filters)\n with _query_scope_ctx(), auto_locking_ctx(self):\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.where(*filters))\n except Exception as e:\n raise DHError(e, \"where operation on the PartitionedTableProxy failed.\") from e\n\n def where_in(self, filter_table: Table, cols: Union[str, Sequence[str]]) -> PartitionedTableProxy:\n \"\"\"Applies the :meth:`~Table.where_in` table operation to all constituent tables of the underlying\n partitioned table with the provided filter table, and produces a new PartitionedTableProxy with the result\n tables as the constituents of its underlying partitioned table.\n\n Args:\n filter_table (Table): the table containing the set of values to filter on\n cols (Union[str, Sequence[str]]): the column name(s)\n\n Returns:\n a new PartitionedTableProxy\n\n Raises:\n DHError\n \"\"\"\n try:\n cols = to_sequence(cols)\n with auto_locking_ctx(self, filter_table):\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.whereIn(filter_table.j_table, *cols))\n except Exception as e:\n raise DHError(e, \"where_in operation on the PartitionedTableProxy failed.\") from e\n\n def where_not_in(self, filter_table: Table, cols: Union[str, Sequence[str]]) -> PartitionedTableProxy:\n \"\"\"Applies the :meth:`~Table.where_not_in` table operation to all constituent tables of the underlying\n partitioned table with the provided filter table, and produces a new PartitionedTableProxy with the result\n tables as the constituents of its underlying partitioned table.\n\n Args:\n filter_table (Table): the table containing the set of values to filter on\n cols (Union[str, Sequence[str]]): the column name(s)\n\n Returns:\n a new PartitionedTableProxy\n\n Raises:\n DHError\n \"\"\"\n try:\n cols = to_sequence(cols)\n with auto_locking_ctx(self, filter_table):\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.whereNotIn(filter_table.j_table, *cols))\n except Exception as e:\n raise DHError(e, \"where_not_in operation on the PartitionedTableProxy failed.\") from e\n\n def view(self, formulas: Union[str, Sequence[str]]) -> PartitionedTableProxy:\n \"\"\"Applies the :meth:`~Table.view` table operation to all constituent tables of the underlying partitioned\n table, and produces a new PartitionedTableProxy with the result tables as the constituents of its underlying\n partitioned table.\n\n Args:\n formulas (Union[str, Sequence[str]]): the column formula(s)\n\n Returns:\n A new PartitionedTableProxy\n\n Raises:\n DHError\n \"\"\"\n try:\n formulas = to_sequence(formulas)\n with _query_scope_ctx(), auto_locking_ctx(self):\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.view(*formulas))\n except Exception as e:\n raise DHError(e, \"view operation on the PartitionedTableProxy failed.\") from e\n\n def update_view(self, formulas: Union[str, Sequence[str]]) -> PartitionedTableProxy:\n \"\"\"Applies the :meth:`~Table.update_view` table operation to all constituent tables of the underlying\n partitioned table, and produces a new PartitionedTableProxy with the result tables as the constituents of its\n underlying partitioned table.\n\n Args:\n formulas (Union[str, Sequence[str]]): the column formula(s)\n\n Returns:\n A new PartitionedTableProxy\n\n Raises:\n DHError\n \"\"\"\n try:\n formulas = to_sequence(formulas)\n with _query_scope_ctx(), auto_locking_ctx(self):\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.updateView(*formulas))\n except Exception as e:\n raise DHError(e, \"update_view operation on the PartitionedTableProxy failed.\") from e\n\n def update(self, formulas: Union[str, Sequence[str]]) -> PartitionedTableProxy:\n \"\"\"Applies the :meth:`~Table.update` table operation to all constituent tables of the underlying partitioned\n table, and produces a new PartitionedTableProxy with the result tables as the constituents of its underlying\n partitioned table.\n\n Args:\n formulas (Union[str, Sequence[str]]): the column formula(s)\n\n Returns:\n A new PartitionedTableProxy\n\n Raises:\n DHError\n \"\"\"\n try:\n formulas = to_sequence(formulas)\n with _query_scope_ctx(), auto_locking_ctx(self):\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.update(*formulas))\n except Exception as e:\n raise DHError(e, \"update operation on the PartitionedTableProxy failed.\") from e\n\n def select(self, formulas: Union[str, Sequence[str]] = None) -> PartitionedTableProxy:\n \"\"\"Applies the :meth:`~Table.select` table operation to all constituent tables of the underlying partitioned\n table, and produces a new PartitionedTableProxy with the result tables as the constituents of its underlying\n partitioned table.\n\n Args:\n formulas (Union[str, Sequence[str]], optional): the column formula(s), default is None\n\n Returns:\n A new PartitionedTableProxy\n\n Raises:\n DHError\n \"\"\"\n try:\n formulas = to_sequence(formulas)\n with _query_scope_ctx(), auto_locking_ctx(self):\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.select(*formulas))\n except Exception as e:\n raise DHError(e, \"select operation on the PartitionedTableProxy failed.\") from e\n\n def select_distinct(self, formulas: Union[str, Sequence[str]] = None) -> PartitionedTableProxy:\n \"\"\"Applies the :meth:`~Table.select_distinct` table operation to all constituent tables of the underlying\n partitioned table, and produces a new PartitionedTableProxy with the result tables as the constituents of its\n underlying partitioned table.\n\n Args:\n formulas (Union[str, Sequence[str]], optional): the column formula(s), default is None\n\n Returns:\n A new PartitionedTableProxy\n\n Raises:\n DHError\n \"\"\"\n try:\n formulas = to_sequence(formulas)\n with _query_scope_ctx(), auto_locking_ctx(self):\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.selectDistinct(*formulas))\n except Exception as e:\n raise DHError(e, \"select_distinct operation on the PartitionedTableProxy failed.\") from e\n\n def natural_join(self, table: Union[Table, PartitionedTableProxy], on: Union[str, Sequence[str]],\n joins: Union[str, Sequence[str]] = None) -> PartitionedTableProxy:\n \"\"\"Applies the :meth:`~Table.natural_join` table operation to all constituent tables of the underlying\n partitioned table with the provided right table or PartitionedTableProxy, and produces a new\n PartitionedTableProxy with the result tables as the constituents of its underlying partitioned table.\n\n In the case of the right table being another PartitionedTableProxy, the :meth:`~Table.natural_join` table\n operation is applied to the matching pairs of the constituent tables from both underlying partitioned tables.\n\n Args:\n table (Union[Table, PartitionedTableProxy]): the right table or PartitionedTableProxy of the join\n on (Union[str, Sequence[str]]): the column(s) to match, can be a common name or an equal expression,\n i.e. \"col_a = col_b\" for different column names\n joins (Union[str, Sequence[str]], optional): the column(s) to be added from the right table to the result\n table, can be renaming expressions, i.e. \"new_col = col\"; default is None\n\n Returns:\n a new PartitionedTableProxy\n\n Raises:\n DHError\n \"\"\"\n try:\n on = to_sequence(on)\n joins = to_sequence(joins)\n table_op = jpy.cast(table.j_object, _JTableOperations)\n with auto_locking_ctx(self, table):\n if joins:\n return PartitionedTableProxy(\n j_pt_proxy=self.j_pt_proxy.naturalJoin(table_op, \",\".join(on), \",\".join(joins)))\n else:\n return PartitionedTableProxy(\n j_pt_proxy=self.j_pt_proxy.naturalJoin(table_op, \",\".join(on)))\n except Exception as e:\n raise DHError(e, \"natural_join operation on the PartitionedTableProxy failed.\") from e\n\n def exact_join(self, table: Union[Table, PartitionedTableProxy], on: Union[str, Sequence[str]],\n joins: Union[str, Sequence[str]] = None) -> PartitionedTableProxy:\n \"\"\"Applies the :meth:`~Table.exact_join` table operation to all constituent tables of the underlying\n partitioned table with the provided right table or PartitionedTableProxy,and produces a new\n PartitionedTableProxy with the result tables as the constituents of its underlying partitioned table.\n\n In the case of the right table being another PartitionedTableProxy, the :meth:`~Table.exact_join` table\n operation is applied to the matching pairs of the constituent tables from both underlying partitioned tables.\n\n Args:\n table (Union[Table, PartitionedTableProxy]): the right table or PartitionedTableProxy of the join\n on (Union[str, Sequence[str]]): the column(s) to match, can be a common name or an equal expression,\n i.e. \"col_a = col_b\" for different column names\n joins (Union[str, Sequence[str]], optional): the column(s) to be added from the right table to the result\n table, can be renaming expressions, i.e. \"new_col = col\"; default is None\n\n Returns:\n a new PartitionedTableProxy\n\n Raises:\n DHError\n \"\"\"\n try:\n on = to_sequence(on)\n joins = to_sequence(joins)\n table_op = jpy.cast(table.j_object, _JTableOperations)\n with auto_locking_ctx(self, table):\n if joins:\n return PartitionedTableProxy(\n j_pt_proxy=self.j_pt_proxy.exactJoin(table_op, \",\".join(on), \",\".join(joins)))\n else:\n return PartitionedTableProxy(\n j_pt_proxy=self.j_pt_proxy.exactJoin(table_op, \",\".join(on)))\n except Exception as e:\n raise DHError(e, \"exact_join operation on the PartitionedTableProxy failed.\") from e\n\n def join(self, table: Union[Table, PartitionedTableProxy], on: Union[str, Sequence[str]] = None,\n joins: Union[str, Sequence[str]] = None) -> PartitionedTableProxy:\n \"\"\"Applies the :meth:`~Table.join` table operation to all constituent tables of the underlying partitioned\n table with the provided right table or PartitionedTableProxy, and produces a new PartitionedTableProxy with\n the result tables as the constituents of its underlying partitioned table.\n\n In the case of the right table being another PartitionedTableProxy, the :meth:`~Table.join` table operation\n is applied to the matching pairs of the constituent tables from both underlying partitioned tables.\n\n Args:\n table (Union[Table, PartitionedTableProxy]): the right table or PartitionedTableProxy of the join\n on (Union[str, Sequence[str]]): the column(s) to match, can be a common name or an equal expression,\n i.e. \"col_a = col_b\" for different column names; default is None\n joins (Union[str, Sequence[str]], optional): the column(s) to be added from the right table to the result\n table, can be renaming expressions, i.e. \"new_col = col\"; default is None\n\n Returns:\n a new PartitionedTableProxy\n\n Raises:\n DHError\n \"\"\"\n try:\n on = to_sequence(on)\n joins = to_sequence(joins)\n table_op = jpy.cast(table.j_object, _JTableOperations)\n with auto_locking_ctx(self, table):\n if joins:\n return PartitionedTableProxy(\n j_pt_proxy=self.j_pt_proxy.join(table_op, \",\".join(on), \",\".join(joins)))\n else:\n return PartitionedTableProxy(\n j_pt_proxy=self.j_pt_proxy.join(table_op, \",\".join(on)))\n except Exception as e:\n raise DHError(e, \"join operation on the PartitionedTableProxy failed.\") from e\n\n def aj(self, table: Union[Table, PartitionedTableProxy], on: Union[str, Sequence[str]],\n joins: Union[str, Sequence[str]] = None) -> PartitionedTableProxy:\n \"\"\"Applies the :meth:`~Table.aj` table operation to all constituent tables of the underlying partitioned\n table with the provided right table or PartitionedTableProxy, and produces a new PartitionedTableProxy with\n the result tables as the constituents of its underlying partitioned table.\n\n In the case of the right table being another PartitionedTableProxy, the :meth:`~Table.aj` table operation\n is applied to the matching pairs of the constituent tables from both underlying partitioned tables.\n\n Args:\n table (Union[Table, PartitionedTableProxy]): the right table or PartitionedTableProxy of the join\n on (Union[str, Sequence[str]]): the column(s) to match, can be a common name or a match condition of two\n columns, e.g. 'col_a = col_b'. The first 'N-1' matches are exact matches. The final match is an inexact\n match. The inexact match can use either '>' or '>='. If a common name is used for the inexact match,\n '>=' is used for the comparison.\n joins (Union[str, Sequence[str]], optional): the column(s) to be added from the right table to the result\n table, can be renaming expressions, i.e. \"new_col = col\"; default is None\n Returns:\n a new PartitionedTableProxy\n\n Raises:\n DHError\n \"\"\"\n try:\n on = \",\".join(to_sequence(on))\n joins = \",\".join(to_sequence(joins))\n table_op = jpy.cast(self.j_object, _JTableOperations)\n r_table_op = jpy.cast(table.j_object, _JTableOperations)\n\n with auto_locking_ctx(self, table):\n return PartitionedTableProxy(j_pt_proxy=table_op.aj(r_table_op, on, joins))\n except Exception as e:\n raise DHError(e, \"as-of join operation on the PartitionedTableProxy failed.\") from e\n\n def raj(self, table: Union[Table, PartitionedTableProxy], on: Union[str, Sequence[str]],\n joins: Union[str, Sequence[str]] = None) -> PartitionedTableProxy:\n \"\"\"Applies the :meth:`~Table.raj` table operation to all constituent tables of the underlying partitioned\n table with the provided right table or PartitionedTableProxy, and produces a new PartitionedTableProxy with\n the result tables as the constituents of its underlying partitioned table.\n\n In the case of the right table being another PartitionedTableProxy, the :meth:`~Table.raj` table operation\n is applied to the matching pairs of the constituent tables from both underlying partitioned tables.\n\n Args:\n table (Union[Table, PartitionedTableProxy]): the right table or PartitionedTableProxy of the join\n on (Union[str, Sequence[str]]): the column(s) to match, can be a common name or a match condition of two\n columns, e.g. 'col_a = col_b'. The first 'N-1' matches are exact matches. The final match is an inexact\n match. The inexact match can use either '<' or '<='. If a common name is used for the inexact match,\n '<=' is used for the comparison.\n joins (Union[str, Sequence[str]], optional): the column(s) to be added from the right table to the result\n table, can be renaming expressions, i.e. \"new_col = col\"; default is None\n Returns:\n a new PartitionedTableProxy\n\n Raises:\n DHError\n \"\"\"\n try:\n on = \",\".join(to_sequence(on))\n joins = \",\".join(to_sequence(joins))\n table_op = jpy.cast(self.j_object, _JTableOperations)\n r_table_op = jpy.cast(table.j_object, _JTableOperations)\n\n with auto_locking_ctx(self, table):\n return PartitionedTableProxy(j_pt_proxy=table_op.raj(r_table_op, on, joins))\n except Exception as e:\n raise DHError(e, \"reverse as-of join operation on the PartitionedTableProxy failed.\") from e\n\n def group_by(self, by: Union[str, Sequence[str]] = None) -> PartitionedTableProxy:\n \"\"\"Applies the :meth:`~Table.group_by` table operation to all constituent tables of the underlying\n partitioned table, and produces a new PartitionedTableProxy with the result tables as the constituents of its\n underlying partitioned table.\n\n Args:\n by (Union[str, Sequence[str]], optional): the group-by column name(s), default is None\n\n Returns:\n a new PartitionedTableProxy\n\n Raises:\n DHError\n \"\"\"\n try:\n by = to_sequence(by)\n with auto_locking_ctx(self):\n if by:\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.groupBy(*by))\n else:\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.groupBy())\n except Exception as e:\n raise DHError(e, \"group-by operation on the PartitionedTableProxy failed.\") from e\n\n def agg_by(self, aggs: Union[Aggregation, Sequence[Aggregation]],\n by: Union[str, Sequence[str]] = None) -> PartitionedTableProxy:\n \"\"\"Applies the :meth:`~Table.agg_by` table operation to all constituent tables of the underlying partitioned\n table, and produces a new PartitionedTableProxy with the result tables as the constituents of its underlying\n partitioned table.\n\n Args:\n aggs (Union[Aggregation, Sequence[Aggregation]]): the aggregation(s)\n by (Union[str, Sequence[str]]): the group-by column name(s), default is None\n\n Returns:\n a new PartitionedTableProxy\n\n Raises:\n DHError\n \"\"\"\n try:\n aggs = to_sequence(aggs)\n by = to_sequence(by)\n j_agg_list = j_array_list([agg.j_aggregation for agg in aggs])\n\n cm = _query_scope_agg_ctx(aggs)\n with cm:\n with auto_locking_ctx(self):\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.aggBy(j_agg_list, *by))\n except Exception as e:\n raise DHError(e, \"agg_by operation on the PartitionedTableProxy failed.\") from e\n\n def agg_all_by(self, agg: Aggregation, by: Union[str, Sequence[str]] = None) -> PartitionedTableProxy:\n \"\"\"Applies the :meth:`~Table.agg_all_by` table operation to all constituent tables of the underlying\n partitioned table, and produces a new PartitionedTableProxy with the result tables as the constituents of its\n underlying partitioned table.\n\n Note, because agg_all_by applies the aggregation to all the columns of the table, it will ignore\n any column names specified for the aggregation.\n\n Args:\n agg (Aggregation): the aggregation\n by (Union[str, Sequence[str]], optional): the group-by column name(s), default is None\n\n Returns:\n a new PartitionedTableProxy\n\n Raises:\n DHError\n \"\"\"\n try:\n by = to_sequence(by)\n\n cm = _query_scope_agg_ctx([agg])\n with cm:\n with auto_locking_ctx(self):\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.aggAllBy(agg.j_agg_spec, *by))\n except Exception as e:\n raise DHError(e, \"agg_all_by operation on the PartitionedTableProxy failed.\") from e\n\n def count_by(self, col: str, by: Union[str, Sequence[str]] = None) -> PartitionedTableProxy:\n \"\"\"Applies the :meth:`~Table.count_by` table operation to all constituent tables of the underlying partitioned\n table with the provided source table, and produces a new PartitionedTableProxy with the result tables as the\n constituents of its underlying partitioned table.\n\n Args:\n col (str): the name of the column to store the counts\n by (Union[str, Sequence[str]], optional): the group-by column name(s), default is None\n\n Returns:\n a new PartitionedTableProxy\n\n Raises:\n DHError\n \"\"\"\n try:\n by = to_sequence(by)\n with auto_locking_ctx(self):\n if by:\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.countBy(col, *by))\n else:\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.countBy(col))\n except Exception as e:\n raise DHError(e, \"count_by operation on the PartitionedTableProxy failed.\") from e\n\n def first_by(self, by: Union[str, Sequence[str]] = None) -> PartitionedTableProxy:\n \"\"\"Applies the :meth:`~Table.first_by` table operation to all constituent tables of the underlying\n partitioned table, and produces a new PartitionedTableProxy with the result tables as the constituents of its\n underlying partitioned table.\n\n Args:\n by (Union[str, Sequence[str]], optional): the group-by column name(s), default is None\n\n Returns:\n a new PartitionedTableProxy\n\n Raises:\n DHError\n \"\"\"\n try:\n by = to_sequence(by)\n with auto_locking_ctx(self):\n if by:\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.firstBy(*by))\n else:\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.firstBy())\n except Exception as e:\n raise DHError(e, \"first_by operation on the PartitionedTableProxy failed.\") from e\n\n def last_by(self, by: Union[str, Sequence[str]] = None) -> PartitionedTableProxy:\n \"\"\"Applies the :meth:`~Table.last_by` table operation to all constituent tables of the underlying partitioned\n table, and produces a new PartitionedTableProxy with the result tables as the constituents of its underlying\n partitioned table.\n\n Args:\n by (Union[str, Sequence[str]], optional): the group-by column name(s), default is None\n\n Returns:\n a new PartitionedTableProxy\n\n Raises:\n DHError\n \"\"\"\n try:\n by = to_sequence(by)\n with auto_locking_ctx(self):\n if by:\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.lastBy(*by))\n else:\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.lastBy())\n except Exception as e:\n raise DHError(e, \"last_by operation on the PartitionedTableProxy failed.\") from e\n\n def min_by(self, by: Union[str, Sequence[str]] = None) -> PartitionedTableProxy:\n \"\"\"Applies the :meth:`~Table.min_by` table operation to all constituent tables of the underlying partitioned\n table, and produces a new PartitionedTableProxy with the result tables as the constituents of its underlying\n partitioned table.\n\n Args:\n by (Union[str, Sequence[str]], optional): the group-by column name(s), default is None\n\n Returns:\n a new PartitionedTableProxy\n\n Raises:\n DHError\n \"\"\"\n try:\n by = to_sequence(by)\n with auto_locking_ctx(self):\n if by:\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.minBy(*by))\n else:\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.minBy())\n except Exception as e:\n raise DHError(e, \"min_by operation on the PartitionedTableProxy failed.\") from e\n\n def max_by(self, by: Union[str, Sequence[str]] = None) -> PartitionedTableProxy:\n \"\"\"Applies the :meth:`~Table.max_by` table operation to all constituent tables of the underlying partitioned\n table, and produces a new PartitionedTableProxy with the result tables as the constituents of its underlying\n partitioned table.\n\n Args:\n by (Union[str, Sequence[str]], optional): the group-by column name(s), default is None\n\n Returns:\n a new PartitionedTableProxy\n\n Raises:\n DHError\n \"\"\"\n try:\n by = to_sequence(by)\n with auto_locking_ctx(self):\n if by:\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.maxBy(*by))\n else:\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.maxBy())\n except Exception as e:\n raise DHError(e, \"max_by operation on the PartitionedTableProxy failed.\") from e\n\n def sum_by(self, by: Union[str, Sequence[str]] = None) -> PartitionedTableProxy:\n \"\"\"Applies the :meth:`~Table.sum_by` table operation to all constituent tables of the underlying partitioned\n table, and produces a new PartitionedTableProxy with the result tables as the constituents of its underlying\n partitioned table.\n\n Args:\n by (Union[str, Sequence[str]], optional): the group-by column name(s), default is None\n\n Returns:\n a new PartitionedTableProxy\n\n Raises:\n DHError\n \"\"\"\n try:\n by = to_sequence(by)\n with auto_locking_ctx(self):\n if by:\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.sumBy(*by))\n else:\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.sumBy())\n except Exception as e:\n raise DHError(e, \"sum_by operation on the PartitionedTableProxy failed.\") from e\n\n def abs_sum_by(self, by: Union[str, Sequence[str]] = None) -> PartitionedTableProxy:\n \"\"\"Applies the :meth:`~Table.abs_sum_by` table operation to all constituent tables of the underlying partitioned\n table, and produces a new PartitionedTableProxy with the result tables as the constituents of its underlying\n partitioned table.\n\n Args:\n by (Union[str, Sequence[str]], optional): the group-by column name(s), default is None\n\n Returns:\n a new PartitionedTableProxy\n\n Raises:\n DHError\n \"\"\"\n try:\n by = to_sequence(by)\n with auto_locking_ctx(self):\n if by:\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.absSumBy(*by))\n else:\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.absSumBy())\n except Exception as e:\n raise DHError(e, \"sum_by operation on the PartitionedTableProxy failed.\") from e\n\n def weighted_sum_by(self, wcol: str, by: Union[str, Sequence[str]] = None) -> PartitionedTableProxy:\n \"\"\"Applies the :meth:`~Table.weighted_sum_by` table operation to all constituent tables of the underlying partitioned\n table, and produces a new PartitionedTableProxy with the result tables as the constituents of its underlying\n partitioned table.\n\n Args:\n wcol (str): the name of the weight column\n by (Union[str, Sequence[str]], optional): the group-by column name(s), default is None\n\n Returns:\n a new PartitionedTableProxy\n\n Raises:\n DHError\n \"\"\"\n try:\n by = to_sequence(by)\n with auto_locking_ctx(self):\n if by:\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.wsumBy(wcol, *by))\n else:\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.wsumBy(wcol))\n except Exception as e:\n raise DHError(e, \"sum_by operation on the PartitionedTableProxy failed.\") from e\n\n def avg_by(self, by: Union[str, Sequence[str]] = None) -> PartitionedTableProxy:\n \"\"\"Applies the :meth:`~Table.avg_by` table operation to all constituent tables of the underlying partitioned\n table, and produces a new PartitionedTableProxy with the result tables as the constituents of its underlying\n partitioned table.\n\n Args:\n by (Union[str, Sequence[str]], optional): the group-by column name(s), default is None\n\n Returns:\n a new PartitionedTableProxy\n\n Raises:\n DHError\n \"\"\"\n try:\n by = to_sequence(by)\n with auto_locking_ctx(self):\n if by:\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.avgBy(*by))\n else:\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.avgBy())\n except Exception as e:\n raise DHError(e, \"avg_by operation on the PartitionedTableProxy failed.\") from e\n\n def weighted_avg_by(self, wcol: str, by: Union[str, Sequence[str]] = None) -> PartitionedTableProxy:\n \"\"\"Applies the :meth:`~Table.weighted_avg_by` table operation to all constituent tables of the underlying partitioned\n table, and produces a new PartitionedTableProxy with the result tables as the constituents of its underlying\n partitioned table.\n\n Args:\n wcol (str): the name of the weight column\n by (Union[str, Sequence[str]], optional): the group-by column name(s), default is None\n\n Returns:\n a new PartitionedTableProxy\n\n Raises:\n DHError\n \"\"\"\n try:\n by = to_sequence(by)\n with auto_locking_ctx(self):\n if by:\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.wavgBy(wcol, *by))\n else:\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.avgBy(wcol))\n except Exception as e:\n raise DHError(e, \"avg_by operation on the PartitionedTableProxy failed.\") from e\n\n def median_by(self, by: Union[str, Sequence[str]] = None) -> PartitionedTableProxy:\n \"\"\"Applies the :meth:`~Table.median_by` table operation to all constituent tables of the underlying\n partitioned table, and produces a new PartitionedTableProxy with the result tables as the constituents of its\n underlying partitioned table.\n\n Args:\n by (Union[str, Sequence[str]], optional): the group-by column name(s), default is None\n\n Returns:\n a new PartitionedTableProxy\n\n Raises:\n DHError\n \"\"\"\n try:\n by = to_sequence(by)\n with auto_locking_ctx(self):\n if by:\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.medianBy(*by))\n else:\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.medianBy())\n except Exception as e:\n raise DHError(e, \"median_by operation on the PartitionedTableProxy failed.\") from e\n\n def std_by(self, by: Union[str, Sequence[str]] = None) -> PartitionedTableProxy:\n \"\"\"Applies the :meth:`~Table.std_by` table operation to all constituent tables of the underlying partitioned\n table, and produces a new PartitionedTableProxy with the result tables as the constituents of its underlying\n partitioned table.\n\n Args:\n by (Union[str, Sequence[str]], optional): the group-by column name(s), default is None\n\n Returns:\n a new PartitionedTableProxy\n\n Raises:\n DHError\n \"\"\"\n try:\n by = to_sequence(by)\n with auto_locking_ctx(self):\n if by:\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.stdBy(*by))\n else:\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.stdBy())\n except Exception as e:\n raise DHError(e, \"std_by operation on the PartitionedTableProxy failed.\") from e\n\n def var_by(self, by: Union[str, Sequence[str]] = None) -> PartitionedTableProxy:\n \"\"\"Applies the :meth:`~Table.var_by` table operation to all constituent tables of the underlying partitioned\n table, and produces a new PartitionedTableProxy with the result tables as the constituents of its underlying\n partitioned table.\n\n Args:\n by (Union[str, Sequence[str]], optional): the group-by column name(s), default is None\n\n Returns:\n a new PartitionedTableProxy\n\n Raises:\n DHError\n \"\"\"\n try:\n by = to_sequence(by)\n with auto_locking_ctx(self):\n if by:\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.varBy(*by))\n else:\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.varBy())\n except Exception as e:\n raise DHError(e, \"var_by operation on the PartitionedTableProxy failed.\") from e\n\n def update_by(self, ops: Union[UpdateByOperation, List[UpdateByOperation]],\n by: Union[str, List[str]] = None) -> PartitionedTableProxy:\n \"\"\"Applies the :meth:`~Table.update_by` table operation to all constituent tables of the underlying partitioned\n table, and produces a new PartitionedTableProxy with the result tables as the constituents of its underlying\n partitioned table.\n\n Args:\n ops (Union[UpdateByOperation, List[UpdateByOperation]]): the update-by operation definition(s)\n by (Union[str, List[str]]): the key column name(s) to group the rows of the table\n\n Returns:\n a new PartitionedTableProxy\n\n Raises:\n DHError\n \"\"\"\n try:\n ops = to_sequence(ops)\n by = to_sequence(by)\n with auto_locking_ctx(self):\n return PartitionedTableProxy(j_pt_proxy=self.j_pt_proxy.updateBy(j_array_list(ops), *by))\n except Exception as e:\n raise DHError(e, \"update-by operation on the PartitionedTableProxy failed.\") from e\n\nclass MultiJoinInput(JObjectWrapper):\n \"\"\"A MultiJoinInput represents the input tables, key columns and additional columns to be used in the multi-table\n natural join. \"\"\"\n j_object_type = _JMultiJoinInput\n\n @property\n def j_object(self) -> jpy.JType:\n return self.j_multijoininput\n\n def __init__(self, table: Table, on: Union[str, Sequence[str]], joins: Union[str, Sequence[str]] = None):\n \"\"\"Creates a new MultiJoinInput containing the table to include for the join, the key columns from the table to\n match with other table keys plus additional columns containing data from the table. Rows containing unique keys\n will be added to the output table, otherwise the data from these columns will be added to the existing output\n rows.\n\n Args:\n table (Table): the right table to include in the join\n on (Union[str, Sequence[str]]): the column(s) to match, can be a common name or an equal expression,\n i.e. \"col_a = col_b\" for different column names\n joins (Union[str, Sequence[str]], optional): the column(s) to be added from the this table to the result\n table, can be renaming expressions, i.e. \"new_col = col\"; default is None\n\n Raises:\n DHError\n \"\"\"\n try:\n self.table = table\n on = to_sequence(on)\n joins = to_sequence(joins)\n self.j_multijoininput = _JMultiJoinInput.of(table.j_table, on, joins)\n except Exception as e:\n raise DHError(e, \"failed to build a MultiJoinInput object.\") from e\n\n\nclass MultiJoinTable(JObjectWrapper):\n \"\"\"A MultiJoinTable is an object that contains the result of a multi-table natural join. To retrieve the underlying\n result Table, use the table() method. \"\"\"\n j_object_type = _JMultiJoinTable\n\n @property\n def j_object(self) -> jpy.JType:\n return self.j_multijointable\n\n def table(self) -> Table:\n \"\"\"Returns the Table containing the multi-table natural join output. \"\"\"\n return Table(j_table=self.j_multijointable.table())\n\n def __init__(self, input: Union[Table, Sequence[Table], MultiJoinInput, Sequence[MultiJoinInput]],\n on: Union[str, Sequence[str]] = None):\n \"\"\"Creates a new MultiJoinTable. The join can be specified in terms of either tables or MultiJoinInputs.\n\n Args:\n input (Union[Table, Sequence[Table], MultiJoinInput, Sequence[MultiJoinInput]]): the input objects\n specifying the tables and columns to include in the join.\n on (Union[str, Sequence[str]], optional): the column(s) to match, can be a common name or an equality\n expression that matches every input table, i.e. \"col_a = col_b\" to rename output column names. Note:\n When MultiJoinInput objects are supplied, this parameter must be omitted.\n\n Raises:\n DHError\n \"\"\"\n try:\n if isinstance(input, Table) or (isinstance(input, Sequence) and all(isinstance(t, Table) for t in input)):\n tables = to_sequence(input, wrapped=True)\n with auto_locking_ctx(*tables):\n j_tables = to_sequence(input)\n self.j_multijointable = _JMultiJoinFactory.of(on, *j_tables)\n elif isinstance(input, MultiJoinInput) or (isinstance(input, Sequence) and all(isinstance(ji, MultiJoinInput) for ji in input)):\n if on is not None:\n raise DHError(message=\"on parameter is not permitted when MultiJoinInput objects are provided.\")\n wrapped_input = to_sequence(input, wrapped=True)\n tables = [ji.table for ji in wrapped_input]\n with auto_locking_ctx(*tables):\n input = to_sequence(input)\n self.j_multijointable = _JMultiJoinFactory.of(*input)\n else:\n raise DHError(message=\"input must be a Table, a sequence of Tables, a MultiJoinInput, or a sequence of MultiJoinInputs.\")\n\n except Exception as e:\n raise DHError(e, \"failed to build a MultiJoinTable object.\") from e\n\n\n\ndef multi_join(input: Union[Table, Sequence[Table], MultiJoinInput, Sequence[MultiJoinInput]],\n on: Union[str, Sequence[str]] = None) -> MultiJoinTable:\n \"\"\" The multi_join method creates a new table by performing a multi-table natural join on the input tables. The result\n consists of the set of distinct keys from the input tables natural joined to each input table. Input tables need not\n have a matching row for each key, but they may not have multiple matching rows for a given key.\n\n Args:\n input (Union[Table, Sequence[Table], MultiJoinInput, Sequence[MultiJoinInput]]): the input objects specifying the\n tables and columns to include in the join.\n on (Union[str, Sequence[str]], optional): the column(s) to match, can be a common name or an equality expression\n that matches every input table, i.e. \"col_a = col_b\" to rename output column names. Note: When\n MultiJoinInput objects are supplied, this parameter must be omitted.\n\n Returns:\n MultiJoinTable: the result of the multi-table natural join operation. To access the underlying Table, use the\n table() method.\n \"\"\"\n return MultiJoinTable(input, on)","repo_name":"deephaven/deephaven-core","sub_path":"py/server/deephaven/table.py","file_name":"table.py","file_ext":"py","file_size_in_byte":167943,"program_lang":"python","lang":"en","doc_type":"code","stars":210,"dataset":"github-code","pt":"48"} +{"seq_id":"19714128781","text":"import time\r\n\r\nfrom appium import webdriver\r\nfrom appium.webdriver.common.appiumby import AppiumBy\r\n\r\ndesired_cap = {\r\n \"appium:deviceName\": \"Android Emulator\",\r\n \"platformName\": \"Android\",\r\n \"appium:appPackage\": \"com.walmart.android\",\r\n \"appium:appWaitActivity\": \"com.walmart.glass.onboarding.view.OnboardingActivity\",\r\n \"appium:app\": \"C:\\\\Users\\\\Pranshu Sharma\\\\Downloads\\\\walmart-22-18.apk\"\r\n}\r\ndriver = webdriver.Remote(\"http://127.0.0.1:4723/wd/hub\",desired_cap)\r\n\r\n\r\ndriver.find_element_by_id(\"com.walmart.android:id/onboarding_get_started_button\").click()\r\ntime.sleep(2)\r\ndriver.find_element_by_id(\"com.walmart.android:id/onboarding_zip_code_button\").click()\r\ntime.sleep(2)\r\ndriver.find_element_by_id(\"com.walmart.android:id/onboarding_zip_code_textinput\").send_keys(\"94088\")\r\ntime.sleep(2)\r\ndriver.find_element_by_id(\"com.walmart.android:id/onboarding_zip_code_search_button\").click()\r\n#driver.find_element_by_id(\"com.walmart.android:id/error_button\").click()\r\n\r\n","repo_name":"PranshuS007/APPIUM","sub_path":"appium1.py","file_name":"appium1.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23865565427","text":"\n####### Return multiple values #############\n\ndef raise_to_power(value1, value2):\n \"\"\"Raise value1 to the power of value2.\"\"\"\n new_value = value1 ** value2\n new_value1 = value1 + value2\n return new_value,new_value1\nresult = raise_to_power(2, 3)\nprint(result) \n\n\n\n'''def raise_both(value1, value2):\n \"\"\"Raise value1 to the power of value2\n and vice versa.\"\"\"\n new_value1 = value1 ** value2\n new_value2 = value2 ** value1\n new_tuple = (new_value1, new_value2)\n return new_tuple\n#Returning multiple values\nresult = raise_both(2, 3)\nprint(result) '''\n","repo_name":"Preeti1122/python","sub_path":"return_multiple_values.py","file_name":"return_multiple_values.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25076837522","text":"from flask import Flask, render_template, redirect, jsonify\r\nfrom data import db_session, us_api\r\nfrom data.users import User\r\nfrom flask import make_response\r\nfrom flask_login import LoginManager, login_user, login_required, current_user, logout_user\r\nfrom data.login import LoginForm\r\nfrom data.register import RegisterForm\r\n\r\n\r\n\r\napp = Flask(__name__)\r\napp.config['SECRET_KEY'] = 'yandexlyceum_secret_key'\r\n\r\n\r\nlogin_manager = LoginManager()\r\nlogin_manager.init_app(app)\r\n\r\n\r\n@app.route('/download', methods=['GET'])\r\ndef download():\r\n form = LoginForm()\r\n if form.validate_on_submit():\r\n db_sess = db_session.create_session()\r\n user = db_sess.query(User).filter(User.email == form.email.data).first()\r\n if user and user.check_password(form.password.data):\r\n login_user(user, remember=form.remember_me.data)\r\n return redirect(\"/\")\r\n return render_template('login.html',\r\n message=\"Неправильный логин или пароль\",\r\n form=form)\r\n return render_template('download.html', title='Скачать версии')\r\n\r\n\r\n@app.route('/login', methods=['GET', 'POST'])\r\ndef login():\r\n form = LoginForm()\r\n if form.validate_on_submit():\r\n db_sess = db_session.create_session()\r\n user = db_sess.query(User).filter(User.email == form.email.data).first()\r\n if user and user.check_password(form.password.data):\r\n login_user(user, remember=form.remember_me.data)\r\n return redirect(\"/\")\r\n return render_template('login.html',\r\n message=\"Неправильный логин или пароль\",\r\n form=form)\r\n return render_template('login.html', title='Авторизация', form=form)\r\n\r\n\r\n@app.route('/register', methods=['GET', 'POST'])\r\ndef reqister():\r\n form = RegisterForm()\r\n if form.validate_on_submit():\r\n if form.password.data != form.password_again.data:\r\n return render_template('register.html', title='Регистрация',\r\n form=form,\r\n message=\"Пароли не совпадают\")\r\n db_sess = db_session.create_session()\r\n if db_sess.query(User).filter(User.email == form.email.data).first():\r\n return render_template('register.html', title='Регистрация',\r\n form=form,\r\n message=\"Такой пользователь уже есть\")\r\n user = User(\r\n name=form.name.data,\r\n email=form.email.data,\r\n about=form.about.data\r\n )\r\n user.set_password(form.password.data)\r\n db_sess.add(user)\r\n db_sess.commit()\r\n login_user(user, remember=form.remember_me.data)\r\n return redirect('/')\r\n return render_template('register.html', title='Регистрация', form=form)\r\n\r\n\r\n@app.route('/logout')\r\n@login_required\r\ndef logout():\r\n logout_user()\r\n return redirect(\"/\")\r\n\r\n\r\n@login_manager.user_loader\r\ndef load_user(user_id):\r\n db_sess = db_session.create_session()\r\n return db_sess.query(User).get(user_id)\r\n\r\n\r\n@app.errorhandler(404)\r\ndef not_found(error):\r\n return make_response(jsonify({'error': 'Not found'}), 404)\r\n\r\n\r\n@app.errorhandler(400)\r\ndef bad_request(_):\r\n return make_response(jsonify({'error': 'Bad Request'}), 400)\r\n\r\n\r\n@app.route('/place')\r\ndef place():\r\n db_sess = db_session.create_session()\r\n user = db_sess.query(User).get(User.user_id).all()[0]\r\n return user.place\r\n\r\n\r\n@app.route('/')\r\ndef table():\r\n return render_template('table.html', title='table')\r\n\r\n\r\n@app.route('/us')\r\ndef us():\r\n return\r\n\r\n\r\ndef main():\r\n db_session.global_init(\"db/blogs.db\")\r\n app.register_blueprint(us_api.blueprint)\r\n app.run(port=5000, host='127.0.0.1')\r\n\r\n\r\nmain()\r\n","repo_name":"mensafromgithub/pg_site","sub_path":"pg_site/pril.py","file_name":"pril.py","file_ext":"py","file_size_in_byte":3960,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4147865575","text":"import re\n\nINPUT_PATH = \"input\"\nSTACKS_COUNT = 9\n\nanswer = 0\nstacks = [ [] for _ in range(STACKS_COUNT) ]\nmoves = []\n\ninput = open(INPUT_PATH)\ncontent = input.readlines()\n\nfor i in reversed(range(8)):\n crates = []\n for j in range(1, len(content[7]), 4):\n crates.append(content[i][j] if content[i][j] != ' ' else None)\n for j in range(STACKS_COUNT):\n if crates[j] is None:\n continue\n stacks[j].append(crates[j])\n\ninstructions = content[10:]\n\nfor instruction in instructions:\n if not instruction:\n continue\n count, src, dest = list(map(int, re.search(r'move (\\d+) from (\\d) to (\\d)', instruction).groups()))\n crates = stacks[src - 1][len(stacks[src - 1]) - count:]\n del stacks[src - 1][len(stacks[src - 1]) - count:]\n stacks[dest - 1].extend(crates)\n\nanswer = ''.join([ stack[-1] for stack in stacks ])\nprint(f\"Answer: {answer}\")","repo_name":"furtivesock/advent-of-code-2022","sub_path":"day5/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18273636533","text":"#Scarlette Bello Barron 0860234\n#Q3\n\n#empty list...\nstudent1 = []\nstudent2 = []\nstudent3 = []\n\n#asking to the user for three student's data to insert it in the lists...\nlastName1, grade1_1, grade2_1, grade3_1, grade4_1 = input(\"Please enter the first student's last name followed by your four grades: \").split()\nlastName2, grade1_2, grade2_2, grade3_2, grade4_2 = input(\"Please enter the second student's last name followed by your four grades: \").split()\nlastName3, grade1_3, grade2_3, grade3_3, grade4_3 = input(\"Please enter the thirth student's last name followed by your four grades: \").split()\n\n#lists wuth data...\nstudent1 = [lastName1, grade1_1, grade2_1, grade3_1, grade4_1]\nstudent2 = [lastName2, grade1_2, grade2_2, grade3_2, grade4_2]\nstudent3 = [lastName3, grade1_3, grade2_3, grade3_3, grade4_3]\n\n#calculating grade averages...\naverage1 = (int(student1[1]) + int(student1[2]) + int(student1[3]) + int(student1[4]))/4\naverage2 = (int(student2[1]) + int(student2[2]) + int(student2[3]) + int(student2[4]))/4\naverage3 = (int(student3[1]) + int(student3[2]) + int(student3[3]) + int(student3[4]))/4\n\n#adding averages into the lists...\nstudent1.append(average1)\nstudent2.append(average2)\nstudent3.append(average3)\n\nprint(student1)\nprint(student2)\nprint(student3)\n\n\n\n\n\n\n\n","repo_name":"ScarletteBel/LearningDataScience-","sub_path":"Python/PyBasics/Assignment2/Q3-Assig1Scarlette.py","file_name":"Q3-Assig1Scarlette.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74905364305","text":"# 여러 번의 거래로 낼 수 있는 최대 이익을 산출하라.\nnums = [7,1,5,3,6,4]\n\ndef maxProfit(nums):\n result = 0\n for i in range(len(nums)-1):\n if nums[i] < nums[i+1]:\n result += nums[i+1] -nums[i]\n return result\n\nprint(maxProfit(nums)) \n\n# pythonic way\ndef maxProfit(nums):\n # 0보다 크면 무조건 합산\n return sum(max(nums[i + 1] - nums[i], 0) for i in range(len(nums) - 1))\nprint(maxProfit(nums))","repo_name":"limnyn/python_codingtest","sub_path":"Algorithm_Interview/78_주식을사고팔기가장좋은시점2.py","file_name":"78_주식을사고팔기가장좋은시점2.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28189331545","text":"try:\n\t_maya_check = True\n\timport Scripts.Global_Constants.Nodes\n\timport Scripts.NodeCls.M_Nodes\n\timport Scripts.UIFns.Find_UI\n\timport maya.cmds as cmds\n\tif not len(cmds.fileInfo( 'AW_Vray_States_Viewer_Version', query=True )):\n\t\t# version = cmds.confirmDialog( title='Viewer Version', message='The Viewer Version For This File Has Not Been Set\\nPlease Select The Version You Would Like To Use\\n\\nWarning!! Version 2 is Still In Beta', button=['Version 1','Version 2'], defaultButton='Version 1', cancelButton='Version 1', dismissString='Version 1' )[-1]\n\t\tcmds.fileInfo( 'AW_Vray_States_Viewer_Version', \"1\" )\nexcept:\n\t_maya_check = False\nimport os\nimport string\nimport yaml\nimport QT\nimport QT.DataModels.Qt_Roles_And_Enums\nimport Scripts.Tools.Vray_Scene_States_Manager.Custom_Widgets\nimport Compiled_UIs.Vray_Scene_State_Viewer\nimport Scripts.General_Maya_Util\nCustom_Widgets = Scripts.Tools.Vray_Scene_States_Manager.Custom_Widgets\nVray_Scene_State_Viewer_Item_Model = Custom_Widgets.Vray_Scene_State_Viewer_Item_Model\nQt_Roles_And_Enums = QT.DataModels.Qt_Roles_And_Enums\nFile_Dialog_Options = QT.DataModels.Qt_Roles_And_Enums.File_Dialog_Options\nQt = QT.Qt\nQtCore = QT.QtCore\nQtGui = QT.QtGui\nuic = QT.uic\n\n\nui_file = os.path.realpath(os.path.dirname(__file__)+\"\\Vray_Scene_State_Viewer.ui\")\nuiform, uibase = uic.loadUiType(ui_file)\n\nclass Enum_List_Delegate(QtGui.QItemDelegate):\n\tdef get_item_from_index(self, index):\n\t\tisinstance(index, QtCore.QModelIndex)\n\t\tm = index.model()\n\t\tif isinstance(m, QtGui.QSortFilterProxyModel):\n\t\t\tpm = m\n\t\t\tm = m.sourceModel()\n\t\t\tindex = pm.mapToSource(index)\n\t\titem = m.itemFromIndex(index)\n\t\treturn item\n\tdef createEditor(self, parent, option, index):\n\t\tisinstance(index, QtCore.QModelIndex)\n\t\titem = self.get_item_from_index(index)\n\t\tif isinstance(item, Custom_Widgets.Enum_Plug_Item):\n\t\t\tif len(item.node_listEnumNames):\n\t\t\t\teditor = QtGui.QComboBox(parent)\n\t\t\t\teditor.addItems(item.node_listEnumNames)\n\t\t\t\treturn editor\n\t\teditor = super(Enum_List_Delegate, self).createEditor(parent, option, index)\n\t\treturn editor\n\n\tdef setEditorData(self, editor, index):\n\t\tif isinstance(editor, QtGui.QComboBox):\n\t\t\titem = self.get_item_from_index(index)\n\t\t\teditor.setCurrentIndex(item._data.value)\n\t\telse:\n\t\t\tsuper(Enum_List_Delegate, self).setEditorData(editor, index)\n\n\tdef setModelData(self, editor, model, index):\n\t\tif isinstance(editor, QtGui.QComboBox):\n\t\t\titem = self.get_item_from_index(index)\n\t\t\titem.setData(editor.currentText())\n\t\telse:\n\t\t\tsuper(Enum_List_Delegate, self).setModelData(editor, model, index)\n\n\tdef updateEditorGeometry(self, editor, option, index):\n\t\teditor.setGeometry(option.rect)\n\n########################################################################\n# uiform, QtGui.QMainWindow\nclass Vray_Scene_States_Viewer_MainWindow(uiform, QtGui.QMainWindow):\n#class Vray_Scene_States_Viewer_MainWindow(Compiled_UIs.Vray_Scene_State_Viewer.Ui_Vray_Scene_States_Viewer,QtGui.QMainWindow):\n\t#----------------------------------------------------------------------\n\tACTIVE_RENDER_LAYER_CHANGED = QT.QtSignal()\n\tNEW_RENDER_LAYER_CREATED = QT.QtSignal()\n\tdef __init__(self, parent=None):\n\t\tif parent == None and _maya_check:\n\t\t\tparent = Scripts.UIFns.Find_UI.getMayaWindow()\n\t\tisinstance(self, Compiled_UIs.Vray_Scene_State_Viewer.Ui_Vray_Scene_States_Viewer)\n\t\tsuper(Vray_Scene_States_Viewer_MainWindow,self).__init__(parent)\n\t\tself.setupUi(self)\n\t\t#self.Asset_Grid_groupBox.hide()\n\t\tself.entity_tree_view.hide()\n\t\tif self.Version_Check() == 2:\n\t\t\tself.Update_Button.hide()\n\t\tself.model = Vray_Scene_State_Viewer_Item_Model(self)\n\t\tself.asset_filtered_model = Custom_Widgets.Master_Asset_Item_Filter_ProxyModel(parent=self)\n\t\tself.asset_filtered_model.setSourceModel(self.model)\n\t\tself.Update_Button.clicked.connect(self.Run_Update)\n\t\tself.rebuild_Render_layer_states_button.clicked.connect(self.Rebuild_Render_Layer_States)\n\t\t# cmds.scriptJob(e=[\"renderLayerChange\", self.update_on_render_layer_Added], killWithScene=True)\n\t\tself._Render_Layer_Changed_Script_Job_ID = cmds.scriptJob(e=[\"renderLayerManagerChange\", self.emit_render_layer_changed], killWithScene=True)\n\t\t\n\tdef Version_Check(self):\n\t\treturn Scripts.Tools.Vray_Scene_States_Manager.Custom_Widgets.Viewer_Version_check()\n\t#----------------------------------------------------------------------\n\tdef run_Item_View_Assinments(self):\n\t\tself.entity_tree_view.setModel(self.asset_filtered_model)\n\t\tdelegate = Enum_List_Delegate()\n\t\tself.entity_tree_view.setItemDelegate(delegate)\n\t\tself.Asset_Grid_widget.build_Master_Assets_Grid(self.model.File_References)\n\t#----------------------------------------------------------------------\n\tdef show(self):\n\t\tsuper(Vray_Scene_States_Viewer_MainWindow, self).show()\n\t\tself.run_Item_View_Assinments()\n\t\t\n\tdef emit_render_layer_changed(self):\n\t\tself.ACTIVE_RENDER_LAYER_CHANGED.emit()\n\t\tif self.Version_Check() == 2:\n\t\t\ttry:\n\t\t\t\tactive_layer = Scripts.NodeCls.M_Nodes.RenderLayer(cmds.editRenderLayerGlobals( query=True, currentRenderLayer=True ))\n\t\t\t\tif cmds.objExists(\"Vray_Scene_States_Global_Render_Group\"):\n\t\t\t\t\tmaster_node = Scripts.NodeCls.M_Nodes.MNODE(\"Vray_Scene_States_Global_Render_Group\")\n\t\t\t\t\tactive_layer.addMembers([master_node])\n\t\t\t\telse:\n\t\t\t\t\tmaster_node = None\n\t\t\texcept:\n\t\t\t\tmaster_node = None\n\t\n\tdef update_on_render_layer_Added(self):\n\t\tfor file_ref in self.model.File_References.Children:\n\t\t\tfor asset in file_ref.Children:\n\t\t\t\tisinstance(asset, Custom_Widgets.Asset_Item)\n\t\t\t\tfor layer in [layer for layer in Scripts.Global_Constants.Nodes.Render_Layers() if not \":\" in layer.name]:\n\t\t\t\t\tasset.enum_render_states_plug.enable_Render_Layer_Overide(layer=layer)\n\t\n\tdef Rebuild_Render_Layer_States(self):\n\t\tactive_layer = Scripts.NodeCls.M_Nodes.RenderLayer(cmds.editRenderLayerGlobals( query=True, currentRenderLayer=True ))\n\t\tlayers = [layer for layer in Scripts.Global_Constants.Nodes.Render_Layers() if not \":\" in layer.name]\n\t\tif self.Version_Check() == 1:\n\t\t\tfor layer in layers:\n\t\t\t\tlayer.makeCurrent()\n\t\t\t\tself.emit_render_layer_changed()\n\t\t\t\t# cmds.refresh(force=True)\n\t\t\t\tfor file_ref in self.model.File_References.Children:\n\t\t\t\t\tfor asset in file_ref.Children:\n\t\t\t\t\t\tisinstance(asset, Custom_Widgets.Asset_Item)\n\t\t\t\t\t\tasset.clear_Children_From_Render_Layer()\n\t\t\t\t\t\t# cmds.refresh(force=True)\n\t\tfor layer in layers:\n\t\t\tisinstance(layer, Scripts.NodeCls.M_Nodes.RenderLayer)\n\t\t\tlayer.makeCurrent()\n\t\t\tself.emit_render_layer_changed()\n\t\t\t# cmds.refresh(force=True)\n\t\t\tfor item in self.Asset_Grid_widget.items:\n\t\t\t\tisinstance(item, Custom_Widgets.Asset_Frame)\n\t\t\t\tcurrent = item.asset_states.currentIndex()\n\t\t\t\titem.asset_states.setCurrentIndex(0)\n\t\t\t\titem.asset_states.update_asset_attribute()\n\t\t\t\t# cmds.refresh(force=True)\n\t\t\t\titem.asset_states.setCurrentIndex(current)\n\t\t\t\titem.asset_states.update_asset_attribute()\n\t\t\t\t# cmds.refresh(force=True)\n\t\tactive_layer.makeCurrent()\n\t#----------------------------------------------------------------------\n\tdef showEvent(self, event):\n\t\tsuper(Vray_Scene_States_Viewer_MainWindow, self).showEvent(event)\n\t#----------------------------------------------------------------------\n\tdef hideEvent(self, event):\n\t\tsuper(Vray_Scene_States_Viewer_MainWindow, self).hideEvent(event)\n\n\t#----------------------------------------------------------------------\n\tdef Run_Update(self):\n\t\t\"\"\"\"\"\"\n\t\tcheck = cmds.confirmDialog( title='Viewer Version', message='If You Update To Version 2.\\nAll Your Render Layers Will Be Cleared\\nAnd Group Node Called\\nVray_Scene_States_Global_Render_Group Will Be Added\\nParent All Top Level Reference Node Under It\\nAnd The Display Layers Will Take Care Of The Rest\\n\\n WARNING!!! BEFORE YOU UPDATE!!!\\nANY FILES THAT ARE REFS.\\nTHAT THE SCENE STATE MANAGER WAS USED ON\\nNEED TO HAVE HAD THE Sync Display Layers RUN FOR THE NEW VERSION TO WORK\\n\\nDo you Want To Continue', button=['yes','no'], defaultButton='no', cancelButton='no', dismissString='no' )\n\t\tif check == \"yes\":\n\t\t\tcmds.fileInfo( 'AW_Vray_States_Viewer_Version', \"2\" )\n\t\t\tself.model.run_update(full=True)\n\t\t\tself.Rebuild_Render_Layer_States()\n\t\t\tself.Update_Button.hide()\nStates_Viewer = None\nisinstance(States_Viewer, Compiled_UIs.Vray_Scene_State_Viewer.Ui_Vray_Scene_States_Viewer)\n\ndef make_ui():\n\tglobal States_Viewer\n\tif States_Viewer == None:\n\t\tStates_Viewer = Vray_Scene_States_Viewer_MainWindow()\n\t\tStates_Viewer.show()\n\t\tcmds.scriptJob(runOnce=True, event= [\"deleteAll\",remove_Viewer])\n\telif Scripts.General_Maya_Util.getModifier() == 'Ctrl+Alt+Shift':\n\t\tcmds.scriptJob(kill=States_Viewer._Render_Layer_Changed_Script_Job_ID)\n\t\tremove_Viewer()\n\t\tStates_Viewer = Vray_Scene_States_Viewer_MainWindow()\n\t\tStates_Viewer.show()\n\telse:\n\t\tStates_Viewer.show()\n\treturn States_Viewer\n\ndef remove_Viewer():\n\tglobal States_Viewer\n\tStates_Viewer.hide()\n\tStates_Viewer.setParent(None)\n\tStates_Viewer = None\n\t\n","repo_name":"SGSMarkNA/Maya","sub_path":"Scripts/Tools/Vray_Scene_States_Manager/old/Vray_Scene_States_Viewer.py","file_name":"Vray_Scene_States_Viewer.py","file_ext":"py","file_size_in_byte":8837,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31358264593","text":"\"\"\"\nReferences of the code:\nhttps://github.com/vikasverma1077/manifold_mixup/blob/master/supervised/plots.py\nThis code is responsible to plot information and save the result as a png file in the GPU Cluster.\n\"\"\"\nimport os, sys\nsys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))\nif sys.version_info[0] < 3:\n import cPickle as pickle\nelse:\n import _pickle as pickle\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\nsns.set(color_codes=True)\n\n\nplot_from_index=-10000\n\n\ndef plotting(exp_dir):\n # Load the training log dictionary:\n train_dict = pickle.load(open(os.path.join(exp_dir, 'log.pkl'), 'rb'))\n\n ###########################################################\n ### Make the vanilla train and test loss per epoch plot ###\n ###########################################################\n \n plt.plot(np.asarray(train_dict['train_loss']), label='train_loss')\n plt.plot(np.asarray(train_dict['test_loss']), label='test_loss')\n\n #plt.ylim(0,2000)\n plt.xlabel('evaluation step')\n plt.ylabel('metrics')\n plt.tight_layout()\n plt.legend(loc='upper right')\n plt.savefig(os.path.join(exp_dir, 'loss.png' ))\n plt.clf()\n \n ## accuracy###\n plt.plot(np.asarray(train_dict['train_acc']), label='train_acc')\n plt.plot(np.asarray(train_dict['test_acc']), label='test_acc')\n \n #plt.ylim(0,2000)\n plt.xlabel('evaluation step')\n plt.ylabel('metrics')\n plt.tight_layout()\n plt.legend(loc='upper right')\n plt.savefig(os.path.join(exp_dir, 'acc.png' ))\n plt.clf()\n\n \nif __name__ == '__main__':\n plotting('temop')\n","repo_name":"chandar-lab/PatchUp","sub_path":"utility/plots.py","file_name":"plots.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"48"} +{"seq_id":"32454614445","text":"from __future__ import absolute_import\n\nimport base64\nimport boto3\nimport pytest\n\npytestmark = pytest.mark.unit\n\nfrom main import (\n create_and_get_semver_dir,\n _get_version_tags,\n create_major_version_artifacts,\n create_minor_version_artifacts,\n create_patch_version_artifacts,\n build_images,\n _push_images_upstream\n)\nfrom utils import get_semver\nimport os\nfrom unittest.mock import patch, Mock, MagicMock\n\n\nclass CreateVersionArgs:\n def __init__(self, runtime_version_upgrade_type, base_patch_version,\n pre_release_identifier=None):\n self.base_patch_version = base_patch_version\n self.runtime_version_upgrade_type = runtime_version_upgrade_type\n self.pre_release_identifier = pre_release_identifier\n self.force = False\n\n\nclass BuildImageArgs:\n def __init__(self, target_patch_version, target_ecr_repo=None):\n self.target_patch_version = target_patch_version\n self.target_ecr_repo = target_ecr_repo\n self.skip_tests = True\n\n\ndef _create_docker_cpu_env_in_file(file_path):\n with open(file_path, 'w') as env_in_file:\n env_in_file.write('conda-forge::ipykernel\\n')\n\n\ndef _create_docker_cpu_env_out_file(file_path):\n with open(file_path, 'w') as env_out_file:\n env_out_file.write('''# This file may be used to create an environment using:\n # $ conda create --name --file \n # platform: linux-64\n @EXPLICIT\n https://conda.anaconda.org/conda-forge/noarch/ipykernel-6.21.3-pyh210e3f2_0.conda#8c1f6bf32a6ca81232c4853d4165ca67\\n''')\n\n\ndef _create_docker_gpu_env_in_file(file_path):\n with open(file_path, 'w') as env_in_file:\n env_in_file.write('conda-forge::numpy\\n')\n\n\ndef _create_docker_gpu_env_out_file(file_path):\n with open(file_path, 'w') as env_out_file:\n env_out_file.write('''# This file may be used to create an environment using:\n # $ conda create --name --file \n # platform: linux-64\n @EXPLICIT\n https://conda.anaconda.org/conda-forge/linux-64/numpy-1.24.2-py38h10c12cc_0.conda#05592c85b9f6931dc2df1e80c0d56294\\n''')\n\n\ndef _create_docker_file(file_path):\n with open(file_path, 'w') as docker_file:\n docker_file.write('''ARG TAG_FOR_BASE_MICROMAMBA_IMAGE\n FROM mambaorg / micromamba:$TAG_FOR_BASE_MICROMAMBA_IMAGE\\n''')\n\n\ndef _create_new_version_artifacts_helper(mocker, tmp_path, version):\n\n def mock_get_dir_for_version(base_version):\n pre_release_suffix = '/v' + str(base_version) if base_version.prerelease else ''\n version_string = f'v{base_version.major}.{base_version.minor}.{base_version.patch}' + \\\n pre_release_suffix\n return tmp_path / version_string\n\n mocker.patch('main.get_dir_for_version', side_effect=mock_get_dir_for_version)\n input_version = get_semver(version)\n # Create directory for base version\n input_version_dir = create_and_get_semver_dir(input_version)\n # Create env.in and env.out for base version\n _create_docker_cpu_env_in_file(input_version_dir / 'cpu.env.in')\n _create_docker_gpu_env_in_file(input_version_dir / 'gpu.env.in')\n _create_docker_cpu_env_out_file(input_version_dir / 'cpu.env.out')\n _create_docker_gpu_env_out_file(input_version_dir / 'gpu.env.out')\n os.makedirs(tmp_path / 'template')\n _create_docker_file(tmp_path / 'template' / 'Dockerfile')\n\n\ndef test_get_semver_version():\n # Test invalid version string.\n with pytest.raises(Exception):\n get_semver('1.124.5d')\n # Test version string with build\n with pytest.raises(Exception):\n get_semver('1.124.5+25')\n # Test version string with build and prerelease\n with pytest.raises(Exception):\n get_semver('1.124.5-prerelease+25')\n # Test valid version string.\n assert get_semver('1.124.5') is not None\n assert get_semver('1.124.5-beta') is not None\n\n\ndef test_new_version_artifacts_for_an_input_prerelease_version():\n input_version = '1.23.0-beta'\n args = CreateVersionArgs('patch', input_version)\n with pytest.raises(Exception):\n create_patch_version_artifacts(args)\n args = CreateVersionArgs('minor', input_version)\n with pytest.raises(Exception):\n create_minor_version_artifacts(args)\n args = CreateVersionArgs('major', input_version)\n with pytest.raises(Exception):\n create_major_version_artifacts(args)\n\n\n@patch('os.path.exists')\n@patch('os.path.isdir')\n@patch('shutil.rmtree')\n@patch('os.makedirs')\ndef test_create_and_get_semver_dir(mock_make_dirs, mock_rmtree,\n mock_path_is_dir, mock_path_exists):\n # case 1: Directory exists and exist_ok is False => Throws Exception\n mock_path_exists.return_value = True\n with pytest.raises(Exception):\n create_and_get_semver_dir(get_semver('1.124.5'))\n # Case 2: Instead of a directory in the path, a file exists.\n mock_path_is_dir.return_value = False\n with pytest.raises(Exception):\n create_and_get_semver_dir(get_semver('1.124.5'), True)\n # Happy case\n mock_path_is_dir.return_value = True\n assert create_and_get_semver_dir(get_semver('1.124.5'), True) is not None\n\n\ndef test_create_new_version_artifacts_for_invalid_upgrade_type():\n input = CreateVersionArgs('test_upgrade', '1.2.3')\n with pytest.raises(Exception):\n create_major_version_artifacts(input)\n with pytest.raises(Exception):\n create_minor_version_artifacts(input)\n with pytest.raises(Exception):\n create_patch_version_artifacts(input)\n\n\ndef _create_and_assert_patch_version_upgrade(rel_path, mocker, tmp_path,\n pre_release_identifier=None):\n input_version = '1.2.5'\n new_version_dir = tmp_path / 'v1.2.6'\n if pre_release_identifier:\n new_version_dir = new_version_dir / ('v1.2.6-' + pre_release_identifier)\n rel_path.side_effect = [str(tmp_path / 'template' / 'Dockerfile')]\n _create_new_version_artifacts_helper(mocker, tmp_path, input_version)\n args = CreateVersionArgs('patch', input_version, pre_release_identifier=pre_release_identifier)\n create_patch_version_artifacts(args)\n # Assert new version directory is created\n\n assert os.path.exists(new_version_dir)\n # Check cpu.env.in and gpu.env.in exists in the new directory\n new_version_dir_files = os.listdir(new_version_dir)\n assert 'cpu.env.in' in new_version_dir_files\n assert 'gpu.env.in' in new_version_dir_files\n assert 'Dockerfile' in new_version_dir_files\n with open(new_version_dir / 'cpu.env.in', 'r') as f:\n contents = f.read()\n # version of ipykernel in cpu.env.out is 6.21.3\n # so we expect the version string to be >=6.21.3,<6.22.0\n expected_version_string = '>=6.21.3,<6.22.0'\n assert contents.find(expected_version_string) != -1\n with open(new_version_dir / 'gpu.env.in', 'r') as f:\n contents = f.read()\n # version of numpy in gpu.env.out is 1.24.2\n # so we expect the version string to be >=1.24.2,<1.25.0\n expected_version_string = '>=1.24.2,<1.25.0'\n assert contents.find(expected_version_string) != -1\n\n\n@patch(\"os.path.relpath\")\ndef test_create_new_version_artifacts_for_patch_version_upgrade(rel_path, mocker, tmp_path):\n _create_and_assert_patch_version_upgrade(rel_path, mocker, tmp_path)\n\n\n@patch(\"os.path.relpath\")\ndef test_create_new_version_artifacts_for_patch_version_upgrade_with_prerelease(rel_path, mocker,\n tmp_path):\n _create_and_assert_patch_version_upgrade(rel_path, mocker, tmp_path, 'beta')\n\n\ndef _create_and_assert_minor_version_upgrade(rel_path, mocker, tmp_path,\n pre_release_identifier=None):\n input_version = '1.2.5'\n new_version_dir = tmp_path / 'v1.3.0'\n if pre_release_identifier:\n new_version_dir = new_version_dir / ('v1.3.0-' + pre_release_identifier)\n rel_path.side_effect = [str(tmp_path / 'template' / 'Dockerfile')]\n _create_new_version_artifacts_helper(mocker, tmp_path, input_version)\n args = CreateVersionArgs('minor', input_version, pre_release_identifier=pre_release_identifier)\n create_minor_version_artifacts(args)\n # Assert new version directory is created\n assert os.path.exists(new_version_dir)\n # Check cpu.env.in and gpu.env.in exists in the new directory\n new_version_dir_files = os.listdir(new_version_dir)\n assert 'cpu.env.in' in new_version_dir_files\n assert 'gpu.env.in' in new_version_dir_files\n assert 'Dockerfile' in new_version_dir_files\n with open(new_version_dir / 'cpu.env.in', 'r') as f:\n contents = f.read()\n # version of ipykernel in cpu.env.out is 6.21.3\n # so we expect the version string to be >=6.21.3,<7.0.0\n expected_version_string = '>=6.21.3,<7.0.0'\n assert contents.find(expected_version_string) != -1\n with open(new_version_dir / 'gpu.env.in', 'r') as f:\n contents = f.read()\n # version of numpy in gpu.env.out is 1.24.2\n # so we expect the version string to be >=1.24.2,<2.0.0\n expected_version_string = '>=1.24.2,<2.0.0'\n assert contents.find(expected_version_string) != -1\n\n\n@patch(\"os.path.relpath\")\ndef test_create_new_version_artifacts_for_minor_version_upgrade(rel_path, mocker, tmp_path):\n _create_and_assert_minor_version_upgrade(rel_path, mocker, tmp_path)\n\n\n@patch(\"os.path.relpath\")\ndef test_create_new_version_artifacts_for_minor_version_upgrade_with_prerelease(rel_path, mocker,\n tmp_path):\n _create_and_assert_minor_version_upgrade(rel_path, mocker, tmp_path, 'beta')\n\n\ndef _create_and_assert_major_version_upgrade(rel_path, mocker, tmp_path,\n pre_release_identifier=None):\n input_version = '1.2.5'\n new_version_dir = tmp_path / 'v2.0.0'\n if pre_release_identifier:\n new_version_dir = new_version_dir / ('v2.0.0-' + pre_release_identifier)\n rel_path.side_effect = [str(tmp_path / 'template' / 'Dockerfile')]\n _create_new_version_artifacts_helper(mocker, tmp_path, input_version)\n args = CreateVersionArgs('major', input_version, pre_release_identifier=pre_release_identifier)\n create_major_version_artifacts(args)\n # Assert new version directory is created\n assert os.path.exists(new_version_dir)\n # Check cpu.env.in and gpu.env.in exists in the new directory\n new_version_dir_files = os.listdir(new_version_dir)\n assert 'cpu.env.in' in new_version_dir_files\n assert 'gpu.env.in' in new_version_dir_files\n assert 'Dockerfile' in new_version_dir_files\n with open(new_version_dir / 'cpu.env.in', 'r') as f:\n contents = f.read()\n # version of ipykernel in cpu.env.out is 6.21.3\n # so we expect the version string to be >=6.21.3,\n expected_version_string = '>=6.21.3,\\''\n assert contents.find(expected_version_string) != -1\n with open(new_version_dir / 'gpu.env.in', 'r') as f:\n contents = f.read()\n # version of numpy in gpu.env.out is 1.24.2\n # so we expect the version string to be >=1.24.2,\n expected_version_string = '>=1.24.2,\\''\n assert contents.find(expected_version_string) != -1\n\n\n@patch(\"os.path.relpath\")\ndef test_create_new_version_artifacts_for_major_version_upgrade(rel_path, mocker, tmp_path):\n _create_and_assert_major_version_upgrade(rel_path, mocker, tmp_path)\n\n\n@patch(\"os.path.relpath\")\ndef test_create_new_version_artifacts_for_major_version_upgrade_with_prerelease(rel_path, mocker,\n tmp_path):\n _create_and_assert_major_version_upgrade(rel_path, mocker, tmp_path, 'beta')\n\n\ndef test_build_images(mocker, tmp_path):\n mock_docker_from_env = MagicMock(name='_docker_client')\n mocker.patch('main._docker_client', new=mock_docker_from_env)\n version = '1.124.5'\n args = BuildImageArgs(version)\n\n def mock_get_dir_for_version(base_version):\n version_string = f'v{base_version.major}.{base_version.minor}.{base_version.patch}'\n return tmp_path / version_string\n\n mocker.patch('main.get_dir_for_version', side_effect=mock_get_dir_for_version)\n input_version = get_semver(version)\n # Create directory for base version\n input_version_dir = create_and_get_semver_dir(input_version)\n # Create env.in for base version\n _create_docker_cpu_env_in_file(input_version_dir / 'cpu.env.in')\n _create_docker_cpu_env_in_file(input_version_dir / 'gpu.env.in')\n _create_docker_file(input_version_dir / 'Dockerfile')\n # Assert env.out doesn't exist\n assert os.path.exists(input_version_dir / 'cpu.env.out') is False\n assert os.path.exists(input_version_dir / 'gpu.env.out') is False\n mock_image_1 = Mock()\n mock_image_1.id.return_value = 'img1'\n mock_image_2 = Mock()\n mock_image_2.id.return_value = 'img2'\n mock_docker_from_env.images.build.side_effect = [(mock_image_1, 'logs1'), (mock_image_2, 'logs2')]\n mock_docker_from_env.containers.run.side_effect = ['container_logs1'.encode('utf-8'),\n 'container_logs2'.encode('utf-8')]\n # Invoke build images\n build_images(args)\n # Assert env.out exists\n assert os.path.exists(input_version_dir / 'cpu.env.out')\n assert os.path.exists(input_version_dir / 'gpu.env.out')\n # Validate the contents of env.out\n actual_output = set()\n with open(input_version_dir / 'cpu.env.out', 'r') as f:\n actual_output.add(f.read())\n with open(input_version_dir / 'gpu.env.out', 'r') as f:\n actual_output.add(f.read())\n expected_output = {'container_logs1', 'container_logs2'}\n assert actual_output == expected_output\n\n\n@patch('os.path.exists')\ndef test_get_version_tags(mock_path_exists):\n version = get_semver('1.124.5')\n # case 1: The given version is the latest for patch, minor and major\n mock_path_exists.side_effect = [False, False, False]\n assert _get_version_tags(version) == ['1.124.5', '1.124', '1', 'latest']\n # case 2: The given version is the latest for patch, minor but not major\n # case 2.1 The major version is a prerelease version\n mock_path_exists.side_effect = [False, False, True, False]\n assert _get_version_tags(version) == ['1.124.5', '1.124', '1', 'latest']\n # case 2.2 The major version is not a prerelease version\n mock_path_exists.side_effect = [False, False, True, True]\n assert _get_version_tags(version) == ['1.124.5', '1.124', '1']\n # case 3: The given version is the latest for patch and major but not for minor\n # case 3.1 The minor version is a prerelease version (we need to mock path.exists for major\n # version twice - one for the actual directory, one for the docker file)\n mock_path_exists.side_effect = [False, True, False, True, True]\n assert _get_version_tags(version) == ['1.124.5', '1.124', '1']\n # case 3.2 The minor version is not a prerelease version\n mock_path_exists.side_effect = [False, True, True]\n assert _get_version_tags(version) == ['1.124.5', '1.124']\n # case 4: The given version is not the latest for patch, minor, major\n # case 4.1 The patch version is a prerelease version (we need to mock path.exists for minor\n # and major twice - one for the actual directory, one for the docker file)\n mock_path_exists.side_effect = [True, False, True, True, True, True]\n assert _get_version_tags(version) == ['1.124.5', '1.124']\n # case 4.2 The patch version is not a prerelease version\n mock_path_exists.side_effect = [True, True]\n assert _get_version_tags(version) == ['1.124.5']\n # case 5: The given version includes a prerelease identifier\n assert _get_version_tags(get_semver('1.124.5-beta')) == ['1.124.5-beta']\n\n\ndef _test_push_images_upstream(mocker, repository):\n boto3_client = MagicMock()\n expected_client_name = 'ecr-public' if repository.startswith('public.ecr.aws') else 'ecr'\n boto3_mocker = mocker.patch('boto3.client', return_value=boto3_client)\n mock_docker_from_env = MagicMock(name='_docker_client')\n mocker.patch('main._docker_client', new=mock_docker_from_env)\n authorization_token_string = 'username:password'\n encoded_authorization_token = base64.b64encode(authorization_token_string.encode('ascii'))\n authorization_data = {\n 'authorizationToken': encoded_authorization_token\n }\n if expected_client_name == 'ecr':\n # Private ECR client returns a list of authorizationData.\n authorization_data = [authorization_data]\n boto3_client.get_authorization_token.return_value = {\n 'authorizationData': authorization_data\n }\n mock_docker_from_env.images.push.side_effect = None\n _push_images_upstream([{'repository': repository, 'tag': '0.1'}], 'us-west-2')\n assert boto3_mocker.call_args[0][0] == expected_client_name\n\n\ndef test_push_images_upstream_for_private_ecr_repository(mocker):\n repository = 'aws_account_id.dkr.ecr.us-west-2.amazonaws.com/my-repository'\n _test_push_images_upstream(mocker, repository)\n\n\ndef test_push_images_upstream_for_public_ecr_repository(mocker):\n repository = 'public.ecr.aws/registry_alias/my-repository'\n _test_push_images_upstream(mocker, repository)\n\n","repo_name":"sjcahill-fcc/sagemaker-distribution","sub_path":"test/test_main.py","file_name":"test_main.py","file_ext":"py","file_size_in_byte":17367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"41262860735","text":"import cv2\nimport os\nimport numpy as np\nimport tensorflow as tf\nimport time\n\n# width and height of the image (pixels)\nwidth = 160\nheight = 160\n\ndef main():\n # load the classifier\n classifier = define_classifier()\n # load the trained model\n model = load_model()\n # creates a mapping pixel for the gamma values\n mapping = creates_mapping(2)\n # capture the video \n video_capture(classifier, model, mapping)\n\ndef load_model():\n # Get the path of the neural network\n model_path = os.path.join(os.getcwd(), 'models', 'modelo5.hdf5')\n # load the model\n model = tf.keras.models.load_model(model_path)\n\n return model\n\ndef define_classifier():\n # path for the model\n prototxtPath = os.path.join(os.getcwd(), \"models\",\"deploy.prototxt\")\n # path for the weights\n weightsPath = os.path.join(os.getcwd(), \"models\",\"res10_300x300_ssd_iter_140000.caffemodel\")\n # create the net with the structure and the weights\n net = cv2.dnn.readNet(prototxtPath, weightsPath)\n\n return net\n\ndef creates_mapping(gamma):\n # build a lookup table mapping the pixel values [0, 255] to\n\t# their adjusted gamma values\n invGamma = (1.0 / gamma)\n table = np.array([((i / 255.0) ** invGamma) * 255 for i in np.arange(0, 256)]).astype(\"uint8\")\n return table\n \n\ndef detect(frame, classifier, model, mapping):\n # make a copy \n frame_copy = np.copy(frame)\n # obtain the width and height of the image\n (h, w) = frame.shape[:2]\n # change the format of the image from \n blob = cv2.dnn.blobFromImage(frame, 1.0 , (300, 300), (104.0, 177.0, 123.0))\n # Input the image into the classifier\n classifier.setInput(blob)\n # retrieve all the faces found in the image\n faces = classifier.forward()\n\n # Iterate over all the faces\n for i in range(0, faces.shape[2]):\n # check the confidence in each face\n confidence = faces[0,0,i,2]\n\n if confidence > 0.5:\n # compute the (x, y)-coordinates of the bounding box for\n # the object\n box = faces[0, 0, i, 3:7] * np.array([w, h, w, h])\n (startX, startY, endX, endY) = box.astype(\"int\")\n\n # ensure the bounding boxes fall within the dimensions of\n # the frame\n (startX, startY) = (max(0, startX), max(0, startY))\n (endX, endY) = (min(w - 1, endX), min(h - 1, endY))\n face = frame_copy[startY:endY, startX:endX]\n\n # prepare the face\n face = prep_face(face, mapping)\n # execute model\n res = execute_model(face, model) \n # draw rectangle\n frame = draw_result(res, frame, (startX, startY, endX, endY))\n\n return frame \n\ndef draw_result(result, frame, coord):\n\n # Define a font for the text\n font = cv2.FONT_HERSHEY_PLAIN\n\n if result[0][0] > result[0][1]:\n #red\n frame = cv2.rectangle(frame, (coord[0], coord[1]), (coord[2], coord[3]), (0,0,255), 2)\n cv2.putText(frame,'Sin tapabocas',(coord[0],coord[1]-6),font,(2*((coord[3]-coord[0])+(coord[2]-coord[1])))/500,(0,0,255),2,cv2.LINE_AA)\n else:\n #green\n frame = cv2.rectangle(frame, (coord[0], coord[1]), (coord[2], coord[3]), (0,255,0), 2)\n cv2.putText(frame,'Con tapabocas',(coord[0],coord[1]-6),font,(2*((coord[3]-coord[0])+(coord[2]-coord[1])))/500,(0,255,0),2,cv2.LINE_AA)\n \n \n return frame\n\ndef execute_model(face, model):\n # Predict based on an entry\n result = model.predict(face)\n\n return result\n\ndef prep_face(face, mapping):\n # modify the width and height of the image\n image_f = cv2.resize(face, (width, height))\n # Adjust the gamma of the image\n image_f = cv2.LUT(image_f, mapping)\n # change the color from RGB to grayscale\n image_f = cv2.cvtColor(image_f, cv2.COLOR_BGR2GRAY)\n image_f = cv2.equalizeHist(image_f)\n # reshape\n image_f = np.reshape(image_f, (-1, width, height, 1))\n # normalize the image\n image_f = image_f/255\n\n return image_f\n\ndef video_capture(classifier, model, mapping):\n # the argument is the \"position\" of the camera\n cam = cv2.VideoCapture(0)\n\n while(True):\n # Capture frame by frame\n ret, frame = cam.read()\n\n # In here we should do our operations\n frame = detect(frame, classifier, model, mapping)\n\n # Display the resulting frame\n cv2.imshow('frame',frame)\n\n time.sleep(0.025)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n \n # When everything done, release the capture\n cam.release()\n cv2.destroyAllWindows()\n\nif __name__ == \"__main__\":\n main()","repo_name":"mateoepalza/AI_mask","sub_path":"video_cv.py","file_name":"video_cv.py","file_ext":"py","file_size_in_byte":4609,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14274472797","text":"import numpy as np\nimport cv2\nimport mediapipe as mp\nfrom mediapipe.tasks import python\nfrom mediapipe.tasks.python import vision\n\n\nfrom mediapipe import solutions\nfrom mediapipe.framework.formats import landmark_pb2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nINDEX_LANDMARK = 8\nTHUMB_LANDMARK = 4\n\nMARGIN = 10 # pixels\nFONT_SIZE = 1\nFONT_THICKNESS = 1\nHANDEDNESS_TEXT_COLOR = (88, 205, 54) # vibrant green\n\ndef draw_landmarks_on_image(rgb_image, detection_result):\n hand_landmarks_list = detection_result.hand_landmarks\n handedness_list = detection_result.handedness\n annotated_image = np.copy(rgb_image)\n\n # Loop through the detected hands to visualize.\n for idx in range(len(hand_landmarks_list)):\n hand_landmarks = hand_landmarks_list[idx]\n handedness = handedness_list[idx]\n\n # Draw the hand landmarks.\n hand_landmarks_proto = landmark_pb2.NormalizedLandmarkList()\n hand_landmarks_proto.landmark.extend([\n landmark_pb2.NormalizedLandmark(x=landmark.x, y=landmark.y, z=landmark.z) for landmark in hand_landmarks\n ])\n solutions.drawing_utils.draw_landmarks(\n annotated_image,\n hand_landmarks_proto,\n solutions.hands.HAND_CONNECTIONS,\n solutions.drawing_styles.get_default_hand_landmarks_style(),\n solutions.drawing_styles.get_default_hand_connections_style())\n # Get the top left corner of the detected hand's bounding box.\n height, width, _ = annotated_image.shape\n x_coordinates = [landmark.x for landmark in hand_landmarks]\n y_coordinates = [landmark.y for landmark in hand_landmarks]\n text_x = int(min(x_coordinates) * width)\n text_y = int(min(y_coordinates) * height) - MARGIN\n\n # Draw handedness (left or right hand) on the image.\n cv2.putText(annotated_image, f\"{handedness[0].category_name}\",\n (text_x, text_y), cv2.FONT_HERSHEY_DUPLEX,\n FONT_SIZE, HANDEDNESS_TEXT_COLOR, FONT_THICKNESS, cv2.LINE_AA)\n\n \n\n\n return annotated_image\n\n\ncap = cv2.VideoCapture(0)\n\n# crear detector\nMODEL_PATH = \"13.mediapipe/models/hand_landmarker.task\"\nbase_options = python.BaseOptions(model_asset_path=MODEL_PATH)\noptions = vision.HandLandmarkerOptions(base_options=base_options,\n num_hands=2)\n# detector = vision.HandLandmarker.create_from_options(options)\n\n# verificar conexion\nif not cap.isOpened():\n print(\"No se puede abrir webcam\")\n\n\n# para usar frames de la webcam se necesita un context manager\nwith vision.HandLandmarker.create_from_options(options) as detector:\n\n while True:\n # lectura de un frame\n ret, frame = cap.read()\n # operaciones con el frame\n rgb_frame = mp.Image(image_format=mp.ImageFormat.SRGB, data=frame)\n \n # deteccion del face mesh\n detections = detector.detect(rgb_frame)\n\n out = frame.copy()\n # dibujar landmarks en la imagen\n out = draw_landmarks_on_image(out, detections)\n cv2.imshow(\"out\", out)\n\n # detectar una tecla\n c = cv2.waitKey(1)\n # si la tecla es 'esc'\n if c == 27:\n # salir del bucle\n break\n\n# liberar recursos\ncap.release()\ncv2.destroyAllWindows()\n","repo_name":"tabris2015/infografia-2-2023","sub_path":"13.mediapipe/hand_tracker.py","file_name":"hand_tracker.py","file_ext":"py","file_size_in_byte":3271,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"23970281750","text":"import datetime as dt\nimport helper_function.ask_y_n_statement as ask\nimport uuid\nimport pandas as pd\nimport helper_function.table_dicts as table_dicts\n\n\ndef update_single(conn, cursor, table, column, file_number, var):\n # update a single column in a sql db. Key is user defined.\n sql_update = \"UPDATE \" + table + \" SET \" + column + \"= ? WHERE file_number = '\" + file_number + \"'\"\n cursor.execute(sql_update, [var])\n conn.commit()\n\n\ndef update_single_pk(conn, cursor, table, column, pk_value, pk, var):\n # update a single column in a sql db. Key is user defined.\n sql_update = \"UPDATE \" + table + \" SET \" + column + \"= ? WHERE \" + pk_value + \" = '\" + pk + \"'\"\n cursor.execute(sql_update, [var])\n conn.commit()\n\n\ndef update_single_key(conn, cursor, table, col_list, key_name, key_value, var):\n # update a single column in a sql db. Key is user defined.\n sql_update = \"UPDATE \" + table + \" SET \" + col_list + \"= ? WHERE \" + key_name + \"= '\" + key_value + \"'\"\n cursor.execute(sql_update, [var])\n conn.commit()\n\n\ndef insert(conn, cursor, table, columns, data):\n # insert data in multiple cols in a sql db. adds a new row\n col_number = len(data)\n place_holder = [\"?\"] * col_number\n place_str = \",\".join(place_holder)\n sql_insert = \"INSERT INTO \" + table + \"(\" + columns + \") VALUES (\" + place_str + \")\"\n cursor.execute(sql_insert, data)\n conn.commit()\n\n\ndef insert_file_number(conn, cursor, file_number):\n # insert data in multiple cols in a sql db. adds a new row\n sql_insert = \"INSERT INTO Patient_Information_History(file_number) VALUES (?)\"\n cursor.execute(sql_insert, file_number)\n conn.commit()\n\n\ndef update_multiple(conn, cursor, table, columns, file_number, data):\n # update multiple columns in a sql db. Key is file_number.\n print(data)\n col_number = len(data)\n for index in range(0, col_number):\n sql_update = \"UPDATE \" + table + \" SET \" + columns[index] + \"= ? WHERE file_number = '\" + file_number + \"'\"\n var = data[index]\n cursor.execute(sql_update, [var])\n conn.commit()\n\n\ndef update_multiple_key(conn, cursor, table, columns, key_name, key_value, data):\n # update multiple columns in a sql db. Key is defined at use.\n col_number = len(data)\n # print('col_number is ' + str(col_number))\n for index in range(0, col_number):\n sql_update = \"UPDATE \" + table + \" SET \" + columns[index] + \"= ? WHERE \" + key_name + \"= '\" + key_value + \"'\"\n var = data[index]\n # print(sql_update, var)\n cursor.execute(sql_update, [var])\n conn.commit()\n\n\ndef add_columns(cursor, table, column):\n sql_statement = \"ALTER TABLE \" + table + \" ADD \" + column\n cursor.execute(sql_statement)\n\n\ndef add_columns_old(cursor, table, columns):\n col_number = len(columns)\n for index in range(0, col_number):\n sql_add = \"ALTER TABLE \" + table + \" ADD \" + columns[index]\n cursor.execute(sql_add)\n\n\ndef review_input(file_number, columns, data):\n col_number = len(data)\n print(\"Entries for database are as follows : \")\n for index in range(0, col_number):\n try:\n print(columns[index] + \": \" + data[index])\n except TypeError:\n print('col' + str(columns[index]) + str(data[index]))\n ans = ask.ask_y_n(\"Are entries for file \" + file_number + \" correct ?\", True, False)\n return ans\n\n\ndef review_data(conn, cursor, table, file_number, col_list):\n sql_statement = ('SELECT ' + \", \".join(col_list) + ' FROM ' + table + \" WHERE file_number = '\" + file_number + \"'\")\n data = cursor.execute(sql_statement)\n data_list = data.fetchall()\n data_list = list(data_list[0])\n col_number = len(col_list)\n if data_list == [None]*len(data_list):\n print(\"This section of the database has not been entered\")\n enter = ask.ask_y_n(\"Do you want to enter now\")\n return enter\n if None in set(data_list):\n print(\"Some entries are missing from the database: \")\n for index in range(0, col_number):\n print(col_list[index] + \" : \" + str(data_list[index]))\n enter = ask.ask_option(\"Do you want to proceed?\", [\"Edit all\", \"Add new data only\"])\n if enter == \"Edit all\":\n return True\n else:\n edit_few(conn, cursor, table, col_list, file_number, data_list)\n else:\n print(\"Entries present in database are as follows : \")\n for index in range(0, col_number):\n print(col_list[index] + \" : \" + str(data_list[index]))\n enter = ask.ask_option(\"Do you want to\", [\"Edit all\", \"Edit some entries\", \"Edit None\"])\n if enter == \"Edit some entries\":\n for index in range(0, col_number):\n print(col_list[index] + \" : \" + str(data_list[index]))\n edit = ask.ask_y_n(\"Edit\")\n if edit:\n data = input(\"Data for \" + col_list[index] + \": \")\n update_single(conn, cursor, table, col_list[index], file_number, data)\n return False\n elif enter == \"Edit all\":\n return True\n else:\n return False\n\n\ndef review_data_key(conn, cursor, table, key_name, key_value, columns, col_name, col_value):\n if 'file_number' in columns:\n # remove 1st position from column names (assumes it is file_number)\n col_list = columns[1:]\n else:\n col_list = columns\n sql_statement = 'SELECT ' + \", \".join(col_list) + ' FROM ' + table + \" WHERE \" + key_name + \"= '\" + key_value + \"'\"\n data = cursor.execute(sql_statement)\n data_list = data.fetchall()\n if not data_list:\n print(\"This \" + col_name + ' ' + col_value + ' has not been entered in ' + table)\n enter = ask.ask_y_n(\"Do you want to enter now\")\n if enter:\n add_pk_fk_to_table(conn, cursor, table, col_name=key_name, pk=key_value)\n print('added new row for this ' + key_name)\n return enter\n else:\n data_list = list(data_list[0])\n col_number = len(col_list)\n if data_list == [None]*len(data_list):\n print(\"This section of the database has not been entered\")\n enter = ask.ask_y_n(\"Do you want to enter now\")\n return enter\n elif None in set(data_list):\n print(\"Some entries are missing from the database: \")\n for index in range(0, col_number):\n print(col_list[index] + \" : \" + str(data_list[index]))\n enter = ask.ask_option(\"Do you want to proceed?\", [\"Edit all\", \"Add new data only\"])\n if enter == \"Edit all\":\n return True\n else:\n enter = edit_few(conn, cursor, table, col_list, key_value, data_list)\n return enter\n else:\n print(\"Entries present in database are as follows : \")\n for index in range(0, col_number):\n print(col_list[index] + \" : \" + str(data_list[index]))\n enter = ask.ask_option(\"Do you want to\", [\"Edit all\", \"Edit some entries\", \"Edit None\"])\n if enter == \"Edit some entries\":\n for index in range(0, col_number):\n print(col_list[index] + \" : \" + str(data_list[index]))\n edit = ask.ask_y_n(\"Edit\")\n if edit:\n data = input(\"Data for \" + col_list[index] + \": \")\n update_single_pk(conn, cursor, table, col_list[index], pk_value=key_name, pk=key_value, var=data)\n return False\n elif enter == \"Edit all\":\n return True\n else:\n return False\n\n\ndef edit_few(conn, cursor, table, col_list, file_number, data_list):\n col_number = len(col_list)\n for index in range(0, col_number):\n if data_list[index] is None:\n data = input(\"Data for \"+col_list[index]+\": \")\n update_single(conn, cursor, table, col_list[index], file_number, data)\n return False\n\n\ndef edit_few_key(conn, cursor, table, col_list, key_name, key_value, data_list):\n col_number = len(col_list)\n for index in range(0, col_number):\n if data_list[index] is None:\n data = input(\"Data for \"+col_list[index]+\": \")\n update_single_key(conn, cursor, table, col_list[index], key_name, key_value, data)\n return False\n\n\ndef check_file(conn, cursor, table, file_number, user_name, folders, file):\n from add_edit.edit_record import edit_record\n from add_edit.add_new import add_new\n from reports.radiology import Radiology\n if table != 'radiology':\n sql_statement = \"SELECT rowid FROM \" + table + \" WHERE file_number = ?\"\n cursor.execute(sql_statement, (file_number, ))\n data = cursor.fetchall()\n if len(data) == 0:\n if table not in {\"follow_up_data\", \"pet_reports\", 'radiology'}:\n cursor.execute(\"INSERT INTO \" + table + \"(file_number) VALUES ('\" + file_number + \"')\")\n print(file_number + \" does not exist in table \" + table + \". Enter new record\")\n add_new(conn, cursor, file_number, table, user_name, folders, file)\n else:\n todo = ask.ask_list(file_number + \" already exists in table \" + table + \".\", [\"Edit record\",\n \"Add new record for same file number\",\n \"Edit None\"])\n if todo == \"Edit record\":\n edit_record(conn, cursor, file_number, table, user_name, folders, file)\n elif todo == \"Add new record for same file number\":\n print(\"Add additional record module TBD\")\n ask_table = ask.ask_y_n(\"Add another table?\")\n else:\n radio = Radiology(conn, cursor, file_number, user_name)\n tables = radio.tables\n for tab in tables:\n ask_table = True\n while ask_table:\n sql_statement = \"SELECT rowid FROM \" + tab + \" WHERE file_number = ?\"\n cursor.execute(sql_statement, (file_number, ))\n dat = cursor.fetchall()\n if len(dat) == 0:\n print(file_number + \" does not exist in table \" + tab)\n enter_tab = ask.ask_y_n('Enter data?')\n if enter_tab:\n cursor.execute(\"INSERT INTO \" + tab + \"(file_number) VALUES ('\" + file_number + \"')\")\n add_new(conn, cursor, file_number, tab, user_name, folders, file)\n else:\n todo = ask.ask_list(file_number + \" already exists in table \" + tab + \".\", [\"Edit record\", \"Edit None\"])\n if todo == \"Edit record\":\n edit_record(conn, cursor, file_number, tab, user_name, folders, file)\n # data.append(dat)\n # print(data, 'length data is =', len(data)) \n # # remove later - test_function\n ask_table = ask.ask_y_n(\"Add another data set for \" + tab + \"?\")\n return ask_table\n\n\ndef review_df(df):\n print_df(df)\n check = ask.ask_y_n(\"Is data entered correct?\")\n return check\n\n\ndef table_check(cursor, table_name):\n sql_statement = \"SELECT count(*) FROM sqlite_master WHERE type='table' AND name='\" + table_name + \"'\"\n cursor.execute(sql_statement)\n [table_exists] = cursor.fetchall()\n test = list(table_exists)[0]\n return test\n\n\ndef view_multiple(conn, table, col_list, file_number):\n sql_statement = ('SELECT ' + \", \".join(col_list) + ' FROM ' + table + \" WHERE file_number = '\" + file_number + \"'\")\n df = pd.read_sql(sql_statement, conn)\n print_df(df)\n enter = ask.ask_list(\"Do you want to add or edit data\", [\"Add data\", 'Edit data', 'Do not add or edit'])\n return enter\n\n\ndef delete_multiple(cursor, table, file_number):\n sql_statement = \"DELETE FROM \" + table + \" WHERE file_number = '\" + file_number + \"'\"\n cursor.execute(sql_statement)\n\n\ndef delete_rows(cursor, table, col_name, col_data):\n sql_statement = \"DELETE FROM \" + table + \" WHERE \"+col_name+\" = '\" + col_data + \"'\"\n cursor.execute(sql_statement)\n\n\ndef review_df_row(df):\n check_row = len(df)-1\n print(df.iloc[check_row].to_string())\n check = ask.ask_y_n(\"Is data entered correct?\")\n if check:\n return check, df\n else:\n df = df.drop(df.index[check_row])\n return check, df\n\n\ndef get_sql_data(file_number, conn, module, table):\n columns = []\n cols = table_dicts.db_dict(table, module)\n columns = columns + cols\n col_list = table_dicts.create_col_list(columns)\n sql_statement = ('SELECT ' + \", \".join(col_list) + \" FROM '\" + str(table) + \"' WHERE file_number = '\" +\n file_number + \"'\")\n df = pd.read_sql(sql_statement, conn)\n return df\n\n\ndef get_value(col_name, table, pk, pk_name, cursor, error_statement):\n try:\n sql_statement = \"SELECT \" + col_name + \" FROM \" + table + \" WHERE \" + pk_name + \" = '\" + pk + \"'\"\n cursor.execute(sql_statement)\n value_ = cursor.fetchall()\n value = value_[0][0]\n except (ValueError, IndexError):\n value = input(error_statement)\n return value\n\n\ndef get_value_no_error(col_name, table, pk, pk_name, cursor):\n try:\n sql_statement = \"SELECT \" + col_name + \" FROM \" + table + \" WHERE \" + pk_name + \" = '\" + pk + \"'\"\n cursor.execute(sql_statement)\n value_ = cursor.fetchall()\n value = value_[0][0]\n except (ValueError, IndexError):\n value = False\n return value\n\n\ndef print_df(df):\n rows = df.shape[0]\n for row in range(0, rows):\n print(df.iloc[row].to_string() + '\\n')\n\n\ndef edit_table(df, pk_col, df_col, update_by):\n import sql.add_update_sql as sql\n rows = df.shape[0]\n for row in range(0, rows):\n print(df.iloc[row].to_string() + '\\n')\n to_correct = ask.ask_y_n(\"Are entries correct?\")\n if not to_correct:\n print('To delete a single entry select No here and proceed')\n to_correct = ask.ask_y_n(\"Re-enter entire table?\")\n if to_correct:\n return to_correct, df\n else:\n change_row = True\n while change_row:\n pk_list = list(df[pk_col])\n print(pk_list)\n pk = input(\"Enter \" + pk_col + \" to change: \")\n index = pk_list.index(pk)\n to_do = True\n while to_do:\n print(df.loc[index, :])\n print(\"\\nTo delete a single entry select 'file_number' column here and change file number by \\n\",\n \"appending (_delete) eg., 123/13 file becomes 123/13_delete\\n\")\n col_change = ask.ask_option(\"Name of column to change\", df_col)\n old_val = df.loc[index, col_change]\n print(old_val + '\\n')\n new_val = input(\"Enter correct value for \" + col_change + ' for ' + pk + \": \")\n df.loc[index, col_change] = new_val\n df.ix[index, 'update_by'] = update_by\n df.ix[index, 'last_update'] = sql.last_update()\n print(df.iloc[index].to_string() + '\\n')\n to_do = ask.ask_y_n(\"Make more changes to \" + pk_col + ' ' + pk + '?')\n sql.print_df(df)\n change_row = ask.ask_y_n(\"Change another row?\")\n to_correct = False\n return to_correct, df\n\n# def edit_table(df, pk_col, df_col, update_by):\n# print('To delete a single entry select No here and proceed')\n# to_correct = ask.ask_y_n(\"Re-enter entire table?\")\n# if to_correct:\n# return to_correct, df\n# else:\n# change_row = True\n# while change_row:\n# pk_list = list(df[pk_col])\n# pk_list = ['None' if pk is None else pk for pk in pk_list]\n# print(pk_list)\n# pk = input(\"Enter \" + pk_col + \" to change: \")\n# index = pk_list.index(pk)\n# to_do = True\n# while to_do:\n# print(df.loc[index, :])\n# #print(df.loc[index])\n# print(\"\\nTo delete a single entry select 'file_number' column here and change file number by \\n\",\n# \"appending (_delete) eg., 123/13 file becomes 123/13_delete\\n\")\n# col_change = ask.ask_option(\"Name of column to change\", df_col)\n# old_val = df.loc[index, col_change]\n# print(str(old_val) + '\\n')\n# # if old_val is None it will become 'None'\n# new_val = input(\"Enter correct value for \" + col_change + ' for ' + pk + \": \")\n# df.loc[index, col_change] = new_val\n# df.ix[index, 'update_by'] = update_by\n# df.ix[index, 'last_update'] = last_update()\n# print(df.iloc[index].to_string() + '\\n')\n# to_do = ask.ask_y_n(\"Make more changes to \" + pk_col + ' ' + pk + '?')\n# print_df(df)\n# change_row = ask.ask_y_n(\"Change another row?\")\n# to_correct = False\n# return to_correct, df\n\n\ndef retrieve_with_pk_to_edit(df, value_col, table, cursor, pk=False, value_row_to_edit=False):\n print('To delete a single entry select No here and proceed')\n to_correct = ask.ask_y_n(\"Re-enter entire table?\")\n if to_correct:\n return pk, value_row_to_edit\n else:\n value_list = list(df[value_col])\n value_list = ['None' if value is None else value for value in value_list]\n print(value_list)\n value = input(\"Enter \" + value_col + \" to change: \")\n pk = get_value_no_error(col_name='pk', table=table, pk=str(value), pk_name=value_col, cursor=cursor)\n return pk, str(value_row_to_edit)\n\n\ndef check_db_value(col_name, table, file_number, cursor, error_statement):\n try:\n sql_statement = \"SELECT \" + col_name + \" FROM \" + table + \" WHERE file_number = '\" + file_number + \"'\"\n cursor.execute(sql_statement)\n value_ = cursor.fetchall()\n value = value_[0][0]\n print(col_name.capitalize().replace('_', ' ') + \": \" + str(value))\n check = ask.ask_y_n('Is this correct')\n if not check:\n value = input(error_statement)\n except (IndexError, ValueError):\n value = input(error_statement)\n return value\n\n\ndef last_update():\n update_stamp = dt.datetime.now().strftime(\"%Y_%m_%d|%H_%M\")\n return update_stamp\n\n\ndef create_pk():\n pk = uuid.uuid4().hex\n return pk\n\n\ndef check_file_number_exist(cursor, file_number, table):\n sql_statement = \"SELECT rowid FROM \" + table + \" WHERE file_number = ?\"\n cursor.execute(sql_statement, (file_number,))\n data = cursor.fetchall()\n if len(data) == 0:\n return False\n else:\n return True\n\n\ndef check_pk_fk_exist(cursor, col_filter, pk, table):\n sql_statement = \"SELECT rowid FROM \" + table + \" WHERE \" + col_filter + \" = ?\"\n cursor.execute(sql_statement, (pk,))\n data = cursor.fetchall()\n if len(data) == 0:\n return False\n else:\n return True\n\n\ndef check_value_not_exist(cursor, value_name, value, table):\n sql_statement = \"SELECT rowid FROM \" + table + \" WHERE \" + value_name + \" = ?\"\n cursor.execute(sql_statement, (value,))\n data = cursor.fetchall()\n if len(data) == 0:\n return True\n else:\n print('This ' + value_name + ' already exists. Please check source and enter another value')\n return False\n\n\ndef extract_multiple_value_select_column(conn, columns, table='block_list', file_number='test', col_select='block_id',\n col_filter='block_type', col_filter_value='biopsy'):\n # extracts multiple values (columns) form a row/rows in a table defined by presence of a filter value\n # (col_filter_value) in a defined column (col_filter). Returns only a single column (col_select)\n\n sql_statement = ('SELECT ' + \", \".join(columns) + \" FROM '\" + table + \"' WHERE file_number = '\" + file_number +\n \"' AND \" + col_filter + \" = '\" + col_filter_value + \"'\")\n df = pd.read_sql(sql_statement, conn)\n data = set(df[col_select])\n return list(data)\n\n\ndef extract_multiple_value_select_column_pk(conn, columns, table='block_list',\npk='test', col_select='block_id', col_filter='block_type', col_filter_value='biopsy'):\n sql_statement = ('SELECT ' + \", \".join(columns) + \" FROM '\" + table + \"' WHERE pk = '\" + pk +\n \"' AND \" + col_filter + \" = '\" + col_filter_value + \"'\")\n df = pd.read_sql(sql_statement, conn)\n data = set(df[col_select])\n if len(data) == 1:\n data = list(data)[0]\n else:\n data = list(data)\n return data\n\n\ndef extract_select_column_key(conn, columns, table, col_select, key_name, key_value):\n # extracts multiple values (columns) form a row/rows in a table defined by presence of a key value\n # (key_value) in a defined column (key_name). Returns a set from only a single column (col_select)\n sql_statement = ('SELECT ' + \", \".join(columns) + \" FROM '\" + table + \"' WHERE \" + key_name + \" = '\" + key_value +\n \"'\")\n df = pd.read_sql(sql_statement, conn)\n data = set(df[col_select])\n if len(data) == 1:\n data = list(data)[0]\n else:\n data = list(data)\n return data\n\n\ndef add_pk_fk_to_table(conn, cursor, table, col_name, pk):\n sql_insert = \"INSERT INTO \" + table + \"(\" + col_name + \") VALUES (?)\"\n cursor.execute(sql_insert, (pk, ))\n conn.commit()\n","repo_name":"shwetakadupccm/pccm_db_sk","sub_path":"sql/add_update_sql.py","file_name":"add_update_sql.py","file_ext":"py","file_size_in_byte":21408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70777542866","text":"from time import sleep\n\nvel = int(input('Digite a velocidade atual do carro: '))\n\nprint('Processando...')\nsleep(1.5)\n\nif vel > 80:\n multa = (vel - 80) * 7\n print('Você foi multado e a multa é de: {}'.format(multa))\nelse:\n print('Parabéns, você está em uma velocidade aceitável')","repo_name":"dtasso/Python_CursoEmVideo","sub_path":"pythontestes/Mundo 1/desafio029.py","file_name":"desafio029.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15819533328","text":"import math\nimport numpy as np\nimport random\nimport torch\nfrom torchvision import transforms\nfrom PIL import Image, ImageOps, ImageFilter\n\ndef flip(x, dim=-1):\n indices = [slice(None)] * x.dim()\n indices[dim] = torch.arange(x.size(dim) - 1, -1, -1,\n dtype=torch.long, device=x.device)\n return x[tuple(indices)]\n\ndef resize(images, size):\n return torch.nn.functional.interpolate(\n images,\n size=(size, size),\n mode=\"bilinear\",\n align_corners=False,\n )\n\ndef uniform_crop(images, size, spatial_idx=1):\n \"\"\"\n Perform uniform spatial sampling on the images and corresponding boxes.\n Args:\n images (tensor): images to perform uniform crop. The dimension is\n `num frames` x `channel` x `height` x `width`.\n size (int): size of height and weight to crop the images.\n spatial_idx (int): 0, 1, or 2 for left, center, and right crop if width\n is larger than height. Or 0, 1, or 2 for top, center, and bottom\n crop if height is larger than width.\n Returns:\n cropped (tensor): images with dimension of\n `num frames` x `channel` x `size` x `size`.\n \"\"\"\n assert spatial_idx in [0, 1, 2]\n height = images.shape[2]\n width = images.shape[3]\n\n y_offset = int(math.ceil((height - size) / 2))\n x_offset = int(math.ceil((width - size) / 2))\n\n if height > width:\n if spatial_idx == 0:\n y_offset = 0\n elif spatial_idx == 2:\n y_offset = height - size\n else:\n if spatial_idx == 0:\n x_offset = 0\n elif spatial_idx == 2:\n x_offset = width - size\n cropped = images[\n :, :, y_offset : y_offset + size, x_offset : x_offset + size\n ]\n\n return cropped\n\ndef grayscale(images):\n \"\"\"\n Get the grayscale for the input images. The channels of images should be\n in order RGB.\n Args:\n images (tensor): the input images for getting grayscale. Dimension is\n `num frames` x `channel` x `height` x `width`.\n Returns:\n img_gray (tensor): blended images, the dimension is\n `num frames` x `channel` x `height` x `width`.\n \"\"\"\n # R -> 0.299, G -> 0.587, B -> 0.114.\n img_gray = images.clone()\n gray_channel = 0.299 * images[:, 0] + 0.587 * images[:, 1] + 0.114 * images[:, 2]\n img_gray[:, 0] = gray_channel\n img_gray[:, 1] = gray_channel\n img_gray[:, 2] = gray_channel\n return img_gray\n\n\ndef color_jitter(images, img_brightness=0, img_contrast=0, img_saturation=0, img_hue=0, img_blur=0):\n \"\"\"\n Perfrom a color jittering on the input images. The channels of images\n should be in order RGB.\n Args:\n images (tensor): images to perform color jitter. Dimension is\n `num frames` x `channel` x `height` x `width`.\n img_brightness (float): jitter ratio for brightness.\n img_contrast (float): jitter ratio for contrast.\n img_saturation (float): jitter ratio for saturation.\n Returns:\n images (tensor): the jittered images, the dimension is\n `num frames` x `channel` x `height` x `width`.\n \"\"\"\n order = np.random.permutation(np.arange(4))\n b_var = 1 + random.uniform(-img_brightness, img_brightness)\n c_var = 1 + random.uniform(-img_contrast, img_contrast)\n s_var = 1 + random.uniform(-img_saturation, img_saturation)\n h_var = random.uniform(-img_hue, img_hue)\n if img_blur == 0:\n g_apply = False\n else:\n g_var = random.uniform(0.1, 2.0)\n g_apply = random.uniform(0,1) < img_blur\n for i in range(len(images)):\n img = transforms.functional.to_pil_image(images[i])\n for idx in range(4):\n if order[idx] == 0:\n img = transforms.functional.adjust_brightness(img, b_var)\n elif order[idx] == 1:\n img = transforms.functional.adjust_contrast(img, c_var)\n elif order[idx] == 2:\n img = transforms.functional.adjust_saturation(img, s_var)\n elif order[idx] == 3:\n img = transforms.functional.adjust_hue(img, h_var)\n if g_apply:\n img = img.filter(ImageFilter.GaussianBlur(radius=g_var))\n images[i] = transforms.functional.to_tensor(img)\n return images\n\n\ndef brightness_jitter(images, var=0):\n \"\"\"\n Perfrom brightness jittering on the input images. The channels of images\n should be in order RGB.\n Args:\n var (float): jitter ratio for brightness.\n images (tensor): images to perform color jitter. Dimension is\n `num frames` x `channel` x `height` x `width`.\n Returns:\n images (tensor): the jittered images, the dimension is\n `num frames` x `channel` x `height` x `width`.\n \"\"\"\n alpha = 1.0 + random.uniform(-var, var)\n\n for i in range(len(images)):\n img = transforms.functional.to_pil_image(images[i])\n img = transforms.functional.adjust_brightness(img, alpha)\n images[i] = transforms.functional.to_tensor(img)\n\n return images\n\n\ndef contrast_jitter(images, var=0):\n \"\"\"\n Perfrom contrast jittering on the input images. The channels of images\n should be in order RGB.\n Args:\n var (float): jitter ratio for contrast.\n images (tensor): images to perform color jitter. Dimension is\n `num frames` x `channel` x `height` x `width`.\n Returns:\n images (tensor): the jittered images, the dimension is\n `num frames` x `channel` x `height` x `width`.\n \"\"\"\n alpha = 1.0 + random.uniform(-var, var)\n\n for i in range(len(images)):\n img = transforms.functional.to_pil_image(images[i])\n img = transforms.functional.adjust_contrast(img, alpha)\n images[i] = transforms.functional.to_tensor(img)\n\n return images\n\n\ndef saturation_jitter(images, var=0):\n \"\"\"\n Perfrom saturation jittering on the input images. The channels of images\n should be in order RGB.\n Args:\n var (float): jitter ratio for saturation.\n images (tensor): images to perform color jitter. Dimension is\n `num frames` x `channel` x `height` x `width`.\n Returns:\n images (tensor): the jittered images, the dimension is\n `num frames` x `channel` x `height` x `width`.\n \"\"\"\n alpha = 1.0 + random.uniform(-var, var)\n for i in range(len(images)):\n img = transforms.functional.to_pil_image(images[i])\n img = transforms.functional.adjust_saturation(img, alpha)\n images[i] = transforms.functional.to_tensor(img)\n\n return images\n\ndef hue_jitter(images, var=0):\n \"\"\"\n Perfrom hue jittering on the input images. The channels of images\n should be in order RGB.\n Args:\n var (float): jitter ratio for hue.\n images (tensor): images to perform color jitter. Dimension is\n `num frames` x `channel` x `height` x `width`.\n Returns:\n images (tensor): the jittered images, the dimension is\n `num frames` x `channel` x `height` x `width`.\n \"\"\"\n alpha = random.uniform(-var, var)\n for i in range(len(images)):\n img = transforms.functional.to_pil_image(images[i])\n img = transforms.functional.adjust_hue(img, alpha)\n images[i] = transforms.functional.to_tensor(img)\n\n return images\n\n\ndef color_normalization(images, mean=[0.485, 0.456, 0.406], stddev=[0.229, 0.224, 0.225]):\n \"\"\"\n Perform color nomration on the given images.\n Args:\n images (tensor): images to perform color normalization. Dimension is\n `num frames` x `channel` x `height` x `width`.\n mean (list): mean values for normalization.\n stddev (list): standard deviations for normalization.\n Returns:\n out_images (tensor): the noramlized images, the dimension is\n `num frames` x `channel` x `height` x `width`.\n \"\"\"\n assert len(mean) == images.shape[1], \"channel mean not computed properly\"\n assert (\n len(stddev) == images.shape[1]\n ), \"channel stddev not computed properly\"\n\n out_images = torch.zeros_like(images)\n for idx in range(len(mean)):\n out_images[:, idx] = (images[:, idx] - mean[idx]) / stddev[idx]\n\n return out_images\n\n\ndef _get_param_spatial_crop(scale, ratio, height, width):\n \"\"\"\n Given scale, ratio, height and width, return sampled coordinates of the videos.\n \"\"\"\n for _ in range(10):\n area = height * width\n target_area = random.uniform(*scale) * area\n log_ratio = (math.log(ratio[0]), math.log(ratio[1]))\n aspect_ratio = math.exp(random.uniform(*log_ratio))\n\n w = int(round(math.sqrt(target_area * aspect_ratio)))\n h = int(round(math.sqrt(target_area / aspect_ratio)))\n\n if 0 < w <= width and 0 < h <= height:\n i = random.randint(0, height - h)\n j = random.randint(0, width - w)\n return i, j, h, w\n\n # Fallback to central crop\n in_ratio = float(width) / float(height)\n if in_ratio < min(ratio):\n w = width\n h = int(round(w / min(ratio)))\n elif in_ratio > max(ratio):\n h = height\n w = int(round(h * max(ratio)))\n else: # whole image\n w = width\n h = height\n i = (height - h) // 2\n j = (width - w) // 2\n return i, j, h, w\n\n\ndef random_resized_crop(\n images,\n target_height,\n target_width,\n scale=(0.8, 1.0),\n ratio=(3.0 / 4.0, 4.0 / 3.0),\n):\n \"\"\"\n Crop the given images to random size and aspect ratio. A crop of random\n size (default: of 0.8 to 1.0) of the original size and a random aspect\n ratio (default: of 3/4 to 4/3) of the original aspect ratio is made. This\n crop is finally resized to given size. This is popularly used to train the\n Inception networks.\n Args:\n images: Images to perform resizing and cropping.\n target_height: Desired height after cropping.\n target_width: Desired width after cropping.\n scale: Scale range of Inception-style area based random resizing.\n ratio: Aspect ratio range of Inception-style area based random resizing.\n \"\"\"\n height = images.shape[2]\n width = images.shape[3]\n\n i, j, h, w = _get_param_spatial_crop(scale, ratio, height, width)\n cropped = images[:, :, i : i + h, j : j + w]\n result = torch.nn.functional.interpolate(\n cropped,\n size=(target_height, target_width),\n mode=\"bilinear\",\n align_corners=False)\n return result\n\nclass AugmentOp:\n \"\"\"\n Apply for video.\n \"\"\"\n def __init__(self, aug_fn, *args, **kwargs):\n self.aug_fn = aug_fn\n self.args = args\n self.kwargs = kwargs\n\n def __call__(self, images):\n return self.aug_fn(images, *self.args, **self.kwargs)\n\nclass RandomOp:\n \"\"\"\n Apply for video.\n \"\"\"\n def __init__(self, aug_fn, prob, *args, **kwargs):\n self.aug_fn = aug_fn\n self.prob = prob\n self.args = args\n self.kwargs = kwargs\n\n def __call__(self, images):\n if random.uniform(0,1) < self.prob:\n images = self.aug_fn(images, *self.args, **self.kwargs)\n return images\n\nclass ComposeOp:\n def __init__(self, ops):\n self.ops = ops\n\n def __call__(self, img_list):\n for op in self.ops:\n # start_time = time.time()\n img_list = op(img_list)\n # if torch.cuda.device_count() == 1:\n # print(f\"op time: {time.time()-start_time:.3f}\")\n return img_list\n\ndef create_ssl_data_augment(cfg, augment):\n ops = []\n if augment:\n \"\"\"Return a set of data augmentation transformations as described in the SimCLR paper.\"\"\"\n s = cfg.AUGMENTATION.STRENGTH\n ops.append(AugmentOp(random_resized_crop, **{\n 'target_height': cfg.IMAGE_SIZE,\n 'target_width': cfg.IMAGE_SIZE\n }))\n ops.append(RandomOp(flip, 0.5))\n ops.append(RandomOp(color_jitter, 0.8, **{\n 'img_brightness': 0.8*s,\n 'img_contrast': 0.8*s,\n 'img_saturation': 0.8*s,\n 'img_hue': 0.2*s,\n 'img_blur': 0.0 if cfg.DATASETS[0] == \"finegym\" else 0.5*s,\n }))\n ops.append(RandomOp(grayscale, 0.2))\n else:\n ops.append(AugmentOp(uniform_crop, **{\n 'size': cfg.IMAGE_SIZE\n }))\n ops.append(AugmentOp(resize, **{\n 'size': cfg.IMAGE_SIZE\n }))\n ops.append(AugmentOp(color_normalization, **{\n \"mean\" : [0.485, 0.456, 0.406],\n \"stddev\": [0.229, 0.224, 0.225]\n }))\n return ComposeOp(ops)\n\ndef create_data_augment(cfg, augment):\n ops = []\n if augment:\n if cfg.AUGMENTATION.BRIGHTNESS:\n ops.append(AugmentOp(brightness_jitter, **{\n 'var': cfg.AUGMENTATION.BRIGHTNESS_MAX_DELTA,\n }))\n if cfg.AUGMENTATION.CONTRAST:\n ops.append(AugmentOp(contrast_jitter, **{\n 'var': cfg.AUGMENTATION.CONTRAST_MAX_DELTA,\n }))\n if cfg.AUGMENTATION.HUE:\n ops.append(AugmentOp(hue_jitter, **{\n 'var': cfg.AUGMENTATION.HUE_MAX_DELTA,\n }))\n if cfg.AUGMENTATION.SATURATION:\n ops.append(AugmentOp(saturation_jitter, **{\n 'var': cfg.AUGMENTATION.SATURATION_MAX_DELTA,\n }))\n if cfg.AUGMENTATION.RANDOM_CROP:\n ops.append(AugmentOp(random_resized_crop, **{\n 'target_height': cfg.IMAGE_SIZE,\n 'target_width': cfg.IMAGE_SIZE\n }))\n if cfg.AUGMENTATION.RANDOM_FLIP:\n ops.append(RandomOp(flip, 0.5))\n else:\n if cfg.AUGMENTATION.RANDOM_CROP:\n ops.append(AugmentOp(uniform_crop, **{\n 'size': cfg.IMAGE_SIZE\n }))\n ops.append(AugmentOp(resize, **{\n 'size': cfg.IMAGE_SIZE\n }))\n ops.append(AugmentOp(color_normalization, **{\n \"mean\" : [0.485, 0.456, 0.406],\n \"stddev\": [0.229, 0.224, 0.225]\n }))\n return ComposeOp(ops)","repo_name":"minghchen/CARL_code","sub_path":"datasets/data_augment.py","file_name":"data_augment.py","file_ext":"py","file_size_in_byte":13966,"program_lang":"python","lang":"en","doc_type":"code","stars":67,"dataset":"github-code","pt":"48"} +{"seq_id":"41956307758","text":"\nfrom pssparser.model.field_pool import FieldPool\nfrom pssparser.model.activity import Activity\nfrom pssparser.model.exec_block_target_template import ExecBlockTargetTemplate\nfrom pssparser.model.exec_kind import ExecKind\nfrom pssparser.model.exec_block_file import ExecBlockFile\nfrom pssparser.model.exec_block_procedural_interface import ExecBlockProceduralInterface\nfrom pssparser.model.exec_stmt_super import ExecStmtSuper\nfrom pssparser.model.method_prototype import MethodPrototype\nfrom pssparser.model.method_parameter_dir import MethodParameterDir\nfrom pssparser.model.method_parameter import MethodParameter\nfrom pssparser.model.function_qualifier_spec import FunctionQualifierSpec\nfrom pssparser.model.function_import import FunctionImport\nfrom pssparser.model.function_qualifiers import FunctionQualifiers\nfrom pssparser.model.method_qualifiers import MethodQualifiers\nfrom pssparser.model.function_target_template import FunctionTargetTemplate\nfrom _ast import FunctionDef\nfrom pssparser.model.function_definition import FunctionDefinition\nfrom pssparser.model.exec_block_stmt import ExecBlockStmt\nfrom pssparser.model.exec_stmt_return import ExecStmtReturn\nfrom pssparser.model.exec_stmt_expr import ExecStmtExpr\nfrom pssparser.model.exec_stmt_assign import ExecStmtAssign\nfrom pssparser.model.exec_assign_op import ExecAssignOp\nfrom pssparser.model.exec_stmt_if_else import ExecStmtIfElse\nfrom pssparser.model.exec_stmt_match_choice import ExecStmtMatchChoice\nfrom pssparser.model.exec_stmt_match import ExecStmtMatch\nfrom pssparser.model.exec_stmt_while import ExecStmtWhile\nfrom pssparser.model.exec_stmt_repeat import ExecStmtRepeat\nfrom pssparser.model.exec_stmt_repeat_while import ExecStmtRepeatWhile\nfrom pssparser.model.exec_stmt_break import ExecStmtBreak\nfrom pssparser.model.exec_stmt_continue import ExecStmtContinue\nfrom pssparser.model.exec_stmt_foreach import ExecStmtForeach\nfrom pssparser.model.activity_stmt_match import ActivityStmtMatch\nfrom pssparser.model.activity_stmt_match_branch import ActivityStmtMatchBranch\nfrom pssparser.model.activity_stmt_bind import ActivityStmtBind\nfrom pssparser.model.activity_stmt_super import ActivityStmtSuper\nfrom pssparser.model.pool_bind_stmt import PoolBindStmt\nfrom pssparser.model.activity_stmt_traverse_handle import ActivityStmtTraverseHandle\nfrom pssparser.model.activity_stmt_traverse_type import ActivityStmtTraverseType\nfrom pssparser.model.data_type_string import DataTypeString\nfrom pssparser.model.domain_open_range_list import DomainOpenRangeList\nfrom pssparser.model.domain_open_range_value import DomainOpenRangeValue\nfrom pssparser.model.expr_function_call import ExprFunctionCall\nfrom pssparser.model.expr_cast import ExprCast\nfrom pssparser.model.expr_method_call import ExprMethodCall\nimport traceback\nfrom pssparser.model.field_flow_object_claim import FieldFlowObjectClaim\nfrom pssparser.model.field_resource_claim import FieldResourceClaim\nfrom pssparser.model.field_action_handle import FieldActionHandle\nfrom pssparser.model.covergroup import Covergroup\nfrom pssparser.model.covergroup_port import CovergroupPort\nfrom pssparser.model.covergroup_option import CovergroupOption\nfrom pssparser.model.covergroup_coverpoint import CovergroupCoverpoint\nfrom pssparser.model.covergroup_inline import CovergroupInline\nfrom _io import StringIO\nfrom antlr4.InputStream import InputStream\nfrom pssparser.model.exec_target_template_ref import ExecTargetTemplateRef\nfrom pssparser.model.component_path import ComponentPath\nfrom pssparser.model.component_path_elem import ComponentPathElem\nfrom antlr4.error.DiagnosticErrorListener import DiagnosticErrorListener\nfrom antlr4.Token import CommonToken\nimport pickle\n\n'''\nCreated on Feb 17, 2020\n\n@author: ballance\n'''\nfrom typing import List, Tuple\n\nfrom antlr4.BufferedTokenStream import TokenStream\nfrom antlr4.CommonTokenStream import CommonTokenStream\nfrom antlr4.error.ErrorListener import ErrorListener\nfrom antlr4.tree.Tree import TerminalNodeImpl\n\nfrom pssparser.antlr_gen.PSSLexer import PSSLexer\nfrom pssparser.antlr_gen.PSSParser import PSSParser\nfrom pssparser.antlr_gen.PSSVisitor import PSSVisitor\nfrom pssparser.model.action_type import ActionType\nfrom pssparser.model.attr_decl_stmt import AttrFlags\nfrom pssparser.model.buffer_type import BufferType\nfrom pssparser.model.compilation_unit import CompilationUnit\nfrom pssparser.model.component_type import ComponentType\nfrom pssparser.model.constraint_block import ConstraintBlock\nfrom pssparser.model.constraint_declaration import ConstraintDeclaration\nfrom pssparser.model.constraint_expression import ConstraintExpression\nfrom pssparser.model.constraint_implies import ConstraintImplies\nfrom pssparser.model.cu_type import CUType\nfrom pssparser.model.data_type_enum import DataTypeEnum\nfrom pssparser.model.data_type_scalar import DataTypeScalar, ScalarType\nfrom pssparser.model.enum_declaration import EnumDeclaration\nfrom pssparser.model.enum_item import EnumItem\nfrom pssparser.model.expr_bin_type import ExprBinType, ExprBinOp\nfrom pssparser.model.expr_bool_literal import ExprBoolLiteral\nfrom pssparser.model.expr_compile_has import ExprCompileHas\nfrom pssparser.model.expr_cond_type import ExprCondType\nfrom pssparser.model.expr_hierarchical_id import ExprHierarchicalId\nfrom pssparser.model.expr_hierarchical_id_elem import ExprHierarchicalIdElem\nfrom pssparser.model.expr_hierarchical_id_list import ExprHierarchicalIdList\nfrom pssparser.model.expr_id import ExprId\nfrom pssparser.model.expr_in import ExprIn\nfrom pssparser.model.expr_num_literal import ExprNumLiteral\nfrom pssparser.model.expr_open_range_list import ExprOpenRangeList\nfrom pssparser.model.expr_open_range_value import ExprOpenRangeValue\nfrom pssparser.model.expr_static_ref_path import ExprStaticRefPath\nfrom pssparser.model.expr_static_ref_path_elem import ExprStaticRefPathElem\nfrom pssparser.model.expr_str_literal import ExprStrLiteral\nfrom pssparser.model.expr_template_param_value import ExprTemplateParamValue\nfrom pssparser.model.expr_template_param_value_list import ExprTemplateParamValueList\nfrom pssparser.model.expr_unary import UnaryOp, ExprUnary\nfrom pssparser.model.expr_var_ref_path import ExprVarRefPath\nfrom pssparser.model.extend_stmt import ExtendStmt, ExtendTarget\nfrom pssparser.model.import_stmt import ImportStmt\nfrom pssparser.model.marker import Marker\nfrom pssparser.model.package_type import PackageType\nfrom pssparser.model.reference import Reference\nfrom pssparser.model.resource_type import ResourceType\nfrom pssparser.model.source_info import SourceInfo\nfrom pssparser.model.state_type import StateType\nfrom pssparser.model.stream_type import StreamType\nfrom pssparser.model.struct_type import StructType\nfrom pssparser.model.template_category_type_param_decl import TemplateCategoryTypeParamDecl, \\\n TemplateTypeCategory\nfrom pssparser.model.template_generic_type_param_decl import TemplateGenericTypeParamDecl\nfrom pssparser.model.template_param_decl_list import TemplateParamDeclList\nfrom pssparser.model.template_value_param_decl import TemplateValueParamDecl\nfrom pssparser.model.type_identifier import TypeIdentifier\nfrom pssparser.model.type_identifier_elem import TypeIdentifierElem\nfrom pssparser.model.typedef import Typedef\nfrom pssparser.model.constraint_default import ConstraintDefault\nfrom pssparser.model.constraint_default_disable import ConstraintDefaultDisable\nfrom pssparser.model.constraint_forall import ConstraintForall\nfrom pssparser.model.constraint_if_else import ConstraintIfElse\nfrom pssparser.model.constraint_unique import ConstraintUnique\nfrom pssparser.model.constraint_foreach import ConstraintForeach\nfrom pssparser.model.activity_stmt_if_else import ActivityStmtIfElse\nfrom pssparser.model.activity_stmt_while import ActivityStmtWhile\nfrom pssparser.model.activity_stmt_repeat import ActivityStmtRepeat\nfrom pssparser.model.activity_stmt_do_while import ActivityStmtDoWhile\nfrom pssparser.model.activity_stmt_replicate import ActivityStmtReplicate\nfrom pssparser.model.activity_stmt_sequence import ActivityStmtSequence\nfrom pssparser.model.activity_stmt_constraint import ActivityStmtConstraint\nfrom pssparser.model.activity_stmt_foreach import ActivityStmtForeach\nfrom pssparser.model.activity_stmt_parallel import ActivityStmtParallel\nfrom pssparser.model.activity_stmt_schedule import ActivityStmtSchedule\nfrom pssparser.model.activity_stmt_select import ActivityStmtSelect\nfrom pssparser.model.activity_stmt_select_branch import ActivityStmtSelectBranch\nfrom pssparser.model.activity_join_branch import ActivityJoinBranch\nfrom pssparser.model.activity_join_select import ActivityJoinSelect\nfrom pssparser.model.activity_join_none import ActivityJoinNone\nfrom pssparser.model.activity_join_first import ActivityJoinFirst\nfrom pssparser.model.data_type_user import DataTypeUser\nfrom pssparser.model.field_attr import FieldAttr, FieldAttrFlags\nfrom pssparser.model.override_block import OverrideBlock\nfrom pssparser.model.override_stmt_type import OverrideStmtType\nfrom pssparser.model.override_stmt_inst import OverrideStmtInst\nfrom pssparser.model.compile_if import CompileIf\nfrom pssparser.model.compile_assert import CompileAssert\n\n\nclass CUParser(PSSVisitor, ErrorListener):\n \n class ScopeTracker(object):\n\n def __init__(self, parser, name, scope):\n self.parser = parser\n self.name = name\n self.scope = scope\n \n def __enter__(self):\n self.parser._enter_type_scope(self.name, self.scope)\n \n def __exit__(self, t, v, tb):\n self.parser._leave_type_scope(self.name, self.scope)\n \n def __init__(self, input_stream, filename):\n lexer = PSSLexer(input_stream)\n stream = CommonTokenStream(lexer)\n self._parser = PSSParser(stream)\n self._parser.removeErrorListeners()\n# self._parser.addErrorListener(DiagnosticErrorListener())\n self._parser.addErrorListener(self)\n\n self._scope_s : List['CompositeType'] = []\n self._namespace_s : List[str] = []\n self._package_m : Dict[str, PackageType] = {}\n self._attr_flags_s : List[AttrFlags] = []\n \n cu = CUType(filename)\n self._scope_s.append(cu)\n \n def _typescope(self, name, scope):\n return CUParser.ScopeTracker(self, name, scope)\n \n def parse(self) -> CompilationUnit:\n cu_model = self._parser.compilation_unit()\n \n cu = self._scope_s[-1]\n \n if len(cu.markers) > 0:\n # Don't try to process with errors\n return cu\n\n for c in cu_model.portable_stimulus_description():\n if c.package_body_item() is not None:\n it = c.package_body_item().accept(self)\n elif c.package_declaration() is not None:\n it = c.package_declaration().accept(self)\n elif c.component_declaration() is not None:\n it = c.component_declaration().accept(self)\n else:\n print(\"None of the above\")\n it = None\n \n if it is not None:\n if isinstance(it, list):\n for ii in it:\n cu.add_child(ii)\n else:\n cu.add_child(it)\n \n return cu\n \n def _get_typescope(self):\n return self._typescope_s[-1] if len(self._typescope_s) > 0 else None\n\n #****************************************************************\n # * B02 Action\n #****************************************************************\n \n def visitAction_declaration(self, ctx:PSSParser.Action_declarationContext):\n\n # TODO: action can be inside a component, package, or extension\n scope = self._scope_s[-1]\n \n if isinstance(scope, ComponentType):\n component = scope\n else:\n component = None\n \n name = ctx.action_identifier()\n ret = ActionType(\n ctx.action_identifier().accept(self),\n component,\n None if ctx.template_param_decl_list() is None else ctx.template_param_decl_list().accept(self),\n None if ctx.action_super_spec() is None else ctx.action_super_spec().accept(self))\n self._set_srcinfo(ret, ctx.start)\n \n with self._typescope(name, ret):\n for i in ctx.action_body_item():\n a_elem = i.accept(self)\n \n if a_elem is not None:\n if isinstance(a_elem, list):\n for a in a_elem:\n ret.add_child(a)\n else:\n ret.add_child(a_elem)\n \n return ret\n \n def visitAbstract_action_declaration(self, ctx:PSSParser.Abstract_action_declarationContext):\n name = ctx.action_identifier()\n ret = ActionType(\n self._get_type_qname(name),\n None,\n None if ctx.template_param_decl_list() is None else ctx.template_param_decl_list().accept(self),\n None if ctx.action_super_spec() is None else ctx.action_super_spec().accept(self))\n self._set_srcinfo(ret, ctx.start)\n \n with self._typescope(name, ret):\n for i in ctx.action_body_item():\n a_elem = i.accept(self)\n \n if a_elem is not None:\n if isinstance(a_elem, list):\n for e in a_elem:\n ret.add_child(e)\n else:\n ret.add_child(a_elem)\n \n return ret \n \n def visitActivity_declaration(self, ctx:PSSParser.Activity_declarationContext):\n ret = Activity()\n \n for s in ctx.activity_stmt():\n stmt = s.accept(self)\n \n if stmt is not None:\n if isinstance(stmt, list):\n ret.statements.extend(stmt)\n else:\n ret.statements.append(stmt)\n \n return ret\n \n def visitFlow_ref_declaration(self, ctx:PSSParser.Flow_ref_declarationContext):\n ret = []\n is_input = ctx.is_input is not None\n flow_object_type = ctx.flow_object_type().accept(self)\n \n for r in ctx.object_ref_field():\n ret.append(FieldFlowObjectClaim(\n r.identifier().accept(self),\n is_input,\n flow_object_type,\n None if r.array_dim() is None else r.array_dim().accept(self)))\n \n return ret\n \n def visitResource_ref_declaration(self, ctx:PSSParser.Resource_ref_declarationContext):\n ret = []\n is_lock = ctx.lock is not None\n resource_object_type = ctx.resource_object_type().accept(self)\n \n for r in ctx.object_ref_field():\n ret.append(FieldResourceClaim(\n r.identifier().accept(self),\n is_lock,\n resource_object_type,\n None if r.array_dim() is None else r.array_dim().accept(self)))\n \n return ret\n \n def visitAction_handle_declaration(self, ctx:PSSParser.Action_handle_declarationContext):\n ret = []\n action_type = ctx.action_type_identifier().accept(self)\n \n for ai in ctx.action_instantiation():\n ret.append(FieldActionHandle(\n ai.action_identifier().accept(self),\n action_type,\n None if ai.array_dim() is None else ai.array_dim().accept(self)))\n\n return ret\n \n def visitActivity_data_field(self, ctx:PSSParser.Activity_data_fieldContext):\n ret = ctx.data_declaration().accept(self)\n \n for f in ret:\n f.flags |= FieldAttrFlags.Action\n \n return ret\n \n def visitExec_block(self, ctx:PSSParser.Exec_blockContext):\n ret = ExecBlockProceduralInterface(\n ExecKind[ctx.exec_kind_identifier().getText()])\n\n for s in ctx.exec_stmt():\n stmt = s.accept(self)\n \n if stmt is not None:\n if isinstance(stmt, list):\n ret.statements.extend(stmt)\n else:\n ret.statements.append(stmt)\n \n return ret\n \n def visitExec_super_stmt(self, ctx:PSSParser.Exec_super_stmtContext):\n ret = ExecStmtSuper()\n \n return ret\n \n def visitTarget_code_exec_block(self, ctx:PSSParser.Target_code_exec_blockContext):\n content = ctx.string().getText()\n \n if content.startswith(\"\\\"\\\"\\\"\"):\n content = content[3:]\n content = content[:-3]\n elif content.startsWith(\"\\\"\"):\n content = content[1:]\n content = content[:-1]\n \n ret = ExecBlockTargetTemplate(\n ExecKind[ctx.exec_kind_identifier().getText()],\n ctx.language_identifier().getText(),\n content)\n\n # Parse the target-template exec string to extract\n # out mustache references \n i = 0\n while i < len(content):\n ref_start_idx = content.find(\"{{\", i)\n \n if ref_start_idx != -1:\n ref_end_idx = content.find(\"}}\", ref_start_idx)\n ref = content[ref_start_idx + 2:ref_end_idx]\n lexer = PSSLexer(InputStream(ref))\n stream = CommonTokenStream(lexer)\n parser = PSSParser(stream)\n expr_ast = parser.expression()\n expr = expr_ast.accept(self)\n \n ret.refs.append(ExecTargetTemplateRef(\n ref_start_idx,\n ref_end_idx + 1,\n expr))\n \n else:\n break\n \n i = ref_start_idx + 1\n \n return ret\n \n def visitTarget_file_exec_block(self, ctx:PSSParser.Target_file_exec_blockContext):\n content = ctx.string().getText()\n \n if content.startswith(\"\\\"\\\"\\\"\"):\n content = content[3:]\n content = content[:-3]\n elif content.startsWith(\"\\\"\"):\n content = content[1:]\n content = content[:-1]\n \n ret = ExecBlockFile(\n ctx.filename_string().getText(),\n ctx.string().getText()\n )\n # Parse the target-template exec string to extract\n # out mustache references \n i = 0\n while i < len(content):\n ref_start_idx = content.find(\"{{\", i)\n \n if ref_start_idx != -1:\n ref_end_idx = content.find(\"}}\", ref_start_idx)\n ref = content[ref_start_idx + 2:ref_end_idx]\n lexer = PSSLexer(InputStream(ref))\n stream = CommonTokenStream(lexer)\n parser = PSSParser(stream)\n expr_ast = parser.expression()\n expr = expr_ast.accept(self)\n \n ret.refs.append(ExecTargetTemplateRef(\n ref_start_idx,\n ref_end_idx + 1,\n expr))\n \n else:\n break\n \n i = ref_start_idx + 1\n \n return ret\n \n def visitAttr_field(self, ctx:PSSParser.Attr_fieldContext):\n ret = ctx.data_declaration().accept(self)\n\n if ctx.rand is not None: \n for a in ret:\n a.flags |= FieldAttrFlags.Rand\n \n return ret\n \n #****************************************************************\n # * B03 Struct\n #****************************************************************\n \n def visitStruct_declaration(self, ctx:PSSParser.Struct_declarationContext):\n s_ctor = {\n \"struct\" : StructType,\n \"buffer\" : BufferType,\n \"stream\" : StreamType,\n \"state\" : StateType,\n \"resource\" : ResourceType}[ctx.struct_kind().getText()]\n \n ret = s_ctor(\n ctx.identifier().accept(self),\n None if ctx.template_param_decl_list() is None else ctx.template_param_decl_list().accept(self),\n None if ctx.struct_super_spec() is None else ctx.struct_super_spec().accept(self)\n )\n \n with self._typescope(ret.name, ret):\n for i in ctx.struct_body_item():\n s_elem = i.accept(self)\n if s_elem is not None:\n if isinstance(s_elem, list):\n for e in s_elem:\n ret.add_child(e)\n else:\n ret.add_child(s_elem)\n \n return ret\n \n #****************************************************************\n # * B04 PI\n #****************************************************************\n \n def visitFunction_decl(self, ctx:PSSParser.Function_declContext):\n ret = ctx.method_prototype().accept(self)\n return ret\n \n def visitMethod_prototype(self, ctx:PSSParser.Method_prototypeContext):\n ret = MethodPrototype(\n ctx.method_identifier().accept(self),\n None if ctx.method_return_type().getText() == \"void\" else ctx.method_return_type().accept(self))\n\n last_dir = MethodParameterDir.input \n for p in ctx.method_parameter_list_prototype().method_parameter():\n p_t = p.accept(self)\n if p_t.direction is None:\n p_t.direction = last_dir\n else:\n last_dir = p_t.direction\n ret.parameters.append(p_t)\n\n return ret\n \n def visitMethod_parameter(self, ctx:PSSParser.Method_parameterContext):\n direction = None if ctx.method_parameter_dir() is None else MethodParameterDir[ctx.method_parameter_dir().getText()]\n ret = MethodParameter(\n ctx.identifier().accept(self),\n direction,\n ctx.data_type().accept(self))\n\n return ret\n \n def visitMethod_parameter_list(self, ctx:PSSParser.Method_parameter_listContext):\n ret = []\n for e in ctx.expression():\n ret.append(e.accept(self))\n \n return ret\n \n def visitFunction_qualifiers(self, ctx:PSSParser.Function_qualifiersContext):\n if ctx.type_identifier() is not None:\n # Specification on an existing function\n ret = FunctionQualifierSpec(\n ctx.type_identifier().accept(self),\n None if ctx.import_function_qualifiers() is None else ctx.import_function_qualifiers().accept(self))\n else:\n # Standalone import of an external function\n ret = FunctionImport(\n ctx.method_prototype().accept(self),\n None if ctx.import_function_qualifiers() is None else ctx.import_function_qualifiers().accept(self))\n \n return ret\n\n def visitImport_function_qualifiers(self, ctx:PSSParser.Import_function_qualifiersContext):\n phase = None if ctx.method_qualifiers() is None else MethodQualifiers[ctx.method_qualifiers().getText()]\n language = None if ctx.language_identifier() is None else ctx.language_identifier().getText()\n\n ret = FunctionQualifiers(phase, language)\n \n return ret\n \n def visitTarget_template_function(self, ctx:PSSParser.Target_template_functionContext):\n ret = FunctionTargetTemplate(\n ctx.method_prototype().accept(self),\n ctx.language_identifier().getText(),\n ctx.string().getText())\n\n return ret \n \n def visitPss_function_defn(self, ctx:PSSParser.Pss_function_defnContext):\n ret = FunctionDefinition(\n ctx.method_prototype().accept(self),\n None if ctx.method_qualifiers() is None else ctx.method_qualifiers().accept(self))\n \n for s in ctx.procedural_stmt():\n stmt = s.accept(self)\n \n if stmt is not None:\n if isinstance(stmt, list):\n ret.statements.extend(stmt)\n else:\n ret.statements.append(stmt)\n \n return ret\n \n def visitProcedural_block_stmt(self, ctx:PSSParser.Procedural_block_stmtContext):\n ret = ExecBlockStmt()\n \n for s in ctx.procedural_stmt():\n stmt = s.accept(self)\n if stmt is not None:\n if isinstance(stmt, list):\n ret.statements.extend(stmt)\n else:\n ret.statements.append(stmt)\n \n return ret\n \n def visitProcedural_var_decl_stmt(self, ctx:PSSParser.Procedural_var_decl_stmtContext):\n var_l = ctx.data_declaration().accept(self)\n return var_l\n \n def visitProcedural_expr_stmt(self, ctx:PSSParser.Procedural_expr_stmtContext):\n if ctx.variable_ref_path() is not None:\n op = {\n \"=\" : ExecAssignOp.Eq,\n \"+=\" : ExecAssignOp.PlusEq,\n \"-=\" : ExecAssignOp.MinusEq,\n \"<<=\" : ExecAssignOp.SllEq,\n \">>=\" : ExecAssignOp.SrlEq,\n \"|=\" : ExecAssignOp.OrEq,\n \"&=\" : ExecAssignOp.AndEq\n }[ctx.assign_op().getText()]\n ret = ExecStmtAssign(\n ctx.variable_ref_path().accept(self),\n op,\n ctx.expression().accept(self))\n else:\n ret = ExecStmtExpr(ctx.expression().accept(self))\n\n return ret \n \n def visitProcedural_if_else_stmt(self, ctx:PSSParser.Procedural_if_else_stmtContext):\n ret = ExecStmtIfElse(\n ctx.expression().accept(self),\n ctx.procedural_stmt(0).accept(),\n None if ctx.procedural_stmt(1) is None else ctx.procedural_stmt(1).accept(self))\n \n return ret\n \n def visitProcedural_return_stmt(self, ctx:PSSParser.Procedural_return_stmtContext):\n ret = ExecStmtReturn(\n None if ctx.expression() is None else ctx.expression().accept(self))\n \n return ret\n \n def visitProcedural_match_stmt(self, ctx:PSSParser.Procedural_match_stmtContext):\n ret = ExecStmtMatch(ctx.expression().accept(self))\n \n for c in ctx.procedural_match_choice():\n ret.choices.append(c.accept(self))\n\n return ret \n \n def visitProcedural_match_choice(self, ctx:PSSParser.Procedural_match_choiceContext):\n ret = ExecStmtMatchChoice(\n None if ctx.open_range_list() is None else ctx.open_range_list().accept(self),\n ctx.procedural_stmt().accept(self))\n \n return ret\n \n def visitProcedural_repeat_stmt(self, ctx:PSSParser.Procedural_repeat_stmtContext):\n if ctx.is_while is not None:\n ret = ExecStmtWhile(\n ctx.expression().accept(self),\n ctx.procedural_stmt().accept(self))\n elif ctx.is_repeat is not None:\n ret = ExecStmtRepeat(\n ctx.expression().accept(self),\n None if ctx.identifier() is None else ctx.identifier().accept(self),\n ctx.procedural_stmt().accept(self))\n else:\n ret = ExecStmtRepeatWhile(\n ctx.expression().accept(self),\n ctx.procedural_stmt().accept(self))\n \n return ret\n \n def visitProcedural_foreach_stmt(self, ctx:PSSParser.Procedural_foreach_stmtContext):\n ret = ExecStmtForeach(\n None if ctx.iterator_identifier() is None else ctx.iterator_identifier().accept(self),\n ctx.expression().accept(self),\n None if ctx.index_identifier() is None else ctx.index_identifier().accelt(self))\n \n return ret\n \n def visitProcedural_break_stmt(self, ctx:PSSParser.Procedural_break_stmtContext):\n ret = ExecStmtBreak()\n \n return ret\n\n def visitProcedural_continue_stmt(self, ctx:PSSParser.Procedural_continue_stmtContext):\n ret = ExecStmtContinue()\n \n return ret\n \n #****************************************************************\n # * B04 Component\n #****************************************************************\n \n def visitComponent_declaration(self, ctx:PSSParser.Component_declarationContext):\n name = ctx.component_identifier() \n ret = ComponentType(\n ctx.component_identifier().accept(self),\n None if ctx.template_param_decl_list() is None else ctx.template_param_decl_list().accept(self),\n None if ctx.component_super_spec() is None else ctx.component_super_spec().accept(self)\n )\n\n self._set_srcinfo(ret, ctx.start)\n \n# self._scope_s[-1].add_child(ret)\n \n with self._typescope(name, ret):\n for c in ctx.component_body_item():\n c_elem = c.accept(self)\n if c_elem is not None:\n if isinstance(c_elem, list):\n for e in c_elem:\n ret.add_child(e)\n else:\n ret.add_child(c_elem)\n\n return ret\n \n def visitComponent_data_declaration(self, ctx:PSSParser.Component_data_declarationContext):\n field_l = ctx.data_declaration().accept(self)\n\n for f in field_l:\n if ctx.is_static is not None:\n f.flags |= FieldAttrFlags.Static\n \n if ctx.is_const is not None:\n f.flags |= FieldAttrFlags.Const\n \n return field_l\n \n def visitComponent_pool_declaration(self, ctx:PSSParser.Component_pool_declarationContext):\n field_l = []\n size = None if ctx.expression() is None else ctx.expression().accept(self)\n typeid = ctx.type_identifier().accept(self)\n \n for id in ctx.identifier():\n field_l.append(FieldPool(\n id.accept(self),\n typeid,\n size))\n \n return field_l\n \n def visitObject_bind_stmt(self, ctx:PSSParser.Object_bind_stmtContext):\n ret = PoolBindStmt(\n ctx.hierarchical_id().accept(self))\n \n for p in ctx.object_bind_item_or_list().component_path():\n ret.bindlist.append(p.accept(self))\n \n return ret\n \n def visitComponent_path(self, ctx:PSSParser.Component_pathContext):\n if ctx.is_wildcard is not None:\n ret = ComponentPath(True)\n else:\n ret = ComponentPath(False)\n ret.path_elements.append(ComponentPathElem(\n False, \n ctx.component_identifier().accept(self),\n None # TODO: do we need index?\n ))\n \n for e in ctx.component_path_elem():\n ret.path_elements.append(e.accept(self))\n \n return ret\n \n def visitComponent_path_elem(self, ctx:PSSParser.Component_path_elemContext):\n if ctx.is_wildcard is not None:\n ret = ComponentPathElem(True, None, None)\n else:\n ret = ComponentPathElem(\n False,\n ctx.component_action_identifier().accept(self),\n None if ctx.constant_expression() is None else ctx.constant_expression().accept(self))\n \n return ret\n \n def visitType_identifier(self, ctx:PSSParser.Type_identifierContext):\n ret = TypeIdentifier(ctx.is_global is not None)\n \n for tie in ctx.type_identifier_elem():\n ret.path.append(tie.accept(self))\n \n try:\n pickle.dumps(ret)\n except Exception as e:\n print(\"Error dumping type identifier\")\n raise e\n \n return ret\n \n def visitType_identifier_elem(self, ctx:PSSParser.Type_identifier_elemContext):\n ret = TypeIdentifierElem(ctx.identifier().accept(self))\n \n if ctx.template_param_value_list() is not None:\n ret.templ_pvl = ctx.template_param_value_list().accept(self)\n \n return ret\n \n def visitExpression(self, ctx:PSSParser.ExpressionContext):\n ret = None\n \n lhs_e = None if ctx.lhs is None else ctx.lhs.accept(self)\n rhs_e = None if ctx.rhs is None else ctx.rhs.accept(self)\n\n if ctx.unary_op() is not None:\n op = {\n \"+\" : UnaryOp.Plus,\n \"-\" : UnaryOp.Minus,\n \"!\" : UnaryOp.BoolNot,\n \"~\" : UnaryOp.BitNot,\n \"&\" : UnaryOp.BitAnd,\n \"|\" : UnaryOp.BitOr,\n \"^\" : UnaryOp.BitXor\n }[ctx.unary_op().getText()]\n ret = ExprUnary(lhs_e, op)\n elif ctx.exp_op() is not None:\n ret = ExprBinType(\n lhs_e,\n ExprBinOp.Exp,\n rhs_e)\n elif ctx.mul_div_mod_op() is not None:\n op = {\n \"*\" : ExprBinOp.Mul,\n \"/\" : ExprBinOp.Div,\n \"%\" : ExprBinOp.Mod}[ctx.mul_div_mod_op().getText()]\n \n ret = ExprBinType(\n lhs_e,\n op,\n rhs_e)\n elif ctx.add_sub_op() is not None:\n op = {\n \"+\" : ExprBinOp.Add,\n \"-\" : ExprBinOp.Sub}[ctx.add_sub_op().getText()]\n ret = ExprBinType(\n lhs_e,\n op,\n rhs_e)\n elif ctx.shift_op() is not None:\n # TODO: the op might show up as \">\" ... \">\"\n op = {\n \"<<\" : ExprBinOp.Sll,\n \">>\" : ExprBinOp.Srl}[ctx.shift_op().getText()]\n ret = ExprBinType(\n lhs_e,\n op,\n rhs_e)\n elif ctx.inside_expr_term() is not None:\n ret = ExprIn(\n lhs_e,\n ctx.inside_expr_term().accept(self))\n elif ctx.logical_inequality_op() is not None:\n op = {\n \"<\" : ExprBinOp.LT,\n \">\" : ExprBinOp.GT,\n \"<=\" : ExprBinOp.LE,\n \">=\" : ExprBinOp.GE}[ctx.logical_inequality_op().getText()]\n ret = ExprBinType(\n lhs_e,\n op,\n rhs_e)\n elif ctx.eq_neq_op() is not None:\n op = {\n \"==\" : ExprBinOp.EqEq,\n \"!=\" : ExprBinOp.Neq}[ctx.eq_neq_op().getText()]\n ret = ExprBinType(\n lhs_e,\n op,\n rhs_e)\n elif ctx.binary_and_op() is not None:\n ret = ExprBinType(\n lhs_e,\n ExprBinOp.BinAnd,\n rhs_e)\n elif ctx.binary_xor_op() is not None:\n ret = ExprBinType(\n lhs_e,\n ExprBinOp.BinXor,\n rhs_e)\n elif ctx.binary_or_op() is not None:\n ret = ExprBinType(\n lhs_e,\n ExprBinOp.BinOr,\n rhs_e)\n elif ctx.logical_and_op() is not None:\n ret = ExprBinType(\n lhs_e,\n ExprBinOp.LogAnd,\n rhs_e)\n elif ctx.logical_or_op() is not None:\n ret = ExprBinType(\n lhs_e,\n ExprBinOp.LogOr,\n rhs_e)\n elif ctx.conditional_expr():\n ret = ExprCondType(\n lhs_e,\n ctx.conditional_expr().true_expr.accept(self),\n ctx.conditional_expr().false_expr.accept(self))\n elif ctx.primary():\n ret = ctx.primary().accept(self)\n else:\n print(\"Unknown expression op\")\n \n return ret\n \n def visitInside_expr_term(self, ctx:PSSParser.Inside_expr_termContext):\n ret = ExprOpenRangeList()\n \n for r in ctx.open_range_list().open_range_value():\n ret.val_l.append(r.accept(self))\n \n return ret\n \n def visitPrimary(self, ctx:PSSParser.PrimaryContext):\n if ctx.is_super is not None:\n # TODO:\n pass\n else:\n return super().visitPrimary(ctx)\n\n def visitBased_hex_number(self, ctx:PSSParser.Based_hex_numberContext):\n # TODO: deal with width\n hex = ctx.BASED_HEX_LITERAL().getText()\n if hex[0] == \"'\":\n hex = hex[1:]\n if hex[0] == \"s\" or hex[0] == \"S\":\n hex = hex[1:]\n if hex == \"h\" or hex == \"H\":\n hex = hex[1:]\n \n ret = ExprNumLiteral(\n int(hex.replace(\"_\", \"\"), 16),\n ctx.getText())\n \n return ret\n \n def visitBased_dec_number(self, ctx:PSSParser.Based_dec_numberContext):\n dec = ctx.BASED_HEX_LITERAL().getText()\n if dec[0] == \"'\":\n dec = dec[1:]\n if dec[0] == \"s\" or dec[0] == \"S\":\n dec = dec[1:]\n if dec == \"d\" or dec == \"D\":\n dec = dec[1:]\n ret = ExprNumLiteral(\n int(dec.replace(\"_\", \"\"), 10),\n ctx.getText())\n \n return ret\n \n def visitBased_oct_number(self, ctx:PSSParser.Based_oct_numberContext):\n oct = ctx.BASED_HEX_LITERAL().getText()\n if oct[0] == \"'\":\n oct = oct[1:]\n if oct[0] == \"s\" or oct[0] == \"S\":\n oct = oct[1:]\n if oct == \"o\" or oct == \"O\":\n oct = oct[1:]\n ret = ExprNumLiteral(\n int(oct.replace(\"_\", \"\"), 8),\n ctx.getText())\n \n return ret\n \n def visitDec_number(self, ctx:PSSParser.Dec_numberContext):\n ret = ExprNumLiteral(\n int(ctx.getText().replace(\"_\", \"\"), 10),\n ctx.getText())\n return ret\n \n def visitOct_number(self, ctx:PSSParser.Oct_numberContext):\n val = ctx.getText()\n if len(val) > 1:\n val = val[1:].replace(\"_\", \"\")\n ret = ExprNumLiteral(\n int(val, 8),\n ctx.getText())\n \n return ret\n \n def visitHex_number(self, ctx:PSSParser.Oct_numberContext):\n ret = ExprNumLiteral(\n int(ctx.getText()[2:].replace(\"_\", \"\"), 16),\n ctx.getText())\n \n return ret\n \n def visitBool_literal(self, ctx:PSSParser.Bool_literalContext):\n return ExprBoolLiteral(ctx.getText() == \"true\")\n \n def visitParen_expr(self, ctx:PSSParser.Paren_exprContext):\n return ctx.expression().accept(self)\n \n def visitString(self, ctx:PSSParser.StringContext):\n if ctx.DOUBLE_QUOTED_STRING() is not None:\n return ExprStrLiteral(ctx.DOUBLE_QUOTED_STRING().getText())\n else:\n return ExprStrLiteral(ctx.TRIPLE_DOUBLE_QUOTED_STRING().getText())\n \n def visitCast_expression(self, ctx:PSSParser.Cast_expressionContext):\n ret = ExprCast(\n ctx.casting_type().accept(self),\n ctx.expression().accept(self))\n \n return ret\n \n def visitVariable_ref_path(self, ctx:PSSParser.Variable_ref_pathContext):\n hid = ctx.hierarchical_id().accept(self)\n \n if ctx.expression(0) is not None:\n ret = ExprVarRefPath(hid)\n ret.lhs = ctx.expression(0).accept(self)\n \n if ctx.expression(1) is not None:\n ret.rhs = ctx.expression(1).accept(self)\n else:\n ret = hid\n \n return ret\n \n def visitFunction_symbol_call(self, ctx:PSSParser.Function_symbol_callContext):\n hid = ExprHierarchicalId()\n if ctx.function_symbol_id().function_id() is not None:\n for id in ctx.function_symbol_id().function_id().identifier():\n hid.path_l.append(ExprHierarchicalIdElem(id.accept(self)))\n else:\n hid.path_l.append(ExprHierarchicalIdElem(ctx.function_symbol_id().symbol_identifier().accept(self)))\n \n ret = ExprFunctionCall(\n hid,\n ctx.method_parameter_list().accept(self))\n \n return ret\n \n def visitMethod_call(self, ctx:PSSParser.Method_callContext):\n hid = ctx.hierarchical_id().accept(self)\n \n if len(hid.path_l) == 1:\n # This is really a function call\n ret = ExprFunctionCall(\n hid,\n ctx.method_parameter_list().accept(self))\n else:\n ret = ExprMethodCall(\n hid,\n ctx.method_parameter_list().accept(self))\n \n return ret\n \n def visitHierarchical_id(self, ctx:PSSParser.Hierarchical_idContext):\n ret = ExprHierarchicalId()\n\n for e in ctx.hierarchical_id_elem():\n ret.path_l.append(e.accept(self))\n \n return ret\n \n def visitHierarchical_id_elem(self, ctx:PSSParser.Hierarchical_id_elemContext):\n ret = ExprHierarchicalIdElem(ctx.identifier().accept(self))\n \n if ctx.expression() is not None:\n ret.lhs = ctx.expression().accept(self)\n \n return ret\n \n def visitHierarchical_id_list(self, ctx:PSSParser.Hierarchical_id_listContext):\n ret = ExprHierarchicalIdList()\n \n for e in ctx.hierarchical_id():\n ret.hid_l.append(e.accept(self))\n \n return ret\n \n def visitIdentifier(self, ctx:PSSParser.IdentifierContext):\n if ctx.ID() is not None:\n id = ctx.ID().getText()\n else:\n id = ctx.ESCAPED_ID().getText()\n\n ret = ExprId(id)\n \n return ret\n \n def visitTemplate_param_value(self, ctx:PSSParser.Template_param_valueContext):\n if ctx.constant_expression():\n ret = ExprTemplateParamValue(True, ctx.constant_expression().accept(self))\n else:\n ret = ExprTemplateParamValue(False, ctx.type_identifier().accept(self))\n \n return ret\n \n def visitTemplate_param_value_list(self, ctx:PSSParser.Template_param_value_listContext):\n ret = ExprTemplateParamValueList()\n \n for pv in ctx.template_param_value():\n ret.param_l.append(pv.accept(self))\n \n return ret\n \n #****************************************************************\n # * B06 Activity Statements\n #****************************************************************\n def visitActivity_stmt(self, ctx:PSSParser.Activity_stmtContext):\n s = PSSVisitor.visitActivity_stmt(self, ctx)\n\n # Note: null statement returns None \n if ctx.identifier() is not None and s is not None:\n s.label = ctx.identifier().accept(self)\n \n return s\n\n def visitActivity_constraint_stmt(self, ctx:PSSParser.Activity_constraint_stmtContext):\n ret = ActivityStmtConstraint(ctx.constraint_set().accept(self))\n \n return ret\n \n def visitForeach_constraint_item(self, ctx:PSSParser.Foreach_constraint_itemContext):\n ret = ActivityStmtForeach(\n None if ctx.iterator_identifier() is None else ctx.iterator_identifier().accept(self),\n ctx.expression().accept(self),\n None if ctx.index_identifier() is None else ctx.index_identifier().accept(self),\n ctx.activity_stmt().accept(self)\n )\n \n return ret\n \n def visitActivity_if_else_stmt(self, ctx:PSSParser.Activity_if_else_stmtContext):\n ret = ActivityStmtIfElse(\n ctx.expression().accept(self),\n ctx.activity_stmt(0).accept(self),\n None if len(ctx.activity_stmt()) == 1 else ctx.activity_stmt(1).accept(self))\n \n return ret\n \n def visitActivity_join_branch_spec(self, ctx:PSSParser.Activity_join_branch_specContext):\n ret = ActivityJoinBranch()\n \n for l in ctx.label_identifier():\n ret.label_identifiers.append(l.accept(self))\n \n return ret\n \n def visitActivity_join_first_spec(self, ctx:PSSParser.Activity_join_first_specContext):\n ret = ActivityJoinFirst(ctx.expression().accept(self))\n \n return ret\n \n def visitActivity_join_none_spec(self, ctx:PSSParser.Activity_join_none_specContext):\n ret = ActivityJoinNone()\n \n return ret\n \n def visitActivity_join_select_spec(self, ctx:PSSParser.Activity_join_select_specContext):\n ret = ActivityJoinSelect(ctx.expression().accept(self))\n \n return ret\n \n def visitActivity_match_stmt(self, ctx:PSSParser.Activity_match_stmtContext):\n ret = ActivityStmtMatch(\n ctx.expression().accept(self))\n \n for c in ctx.match_choice():\n ret.branches.append(c.accept(self))\n \n return ret\n \n def visitMatch_choice(self, ctx:PSSParser.Match_choiceContext):\n ret = ActivityStmtMatchBranch(\n None if ctx.is_default is not None else ctx.open_range_list().accept(self),\n ctx.activity_stmt().accept(self))\n \n return ret\n \n def visitActivity_parallel_stmt(self, ctx:PSSParser.Activity_parallel_stmtContext):\n ret = ActivityStmtParallel(\n None if ctx.activity_join_spec() is None else ctx.activity_join_spec().accept(self)\n )\n \n for stmt in ctx.activity_stmt():\n s = stmt.accept(self)\n if s is not None:\n ret.statements.append(s)\n \n return ret\n \n def visitActivity_repeat_stmt(self, ctx:PSSParser.Activity_repeat_stmtContext):\n if ctx.is_while is not None:\n ret = ActivityStmtWhile(\n ctx.expression().accept(self),\n ctx.activity_stmt().accept(self))\n \n elif ctx.is_repeat is not None:\n ret = ActivityStmtRepeat(\n None if ctx.identifier() is None else ctx.identifier().accept(self),\n ctx.expression().accept(self),\n ctx.activity_stmt().accept(self))\n else:\n ret = ActivityStmtDoWhile(\n ctx.expression().accept(self),\n ctx.activity_stmt().accept(self))\n \n return ret\n \n def visitActivity_replicate_stmt(self, ctx:PSSParser.Activity_replicate_stmtContext):\n ret = ActivityStmtReplicate(\n None if ctx.index_identifier() is None else ctx.index_identifier().accept(self),\n ctx.expression().accept(self),\n None if ctx.identifier() is None else ctx.identifier().accept(self),\n ctx.labeled_activity_stmt().accept(self))\n \n return ret\n \n def visitActivity_schedule_stmt(self, ctx:PSSParser.Activity_schedule_stmtContext):\n ret = ActivityStmtSchedule(\n None if ctx.activity_join_spec() is None else ctx.activity_join_spec().accept(self)\n )\n \n return ret\n \n def visitActivity_foreach_stmt(self, ctx:PSSParser.Activity_foreach_stmtContext):\n ret = ActivityStmtForeach(\n None if ctx.iterator_identifier() is None else ctx.iterator_identifier().accept(self),\n ctx.expression().accept(self),\n None if ctx.index_identifier() is None else ctx.index_identifier().accept(self),\n ctx.activity_stmt().accept(self))\n\n return ret\n \n def visitActivity_action_traversal_stmt(self, ctx:PSSParser.Activity_action_traversal_stmtContext):\n if ctx.is_do is not None:\n ret = ActivityStmtTraverseType(\n ctx.type_identifier().accept(self),\n None if ctx.constraint_set() is None else ctx.constraint_set().accept(self))\n else:\n path = ExprVarRefPath(ExprHierarchicalId([\n ExprHierarchicalIdElem(ctx.identifier().accept(self))\n ]))\n \n if ctx.expression() is not None:\n path.lhs = ctx.expression().accept(self)\n \n ret = ActivityStmtTraverseHandle(\n path,\n None if ctx.constraint_set() is None else ctx.constraint_set().accept(self))\n \n return ret\n \n def visitActivity_select_stmt(self, ctx:PSSParser.Activity_select_stmtContext):\n ret = ActivityStmtSelect()\n \n for b in ctx.select_branch():\n ret.statements.append(b.accept(self))\n \n return ret\n \n def visitSelect_branch(self, ctx:PSSParser.Select_branchContext):\n ret = ActivityStmtSelectBranch(\n None if ctx.guard is None else ctx.guard.accept(self),\n None if ctx.weight is None else ctx.weight.accept(self),\n ctx.activity_stmt().accept(self)\n )\n \n return ret\n \n def visitActivity_sequence_block_stmt(self, ctx:PSSParser.Activity_sequence_block_stmtContext):\n ret = ActivityStmtSequence()\n \n for stmt in ctx.activity_stmt():\n s = stmt.accept(self)\n if s is not None:\n ret.statements.append(s)\n \n return ret\n \n def visitActivity_bind_stmt(self, ctx:PSSParser.Activity_bind_stmtContext):\n ret = ActivityStmtBind()\n \n ret.targets.append(ctx.hierarchical_id().accept(self))\n \n for hid in ctx.activity_bind_item_or_list().hierarchical_id():\n ret.targets.append(hid.accept(self))\n \n return ret\n \n def visitActivity_super_stmt(self, ctx:PSSParser.Activity_super_stmtContext):\n ret = ActivityStmtSuper()\n \n return ret\n \n #****************************************************************\n # * B07 Activity Statements\n #****************************************************************\n def visitOverrides_declaration(self, ctx:PSSParser.Overrides_declarationContext):\n ret = OverrideBlock()\n \n for sm in ctx.override_stmt():\n s = sm.accept(self)\n if s is not None:\n ret.statements.append(s)\n \n return ret\n \n def visitType_override(self, ctx:PSSParser.Type_overrideContext):\n ret = OverrideStmtType(\n ctx.type_identifier(0).accept(self),\n ctx.type_identifier(1).accept(self))\n\n return ret\n \n def visitInstance_override(self, ctx:PSSParser.Instance_overrideContext):\n ret = OverrideStmtInst(\n ctx.hierarchical_id().accept(self),\n ctx.type_identifier().accept(self))\n \n return ret\n \n #****************************************************************\n # * B10 Constraints\n #****************************************************************\n \n def visitConstraint_declaration(self, ctx:PSSParser.Constraint_declarationContext):\n ret = ConstraintDeclaration(\n None if ctx.identifier() is None else ctx.identifier().accept(self),\n ctx.is_dynamic is not None)\n \n if ctx.constraint_set() is not None:\n if ctx.constraint_set().constraint_body_item() is not None:\n # Single constraint\n c = ctx.constraint_set().constraint_body_item().accept(self)\n if c is not None:\n ret.add_constraint(c)\n else:\n # Block of constraints\n for ci in ctx.constraint_set().constraint_block().constraint_body_item():\n c = ci.accept(self)\n if c is not None:\n ret.add_constraint(c)\n else:\n for ci in ctx.constraint_body_item():\n c = ci.accept(self)\n if c is not None:\n ret.add_constraint(c)\n \n return ret\n \n def visitDefault_constraint(self, ctx:PSSParser.Default_constraintContext):\n ret = ConstraintDefault(\n ctx.hierarchical_id().accept(self),\n ctx.constant_expression().accept(self)\n )\n \n return ret\n \n def visitDefault_disable_constraint(self, ctx:PSSParser.Default_disable_constraintContext):\n ret = ConstraintDefaultDisable(\n ctx.hierarchical_id().accept(self))\n \n return ret\n \n def visitForall_constraint_item(self, ctx:PSSParser.Forall_constraint_itemContext):\n ret = ConstraintForall(\n ctx.identifier().accept(self),\n ctx.type_identifier().accept(self),\n None if ctx.variable_ref_path() is None else ctx.variable_ref_path().accept(self),\n ctx.constraint_set().accept(self))\n \n return ret;\n \n def visitForeach_constraint_item(self, ctx:PSSParser.Foreach_constraint_itemContext):\n ret = ConstraintForeach(\n None if ctx.iterator_identifier() is None else ctx.iterator_identifier().accept(self),\n ctx.expression().accept(self),\n None if ctx.index_identifier() is None else ctx.index_identifier().accept(self),\n ctx.constraint_set().accept(self))\n \n return ret\n \n def visitIf_constraint_item(self, ctx:PSSParser.If_constraint_itemContext):\n ret = ConstraintIfElse(\n ctx.expression().accept(self),\n ctx.constraint_set(0).accept(self),\n None if len(ctx.constraint_set()) == 1 else ctx.constraint_set(1).accept(self)\n )\n \n return ret\n \n def visitConstraint_set(self, ctx:PSSParser.Constraint_setContext):\n ret = ConstraintBlock()\n\n if ctx.constraint_body_item() is not None:\n # Single constraint\n c = ctx.constraint_body_item().accept(self)\n if c is not None:\n ret.add_constraint(c)\n else:\n # Block of constraints\n for ci in ctx.constraint_block().constraint_body_item():\n c = ci.accept(self)\n if c is not None:\n ret.add_constraint(c) \n \n return ret\n \n def visitUnique_constraint_item(self, ctx:PSSParser.Unique_constraint_itemContext):\n ret = ConstraintUnique(\n ctx.hierarchical_id_list().accept(self))\n \n return ret\n \n def visitExpression_constraint_item(self, ctx:PSSParser.Expression_constraint_itemContext):\n return ConstraintExpression(ctx.expression().accept(self))\n \n def visitImplication_constraint_item(self, ctx:PSSParser.Implication_constraint_itemContext):\n return ConstraintImplies(\n ctx.expression().accept(self),\n ctx.constraint_set().accept(self))\n \n #****************************************************************\n # * B11 Coverage\n #****************************************************************\n \n def visitCovergroup_declaration(self, ctx:PSSParser.Covergroup_declarationContext):\n ret = Covergroup(\n ctx.covergroup_identifier().accept(self))\n \n for p in ctx.covergroup_port():\n ret.ports.append(CovergroupPort(\n p.identifier().accept(self),\n p.data_type().accept(self)))\n \n for i in ctx.covergroup_body_item():\n it = i.accept(self)\n \n if it is not None:\n ret.body_items.append(it)\n \n return ret\n \n def visitCovergroup_option(self, ctx:PSSParser.Covergroup_optionContext):\n ret = CovergroupOption(\n ctx.identifier().accept(self),\n ctx.constant_expression().accept(self))\n \n return ret\n \n def visitInline_covergroup(self, ctx:PSSParser.Inline_covergroupContext):\n ret = CovergroupInline(ctx.identifier().accept(self))\n \n for i in ctx.covergroup_body_item():\n it = i.accept(self)\n if it is not None:\n ret.body_items.append(it)\n \n return ret\n \n def visitCovergroup_coverpoint(self, ctx:PSSParser.Covergroup_coverpointContext):\n ret = CovergroupCoverpoint(\n None if ctx.data_type() is None else ctx.data_type().accept(self),\n None if ctx.coverpoint_identifier() is None else ctx.coverpoint_identifier().accept(self),\n ctx.expression(0).accept(self), # target\n None if ctx.expression(1) is None else ctx.expression(1).accept(self))\n\n for b in ctx.bins_or_empty().covergroup_coverpoint_body_item():\n bi = b.accept(self)\n if bi is not None:\n ret.bins.append(bi)\n \n return ret\n \n #****************************************************************\n # * B12 Conditional Compile\n #****************************************************************\n \n def visitPackage_body_compile_if(self, ctx:PSSParser.Package_body_compile_ifContext):\n ret = CompileIf(ctx.constant_expression().accept(self))\n \n for elem in map(lambda e:e.accept(self), ctx.package_body_compile_if_item(0).package_body_item()):\n if isinstance(elem, list):\n for e in elem:\n ret.statements_true.append(e)\n else:\n ret.statements_true.append(elem)\n\n if ctx.package_body_compile_if_item(1) is not None:\n for elem in map(lambda e:e.accept(self), ctx.package_body_compile_if_item(1).package_body_item()):\n if isinstance(elem, list):\n for e in elem:\n ret.statements_false.append(e)\n else:\n ret.statements_false.append(elem)\n \n return ret\n \n def visitAction_body_compile_if(self, ctx:PSSParser.Action_body_compile_ifContext):\n ret = CompileIf(ctx.constant_expression().accept(self))\n \n for elem in map(lambda e:e.accept(self), ctx.action_body_compile_if_item(0).action_body_item()):\n if isinstance(elem, list):\n for e in elem:\n ret.statements_true.append(e)\n else:\n ret.statements_true.append(elem)\n\n if ctx.action_body_compile_if_item(1) is not None:\n for elem in map(lambda e:e.accept(self), ctx.action_body_compile_if_item(1).action_body_item()):\n if isinstance(elem, list):\n for e in elem:\n ret.statements_false.append(e)\n else:\n ret.statements_false.append(elem)\n \n return ret \n \n def visitComponent_body_compile_if(self, ctx:PSSParser.Component_body_compile_ifContext):\n ret = CompileIf(ctx.constant_expression().accept(self))\n \n for elem in map(lambda e:e.accept(self), ctx.component_body_compile_if_item(0).component_body_item()):\n if isinstance(elem, list):\n for e in elem:\n ret.statements_true.append(e)\n else:\n ret.statements_true.append(elem)\n\n if ctx.component_body_compile_if_item(1) is not None:\n for elem in map(lambda e:e.accept(self), ctx.component_body_compile_if_item(1).component_body_item()):\n if isinstance(elem, list):\n for e in elem:\n ret.statements_false.append(e)\n else:\n ret.statements_false.append(elem)\n \n return ret \n \n def visitStruct_body_compile_if(self, ctx:PSSParser.Struct_body_compile_ifContext):\n ret = CompileIf(ctx.constant_expression().accept(self))\n \n for elem in map(lambda e:e.accept(self), ctx.struct_body_compile_if_item(0).struct_body_item()):\n if isinstance(elem, list):\n for e in elem:\n ret.statements_true.append(e)\n else:\n ret.statements_true.append(elem)\n\n if ctx.struct_body_compile_if_item(1) is not None:\n for elem in map(lambda e:e.accept(self), ctx.struct_body_compile_if_item(1).struct_body_item()):\n if isinstance(elem, list):\n for e in elem:\n ret.statements_false.append(e)\n else:\n ret.statements_false.append(elem)\n \n return ret \n \n def visitCompile_assert_stmt(self, ctx:PSSParser.Compile_assert_stmtContext):\n ret = CompileAssert(\n ctx.constant_expression().accept(self),\n None if ctx.msg is None else ctx.msg.getText())\n \n return ret\n \n def visitStatic_ref_path(self, ctx:PSSParser.Static_ref_pathContext):\n\n ret = ExprStaticRefPath(ctx.is_global is not None)\n \n for elem in ctx.static_ref_path_elem():\n ret.path.append(elem.accept(self))\n \n return ret\n \n def visitStatic_ref_path_elem(self, ctx:PSSParser.Static_ref_path_elemContext):\n ret = ExprStaticRefPathElem(ctx.identifier().accept(self))\n \n if ctx.template_param_value_list() is not None:\n ret.templ_param_values = ctx.template_param_value_list().accept(self)\n \n return ret\n \n def visitCompile_has_expr(self, ctx:PSSParser.Compile_has_exprContext):\n ret = ExprCompileHas(ctx.static_ref_path().accept(self))\n \n return ret;\n \n def visitOpen_range_list(self, ctx:PSSParser.Open_range_listContext):\n ret = ExprOpenRangeList()\n \n for rv in ctx.open_range_value():\n ret.val_l.append(rv.accept(self))\n \n return ret\n \n def visitOpen_range_value(self, ctx:PSSParser.Open_range_valueContext):\n lhs = ctx.lhs.accept(self)\n rhs = None if ctx.rhs is None else ctx.rhs.accept(self)\n \n ret = ExprOpenRangeValue(lhs, rhs)\n \n return ret\n \n def visitExtend_stmt(self, ctx:PSSParser.Extend_stmtContext):\n\n if ctx.ext_type is None:\n ext_type = ExtendTarget.Struct\n else:\n ext_type = {\n \"action\" : ExtendTarget.Action,\n \"component\" : ExtendTarget.Component,\n \"enum\" : ExtendTarget.Enum}[ctx.ext_type.text]\n\n ext = ExtendStmt(\n ext_type,\n self._typeid2reference(ctx.type_identifier())\n )\n \n self._scope_s[-1].add_child(ext)\n self._scope_s.append(ext)\n # TODO: we may need to treat action/component extend and enum extend differently\n\n if ext_type == ExtendTarget.Action:\n for it in ctx.action_body_item():\n it.accept(self)\n elif ext_type == ExtendTarget.Component:\n for it in ctx.component_body_item():\n it.accept(self)\n elif ext_type == ExtendTarget.Struct:\n for it in ctx.struct_body_item():\n it.accept(self)\n else:\n print(\"TODO: handle extend enum\")\n \n self._scope_s.pop()\n \n return ext\n \n #****************************************************************\n # * B01 Package\n #****************************************************************\n \n def visitImport_stmt(self, ctx:PSSParser.Import_stmtContext):\n \n imp = ImportStmt(\n ctx.package_import_pattern().type_identifier().accept(self),\n ctx.package_import_pattern().wildcard is not None\n )\n# self._set_srcinfo(imp, ctx.start)\n\n self._scope_s[-1].add_child(imp)\n\n return PSSVisitor.visitImport_stmt(self, ctx)\n \n def visitPackage_declaration(self, ctx:PSSParser.Package_declarationContext):\n cu = self._scope_s[-1]\n pkg_name = self._identifier2str(ctx.name.identifier())\n\n # Note: package doesn't have a source location associated\n # with it, because we combine content from multiple package statements\n if pkg_name in cu.package_m.keys():\n pkg = self.package_m[pkg_name]\n else:\n pkg = PackageType((pkg_name,))\n cu.package_m[pkg_name] = pkg\n cu.add_child(pkg)\n \n with self._typescope(ctx.name, pkg):\n for c in ctx.package_body_item():\n it = c.accept(self)\n \n def visitPackage_body_item(self, ctx:PSSParser.Package_body_itemContext):\n ret = PSSVisitor.visitPackage_body_item(self, ctx)\n \n return ret\n \n def visitConst_field_declaration(self, ctx:PSSParser.Const_field_declarationContext):\n field_l = ctx.const_data_declaration().accept(self)\n \n for f in field_l:\n f.flags |= FieldAttrFlags.Const\n \n return field_l\n \n def visitConst_data_declaration(self, ctx:PSSParser.Const_data_declarationContext):\n data_type = ctx.scalar_data_type().accept(self)\n \n field_l = list(map(lambda e:e.accept(self), ctx.const_data_instantiation()))\n \n for f in field_l:\n f.ftype = data_type\n \n return field_l\n \n def visitConst_data_instantiation(self, ctx:PSSParser.Const_data_instantiationContext):\n ret = FieldAttr(\n ctx.identifier().accept(self),\n 0, # Flags\n None, # field-type\n None, # array-dim\n ctx.constant_expression().accept(self)\n )\n \n return ret\n \n def visitStatic_const_field_declaration(self, ctx:PSSParser.Static_const_field_declarationContext):\n field_l = ctx.const_data_declaration().accept(self)\n \n for f in field_l:\n f.flags |= FieldAttrFlags.Static\n f.flags |= FieldAttrFlags.Const\n \n return field_l\n \n def visitTemplate_param_decl_list(self, ctx:PSSParser.Template_param_decl_listContext):\n params = []\n for p in ctx.template_param_decl():\n params.append(p.accept(self))\n \n return TemplateParamDeclList(params)\n \n def visitGeneric_type_param_decl(self, ctx:PSSParser.Generic_type_param_declContext):\n ret = TemplateGenericTypeParamDecl(\n ctx.identifier().accept(self),\n None if ctx.type_identifier() is None else ctx.type_identifier().accept(self)\n )\n \n return ret\n \n def visitCategory_type_param_decl(self, ctx:PSSParser.Category_type_param_declContext):\n category = {\n \"action\" : TemplateTypeCategory.Action,\n \"component\" : TemplateTypeCategory.Component,\n \"struct\" : TemplateTypeCategory.Struct,\n \"buffer\" : TemplateTypeCategory.Buffer,\n \"stream\" : TemplateTypeCategory.Stream,\n \"state\" : TemplateTypeCategory.State,\n \"resource\" : TemplateTypeCategory.Resource}[ctx.type_category().getText()]\n \n ret = TemplateCategoryTypeParamDecl(\n ctx.identifier().accept(self),\n category,\n None if ctx.type_restriction() is None else ctx.type_restriction().accept(self),\n None if ctx.type_identifier() is None else ctx.type_identifier().accept(self)\n )\n \n return ret\n \n def visitValue_param_decl(self, ctx:PSSParser.Value_param_declContext):\n ret = TemplateValueParamDecl(\n ctx.identifier().accept(self),\n ctx.data_type().accept(self),\n None if ctx.constant_expression() is None else ctx.constant_expression().accept(self))\n \n return ret\n \n # B09_DataTypes\n \n def visitDomain_open_range_list(self, ctx:PSSParser.Domain_open_range_listContext):\n ret = DomainOpenRangeList()\n \n for e in ctx.domain_open_range_value():\n ret.rangelist.append(e.accept(self))\n\n return ret \n \n def visitDomain_open_range_value(self, ctx:PSSParser.Domain_open_range_valueContext):\n \n if ctx.limit_low is not None or ctx.limit_high is not None:\n # \n ret = DomainOpenRangeValue(\n None if ctx.lhs is None else ctx.lhs.accept(self),\n None if ctx.rhs is None else ctx.rhs.accept(self))\n else:\n ret = ctx.lhs.accept(self)\n\n return ret \n \n def visitString_type(self, ctx:PSSParser.String_typeContext):\n if ctx.DOUBLE_QUOTED_STRING(0) is not None:\n in_spec = []\n for s in ctx.DOUBLE_QUOTED_STRING():\n in_spec.append(s.getText())\n else:\n in_spec = None\n \n ret = DataTypeString(in_spec)\n \n return ret\n\n def visitBool_type(self, ctx:PSSParser.Bool_typeContext):\n return DataTypeScalar(ScalarType.Bool, None, None, None)\n\n def visitChandle_type(self, ctx:PSSParser.Chandle_typeContext):\n return DataTypeScalar(ScalarType.Chandle, None, None, None)\n \n def visitInteger_type(self, ctx:PSSParser.Integer_typeContext):\n if ctx.integer_atom_type().getText() == \"int\":\n scalar_type = ScalarType.Integer\n else:\n scalar_type = ScalarType.Bit\n\n ret = DataTypeScalar(\n scalar_type,\n None if ctx.lhs is None else ctx.lhs.accept(self),\n None if ctx.rhs is None else ctx.rhs.accept(self),\n None if ctx.domain_open_range_list() is None else ctx.domain_open_range_list().accept(self))\n \n return ret\n \n def visitEnum_declaration(self, ctx:PSSParser.Enum_declarationContext):\n enumerators = []\n for ei in ctx.enum_item():\n enumerators.append(ei.accept(self))\n \n ret = EnumDeclaration(\n ctx.enum_identifier().accept(self),\n enumerators)\n \n return ret\n \n def visitEnum_item(self, ctx:PSSParser.Enum_itemContext):\n ret = EnumItem(\n ctx.identifier().accept(self),\n None if ctx.constant_expression() is None else ctx.constant_expression().accept(self))\n \n return ret\n \n def visitEnum_type(self, ctx:PSSParser.Enum_typeContext):\n ret = DataTypeEnum(\n ctx.enum_type_identifier().accept(self),\n None if ctx.open_range_list() is None else ctx.open_range_list().accept(self))\n \n return ret \n \n def visitTypedef_declaration(self, ctx:PSSParser.Typedef_declarationContext):\n ret = Typedef(\n ctx.data_type().accept(self),\n ctx.type_identifier().accept(self))\n \n return ret\n \n def visitUser_defined_datatype(self, ctx:PSSParser.User_defined_datatypeContext):\n ret = DataTypeUser(\n ctx.type_identifier().accept(self))\n \n return ret\n\n #**************************************************************** \n # * B08 Data Declarations\n #**************************************************************** \n def visitData_declaration(self, ctx:PSSParser.Data_declarationContext):\n ret = []\n \n ftype = ctx.data_type().accept(self)\n \n for decl in ctx.data_instantiation():\n decl_i = decl.accept(self)\n decl_i.ftype = ftype\n ret.append(decl_i)\n \n return ret\n\n def visitData_instantiation(self, ctx:PSSParser.Data_instantiationContext):\n ret = FieldAttr(\n ctx.identifier().accept(self),\n 0, # No flags for now\n None, # Type gets filled in later\n None if ctx.array_dim() is None else ctx.array_dim().accept(self),\n None if ctx.constant_expression() is None else ctx.constant_expression().accept(self)\n )\n \n return ret\n \n def check_elem(self, e, t):\n pass\n# if e is None:\n# print()\n# print(\"Note: Failed to elaborate a \\\"\" + str(type(t)) + \"\\\" \" + t.getText())\n# raise Exception(\"Failed to elaborate a \\\"\" + str(type(t)) + \"\\\" \" + t.getText())\n \n def syntaxError(self, recognizer : PSSParser, offendingSymbol : CommonToken, line, column, msg, e):\n print(\"syntaxError: \" + offendingSymbol.text + \" @ \" + str(line) + \":\" + str(column) + \" \" + msg)\n expected = recognizer.getExpectedTokensWithinCurrentRule()\n stack = recognizer.getRuleInvocationStack()\n print(\"stack=\" + str(stack))\n for exp in expected:\n print(\" exp: \" + str(exp))\n if exp < len(recognizer.literalNames):\n print(\" Literal: \" + str(recognizer.literalNames[exp]))\n elif exp < len(recognizer.symbolicNames):\n print(\" Symbol: \" + str(recognizer.symbolicNames[exp]))\n self._scope_s[-1].add_marker(Marker(line, column, msg))\n super().syntaxError(recognizer, offendingSymbol, line, column, msg, e)\n # TODO: Add error to CU output\n # raise Exception(\"TODO: parse error\")\n\n def _enter_type_scope(self, name, scope):\n if hasattr(name, \"identifier\"):\n name = name.identifier().ID().getText()\n \n self._namespace_s.append(name)\n if scope is not None:\n self._scope_s.append(scope)\n \n def _leave_type_scope(self, name, scope):\n e = self._namespace_s.pop()\n# if e != name:\n# raise Exception(\"Type-scope mismatch: leaving scope \\\"\" + e + \"\\\", but expect to leave scope \\\"\" + name + \"\\\"\")\n if scope is not None:\n self._scope_s.pop()\n \n def _get_type_qname(self, name : str) -> Tuple[str]:\n \"\"\"Returns a qualified type name\"\"\"\n if hasattr(name, \"identifier\"):\n name = name.identifier().ID().getText()\n \n ret = self._namespace_s.copy()\n ret.append(name)\n \n return tuple(ret)\n \n def _type_identifier2tuple(self, ti : PSSParser.Type_identifierContext):\n ret = []\n for elem in ti.type_identifier_elem():\n ret.append(elem.identifier().ID().getText())\n \n return tuple(ret)\n \n def _identifier2str(self, id : PSSParser.IdentifierContext):\n return id.ID().getText()\n \n def _set_srcinfo(self, obj, tok):\n obj.srcinfo = SourceInfo(-1, tok.line, tok.column)\n \n def _typeid2reference(self, ti : PSSParser.Type_identifierContext):\n ref = []\n for elem in ti.type_identifier_elem():\n ref.append(elem.identifier().ID().getText())\n \n ret = Reference(tuple(ref), ti.is_global is not None)\n self._set_srcinfo(ret, ti.start)\n \n return ret\n \n def _get_attr_flags(self):\n \n flags = AttrFlags.Default\n \n # TODO: move back through the stack and aggregate flags\n \n return flags\n \n","repo_name":"PSSTools/pssparser","sub_path":"src/pssparser/cu_parser.py","file_name":"cu_parser.py","file_ext":"py","file_size_in_byte":74650,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"33119117152","text":"import sys\nimport pytest\nfrom fastapi import FastAPI\nfrom httpx import AsyncClient\nfrom sqlalchemy.orm import Session\nfrom AkvoResponseGrouper.db import view_exist\n\npytestmark = pytest.mark.asyncio\nsys.path.append(\"..\")\n\n\nclass TestRouteCollection:\n @pytest.mark.asyncio\n async def test_if_route_successfully_attached(\n self, app: FastAPI, session: Session, client: AsyncClient\n ) -> None:\n response = await client.get(\n app.url_path_for(\"collection:get_index_category\")\n )\n assert response.status_code == 200\n\n @pytest.mark.asyncio\n async def test_if_grouped_categories_route_successfully_added(\n self, app: FastAPI, session: Session, client: AsyncClient\n ) -> None:\n response = await client.get(\n app.url_path_for(\"collection:get_grouped_categories\")\n )\n assert response.status_code == 200\n\n @pytest.mark.asyncio\n async def test_if_refresh_route_successfully_added(\n self, app: FastAPI, session: Session, client: AsyncClient\n ) -> None:\n response = await client.get(\n app.url_path_for(\"collection:refresh_materialized_view\")\n )\n assert response.status_code == 200\n\n @pytest.mark.asyncio\n async def test_if_view_is_exists(\n self, app: FastAPI, session: Session, client: AsyncClient\n ) -> None:\n assert view_exist() is True\n","repo_name":"akvo/Akvo-ResponseGrouper","sub_path":"dev/backend/tests/test_04_collection.py","file_name":"test_04_collection.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"22474843641","text":"from django.conf import settings\nfrom django.db.models import Q\nfrom pusher import Pusher\n\nfrom chat.models import UserStatus\n\n\ndef get_pusher_client() -> Pusher:\n return Pusher(\n app_id=settings.PUSHER_APP_ID,\n key=settings.PUSHER_APP_KEY,\n secret=settings.PUSHER_APP_SECRET,\n host=settings.PUSHER_HOST,\n port=int(settings.PUSHER_PORT) if settings.PUSHER_PORT else None,\n ssl=False if settings.PUSHER_HOST else True,\n )\n\n\ndef event_channel_occupied(event):\n channel_name: str = event[\"channel\"]\n\n if channel_name.startswith(\"User.\"):\n user_id = channel_name.replace(\"User.\", \"\")\n status = UserStatus.StatusType.ONLINE\n\n UserStatus.objects.filter(Q(user=user_id) & ~Q(status=status)).update(\n status=status\n )\n\n\ndef event_channel_vacated(event):\n channel_name = event[\"channel\"]\n\n if channel_name.startswith(\"User.\"):\n user_id = channel_name.replace(\"User.\", \"\")\n status = UserStatus.StatusType.OFFLINE\n\n UserStatus.objects.filter(Q(user=user_id) & ~Q(status=status)).update(\n status=status\n )\n","repo_name":"sithuhpyomyanmarunity/django-chatii","sub_path":"chat/pusher.py","file_name":"pusher.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19675465471","text":"\"\"\"\nKnow more, visit my Python tutorial page: https://morvanzhou.github.io/tutorials/\nMy Youtube Channel: https://www.youtube.com/user/MorvanZhou\n\nDependencies:\ntensorflow: 1.1.0\nmatplotlib\nnumpy\n\"\"\"\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ntf.set_random_seed(1)\nnp.random.seed(1)\n\nmnist = input_data.read_data_sets('./mnist', one_hot=True) # they has been normalized to range (0,1)\ntest_x = mnist.test.images[:2000]\ntest_y = mnist.test.labels[:2000]\n\n\nclass CNNModel(object):\n def __init__(self, batch_size, learning_rate):\n self.batch_size = batch_size\n self.learning_rate = learning_rate\n\n def build(self):\n with tf.Graph().as_default():\n self.tf_x = tf.placeholder(dtype=tf.float32, shape=[None, 28*28])\n self.tf_y = tf.placeholder(dtype=tf.float32, shape=[None, 10])\n\n self.reshape_tf_x = tf.reshape(self.tf_x, shape=[-1, 28, 28, 1])\n # conv1\n conv1 = tf.layers.conv2d(inputs=self.reshape_tf_x,\n filters=16,\n kernel_size=(5, 5),\n strides=(1, 1),\n padding='SAME',\n activation=tf.nn.relu)\n # pool1\n pool1 = tf.layers.max_pooling2d(inputs=conv1,\n pool_size=(2, 2),\n strides=(2, 2),\n )\n # conv2\n conv2 = tf.layers.conv2d(inputs=pool1,\n filters=32,\n kernel_size=(5, 5),\n strides=(1, 1),\n padding='SAME',\n activation=tf.nn.relu)\n # pool2\n pool2 = tf.layers.max_pooling2d(inputs=conv2,\n pool_size=(2, 2),\n strides=(2, 2))\n # flat\n flat = tf.reshape(tensor=pool2, shape=[-1, 7*7*32])\n output = tf.layers.dense(flat, 10)\n\n self.loss = tf.losses.softmax_cross_entropy(self.tf_y, logits=output)\n self.train_op = tf.train.GradientDescentOptimizer(learning_rate=self.learning_rate).minimize(self.loss)\n\n self.accuracy = tf.metrics.accuracy(labels=tf.argmax(self.tf_y, axis=1), predictions=tf.argmax(output, axis=1),)[1]\n\n def run(self):\n with tf.Session() as sess:\n init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())\n sess.run(init_op)\n\n for step in range(1000):\n b_x, b_y = mnist.train.next_batch(self.batch_size)\n\n _, train_loss, train_accuracy = sess.run(fetches=[self.train_op, self.loss, self.accuracy],\n feed_dict={\n self.tf_x: b_x,\n self.tf_y: b_y\n })\n if step % 50 == 0:\n test_loss, test_accuracy = sess.run([self.loss, self.accuracy]\n , feed_dict={self.tf_x: test_x, self.tf_y: test_y})\n print(\"Step:\", step, '|test loss %.4f' % test_loss, '|test accuracy %.4f' % test_accuracy)\n\n\nflags = tf.app.flags\nflags.DEFINE_integer(\"batch_size\", 32, \"The size of train images [32]\")\nflags.DEFINE_float(\"learning_rate\", 0.05, \"Learning rate for GradientDesent\")\nFLAGS = flags.FLAGS\n\n\ndef main(_):\n cnnModel = CNNModel(batch_size=FLAGS.batch_size,\n learning_rate=FLAGS.learning_rate)\n cnnModel.build()\n cnnModel.run()\n\nif __name__ == '__main__':\n tf.app.run()\n","repo_name":"ljsun/tensorflow_learn","sub_path":"tutorial-contents/CNN.py","file_name":"CNN.py","file_ext":"py","file_size_in_byte":3915,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"24240067297","text":"import candle\nimport torch\nimport torch.nn.functional as F\n\nfrom . import backend\nfrom . import modules\n\n\ndef create_feedforward(output_shape, sig=True, sig_depth=4, final_nonlinearity=lambda x: x, \n layer_sizes=(32, 32, 32)):\n \"\"\"This simple model uses a few hidden layers with signature nonlinearities between them.\n If :sig: is falsy then the signature layers will be replaced with ReLU instead.\n It expects input tensors of two dimensions: (batch, features).\n\n Note that whilst this is a simple example, this is fundamentally quite a strange idea: there's no natural path-like\n structure here, we just reshape things so that it's present.\n \"\"\"\n\n if sig:\n nonlinearity = lambda: modules.ViewSignature(channels=2, length=16, sig_depth=sig_depth)\n else:\n nonlinearity = lambda: F.relu\n\n layers = []\n for layer_size in layer_sizes:\n layers.append(layer_size)\n layers.append(nonlinearity())\n return candle.CannedNet((candle.Flatten(),\n *layers,\n torch.Size(output_shape).numel(),\n candle.View(output_shape),\n final_nonlinearity))\n\n\ndef create_simple(output_shape, sig=True, sig_depth=4, final_nonlinearity=lambda x: x, \n augment_layer_sizes=(8, 8, 2), augment_kernel_size=1, augment_include_original=True, \n augment_include_time=True, layer_sizes=(32, 32)):\n \"\"\"This model uses a single signature layer:\n - Augment the features with something learnable\n - Apply signature\n - Small ReLU network afterwards.\n If :sig: is falsy then the signature layers will be replaced with flatten-and-ReLU instead.\n It expects input tensors of three dimensions: (batch, channels, length).\n \"\"\"\n\n if sig:\n siglayer = (backend.Signature(sig_depth),)\n else:\n siglayer = (candle.Flatten(), F.relu)\n\n layers = []\n for layer_size in layer_sizes:\n layers.append(layer_size)\n layers.append(F.relu)\n\n return candle.CannedNet((modules.Augment(layer_sizes=augment_layer_sizes,\n kernel_size=augment_kernel_size,\n include_original=augment_include_original,\n include_time=augment_include_time),\n *siglayer,\n *layers,\n torch.Size(output_shape).numel(),\n candle.View(output_shape),\n final_nonlinearity))\n\n\ndef create_windowed_simpler(output_shape, sig=True, sig_depth=4, final_nonlinearity=lambda x: x):\n \"\"\"As create_windowed, but is less general, to provide a simpler example of how these things fit together.\n \n Basically applies a couple of RNNs to the input data with signatures in between.\n \"\"\"\n \n if sig:\n transformation = lambda: backend.Signature(depth=sig_depth)\n else:\n transformation = lambda: candle.batch_flatten\n \n output_size = torch.Size(output_shape).numel()\n\n return candle.CannedNet((modules.Augment(layer_sizes=(16, 16, 2), kernel_size=4),\n candle.Window(length=5, stride=1, transformation=transformation()),\n # We could equally well have an Augment here instead of a Recur; both are path-preserving\n # neural networks.\n candle.Recur(module=candle.CannedNet((candle.Concat(),\n 32, F.relu,\n 16, # memory size + output size\n candle.Split((8, 8)))), # memory size, output size\n memory_shape=(8,)), # memory size\n candle.Window(length=10, stride=5, transformation=transformation()),\n candle.Recur(module=candle.CannedNet((candle.Concat(),\n 32, F.relu, 16, F.relu,\n 8 + output_size, # memory size + output size\n candle.Split((8, output_size)))), # memory size, output size\n memory_shape=(8,), # memory size\n intermediate_outputs=False),\n candle.View(output_shape),\n final_nonlinearity))\n\n\n# Now THIS is deep signatures!\ndef create_windowed(output_shape, sig=True, sig_depth=4, final_nonlinearity=lambda x: x,\n augment_layer_sizes=(32, 32, 2), augment_kernel_size=8, augment_include_original=True,\n augment_include_time=True,\n lengths=(5, 5, 10), strides=(1, 1, 5), adjust_lengths=(0, 0, 0), memory_sizes=(8, 8, 8),\n layer_sizes_s=((32,), (32,), (32, 16)), hidden_output_sizes=(8, 8)):\n \"\"\"This model stacks multiple layers of signatures on top of one another in a natural way, using the RecurrentSig\n Module:\n - Augment the features with something learnable\n - Slide a window across the augmented features\n - Take the signature of each window\n - Put this list of signatures back together to recover the path dimension\n - Apply a RNN across the path dimension, preserving the intermediate outputs, so the path dimension is preserved\n - Slide another window\n - Take another signature\n - Reassemble signatures along path dimension\n - Another RNN\n - ... \n - etc. for some number of times\n - ...\n - Slide another window\n - Take another signature\n - Reassemble signatures along path dimension\n - Another RNN; this time throw away intermediate outputs and just present the final output as the overall output.\n If :sig: is falsy then the signature layers will be replaced with flattening instead.\n It expects input tensors of three dimensions: (batch, channels, length).\n \n For a simpler example in the same vein, see create_windowed_simpler.\n\n Arguments:\n output_shape: The final output shape from the network.\n sig: Optional, whether to use signatures in the network. If True a signature will be applied between each \n window. If False then the output is simply flattened. Defaults to True.\n sig_depth: Optional. If signatures are used, then this specifies how deep they should be truncated to.\n final_nonlinearity: Optional. What final nonlinearity to feed the final tensors of the network through, e.g. a\n sigmoid when desiring output between 0 and 1. Defaults to the identity.\n augment_layer_sizes: Optional. A tuple of integers specifying the size of the hidden layers of the feedforward\n network that is swept across the input stream to augment it. May be set to the empty tuple to do no \n augmentation.\n augment_kernel_size: Optional. How far into the past the swept feedforward network (that is doing augmenting) \n should take inputs from. For example if this is 1 then it will just take data from a single 'time', making\n it operate in a 'pointwise' manner. If this is 2 then it will take the present and the most recent piece of\n past information, and so on.\n augment_include_original: Optional. Whether to include the original path in the augmentation.\n augment_include_time: Optional. Whether to include an increasing 'time' parameter in the augmentation.\n lengths, strides, adjust_lengths, memory_sizes: Optional. Should each be a tuple of integers, all of the same\n length as one another. The length of these arguments determines the number of windows; this length must be\n at least one. The ith values determine the length, stride and adjust_length arguments of the ith Window,\n and the size of the memory of the ith RNN.\n layer_sizes_s: Optional. Should be a tuple of the same length as lengths, strides, adjust_lengths, \n memory_sizes. Each element of the tuple should itself be a tuple of integers specifying the sizes of the\n hidden layers of each RNN.\n hidden_output_sizes: Optional. Should be a tuple of integers one shorter than the length of lengths, strides,\n adjust_lengths, memory_sizes. It determines the output size of each RNN. It is of a slightly shorter length\n because the final output size is actually already determined by the output_shape argument!\n \"\"\"\n # TODO: Explain all of this a bit better... it's a bit convoluted! (Pun intended.)\n \n num_windows = len(lengths)\n assert num_windows >= 1\n assert len(strides) == num_windows\n assert len(adjust_lengths) == num_windows\n assert len(layer_sizes_s) == num_windows\n assert len(memory_sizes) == num_windows\n assert len(hidden_output_sizes) == num_windows - 1\n\n if sig:\n transformation = lambda: backend.Signature(depth=sig_depth)\n else:\n transformation = lambda: candle.batch_flatten\n \n final_output_size = torch.Size(output_shape).numel()\n output_sizes = (*hidden_output_sizes, final_output_size)\n \n recurrent_layers = []\n for (i, length, stride, adjust_length, layer_sizes, memory_size, output_size\n ) in zip(range(num_windows), lengths, strides, adjust_lengths, layer_sizes_s, memory_sizes, output_sizes):\n \n window_layers = []\n for layer_size in layer_sizes:\n window_layers.append(layer_size)\n window_layers.append(F.relu)\n \n intermediate_outputs = (num_windows - 1 != i)\n\n recurrent_layers.append(candle.Window(length=length, stride=stride, adjust_length=adjust_length,\n transformation=transformation()))\n recurrent_layers.append(candle.Recur(module=candle.CannedNet((candle.Concat(),\n *window_layers,\n memory_size + output_size,\n candle.Split((memory_size, output_size)))),\n memory_shape=(memory_size,),\n intermediate_outputs=intermediate_outputs))\n\n return candle.CannedNet((modules.Augment(layer_sizes=augment_layer_sizes, \n kernel_size=augment_kernel_size,\n include_original=augment_include_original, \n include_time=augment_include_time),\n *recurrent_layers,\n candle.View(output_shape),\n final_nonlinearity))\n","repo_name":"bwang482/Deep-Signatures-NLP","sub_path":"packages/siglayer/examples.py","file_name":"examples.py","file_ext":"py","file_size_in_byte":11141,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14540169331","text":"from user_and_pair import *\r\nimport random\r\nfrom btree import *\r\nimport time\r\nimport matplotlib.pyplot as plt\r\n\r\nref_gender = ['male', 'female']\r\nref_interest = ['sprots', 'read', 'dance', 'travel', 'write', 'draw', 'movie', 'music', 'game']\r\nls = []\r\n\r\nfor j in range(5000):\r\n interest_generating = random.choices(list(range(0,9)), k=3)\r\n name = 'x'\r\n age = random.randint(18,35)\r\n gender = ref_gender[j%2]\r\n interest = [ref_interest[j%9],ref_interest[(j+1)%9], ref_interest[(j+2)%9]]\r\n user_created = user(name, age, gender, interest, random.randint(18,35),\r\n ref_gender[(j+1+int(bool(j%40 == 0)))%2])\r\n ls.append(user_created)\r\n\r\ntest_binary_tree = tree()\r\nsampling_n = []\r\nincremental_complexity = []\r\n\r\nfor r in range(1,5001):\r\n if r% 50 == 0:\r\n sampling_n.append(r)\r\nstart = time.time()\r\nfor k in range(5000):\r\n \r\n test_binary_tree.insert(ls[k])\r\n if k % 50 == 49:\r\n sample = time.time()\r\n incremental_complexity.append((sample - start))\r\n\r\nplt.plot(sampling_n, incremental_complexity)\r\nplt.title('binary tree n_insertion complexity')\r\nplt.xlabel('number of nodes')\r\nplt.ylabel('time')\r\nplt.show()\r\n","repo_name":"melody16483/data-structure--final-project","sub_path":"Time Analysis/btree_analysis.py","file_name":"btree_analysis.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12185951413","text":"from turtle import Turtle\nfrom art import logo\n\nclass Setup(Turtle):\n def __init__(self, screen_width, screen_height):\n super().__init__()\n self.hideturtle()\n self.penup()\n\n self.goto(x=-screen_width / 2 + screen_width / 5, y=0)\n self.color('white')\n self.speed('fastest')\n self.write(logo, move=False, font=('consolas', 8, 'normal'))\n\n self.goto(x=-screen_width / 2 + screen_width / 2.5, y=-50)\n self.write('Snake', move=False, font=('consolas', 30, 'normal'))\n\n self.goto(x=-screen_width / 2 + screen_width / 5, y=-100)\n self.write('Choose Difficulty', move=False, font=('consolas', 30, 'normal'))\n","repo_name":"LucasLeow/PythonBootCamp","sub_path":"20_SnakeGame/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":"48"} +{"seq_id":"72980196625","text":"import math\r\n\r\nglobal displayableChars, displayableCharLen, brightnessPerStep\r\ndisplayableChars = \" .\\'`^\\\",:;Il!i><~+_-?][}{1)(|\\\\/tfjrxnuvczXYUJCLQ0OZmwqpdbkhao*#MW&8%B@$\"\r\ndisplayableCharLen = len(displayableChars)\r\nbrightnessPerStep = 255 / displayableCharLen\r\n\r\n\r\ndef getBrightnessMap2(imageArr, width, height):\r\n xGroups = math.floor(len(imageArr[0]) / width)\r\n yGroups = math.floor(len(imageArr) / height)\r\n width = math.floor(width)\r\n height = math.floor(height)\r\n subgroups = []\r\n for y in range(yGroups):\r\n subgroup = []\r\n yHeight = y * height\r\n for x in range(xGroups):\r\n tempSum = 0\r\n xWidth = x * width\r\n for h in range(yHeight, yHeight + height):\r\n for w in range(xWidth, xWidth + width):\r\n tempSum += imageArr[h][w][0]\r\n subgroup.append(convertBrightnessValue(tempSum / (width * height)))\r\n subgroups.append(\"\".join(subgroup))\r\n\r\n return subgroups\r\n\r\n\r\ndef convertBrightnessValue(bValue):\r\n return displayableChars[int(bValue / brightnessPerStep)]\r\n\r\n\r\ndef getCharMap(data, width, height):\r\n widthPerSquare = len(data[0]) / width\r\n heightPerSquare = len(data) / height\r\n brightness = getBrightnessMap2(data, widthPerSquare, heightPerSquare)\r\n return brightness\r\n","repo_name":"dandersonw/AsciiRendr","sub_path":"src/asciiTools.py","file_name":"asciiTools.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12908719443","text":"import os\nimport re\nimport base64\nimport logging\n\nimport requests\n\nfrom utils.github_url_constructor import GithubURLConstructor\n\nlogging.basicConfig(level=logging.DEBUG, filename='debug.log', filemode='a')\n\nheaders = {\"Authorization\": f\"token {os.environ.get('GITHUB_ACCESS_TOKEN')}\"}\n\nprint(headers)\n\n\nclass DeploymentChecker:\n def __init__(\n self, batch_keywords, web_service_keywords, streaming_keywords, cloud_keywords\n ):\n self.batch_keywords = batch_keywords\n self.web_service_keywords = web_service_keywords\n self.streaming_keywords = streaming_keywords\n self.cloud_keywords = cloud_keywords\n self.url_constructor = GithubURLConstructor()\n\n def check_keywords(self, content, keywords):\n for keyword in keywords:\n if re.search(r'\\b' + re.escape(keyword) + r'\\b', content, re.IGNORECASE):\n return keyword\n return None\n\n def check_cloud_provider(self, content):\n # logging.debug(\n # f\"Checking for cloud provider in content: {content[:100]}...\"\n # )\n provider_counts = {}\n\n for provider, keywords in self.cloud_keywords.items():\n for keyword in keywords:\n if re.search(\n r'\\b' + re.escape(keyword) + r'\\b', content, re.IGNORECASE\n ):\n logging.debug(\n f\"Found cloud provider {provider} for keyword {keyword}\"\n )\n provider_counts[provider] = provider_counts.get(provider, 0) + 1\n\n # If multiple providers are found, prioritize based on frequency and order in cloud_keywords\n if provider_counts:\n sorted_providers = sorted(\n provider_counts.keys(),\n key=lambda x: (\n -provider_counts[x],\n list(self.cloud_keywords.keys()).index(x),\n ),\n )\n return sorted_providers[0]\n\n logging.debug(\"No cloud provider found.\")\n return 'Unknown'\n\n def fetch_readme_via_api(self, project_url):\n (\n api_url_with_main,\n api_url_without_main,\n ) = self.url_constructor.construct_readme_api_url(project_url)\n\n if api_url_with_main is None and api_url_without_main is None:\n return None\n\n # Try the first URL\n response = requests.get(api_url_with_main, headers=headers, timeout=20)\n if response.status_code == 200:\n json_data = response.json()\n readme_content = base64.b64decode(json_data['content']).decode('utf-8')\n return readme_content.lower()\n else:\n logging.debug(\n f\"Failed to fetch README via API for URL {api_url_with_main}: {response.status_code}\"\n )\n\n # Try the second URL if the first one fails\n response = requests.get(api_url_without_main, headers=headers, timeout=20)\n if response.status_code == 200:\n json_data = response.json()\n readme_content = base64.b64decode(json_data['content']).decode('utf-8')\n return readme_content.lower()\n else:\n logging.debug(\n f\"Failed to fetch README via API for URL {api_url_without_main}: {response.status_code}\"\n )\n\n return None\n\n def check_deployment_type(self, url):\n # use Github API instead of web scrape\n try:\n if url is None:\n logging.debug(\"Received None URL. Skipping.\")\n return 'Unknown', 'Unknown', 'Unknown'\n\n # Sanitize the URL to remove any fragment\n sanitized_url = self.url_constructor.sanitize_url(url)\n\n # Now use the sanitized URL to fetch the README\n readme_content = self.fetch_readme_via_api(sanitized_url)\n if readme_content is None:\n logging.debug(f\"No README found for URL: {url}\")\n return 'Unknown', 'Unknown', 'Unknown'\n\n # logging.debug(f\"Entire Readme content for URL {url}: {readme_content}\")\n\n deployment_keyword = 'Unknown'\n reason_keyword = 'Unknown'\n\n # Debug logging for cloud keyword search\n logging.debug(f\"Checking cloud keywords for URL: {url}\")\n # logging.debug(\n # f\"Readme content: {readme_content[:100]}...\"\n # ) # First 100 characters of README\n\n # Check for deployment type\n keyword = self.check_keywords(readme_content, self.batch_keywords)\n if keyword:\n deployment_keyword = 'Batch'\n reason_keyword = keyword\n else:\n keyword = self.check_keywords(readme_content, self.web_service_keywords)\n if keyword:\n deployment_keyword = 'Web Service'\n reason_keyword = keyword\n else:\n keyword = self.check_keywords(\n readme_content, self.streaming_keywords\n )\n if keyword:\n deployment_keyword = 'Streaming'\n reason_keyword = keyword\n\n # Check for cloud tool\n cloud_provider = self.check_cloud_provider(readme_content)\n\n if cloud_provider == 'Unknown':\n logging.debug(f\"No cloud keyword found in README for URL: {url}\")\n else:\n logging.debug(\n f\"Found cloud provider {cloud_provider} in README for URL: {url}\"\n )\n\n return deployment_keyword, reason_keyword, cloud_provider\n\n except requests.exceptions.RequestException as e:\n logging.error(f\"Error checking for URL {url}: {e}\")\n return 'Error', 'Error', 'Error'\n","repo_name":"dimzachar/DataTalksClub-Projects","sub_path":"utils/deployment_checker.py","file_name":"deployment_checker.py","file_ext":"py","file_size_in_byte":5818,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"48"} +{"seq_id":"5486377292","text":"VOCAB = open('wordle-possible-answers.txt', 'r').read().split('\\n')\n\ndef answer_search(letter, position):\n i = 0\n while i < len(VOCAB):\n if VOCAB[i][position] != letter:\n del VOCAB[i]\n else:\n i += 1\n\nk = input(\"Enter known letters, in order of position, with other spaced indicated by underspaces: \")\nx = input(\"Enter excluded letters, not separated: \")\n\ni = 0\nwhile i < len(VOCAB):\n for j in range(len(x)):\n c = x[j]\n if c in VOCAB[i]:\n del VOCAB[i]\n break\n else:\n if j == len(x)-1:\n i += 1\n\nfor i in range(5):\n c = k[i]\n if (c != \"_\"):\n answer_search(c, i)\n\nprint(\"Possible answers:\", VOCAB)\n","repo_name":"alwritescode/wordle-solver","sub_path":"wordle_helper.py","file_name":"wordle_helper.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28323581379","text":"from __future__ import print_function\nimport math, numpy\nimport lsst.pex.config as pexConfig\nimport lsst.meas.mosaic as measMosaic\nimport lsst.afw.cameraGeom as cameraGeom\nimport lsst.afw.cameraGeom.utils as cameraGeomUtils\nimport lsst.afw.geom as afwGeom\nimport lsst.afw.image as afwImage\nimport lsst.afw.table as afwTable\nfrom lsst.meas.photocal import PhotoCalTask\n\nclass PhotometricSolutionConfig(PhotoCalTask.ConfigClass):\n fluxFitOrder = pexConfig.Field(\n doc=\"flux fitting order\",\n dtype=int,\n default=5)\n\n def setDefaults(self):\n self.outputField = \"classification.exposure.photometric\"\n\nclass PhotometricSolutionTask(PhotoCalTask):\n ConfigClass = PhotometricSolutionConfig\n\n def __init__(self, schema, **kwargs):\n super(PhotometricSolutionTask, self).__init__(schema, **kwargs)\n\n def getExtent(self, matchVec):\n u_max = float(\"-inf\")\n v_max = float(\"-inf\")\n for m in matchVec:\n if (math.fabs(m.u) > u_max):\n u_max = math.fabs(m.u)\n if (math.fabs(m.v) > v_max):\n v_max = math.fabs(m.v)\n\n return u_max, v_max\n\n def decodeCcdExposureId(self, ccdId):\n return ccdId/200, ccdId%200\n\n def setCatFlux(self, m, f, key):\n m[0].set(key, f)\n return m\n\n def selectStars(self, matches):\n sourceList = [m[1] for m in matches]\n psfKey = sourceList[0].schema.find(\"calib.psf.used\").getKey()\n extKey = sourceList[0].schema.find(\"classification.extendedness\").getKey()\n stars = list()\n for m, s in zip(matches, sourceList):\n star = ((psfKey is not None and s.get(psfKey)) or\n s.get(extKey) < 0.5)\n if star:\n stars.append(m)\n return stars\n\n def run(self, matchLists, filterName, wcsList, butler):\n\n if self.config.applyColorTerms:\n ct = self.config.colorterms.selectColorTerm(filterName)\n else:\n ct = None\n\n # Convert matchLists to meas_mosaic specific format\n mlVisit = dict()\n for ccdId in matchLists:\n if matchLists[ccdId] is None:\n continue\n visit, ccd = self.decodeCcdExposureId(ccdId)\n if visit not in mlVisit:\n mlVisit[visit] = list()\n matches = [m for m in matchLists[ccdId] if m[0] is not None]\n keys = self.getKeys(matches[0][1].schema)\n matches = self.selectMatches(matches, keys)\n matches = self.selectStars(matches)\n\n # Apply color term\n if ct is not None and len(matches) != 0:\n refSchema = matches[0][0].schema\n key_p = refSchema.find(ct.primary).key\n key_s = refSchema.find(ct.secondary).key\n key_f = refSchema.find(\"flux\").key\n refFlux1 = numpy.array([m[0].get(key_p) for m in matches])\n refFlux2 = numpy.array([m[0].get(key_s) for m in matches])\n refMag1 = -2.5*numpy.log10(refFlux1)\n refMag2 = -2.5*numpy.log10(refFlux2)\n refMag = ct.transformMags(refMag1, refMag2)\n refFlux = numpy.power(10.0, -0.4*refMag)\n matches = [self.setCatFlux(m, f, key_f) for m, f in zip(matches, refFlux) if f == f]\n\n for m in matches:\n if m[0] is not None and m[1] is not None:\n match = (measMosaic.Source(m[0], wcsList[ccdId]), measMosaic.Source(m[1]))\n match[1].setExp(visit)\n match[1].setChip(ccd)\n mlVisit[visit].append(match)\n\n\n matchList = []\n for visit in mlVisit:\n matchList.append(mlVisit[visit])\n\n rootMat = measMosaic.kdtreeMat(matchList)\n allMat = rootMat.mergeMat()\n\n # Read CCD information\n ccdSet = {}\n for ccdId in matchLists:\n if matchLists[ccdId] is None:\n continue\n visit, ccd = self.decodeCcdExposureId(ccdId)\n if ccd not in ccdSet:\n ccdDev = cameraGeomUtils.findCcd(butler.mapper.camera, cameraGeom.Id(int(ccd)))\n ccdSet[ccd] = ccdDev\n\n # meas_mosaic specific wcs information\n wcsDic = {}\n for ccdId in wcsList:\n visit, ccd = self.decodeCcdExposureId(ccdId)\n if visit not in wcsDic and wcsList[ccdId] is not None:\n wcs = wcsList[ccdId]\n ccdDev = ccdSet[ccd]\n offset = afwGeom.Extent2D(ccdDev.getCenter().getPixels(ccdDev.getPixelSize()))\n wcsDic[visit] = wcs.copyAtShiftedPixelOrigin(offset)\n\n # meas_mosaic specific object list\n matchVec = measMosaic.obsVecFromSourceGroup(allMat, wcsDic, ccdSet)\n sourceVec = []\n\n # Apply Jocabian correction calculated from wcs\n for m in matchVec:\n wcs = wcsList[m.iexp*200+m.ichip]\n m.mag -= 2.5*math.log10(measMosaic.computeJacobian(wcs, afwGeom.Point2D(m.x, m.y)))\n\n fluxFitOrder = self.config.fluxFitOrder\n absolute = True\n chebyshev = True\n commonFluxCorr = False\n solveCcdScale = True\n ffpSet = {}\n for visit in wcsDic:\n ffp = measMosaic.FluxFitParams(fluxFitOrder, absolute, chebyshev)\n u_max, v_max = self.getExtent(matchVec)\n ffp.u_max = (math.floor(u_max / 10.) + 1) * 10\n ffp.v_max = (math.floor(v_max / 10.) + 1) * 10\n ffpSet[visit] = ffp\n\n fexp = {}\n fchip = {}\n\n matchVec, sourceVec, wcsDic, ccdSet, fexp, fchip, ffpSet = measMosaic.fluxFit(absolute, commonFluxCorr, matchVec, len(matchVec), sourceVec, len(sourceVec), wcsDic, ccdSet, fexp, fchip, ffpSet, solveCcdScale)\n\n self.writeFcr(butler, list(matchLists.keys()), ccdSet, filterName,\n fexp, fchip, ffpSet)\n\n return (1.0/fexp[list(fexp.keys())[0]])\n\n def writeFcr(self, butler, ccdIdList, ccdSet, filterName,\n fexp, fchip, ffpSet):\n for ccdId in ccdIdList:\n iexp, ichip = self.decodeCcdExposureId(ccdId)\n if ichip not in ccdSet:\n continue\n x0 = 0.0\n y0 = 0.0\n newP = measMosaic.convertFluxFitParams(measMosaic.FluxFitParams(ffpSet[iexp]),\n ccdSet[ichip], x0, y0)\n metadata = measMosaic.metadataFromFluxFitParams(newP)\n exp = afwImage.ExposureI(0,0)\n exp.getMetadata().combine(metadata)\n scale = fexp[iexp] * fchip[ichip]\n exp.setPhotoCalib(afwImage.makePhotoCalibFromCalibZeroPoint(1.0/scale))\n exp.setFilter(afwImage.Filter(filterName))\n try:\n butler.put(exp, 'fcr', {'visit': iexp, 'ccd': ichip})\n except Exception as e:\n print(\"failed to write something: %s\" % (e))\n","repo_name":"lsst-dm/legacy-meas_mosaic","sub_path":"python/lsst/meas/mosaic/photometricSolution.py","file_name":"photometricSolution.py","file_ext":"py","file_size_in_byte":7027,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"39021520387","text":"import random\nimport sys\n\ndef menu():\n\tadjs = [\"Spicy\", \"Sweet\", \"Creamy\", \"Salty\", \"Savory\", \"BBQ\", \"Pesto\", \"Sour\", \"Peppery\", \"Aromatic\"]\n\tstyles = [\"Sauteed\", \"Baked\", \"Seasoned\", \"Fried\", \"Grilled\", \"Roasted\", \"Caramelized\", \"Broiled\", \"Toasted\", \"Flambeed\"]\n\tfoods = [\"Chicken\", \"Turkey\", \"Spinach\", \"Carrots\", \"Potatoes\", \"Steak\", \"Pork Chops\", \"Couscous\", \"Gnocchi\", \"Risotto\"]\n\n\tdef rand_item():\n\t\treturn adjs[random.randint(0,9)] + \" \" + styles[random.randint(0,9)] + \" \" + foods[random.randint(0,9)]\n\n\tfor i in range(10):\n\t\tprint(rand_item())\n\t\ndef band():\n\tarticles = [\"The\", \"Three\", \"A\", \"Five\", \"Four\", \"Twelve\"]\n\tadjs = [\"Happy\", \"Funny\", \"Weird\", \"Running\", \"Loud\", \"Musical\", \"Hungry\", \"Exceptional\", \"Blue\", \"Purple\"]\n\titems = [\"Rocks\", \"Water Bottles\", \"Pens\", \"Rabbits\", \"Computers\", \"Dreams\", \"Oranges\", \"Blueberries\"]\n\tdef band_name():\n\t\treturn articles[random.randint(0,5)] + \" \" + adjs[random.randint(0,9)] + \" \" + items[random.randint(0,7)]\n\tprint(band_name())\n\ndef haiku():\n\tfives = [\"With no leaves to blow\", \"They were whispering\", \"Yesterday morning\", \"It was much too late\", \"The world can decide\", \"It was a lost cause\", \"People will tell you\", \"They ran silently\", \"That was years ago\", \"Gusts of wind rising\"]\n\tsevens = [\"The wind is blowing softly\", \"The sand slipped through my fingers\", \"The enormous machines loom\", \"The orange lies on the desk\", \"Cold water drips on his head\", \"The dark forest was gloomy\", \"The vibrant red flower bloomed\", \"Dust covered the whole cottage\", \"The pungent smoke filled the air\", \"The blazing red fire burned on\"]\n\n\tdef a_haiku():\n\t\treturn fives[random.randint(0,9)] + \"\\n\" + sevens[random.randint(0,9)] + \"\\n\" + fives[random.randint(0,9)]\n\n\tfor i in range(3):\n\t\tprint(a_haiku()+ \"\\n\") \n\ndef hangman():\t\t\n\twords = [\"political\", \"abruptly\", \"galaxy\", \"dwarves\",\"papaya\",\"karaoke\",\"symphony\",\"impromptu\",\"rendezvous\", \"pneumonia\", \"oxygen\",\"vaporize\",\"jawbreaker\",\"microwave\",\"sequoia\",\"exercise\", \"observation\", \"distance\",\"experiment\",\"weather\", \"balance\",\"extraordinary\", \"composition\", \"vegetable\", \"property\", \"jazzy\", \"medicine\", \"conversation\", \"particularly\",\"buzzing\",\"hollow\",\"surround\", \"discover\", \"environment\", \"molecule\", \"available\", \"forgotten\", \"consonant\",\"announce\", \"fireplace\", \"mysterious\",\"official\",\"memory\",\"melted\",\"satellites\", \"occasionally\", \"elephant\", \"notebook\", \"rambunctious\", \"enthusiasm\", \"electronic\", \"activity\", \"character\", \"immutable\", \"submerge\"]\n\tword = words[random.randint(0,len(words)-1)]\n\tanswer = \"\"\n\tfor i in range(len(word)): #prints out number of letters the hidden word has\n\t\tanswer += \"-\"\n\tguesses = [] \n\tdone = False\n\twhile done == False: #repeats until the player guesses the word\n\t\trepeat = True\n\t\twhile repeat == True: #asks for another letter if already guessed\n\t\t\tletter = input(\"Guess a letter: \")\n\t\t\tj = 0\n\t\t\trepeat = False\n\t\t\tfor i in range(len(guesses)): #checks wrong guess list if the user has already guessed the letter\n\t\t\t\tif guesses[j] == letter:\n\t\t\t\t\trepeat = True\n\t\t\t\tj+=1\n\t\t\tj = 0 \n\t\t\tfor i in range(len(answer)): #checks answers if the user has already guessed the letter\n\t\t\t\tif answer[j] == letter:\n\t\t\t\t\trepeat = True\n\t\t\t\tj+=1\n\t\t\t\t\n\t\t\t\t\n\t\ta = 0\n\t\tguessed = False\t\n\t\tfor i in range(len(word)): #checks if the guessed letter is in the word\n\t\t\tif word[a] == letter:\n\t\t\t\tanswer = answer[0:a] + letter + answer[a+1:] #switches the '-' to show the correctly guessed letters\n\t\t\t\tguessed = True\n\t\t\ta+=1\n\t\tif guessed == False:\n\t\t\tguesses.append(letter) #adds the letter to wrong guess list if not in word\n\t\tif answer.find(\"-\") == -1: #if all letters guessed, game over\n\t\t\tdone = True\n\t\tprint(answer)\n\t\tsys.stdout.write(\"Wrong guesses: \")\n\t\tc = 0\n\t\tfor i in range(len(guesses)): #prints all the wrong guessed letters\n\t\t\tsys.stdout.write(guesses[c] + \" \")\n\t\t\tc+=1\n\t\tprint(\"\\n\")\n\tprint(\"You Win!\")\n\n\n\nmenu()\nprint(\"\\n\")\nband()\nprint(\"\\n\")\nhaiku()\nprint(\"\\n\")\nhangman()\n","repo_name":"miranda-lin/GWC_2016_Projects","sub_path":"Python/Random.py","file_name":"Random.py","file_ext":"py","file_size_in_byte":3901,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71224111187","text":"from __future__ import print_function\n\nimport sys\n\nSSA, DESSA, EXPR, ARGRET, TRACE, BLOCK, CODE, MAIN = range(0, 8)\n_name = ['ssa', 'dessa', 'expr', 'argret', 'trace', 'block', 'code', 'main']\nenabled = set()\n\ndebug_level = 0\ndebugout = sys.stdout\nenabled = set()\n\ndef debug(type, level, *args, **kwargs):\n global enabled\n if debug_level >= level and type in enabled:\n print(_name[type].ljust(6).upper(), *args, file=debugout, **kwargs)\n\ndef enable(lst):\n global enabled\n if 'all' in lst:\n lst = _name\n enabled = [list.index(_name, x) for x in lst]\n\ndef debug_enabled(level):\n return debug_level >= level\n","repo_name":"chozekun/decomp","sub_path":"debug.py","file_name":"debug.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"72622437267","text":"# Задание 4 лабораторная 2\n# Вариант 1\n# Збаразский С.С\n\nn = int(input(\"Введите натуральное число: \"))\nsum = 0\n\nfor x in range(1, n + 1):\n if x % 3 == 0:\n sum += x**2\n elif x % 3 == 1:\n sum += x\n\n else:\n sum += x/3\nprint(sum)\n","repo_name":"Zbara/ZbaraLabs","sub_path":"Z_lab_2/Z_2_4.py","file_name":"Z_2_4.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2793264817","text":"'''\n첫 줄에 테스트 케이스의 개수 T가 주어지고, 테스트 케이스 별로 첫 줄에 마지막 노드번호 V와 간선의 개수 E가 주어진다.\n다음 줄부터 E개의 줄에 걸쳐 간선의 양 끝 노드 n1, n2, 가중치 w가 차례로 주어진다.\n1<=T<=50, 1<=V<=1000, 1<=w<=10, 1<=E<=1000000\n[출력]\n각 줄마다 \"#T\" (T는 테스트 케이스 번호)를 출력한 뒤, 답을 출력한다.\n'''\nT = int(input())\nfor tc in range(1,T+1):\n V, E = map(int,input().split()) # 노드갯수, 간선\n adj = [[0]*(V+1) for _ in range(V+1)]\n for _ in range(E):\n x, y, c = map(int,input().split())\n # print(adj)\n adj[x][y] = c\n adj[y][x] = c\n INF = float('inf')\n key = [INF] * (V+1) # 시작점을 제외한 각 배열 객체 최소의 가중치 값이 있음\n p = [-1]*V # 시작점을 제외한 각 배열 객체에는 before 정점이 있음\n mst = [False] * (V+1) # 시작점이 다른 정점으로 이동을 했냐?? 의 유무\n key[0] = 0 # 0 위치의 가중치는 0으로 정의, 0은 시작점이기 때문에 다른 노드에서 오는 경우가 없음\n result = 0\n cnt = 0\n while cnt < V+1: # 다 방문하면 끝\n min = INF\n u = - 10\n ############################################################\n # 인접 정점중 가중치가 가장 낮은값 min을 찾는뒤, 해당 노드번호로 이동\n ############################################################\n for i in range(V+1):\n if not mst[i] and key[i] < min:\n min = key[i]\n u = i\n mst[u] = True\n result += min\n cnt +=1\n # 이동한 노드의 인접한 모든 가중치를 key배열에 넣는다. why?? 다음을 위해\n for j in range(1,V+1):\n if not mst[j] and adj[u][j] > 0 and key[j] > adj[u][j]:\n key[j] = adj[u][j]\n\n print(\"#{} {}\".format(tc,result))\n'''\n3\n2 3\n0 1 1\n0 2 1\n1 2 6\n4 7\n0 1 9\n0 2 3\n0 3 7\n1 4 2\n2 3 8\n2 4 1\n3 4 8\n4 6\n0 1 10\n0 2 7\n1 4 2\n2 3 10\n2 4 3\n3 4 10\n'''","repo_name":"silverjjj/algorithm","sub_path":"DataStructure/09_그래프/MST/SWex5249.py","file_name":"SWex5249.py","file_ext":"py","file_size_in_byte":2097,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23103988767","text":"import pandas as pd\nimport numpy as np \nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score, r2_score\nfrom sklearn.ensemble import GradientBoostingRegressor\nfrom xgboost import XGBRFRegressor\nfrom lightgbm import LGBMRegressor, LGBMClassifier\nfrom sklearn.multioutput import MultiOutputRegressor\nimport lightgbm as lgb\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.preprocessing import LabelEncoder\n\ndef grap_year(data):\n data = str(data)\n return int(data[:4])\n\ndef grap_month(data):\n data = str(data)\n return int(data[4:])\n\n# 날짜 처리\ndata = pd.read_csv('./data/dacon/jeju/201901-202003.csv')\ndata = data.fillna('')\ndata['year'] = data['REG_YYMM'].apply(lambda x: grap_year(x))\ndata['month'] = data['REG_YYMM'].apply(lambda x: grap_month(x))\ndata = data.drop(['REG_YYMM'], axis=1)\n\n# 데이터 정제\ndf = data.copy()\ndf = df.drop(['CARD_CCG_NM', 'HOM_CCG_NM'], axis=1)\n\ncolumns = ['CARD_SIDO_NM', 'STD_CLSS_NM', 'HOM_SIDO_NM', 'AGE', 'SEX_CTGO_CD', 'FLC', 'year', 'month']\ndf = df.groupby(columns).sum().reset_index(drop=False)\n\n# 인코딩\ndtypes = df.dtypes\nencoders = {}\nfor column in df.columns:\n if str(dtypes[column]) == 'object':\n encoder = LabelEncoder()\n encoder.fit(df[column])\n encoders[column] = encoder\n \ndf_num = df.copy() \nfor column in encoders.keys():\n encoder = encoders[column]\n df_num[column] = encoder.transform(df[column])\n\n# feature, target 설정\ntrain_num = df_num.sample(frac=1, random_state=0)\ntrain_features = train_num.drop(['CSTMR_CNT', 'AMT', 'CNT'], axis=1)\ntrain_target = np.log1p(train_num['AMT'])\n\nfrom sklearn.model_selection import GridSearchCV\nparams = {#'n_estimators':[100, 200],\n #'max_depth':[10, 30, 50],\n 'min_samples_leaf':[10, 30],\n 'min_samples_split':[10, 30]\n }\n# 훈련\nrf_clf = RandomForestRegressor(n_jobs=-1, random_state=0, n_estimators=300, max_depth=10)\ngrid_cv = GridSearchCV(rf_clf, param_grid=params, cv=2, n_jobs=-1)\ngrid_cv.fit(train_features, train_target)\n\nprint('최적 하이퍼 파라미터 : \\n', grid_cv.best_params_)\nprint('최고 예측 정확도 : {0:.4f}'.format(grid_cv.best_score_))\n\n","repo_name":"sunho-park/study1","sub_path":"dacon/jeju/share_code_grid.py","file_name":"share_code_grid.py","file_ext":"py","file_size_in_byte":2227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20568238809","text":"\n#!/usr/bin/python\n# coding: utf-8\n\nfrom bs4 import BeautifulSoup\nimport urllib2\n\nurl = \"http://www.stats.gov.cn/tjsj/tjbz/xzqhdm/201703/t20170310_1471429.html\" # 目标 url\nheaders = { 'User-Agent':'Mozilla/5.0' } # 设置 headers\nrequest = urllib2.Request(url, headers = headers) \nresponse = urllib2.urlopen(request)\npages = response.read()\nsoup = BeautifulSoup(pages, 'lxml')\ntag_span = soup.find_all('span', attrs={'style': 'font-family: 宋体'}) # 找到城市名所在的 tag\n\ncity_names = []\nfor name in tag_span:\n if name.string[-1] == u'市': # 仅保留市级城市名,并存储在列表中\n city_names.append(name.string[:-1].strip())\n\ncity_names_text = open('city_names.txt', 'w') # 将城市名存储在 txt 文件中\nfor city in city_names:\n city_names_text.write(city.encode('utf-8'))\n city_names_text.write('\\n')\ncity_names_text.close()\n\n","repo_name":"Sunnyhp/City-Solitaire","sub_path":"get_city_names_from_website.py","file_name":"get_city_names_from_website.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37760773945","text":"case = int(input())\nwords = [0] * case\nalpha = []\nresult = 0\n\nfor i in range(case) :\n words[i] = list(input())\n\n# 입력 받은 case ��� 만큼 반복\nfor i in range(case) :\n alpha.clear()\n previous = -1\n current = -1\n state = 1\n\n # 단어의 알파벳 수만큼 반복\n for j in range(len(words[i])) :\n # 알파벳이 alpha list에 없을 경우\n if alpha.count(words[i][j]) == 0 :\n alpha.append(words[i][j])\n previous = current\n current += 1\n # 알파벳이 alpha list에 있을 경우\n else :\n previous = current\n current = alpha.index(words[i][j])\n if current -previous < 0 :\n state = 0\n break\n \n if state == 1 :\n result += 1\n\nprint(result)","repo_name":"KangGeonyoung/Algorithm","sub_path":"Baekjoon/7. 문자열/1316.py","file_name":"1316.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41687886108","text":"# Licensed under an MIT style license -- see LICENSE.md\n\nimport numpy as np\n\n__author__ = [\"Charlie Hoy \"]\n\n\nclass List(list):\n \"\"\"Base list class to extend the core `list` class\n\n Parameters\n ----------\n *args: tuple\n all arguments are passed to the list class\n **kwargs: dict\n all kwargs are passed to the list class\n\n Attributes\n ----------\n added: list\n list of values appended to the original list\n \"\"\"\n __slots__ = [\"original\", \"cls\", \"added\", \"removed\"]\n\n def __init__(self, *args, **kwargs):\n if len(args) == 1:\n self.original = list(*args)\n self.cls = kwargs.get(\"cls\", None)\n self.added = kwargs.get(\"added\", [])\n self.removed = kwargs.get(\"removed\", [])\n super(List, self).__init__(*args)\n else:\n _, self.original, self.cls, self.added, self.removed = args\n super(List, self).__init__(_)\n\n @property\n def ndim(self):\n return np.array(self).ndim\n\n def __reduce__(self):\n _slots = [getattr(self, i) for i in self.__slots__]\n slots = [list(self)] + _slots\n return (self.__class__, tuple(slots))\n\n def __setstate__(self, state):\n _state = state[1]\n self.original = _state[\"original\"]\n self.cls = _state[\"original\"]\n self.added = _state[\"added\"]\n self.removed = _state[\"removed\"]\n\n def __getitem__(self, *args, **kwargs):\n output = super(List, self).__getitem__(*args, **kwargs)\n if self.cls is None:\n return output\n if isinstance(output, list):\n return [self.cls(value) for value in output]\n else:\n return self.cls(output)\n\n def __add__(self, *args, **kwargs):\n self.added.extend(*args)\n obj = List(super(List, self).__add__(*args, **kwargs))\n for attr in self.__slots__:\n setattr(obj, attr, getattr(self, attr))\n return obj\n\n def __iadd__(self, *args, **kwargs):\n self.added.extend(*args)\n obj = List(super(List, self).__iadd__(*args, **kwargs))\n for attr in self.__slots__:\n setattr(obj, attr, getattr(self, attr))\n return obj\n\n def append(self, *args, **kwargs):\n self.added.append(*args)\n return super(List, self).append(*args, **kwargs)\n\n def extend(self, *args, **kwargs):\n self.added.extend(*args)\n return super(List, self).extend(*args, **kwargs)\n\n def insert(self, index, obj, **kwargs):\n self.added.append(obj)\n return super(List, self).insert(index, obj, **kwargs)\n\n def remove(self, element, **kwargs):\n obj = super(List, self).remove(element, **kwargs)\n self.removed.append(element)\n if element in self.added:\n self.added.remove(element)\n return obj\n\n def pop(self, index, **kwargs):\n self.removed.append(self[index])\n obj = super(List, self).pop(index)\n return obj\n","repo_name":"pesummary/pesummary","sub_path":"pesummary/utils/list.py","file_name":"list.py","file_ext":"py","file_size_in_byte":2993,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"464120390","text":"\"\"\"Routes for the course resource.\n\"\"\"\n\nfrom run import app\nfrom flask import request\nfrom http import HTTPStatus\nimport data\nimport json\nfrom datetime import datetime\nimport re\n\n@app.route(\"/\")\ndef show_data():\n return data.load_data()\n\n\n@app.route(\"/course/\", methods=['GET'])\ndef get_course(id):\n \"\"\"Get a course by id.\n\n :param int id: The record id.\n :return: A single course (see the challenge notes for examples)\n :rtype: object\n \"\"\"\n\n \"\"\"\n -------------------------------------------------------------------------\n Challenge notes:\n ------------------------------------------------------------------------- \n 1. Bonus points for not using a linear scan on your data structure.\n \"\"\"\n # YOUR CODE HERE\n allcourses = data.load_data()\n\n try: \n ans={}\n ans[\"data\"] = allcourses[id]\n return ans\n except:\n return \"Course {} does not exist\".format(id)\n \n\n@app.route(\"/course\", methods=['GET'])\ndef get_courses():\n \"\"\"Get a page of courses, optionally filtered by title words (a list of\n words separated by commas\".\n\n Query parameters: page-number, page-size, title-words\n If not present, we use defaults of page-number=1, page-size=10\n\n :return: A page of courses (see the challenge notes for examples)\n :rtype: object\n \"\"\"\n\n \"\"\"\n -------------------------------------------------------------------------\n Challenge notes:\n ------------------------------------------------------------------------- \n 1. Bonus points for not using a linear scan, on your data structure, if\n title-words is supplied\n 2. Bonus points for returning resulted sorted by the number of words which\n matched, if title-words is supplied.\n 3. Bonus points for including performance data on the API, in terms of\n requests/second.\n \"\"\"\n # YOUR CODE HERE\n if request.args.get(\"title-words\")!=None:\n words = list(request.args.get(\"title-words\"))\n resp={}\n with open(\"json/course.json\") as f:\n temp = json.load(f)\n li=[]\n for i in temp:\n for j in words:\n if j in i[\"title\"]:\n li.append(i)\n resp[\"data\"]=li\n return resp\n\n if request.args.get(\"page-number\")!=None:\n resp={}\n pagenumber= int(request.args.get(\"page-number\"))\n pagesize = int(request.args.get(\"page-size\"))\n with open(\"json/course.json\") as f:\n temp = json.load(f)\n resp[\"data\"]=(temp[(pagenumber-1)*pagesize:((pagenumber-1)*pagesize)+pagesize])\n return resp\n else:\n ans={}\n with open(\"json/course.json\") as f:\n temp = json.load(f)\n ans[\"data\"]=temp\n return ans\n\n\n@app.route(\"/course\", methods=['POST'])\ndef create_course():\n \"\"\"Create a course.\n :return: The course object (see the challenge notes for examples)\n :rtype: object\n \"\"\"\n\n \"\"\"\n -------------------------------------------------------------------------\n Challenge notes:\n -------------------------------------------------------------------------\n 1. Bonus points for validating the POST body fields\n \"\"\"\n # YOUR CODE HERE\n content = request.get_json()\n if request.is_json and content[\"title\"] and content[\"price\"] and len(content[\"title\"])>=6 and len(content[\"title\"])<=100 and len(content[\"description\"])<=255:\n courses = data.load_data()\n content[\"id\"]=list(courses.keys())[-1]+1\n content[\"date_created\"] = datetime.now().strftime(\"%d-%m-%Y %H:%M:%S\")\n content[\"date_updated\"] = datetime.now().strftime(\"%d-%m-%Y %H:%M:%S\")\n with open(\"json/course.json\") as f:\n temp = json.load(f)\n temp.append(content)\n with open(\"json/course.json\",\"w\") as f:\n json.dump(temp,f,indent=4)\n \n return content\n else:\n return \"Error: Content of the data is not proper\"\n\n\n\n@app.route(\"/course/\", methods=['PUT'])\ndef update_course(id):\n \"\"\"Update a a course.\n :param int id: The record id.\n :return: The updated course object (see the challenge notes for examples)\n :rtype: object\n \"\"\"\n\n \"\"\"\n -------------------------------------------------------------------------\n Challenge notes:\n -------------------------------------------------------------------------\n 1. Bonus points for validating the PUT body fields, including checking\n against the id in the URL\n\n \"\"\"\n content = request.get_json()\n courses = data.load_data()\n if request.is_json and content[\"title\"] and content[\"price\"] and type(content[\"on_discount\"])==bool and len(content[\"title\"])>=6 and len(content[\"title\"])<=100 and len(content[\"description\"])<=255:\n content[\"date_created\"] = courses[id][\"date_created\"]\n content[\"date_updated\"] = datetime.now().strftime(\"%d-%m-%Y %H:%M:%S\")\n content[\"id\"]=id\n with open(\"json/course.json\") as f:\n temp = json.load(f)\n x=0\n for i in temp:\n if i[\"id\"]==id:\n temp[x]=content\n break\n x=x+1\n with open(\"json/course.json\",\"w\") as f:\n json.dump(temp,f,indent=4)\n return content\n else:\n return \"The id does not match the payload\"\n\n \n\n\n\n\n\n@app.route(\"/course/\", methods=['DELETE'])\ndef delete_course(id):\n \"\"\"Delete a course\n :return: A confirmation message (see the challenge notes for examples)\n \"\"\"\n \"\"\"\n -------------------------------------------------------------------------\n Challenge notes:\n -------------------------------------------------------------------------\n None\n \"\"\"\n # YOUR CODE HERE\n allcourses = data.load_data()\n\n try: \n ans = allcourses[id]\n with open(\"json/course.json\") as f:\n temp = json.load(f)\n x=0\n for i in temp:\n if i[\"id\"]==id:\n temp.pop(x)\n break\n x=x+1\n with open(\"json/course.json\",\"w\") as f:\n json.dump(temp,f,indent=4)\n \n return \"The specified course was deleted\"\n except:\n return \"Course {} does not exist\".format(id)\n\n\n","repo_name":"HaripriyaB/Flask-based-API-writing-challenge","sub_path":"routes/course.py","file_name":"course.py","file_ext":"py","file_size_in_byte":6289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9446813186","text":"# -*- coding: utf-8 -*-\nfrom getter import Getter\nfrom tester import Tester\nfrom setting import *\nimport time\nfrom multiprocessing import Process\nfrom api import app\nclass Scheduler():\n def schedule_getter(self):\n getter = Getter()\n while GETTER_ENABLED:\n try:\n getter.run()\n except:\n getter.run()\n time.sleep(GETTER_CYLE)\n\n\n def schedule_tester(self):\n tester = Tester()\n while TESTER_ENABLED:\n try:\n tester.run()\n except:\n tester.run()\n time.sleep(TESTER_CYCLE)\n\n def schedule_api(self):\n print('开启API')\n app.run(API_HOST,API_PORT)\n\n\n def run(self):\n print('代理池开始运行')\n tester_process = Process(target=self.schedule_tester)\n tester_process.start()\n\n getter_process = Process(target=self.schedule_getter)\n getter_process.start()\n\n\n api_process = Process(target=self.schedule_api())\n api_process.start()\n\n\n\n","repo_name":"asd111wang/ProxyPool","sub_path":"scheduler.py","file_name":"scheduler.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1872760332","text":"import numpy as np\n\nimport statsmodels.tsa.statespace.sarimax as sarimax\nimport statsmodels.tsa.stattools as stattools\n\nfrom ..node_transformer import NodeTransformer\nfrom ...params.boolean import Boolean\nfrom ...params.condition.param_equals_value import ParamEqualsValue\nfrom ...params.int import BoundedInt\nfrom ...params.select import Select, SelectOption\nfrom ...params.string import String\nfrom ....utils import timedelta_to_period, lags_range_timedelta_to_period\n\nclass SARIMAX(NodeTransformer):\n\n def __init__(self, id):\n super().__init__(id)\n self.set_input_names([])\n self.add_params()\n\n def add_params(self):\n self.add_required_param(String('p', 'p', 'AR order', '7d'))\n self.add_param(BoundedInt('d', 'd', 'Differencing degree', 0, None, 0))\n self.add_param(String('q', 'q', 'MA order', '0'))\n\n self.add_required_param(Boolean('seasonal', 'Seasonal', 'Seasonal components', False))\n\n seasonal_p = String('P', 'P', 'Seasonal AR order', '0')\n seasonal_p.add_condition(ParamEqualsValue('seasonal', True))\n self.add_param(seasonal_p)\n\n seasonal_d = BoundedInt('D', 'D', 'Seasonal differencing degree', 0, None, 0)\n seasonal_d.add_condition(ParamEqualsValue('seasonal', True))\n self.add_param(seasonal_d)\n seasonal_q = String('Q', 'Q', 'Seasonal MA order', '0')\n seasonal_q.add_condition(ParamEqualsValue('seasonal', True))\n self.add_param(seasonal_q)\n\n seasonal_s = String('s', 's', 'Season length', '0')\n seasonal_s.add_condition(ParamEqualsValue('seasonal', True))\n self.add_param(seasonal_s)\n\n output_options = [\n SelectOption(\"resid\", \"Residual\"),\n SelectOption(\"predicted\", \"Predicted\"),\n ]\n self.add_required_param(Select('output', 'Output', 'Model output', output_options, output_options[0].code))\n\n\n def get_params(self):\n p = self.get_param('p').value\n d = self.get_param('d').value\n q = self.get_param('q').value\n P = self.get_param('P').value\n D = self.get_param('D').value\n Q = self.get_param('Q').value\n s = self.get_param('s').value\n output = self.get_param('output').value\n return (p, d, q, P, D, Q, s, output)\n\n def transform(self, seriess, debug):\n series = seriess[0]\n pdseries = series.pdseries\n exog = np.transpose([s.pdseries.tolist() for s in seriess[1:]]) if len(seriess) > 1 else None\n\n p, d, q, P, D, Q, s, output = self.get_params()\n\n calc_p, calc_q = tuple(map(lambda param: lags_range_timedelta_to_period(param, series.step()), (p, q)))\n calc_P, calc_Q = tuple(map(lambda param: lags_range_timedelta_to_period(param, series.step()), (P, Q)))\n calc_s = timedelta_to_period(s, series.step())\n\n order = (calc_p, d, calc_q)\n seasonal_order = (calc_P, D, calc_Q, calc_s)\n\n model = sarimax.SARIMAX(\n pdseries,\n exog=exog,\n order=order,\n seasonal_order=seasonal_order,\n enforce_stationarity=False,\n enforce_invertibility=False,\n trend=None,\n )\n model_fit = model.fit(disp=False)\n offset_start = max(sum([max(calc_p), d, max(calc_q)]), sum([max(calc_P), D, max(calc_Q)]))\n\n # Debug info\n if debug:\n debug_info = {\n \"summary\": str(model_fit.summary()),\n \"offset_start\": offset_start,\n }\n for n, b in model_fit.params[model.k_trend:model.k_trend + model.k_exog].items():\n debug_info[\"exog_coeff_\"+n] = float(b)\n else:\n debug_info = {}\n # Drop offset_start elements\n \n result = None\n if output == 'predicted':\n result = model_fit.fittedvalues\n elif output == 'resid':\n result = model_fit.resid\n else:\n raise ValueError('Invalid output: ' + output)\n\n return (result[offset_start:], debug_info)\n\n def __str__(self):\n return \"SARIMAX\" + str(self.get_params()) + \"[\" + self.id + \"]\"\n\n def display(self):\n return 'SARIMAX'\n\n def desc(self):\n return 'SARIMAX model, with lags, seasonality and exogenous series. Inputs can be in periods or interval length.'\n","repo_name":"GNico/ts-analysis","sub_path":"backend/ts_project/salib/model/pipeline/nodes/transformers/sarimax.py","file_name":"sarimax.py","file_ext":"py","file_size_in_byte":4317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31069226782","text":"import pygame\n\ndef deadScreen(screen, width, height):\n screen.fill((32, 28, 43))\n pygame.draw.rect(screen, pygame.Color('#ffd700'), [width // 4, height // 4, width // 2, height // 2], width=5)\n pygame.draw.rect(screen, pygame.Color('#ffd700'), [width // 4, height // 4, width // 2, height // 4], width=5)\n pygame.draw.rect(screen, pygame.Color('#ffd700'), [width // 4, height // 2, width // 4, height // 4], width=5)\n screen.blit(pygame.image.load('Data/menu/menu.gif'), (400, 500))\n screen.blit(pygame.image.load('Data/menu/game over.gif'), (510, 300))\n screen.blit(pygame.image.load('Data/menu/exit2.gif'), (700, 500))","repo_name":"akorchuganoff/The-Lone-Tower-Warrior","sub_path":"dead_screen.py","file_name":"dead_screen.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"27278882214","text":"import tldextract\nfrom bs4 import BeautifulSoup\n\nfrom ..base_functions import *\nfrom ..data_classes import *\n\n\nclass ShareXCrawler():\n def __init__(self, *, include_id=False):\n self.include_id = include_id\n\n async def fetch(self, session, url):\n url_extract = tldextract.extract(url)\n base_domain = \"{}.{}\".format(url_extract.domain, url_extract.suffix)\n domain_obj = DomainItem(base_domain, {})\n cookies = []\n\n log(\"Starting scrape of \" + url, Fore.WHITE)\n logging.debug(\"Starting scrape of \" + url)\n\n if \"/album/\" in url or \"/a/\" in url:\n results = await self.parse(url, session)\n elif \"/albums\" in url:\n results = await self.get_albums(url, session)\n elif '/image/' in url or '/img/' in url or '/images/' in url:\n results = await self.get_singular(url, session)\n else:\n results = await self.parse_profile(url, session)\n for result in results:\n domain_obj.add_to_album(result['title'], result['url'], result['referral'])\n\n log(\"Finished scrape of \" + url, Fore.WHITE)\n logging.debug(\"Finished scrape of \" + url)\n\n return domain_obj, cookies\n\n async def get_albums(self, url, session):\n results = []\n try:\n async with session.get(url) as response:\n text = await response.text()\n soup = BeautifulSoup(text, 'html.parser')\n albums = soup.select(\"a[class='image-container --media']\")\n for album in albums:\n album_url = album.get('href')\n results.extend(result for result in await self.parse(album_url, session))\n except Exception as e:\n logger.debug(\"Error encountered while handling %s\", url, exc_info=True)\n logger.debug(e)\n return results\n\n async def get_singular(self, url, session):\n results = []\n try:\n async with session.get(url) as response:\n text = await response.text()\n soup = BeautifulSoup(text, 'html.parser')\n link = soup.select_one(\"input[id=embed-code-2]\").get('value')\n link = link.replace('.md.', '.').replace('.th.', '.')\n title = \"ShareX Loose Files\"\n results.append({'url': link, 'title': title, 'referral': url, 'cookies': ''})\n except Exception as e:\n logger.debug(\"Error encountered while handling %s\", url, exc_info=True)\n logger.debug(e)\n return results\n\n async def get_sub_album_links(self, url, session, og_title):\n results = []\n try:\n async with session.get(url) as response:\n text = await response.text()\n soup = BeautifulSoup(text, 'html.parser')\n albums = soup.select(\"div[class=pad-content-listing] div\")\n for album in albums:\n album_url = album.get('data-url-short')\n if album_url is not None:\n results.extend(result for result in await self.parse(album_url, session, og_title=og_title))\n except Exception as e:\n logger.debug(\"Error encountered while handling %s\", url, exc_info=True)\n logger.debug(e)\n return results\n\n async def parse_profile(self, url, session):\n results = []\n try:\n async with session.get(url) as response:\n text = await response.text()\n soup = BeautifulSoup(text, 'html.parser')\n title = soup.select_one(\"div[class=header] h1 strong\").get_text()\n if title is None:\n title = response.url.split('/')\n title = [s for s in title if \".\" in s][-1]\n elif self.include_id:\n titlep2 = response.url.split('/')\n titlep2 = [s for s in titlep2 if \".\" in s][-1]\n title = title + \" - \" + titlep2\n title = make_title_safe(title.replace(r\"\\n\", \"\").strip())\n\n list_recent = soup.select_one(\"a[id=list-most-recent-link]\").get('href')\n results.extend(result for result in await self.get_list_links(list_recent, session, title))\n except Exception as e:\n logger.debug(\"Error encountered while handling %s\", url, exc_info=True)\n logger.debug(e)\n return results\n\n async def get_list_links(self, url, session, title):\n results = []\n try:\n async with session.get(url) as response:\n text = await response.text()\n soup = BeautifulSoup(text, 'html.parser')\n if 'jpg.church' in url:\n links = soup.select(\"a[href*=img] img\")\n else:\n links = soup.select(\"a[href*=image] img\")\n for link in links:\n link = link.get('src')\n link = link.replace('.md.', '.').replace('.th.', '.')\n results.append({'url': link, 'title': title, 'referral': url, 'cookies': ''})\n next_page = soup.select_one('li.pagination-next a')\n if next_page is not None:\n next_page = next_page.get('href')\n if next_page is not None:\n results.extend(result for result in await self.get_list_links(next_page, session, title))\n except Exception as e:\n logger.debug(\"Error encountered while handling %s\", url, exc_info=True)\n logger.debug(e)\n return results\n\n async def parse(self, url, session, og_title=None):\n results = []\n try:\n async with session.get(url) as response:\n text = await response.text()\n soup = BeautifulSoup(text, 'html.parser')\n\n title = soup.select_one(\"a[data-text=album-name]\").get_text()\n if title is None:\n title = response.url.split('/')[-1]\n elif self.include_id:\n titlep2 = response.url.split('/')\n titlep2 = [s for s in titlep2 if \".\" in s][-1]\n title = title + \" - \" + titlep2\n title = make_title_safe(title.replace(r\"\\n\", \"\").strip())\n\n if og_title is not None:\n title = og_title + \"/\" + title\n\n sub_albums = soup.select_one(\"a[id=tab-sub-link]\").get(\"href\")\n results.extend(result for result in await self.get_sub_album_links(sub_albums, session, title))\n\n list_recent = soup.select_one(\"a[id=list-most-recent-link]\").get(\"href\")\n results.extend(result for result in await self.get_list_links(list_recent, session, title))\n\n except Exception as e:\n logger.debug(\"Error encountered while handling %s\", url, exc_info=True)\n logger.debug(e)\n return results","repo_name":"Whitemindy1996/CyberDropDownloader","sub_path":"cyberdrop_dl/utils/crawlers/ShareX_Spider.py","file_name":"ShareX_Spider.py","file_ext":"py","file_size_in_byte":6959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"37622540158","text":"import torch\nimport torch.nn as nn\nimport torch.utils.checkpoint as cp\nfrom torch.nn.modules.batchnorm import _BatchNorm\n\nfrom ...registry import GENERATORS, BLOCKS\nfrom ...utils import pair\nfrom ..base_module import BaseModule, Sequential\nfrom ..initializers import kaiming_init, constant_init\nfrom ..bricks import create_conv_layer, create_deconv_layer, infer_norm_name, create_norm_layer, compute_output_padding, DeconvBlock\n\n\n@BLOCKS.register_class('inv_resnet_basicblock')\nclass InvResNetBasicBlock(BaseModule):\n def __init__(self,\n in_channels,\n out_channels,\n expansion=1, # determines mid_channels\n stride=1,\n dilation=1,\n output_size=None, # determins output_padding\n upsample=None,\n fully_deconv=False,\n with_cp=False,\n conv_cfg=dict(type='conv'),\n deconv_cfg=dict(type='deconv'),\n norm_cfg=dict(type='in'),\n init_cfg=None):\n super().__init__(init_cfg)\n self.in_channels = in_channels\n assert expansion == 1 and out_channels % expansion == 0\n self.out_channels = out_channels\n self.expansion = expansion\n self.mid_channels = out_channels // expansion\n self.stride = stride\n self.dilation = dilation\n self.output_size = output_size\n self.fully_deconv = fully_deconv\n self.with_cp = with_cp\n self.conv_cfg = conv_cfg\n self.deconv_cfg = deconv_cfg\n self.norm_cfg = norm_cfg\n\n if fully_deconv or stride > 1:\n output_padding = compute_output_padding(output_size, 3, stride, dilation, dilation=dilation)\n self.conv1 = create_deconv_layer(deconv_cfg, in_channels, self.mid_channels, output_padding=output_padding,\n kernel_size=3, stride=stride, padding=dilation, dilation=dilation, bias=False)\n else:\n self.conv1 = create_conv_layer(conv_cfg, in_channels, self.mid_channels,\n kernel_size=3, stride=stride, padding=dilation, dilation=dilation, bias=False)\n\n self.norm1_name = infer_norm_name(norm_cfg) + '1'\n norm1 = create_norm_layer(norm_cfg, self.mid_channels)\n self.add_module(self.norm1_name, norm1)\n\n if fully_deconv:\n self.conv2 = create_deconv_layer(deconv_cfg, self.mid_channels, out_channels, kernel_size=3, padding=1, bias=False)\n else:\n self.conv2 = create_conv_layer(conv_cfg, self.mid_channels, out_channels, kernel_size=3, padding=1, bias=False)\n\n self.norm2_name = infer_norm_name(norm_cfg) + '2'\n norm2 = create_norm_layer(norm_cfg, out_channels)\n self.add_module(self.norm2_name, norm2)\n\n self.relu = nn.ReLU(inplace=True)\n self.upsample = upsample\n\n @property\n def norm1(self):\n return getattr(self, self.norm1_name)\n\n @property\n def norm2(self):\n return getattr(self, self.norm2_name)\n\n def forward(self, x):\n def _inner_forward(x):\n identity = x\n\n out = self.conv1(x)\n out = self.norm1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.norm2(out)\n\n if self.upsample is not None:\n identity = self.upsample(x)\n\n out += identity\n\n return out\n\n if self.with_cp and x.requires_grad:\n out = cp.checkpoint(_inner_forward, x)\n else:\n out = _inner_forward(x)\n\n out = self.relu(out)\n\n return out\n\n\n@BLOCKS.register_class('inv_resnet_bottleneck')\nclass InvResNetBottleneck(BaseModule):\n def __init__(self,\n in_channels,\n out_channels,\n expansion=4, # determines mid_channels\n stride=1,\n dilation=1,\n output_size=None, # determins output_padding\n upsample=None,\n fully_deconv=False,\n with_cp=False,\n conv_cfg=dict(type='conv'),\n deconv_cfg=dict(type='deconv'),\n norm_cfg=dict(type='in'),\n init_cfg=None):\n super().__init__(init_cfg)\n self.in_channels = in_channels\n assert out_channels % expansion == 0\n self.out_channels = out_channels\n self.expansion = expansion\n self.mid_channels = out_channels // expansion\n self.stride = stride\n self.dilation = dilation\n self.output_size = output_size\n self.fully_deconv = fully_deconv\n self.with_cp = with_cp\n self.conv_cfg = conv_cfg\n self.deconv_cfg = deconv_cfg\n self.norm_cfg = norm_cfg\n\n if fully_deconv:\n self.conv1 = create_deconv_layer(deconv_cfg, in_channels, self.mid_channels, kernel_size=1, stride=1, bias=False)\n else:\n self.conv1 = create_conv_layer(conv_cfg, in_channels, self.mid_channels, kernel_size=1, stride=1, bias=False)\n\n self.norm1_name = infer_norm_name(norm_cfg) + '1'\n norm1 = create_norm_layer(norm_cfg, self.mid_channels)\n self.add_module(self.norm1_name, norm1)\n\n if fully_deconv or stride > 1:\n output_padding = compute_output_padding(output_size, 3, stride, dilation, dilation=dilation)\n self.conv2 = create_deconv_layer(deconv_cfg, self.mid_channels, self.mid_channels, output_padding=output_padding,\n kernel_size=3, stride=stride, padding=dilation, dilation=dilation, bias=False)\n else:\n self.conv2 = create_conv_layer(conv_cfg, self.mid_channels, self.mid_channels,\n kernel_size=3, stride=stride, padding=dilation, dilation=dilation, bias=False)\n\n self.norm2_name = infer_norm_name(norm_cfg) + '2'\n norm2 = create_norm_layer(norm_cfg, self.mid_channels)\n self.add_module(self.norm2_name, norm2)\n\n if fully_deconv:\n self.conv3 = create_deconv_layer(deconv_cfg, self.mid_channels, out_channels, kernel_size=1, bias=False)\n else:\n self.conv3 = create_conv_layer(conv_cfg, self.mid_channels, out_channels, kernel_size=1, bias=False)\n\n self.norm3_name = infer_norm_name(norm_cfg) + '3'\n norm3 = create_norm_layer(norm_cfg, out_channels)\n self.add_module(self.norm3_name, norm3)\n\n self.relu = nn.ReLU(inplace=True)\n self.upsample = upsample\n\n @property\n def norm1(self):\n return getattr(self, self.norm1_name)\n\n @property\n def norm2(self):\n return getattr(self, self.norm2_name)\n\n @property\n def norm3(self):\n return getattr(self, self.norm3_name)\n\n def forward(self, x):\n def _inner_forward(x):\n identity = x\n\n out = self.conv1(x)\n out = self.norm1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.norm2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.norm3(out)\n\n if self.upsample is not None:\n identity = self.upsample(x)\n\n out += identity\n\n return out\n\n if self.with_cp and x.requires_grad:\n out = cp.checkpoint(_inner_forward, x)\n else:\n out = _inner_forward(x)\n\n out = self.relu(out)\n\n return out\n\n\ndef get_expansion(block, expansion=None):\n if isinstance(expansion, int):\n assert expansion > 0\n elif expansion is None:\n if hasattr(block, 'expansion'):\n expansion = block.expansion\n elif issubclass(block, InvResNetBasicBlock):\n expansion = 1\n elif issubclass(block, InvResNetBottleneck):\n expansion = 4\n else:\n raise TypeError(f\"expansion is not specified for {block.__name__}\")\n else:\n raise TypeError('expansion must be an integer or None')\n return expansion\n\n\n@BLOCKS.register_class('inv_resnet_layer')\nclass InvResNetLayer(Sequential):\n def __init__(self,\n block,\n n_blocks,\n in_channels,\n out_channles,\n expansion=None,\n stride=1,\n dilation=1,\n output_size=None, # determins output_padding\n direct_upsample=False,\n upsample_first=True,\n multigrid_dilations=None,\n contract_first_dilation=False,\n fully_deconv=False,\n conv_cfg=dict(type='conv'),\n deconv_cfg=dict(type='deconv'),\n norm_cfg=dict(type='in'),\n **kwargs):\n self.block = block\n self.n_blocks = n_blocks\n self.in_channels = in_channels\n self.out_channels = out_channles\n self.expansion = get_expansion(block, expansion)\n self.stride = stride\n self.output_size = output_size\n self.direct_upsample = direct_upsample\n self.upsample_first = upsample_first\n self.multigrid_dilations = multigrid_dilations\n self.contract_first_dilation = contract_first_dilation\n self.conv_cfg = conv_cfg\n self.deconv_cfg = deconv_cfg\n self.norm_cfg = norm_cfg\n\n upsample = None\n if stride != 1 or in_channels != out_channles:\n upsample = []\n conv_stride = stride\n if direct_upsample and stride != 1:\n conv_stride = 1\n upsample.append(nn.Upsample(scale_factor=stride, mode='nearest'))\n if fully_deconv or conv_stride > 1:\n output_padding = compute_output_padding(output_size, 1, conv_stride, 0)\n upsample.append(create_deconv_layer(deconv_cfg, in_channels, out_channles, output_padding=output_padding,\n kernel_size=1, stride=conv_stride, padding=0, bias=False))\n else:\n upsample.append(create_conv_layer(conv_cfg, in_channels, out_channles, kernel_size=1, stride=conv_stride, bias=False))\n upsample.append(create_norm_layer(norm_cfg, out_channles))\n upsample = Sequential(*upsample)\n\n grid_dilations = [dilation] * n_blocks\n if multigrid_dilations is None:\n if dilation > 1 and contract_first_dilation:\n grid_dilations[0] = dilation // 2\n else:\n grid_dilations = multigrid_dilations\n\n layers = []\n if upsample_first:\n layers.append(block(in_channels, out_channles, expansion=self.expansion,\n stride=stride, dilation=grid_dilations[0], output_size=output_size, upsample=upsample, fully_deconv=fully_deconv,\n conv_cfg=conv_cfg, deconv_cfg=deconv_cfg, norm_cfg=norm_cfg, **kwargs))\n for i in range(1, n_blocks):\n layers.append(block(out_channles, out_channles, expansion=self.expansion,\n stride=1, dilation=grid_dilations[i], fully_deconv=fully_deconv,\n conv_cfg=conv_cfg, deconv_cfg=deconv_cfg, norm_cfg=norm_cfg, **kwargs))\n else:\n for i in range(0, n_blocks - 1):\n layers.append(block(in_channels, in_channels, expansion=self.expansion,\n stride=1, dilation=grid_dilations[i], fully_deconv=fully_deconv,\n conv_cfg=conv_cfg, deconv_cfg=deconv_cfg, norm_cfg=norm_cfg, **kwargs))\n layers.append(block(in_channels, out_channles, expansion=self.expansion,\n stride=stride, dilation=grid_dilations[-1], output_size=output_size, upsample=upsample, fully_deconv=fully_deconv,\n conv_cfg=conv_cfg, deconv_cfg=deconv_cfg, norm_cfg=norm_cfg, **kwargs))\n\n super().__init__(*layers, init_cfg=kwargs.get('init_cfg'))\n\n\ndef get_output_size(image_size, scale_factor=1):\n image_size = pair(image_size)\n scale_factor = pair(scale_factor)\n return (image_size[0] // scale_factor[0], image_size[1] // scale_factor[1])\n\n\n@GENERATORS.register_class('inv_resnet')\nclass InvResNet(BaseModule):\n _allowed_archs = {\n 18: (InvResNetBasicBlock, (2, 2, 2, 2)),\n 34: (InvResNetBasicBlock, (3, 6, 4, 3)),\n 50: (InvResNetBottleneck, (3, 6, 4, 3)),\n 101: (InvResNetBottleneck, (3, 23, 4, 3)),\n 152: (InvResNetBottleneck, (3, 36, 8, 3))\n }\n\n def __init__(self,\n depth,\n in_channels,\n output_size, # fixed image size (h, w)\n out_channels=3,\n stem_channels=64,\n base_channels=64,\n expansion=None,\n n_stages=4,\n strides=(2, 2, 2, 1),\n dilations=(1, 1, 1, 1),\n direct_upsample=False,\n frozen_stages=-1,\n with_cp=False,\n norm_eval=False,\n zero_init_residual=True,\n multigrid_dilations=None,\n contract_first_dilation=False,\n fully_deconv=False,\n conv_cfg=dict(type='conv'),\n deconv_cfg=dict(type='deconv'),\n norm_cfg=dict(type='in'),\n out_acti_cfg=dict(type='tanh'),\n out_autoscale=False,\n out_autobias=False,\n init_cfg=None):\n super().__init__(init_cfg)\n assert depth in self._allowed_archs, f\"Invalid depth {depth} for resnet\"\n self.depth = depth\n self.in_channels = in_channels\n self.output_size = output_size\n self.out_channels = out_channels\n self.stem_channels = stem_channels\n self.base_channels = base_channels\n self.expansion = expansion\n assert 1 <= n_stages <= 4\n self.n_stages = n_stages\n assert len(strides) == len(dilations) == n_stages\n self.strides = strides\n self.dilations = dilations\n self.direct_upsample = direct_upsample\n self.frozen_stages = frozen_stages\n self.with_cp = with_cp\n self.norm_eval = norm_eval\n self.zero_init_residual = zero_init_residual\n self.fully_deconv = fully_deconv\n self.conv_cfg = conv_cfg\n self.deconv_cfg = deconv_cfg\n self.norm_cfg = norm_cfg\n self.out_acti_cfg = out_acti_cfg\n self.out_autoscale = out_autoscale\n self.out_autobias = out_autobias\n self.block, stage_blocks = self._allowed_archs[depth]\n self.stage_blocks = stage_blocks[:n_stages]\n self.expansion = get_expansion(self.block, expansion)\n\n # contributes prod(strides) stride\n self.layer_names = []\n res_in_channels = in_channels\n res_out_channels = base_channels * self.expansion * 2**(n_stages - 2)\n for i, n_blocks in enumerate(self.stage_blocks):\n stride = strides[i]\n dilation = dilations[i]\n # one stage one resnet_layer\n res_layer = InvResNetLayer(self.block, n_blocks, res_in_channels, res_out_channels, output_size=get_output_size(output_size, 2**(n_stages - i - 1)),\n expansion=self.expansion, stride=stride, dilation=dilation, direct_upsample=direct_upsample,\n multigrid_dilations=multigrid_dilations, contract_first_dilation=contract_first_dilation, fully_deconv=fully_deconv,\n with_cp=with_cp, conv_cfg=conv_cfg, deconv_cfg=deconv_cfg, norm_cfg=norm_cfg)\n res_in_channels = res_out_channels\n res_out_channels = res_out_channels // 2\n layer_name = 'layer' + str(i + 1)\n self.add_module(layer_name, res_layer)\n self.layer_names.append(layer_name)\n res_out_channels = res_in_channels\n\n self.stem = Sequential(\n DeconvBlock(res_out_channels, stem_channels,\n fully_deconv=fully_deconv, kernel_size=3, stride=1, padding=1,\n conv_cfg=conv_cfg, deconv_cfg=deconv_cfg, norm_cfg=norm_cfg),\n DeconvBlock(stem_channels, stem_channels,\n fully_deconv=fully_deconv, kernel_size=3, stride=1, padding=1,\n conv_cfg=conv_cfg, deconv_cfg=deconv_cfg, norm_cfg=norm_cfg),\n DeconvBlock(stem_channels, stem_channels, output_size=output_size,\n fully_deconv=fully_deconv, kernel_size=3, stride=2, padding=1,\n conv_cfg=conv_cfg, deconv_cfg=deconv_cfg, norm_cfg=norm_cfg),\n DeconvBlock(stem_channels, out_channels, output_size=output_size,\n fully_deconv=fully_deconv, kernel_size=1,\n conv_cfg=conv_cfg, deconv_cfg=deconv_cfg, norm_cfg=None, acti_cfg=out_acti_cfg))\n\n self.out_scale = nn.parameter.Parameter(torch.zeros(3, 1, 1)) if out_autoscale else None\n self.out_bias = nn.parameter.Parameter(torch.zeros(3, 1, 1)) if out_autobias else None\n\n @property\n def norm1(self):\n return getattr(self, self.norm1_name)\n\n def freeze_stages(self, frozen_stages=-1):\n frozen_stages = self.frozen_stages if frozen_stages == -1 else frozen_stages\n if frozen_stages >= 0:\n self.stem.eval()\n for param in self.stem.parameters():\n param.requires_grad = False\n\n for i in range(1, frozen_stages + 1):\n m = getattr(self, 'layer' + str(i))\n m.eval()\n for param in m.parameters():\n param.requires_grad = False\n\n def init_weights(self):\n super().init_weights()\n if isinstance(self.init_cfg, dict) and self.init_cfg['type'] == 'pretrained':\n return\n\n for m in self.modules():\n if isinstance(m, (nn.Conv2d, nn.ConvTranspose2d)):\n oc, ic = m.weight.shape[:2]\n kaiming_init(m, mode='fan_out' if oc >= ic else 'fan_in')\n elif isinstance(m, (_BatchNorm, nn.GroupNorm)):\n constant_init(m, 1)\n\n if self.zero_init_residual:\n for m in self.modules():\n if isinstance(m, InvResNetBasicBlock):\n constant_init(m.norm2, 0)\n elif isinstance(m, InvResNetBottleneck):\n constant_init(m.norm3, 0)\n\n if self.out_acti_cfg is None:\n nonlinearity = 'linear'\n elif self.out_acti_cfg['type'] in ('sigmoid', 'sigmoid_ms'):\n nonlinearity = 'sigmoid'\n else:\n nonlinearity = self.out_acti_cfg['type']\n kaiming_init(self.stem[-1].conv, mode='fan_in', nonlinearity=nonlinearity)\n\n def forward(self, x):\n for i, layer_name in enumerate(self.layer_names):\n res_layer = getattr(self, layer_name)\n x = res_layer(x)\n\n x = self.stem(x)\n\n if self.out_scale is not None:\n x = x * torch.exp(self.out_scale)\n\n if self.out_bias is not None:\n x = x + self.out_bias\n\n return x\n\n def train(self, mode=True):\n super().train(mode)\n self.freeze_stages()\n if mode and self.norm_eval:\n for m in self.modules():\n if isinstance(m, _BatchNorm):\n m.eval()\n\n\n@GENERATORS.register_class('inv_resnets16')\nclass InvResNetS16(InvResNet):\n \"\"\" InvResNetS16 changes stage 1's stride from 2 to 1 to make the global stride 16.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n kwargs.update({'strides': (1, 2, 2, 1)})\n super().__init__(*args, **kwargs)\n","repo_name":"netpaladinx/myzonelab","sub_path":"myzonecv/core/model/generators/inv_resnet.py","file_name":"inv_resnet.py","file_ext":"py","file_size_in_byte":19785,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9974034209","text":"#integrating function x**2 from 0 to 1\nimport matplotlib.pyplot as plt\nimport numpy as np\nx=np.linspace(0,2,100)\ndef f(x):\n return x**2\ndef simpson(x0,xn,n):\n h = (xn - x0) / n \n s = f(x0) + f(xn)\n for i in range(1,n):\n k = x0 + i*h \n if i%2 == 0:\n s = s + 2 * f(k)\n else:\n s = s + 4 * f(k)\n s = s * h/3\n return s\nx0 = 0\nxn = 1\nn = 10\nxcord=np.linspace(x0,xn,100)\nresult = simpson(x0,xn,n)\nprint('result =', (result) )\n\n#plot to visualise the area under function\nplt.ylim([0.0,1.5])\nplt.plot(x,f(x),linewidth=2.0,color='red',label=r'$f(x)$')\nplt.fill_between(xcord,f(xcord),color='blue')\nplt.legend()\n","repo_name":"chloegmx/Numerical-Methods","sub_path":"Integration/simpsons_1_third.py","file_name":"simpsons_1_third.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20858581205","text":"# -*- coding: utf-8 -*-\n# © 2016 Camptocamp SA\n# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html)\n\nfrom datetime import datetime\nfrom distutils.version import StrictVersion\n\nfrom .database import IrModuleModule\nfrom .exception import MigrationError\nfrom .output import print_decorated, safe_print\n\nLOG_DECORATION = u'|> '\n\n\nclass Runner(object):\n\n def __init__(self, config, migration, cursor, table):\n self.config = config\n self.migration = migration\n self.cursor = cursor\n self.table = table\n # we keep the addons upgrading during a run in this set,\n # this is only useful when using 'allow_serie',\n # if an addon has just been installed or updated,\n # we don't want to do it again for another version\n self.upgraded_addons = set()\n\n def log(self, message):\n print_decorated(u'migration: {}'.format(message))\n\n def perform(self):\n self.table.create_if_not_exists()\n self.table.lock() # locked until end of transaction\n\n db_versions = self.table.versions()\n\n if not self.config.force_version:\n unfinished = [db_version for db_version\n in db_versions\n if not db_version.date_done]\n if unfinished:\n raise MigrationError(\n u'Upgrade of version {} has been attempted and failed. '\n u'You may want to restore the backup or to run again the '\n u'migration with the MARABUNTA_FORCE_VERSION '\n u'environment variable '\n u'or to fix it manually (in that case, you will have to '\n u'update the \\'marabunta_version\\' table yourself.'\n .format(u','.join(v.number for v in unfinished))\n )\n\n unprocessed = [version for version in self.migration.versions\n if not version.skip(db_versions)]\n\n if not self.config.allow_serie:\n if len(unprocessed) > 1:\n raise MigrationError(\n u'Only one version can be upgraded at a time.\\n'\n u'The following versions need to be applied: {}.\\n'.format(\n [v.number for v in unprocessed]\n )\n )\n\n if not self.config.force_version and db_versions and unprocessed:\n installed = max(StrictVersion(v.number) for v in db_versions)\n next_unprocess = min(StrictVersion(v.number) for v in unprocessed)\n if installed > next_unprocess:\n raise MigrationError(\n u'The version you are trying to install ({}) is below '\n u'the current database version.'.format(\n next_unprocess, installed\n )\n )\n\n for version in self.migration.versions:\n # when we force-execute one version, we skip all the others\n if self.config.force_version:\n if self.config.force_version != version.number:\n continue\n else:\n self.log(\n u'force-execute version {}'.format(version.number)\n )\n\n self.log(u'processing version {}'.format(version.number))\n VersionRunner(self, version).perform()\n\n\nclass VersionRunner(object):\n\n def __init__(self, runner, version):\n self.runner = runner\n self.table = runner.table\n self.migration = runner.migration\n self.config = runner.config\n self.cursor = runner.cursor\n self.version = version\n self.logs = []\n\n def log(self, message, decorated=True, stdout=True):\n self.logs.append(message)\n if not stdout:\n return\n if decorated:\n app_message = u'version {}: {}'.format(\n self.version.number,\n message,\n )\n print_decorated(app_message)\n else:\n safe_print(message)\n\n def start(self):\n self.log(u'start')\n self.table.start_version(self.version.number, datetime.now())\n\n def finish(self):\n self.log(u'done')\n module_table = IrModuleModule(self.cursor)\n addons_state = module_table.read_state()\n self.table.finish_version(self.version.number, datetime.now(),\n u'\\n'.join(self.logs),\n [state._asdict() for state in addons_state])\n\n def perform(self):\n db_versions = self.table.versions()\n\n version = self.version\n if (version.is_processed(db_versions) and\n not self.config.force_version == self.version.number):\n self.log(\n u'version {} is already installed'.format(version.number)\n )\n return\n\n self.start()\n\n if version.is_noop():\n self.log(u'version {} is a noop'.format(version.number))\n\n else:\n self.log(u'execute base pre-operations')\n for operation in version.pre_operations():\n operation.execute(self.log)\n if self.config.mode:\n self.log(u'execute %s pre-operations' % self.config.mode)\n for operation in version.pre_operations(mode=self.config.mode):\n operation.execute(self.log)\n\n self.perform_addons()\n\n self.log(u'execute base post-operations')\n for operation in version.post_operations():\n operation.execute(self.log)\n if self.config.mode:\n self.log(u'execute %s post-operations' % self.config.mode)\n for operation in version.post_operations(self.config.mode):\n operation.execute(self.log)\n\n self.finish()\n\n def perform_addons(self):\n version = self.version\n\n module_table = IrModuleModule(self.cursor)\n addons_state = module_table.read_state()\n\n upgrade_operation = version.upgrade_addons_operation(\n addons_state,\n mode=self.config.mode\n )\n # exclude the addons already installed or updated during this run\n # when 'allow_serie' is active\n exclude = self.runner.upgraded_addons\n self.log(u'installation / upgrade of addons')\n operation = upgrade_operation.operation(exclude_addons=exclude)\n if operation:\n operation.execute(self.log)\n self.runner.upgraded_addons |= (upgrade_operation.to_install |\n upgrade_operation.to_upgrade)\n","repo_name":"leemannd/marabunta","sub_path":"marabunta/runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":6648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"37517199899","text":"import numpy as np\nimport arepo\nimport sys\nfrom tqdm import tqdm\nimport h5py as h5\nimport glob\nimport os\nimport re\nimport time\nfrom numba import njit\nimport shutil\nfrom distutils.dir_util import copy_tree\n\nimport cProfile\n\nfrom joblib import Parallel, delayed\n\ndef read_snap(path, idx, parttype=[0], fields=['Coordinates', 'Masses', 'Velocities', 'ParticleIDs']):\n \n fname = path + '/output'\n \n return arepo.Snapshot(fname, idx, parttype=parttype, fields=fields, combineFiles=True)\n\n@njit\ndef sort_by_id(chunk_ids, tot_ids, pos, vel, acc):\n # This goes through the chunk ids and matches up with total ids\n # but this assumes chunk ids and total ids are already sorted, which greatly\n # speeds things up.\n\n # also properly handles missing ids (e.g. in the case of stars)\n\n Nchunk = len(chunk_ids)\n pos_chunk = np.zeros((Nchunk, 3))\n vel_chunk = np.zeros((Nchunk, 3))\n acc_chunk = np.zeros((Nchunk, 3))\n \n itot = 0\n \n for ichunk in range(Nchunk):\n chk_id = chunk_ids[ichunk]\n \n while chk_id > tot_ids[itot]:\n itot += 1\n \n if chk_id == tot_ids[itot]:\n for j in range(3):\n pos_chunk[ichunk][j] = pos[itot][j]\n vel_chunk[ichunk][j] = vel[itot][j]\n acc_chunk[ichunk][j] = acc[itot][j]\n \n else:\n for j in range(3):\n pos_chunk[ichunk][j] = np.nan\n vel_chunk[ichunk][j] = np.nan\n acc_chunk[ichunk][j] = np.nan\n \n return pos_chunk, vel_chunk, acc_chunk\n\ndef _run_thread(path, name_lvl, snap_idx, id_chunks_halo, id_chunks_disk, id_chunks_bulge, id_chunks_star, data_dir, tmp_dir):\n\n print('starting thread: ', snap_idx)\n\n h5out_list = []\n\n # Create a temporary directory which will store each chunk of ids as a separate file.\n prefix = tmp_dir + str(np.random.rand()) + '/'\n if not os.path.isdir(prefix):\n os.mkdir(prefix)\n \n if id_chunks_star is None:\n has_stars = False\n id_chunks_star = [None for i in range(len(id_chunks_disk))]\n else:\n has_stars = True\n\n # Loop through each id chunk and create the file with temporary output.\n for i,(id_chunk_halo_list, id_chunk_disk_list, id_chunk_bulge_list, id_chunk_star_list) in enumerate(zip(id_chunks_halo, id_chunks_disk, id_chunks_bulge, id_chunks_star)):\n Nids_halo = len(id_chunk_halo_list)\n Nids_disk = len(id_chunk_disk_list)\n Nids_bulge = len(id_chunk_bulge_list)\n if has_stars:\n Nids_star = len(id_chunk_star_list)\n\n fout = prefix + '/tmp' + str(i) + '.hdf5'\n h5out = h5.File(fout, mode='w')\n\n pos_halo = np.zeros((Nids_halo, 3))\n pos_disk = np.zeros((Nids_disk, 3))\n pos_bulge = np.zeros((Nids_bulge, 3))\n if has_stars:\n pos_star = np.zeros((Nids_star, 3))\n \n h5out.create_dataset(\"PartType1/ParticleIDs\", data=id_chunk_halo_list)\n h5out.create_dataset(\"PartType1/Coordinates\", data=pos_halo)\n h5out.create_dataset(\"PartType1/Velocities\", data=pos_halo)\n h5out.create_dataset(\"PartType1/Acceleration\", data=pos_halo)\n \n h5out.create_dataset(\"PartType2/ParticleIDs\", data=id_chunk_disk_list)\n h5out.create_dataset(\"PartType2/Coordinates\", data=pos_disk)\n h5out.create_dataset(\"PartType2/Velocities\", data=pos_disk)\n h5out.create_dataset(\"PartType2/Acceleration\", data=pos_disk)\n\n h5out.create_dataset(\"PartType3/ParticleIDs\", data=id_chunk_bulge_list)\n h5out.create_dataset(\"PartType3/Coordinates\", data=pos_bulge)\n h5out.create_dataset(\"PartType3/Velocities\", data=pos_bulge)\n h5out.create_dataset(\"PartType3/Acceleration\", data=pos_bulge)\n\n if has_stars:\n h5out.create_dataset(\"PartType4/ParticleIDs\", data=id_chunk_star_list)\n h5out.create_dataset(\"PartType4/Coordinates\", data=pos_star)\n h5out.create_dataset(\"PartType4/Velocities\", data=pos_star)\n h5out.create_dataset(\"PartType4/Acceleration\", data=pos_star)\n\n h5out_list.append(h5out)\n \n print('ended first loop on thread', snap_idx)\n\n # Now loop through each index, read the snapshot, then loop through each\n # id chunk and write to the relevant file.\n sn = read_snap(path, snap_idx, parttype=[1, 2, 3, 4], fields=['Coordinates', 'Masses', 'Velocities', 'ParticleIDs', 'Acceleration'])\n\n key_halo = np.argsort(sn.part1.id)\n pos_halo = sn.part1.pos.value[key_halo]\n vel_halo = sn.part1.vel.value[key_halo]\n acc_halo = sn.part1.acce[key_halo]\n halo_ids_sorted = sn.part1.id[key_halo]\n \n key_disk = np.argsort(sn.part2.id)\n pos_disk = sn.part2.pos.value[key_disk]\n vel_disk = sn.part2.vel.value[key_disk]\n acc_disk = sn.part2.acce[key_disk]\n disk_ids_sorted = sn.part2.id[key_disk]\n\n key_bulge = np.argsort(sn.part3.id)\n pos_bulge = sn.part3.pos.value[key_bulge]\n vel_bulge = sn.part3.vel.value[key_bulge]\n acc_bulge = sn.part3.acce[key_bulge]\n bulge_ids_sorted = sn.part3.id[key_bulge]\n\n if has_stars and sn.NumPart_Total[4] > 0:\n key_star = np.argsort(sn.part4.id)\n pos_star = sn.part3.pos.value[key_star]\n vel_star = sn.part3.vel.value[key_star]\n acc_star = sn.part3.acce[key_star]\n \n star_ids_sorted = sn.part4.id[key_star]\n\n for j,(id_chunk_halo_list, id_chunk_disk_list, id_chunk_bulge_list, id_chunk_star_list) in enumerate(zip(id_chunks_halo, id_chunks_disk, id_chunks_bulge, id_chunks_star)):\n h5out_list[j].attrs.create('Time', sn.Time.value)\n \n pos_chunk_halo, vel_chunk_halo, acc_chunk_halo = sort_by_id(id_chunk_halo_list, halo_ids_sorted, pos_halo, vel_halo, acc_halo)\n h5out_list[j]['PartType1/Coordinates'][:] = pos_chunk_halo\n h5out_list[j]['PartType1/Velocities'][:] = vel_chunk_halo\n h5out_list[j]['PartType1/Acceleration'][:] = acc_chunk_halo\n \n pos_chunk_disk, vel_chunk_disk, acc_chunk_disk = sort_by_id(id_chunk_disk_list, disk_ids_sorted, pos_disk, vel_disk, acc_disk)\n h5out_list[j]['PartType2/Coordinates'][:] = pos_chunk_disk\n h5out_list[j]['PartType2/Velocities'][:] = vel_chunk_disk\n h5out_list[j]['PartType2/Acceleration'][:] = acc_chunk_disk\n \n pos_chunk_bulge, vel_chunk_bulge, acc_chunk_bulge = sort_by_id(id_chunk_bulge_list, bulge_ids_sorted, pos_bulge, vel_bulge, acc_bulge)\n h5out_list[j]['PartType3/Coordinates'][:] = pos_chunk_bulge\n h5out_list[j]['PartType3/Velocities'][:] = vel_chunk_bulge\n h5out_list[j]['PartType3/Acceleration'][:] = acc_chunk_bulge\n\n if has_stars:\n if sn.NumPart_Total[4] > 0:\n pos_chunk_star, vel_chunk_star, acc_chunk_star = sort_by_id(id_chunk_star_list, star_ids_sorted, pos_star, vel_star, acc_star)\n else:\n pos_chunk_star = vel_chunk_star = acc_chunk_star = np.full((len(id_chunk_star_list), 3), np.nan)\n h5out_list[j]['PartType4/Coordinates'][:] = pos_chunk_star\n h5out_list[j]['PartType4/Velocities'][:] = vel_chunk_star\n h5out_list[j]['PartType4/Acceleration'][:] = acc_chunk_star\n\n print('ended second loop on thread', snap_idx)\n\n # Close h5 files.\n for i,_ in enumerate(id_chunks_disk):\n h5out_list[i].close()\n \n print('closed h5 files on thread', snap_idx)\n\n # Now copy the tmp directory to the data directory\n copy_tree(prefix, data_dir+name_lvl+'/tmp' + str(snap_idx))\n\n return prefix\n\ndef get_id_indices_chunks(path, nchunk):\n nsnap = len(glob.glob(path+'/output/snapdir*/*.0.hdf5'))\n indices = np.arange(nsnap)\n\n sn = read_snap(path, indices[-1], parttype=[1, 2, 3, 4])\n ids_halo = sn.part1.id\n ids_halo = np.sort(ids_halo)\n \n ids_disk = sn.part2.id\n ids_disk = np.sort(ids_disk)\n\n ids_bulge = sn.part3.id\n ids_bulge = np.sort(ids_bulge)\n\n if sn.NumPart_Total[4] > 0:\n ids_star = sn.part4.id\n ids_star = np.sort(ids_star)\n id_chunks_star = np.array_split(ids_star, nchunk)\n else:\n id_chunks_star = None\n\n id_chunks_halo = np.array_split(ids_halo, nchunk)\n id_chunks_disk = np.array_split(ids_disk, nchunk)\n id_chunks_bulge = np.array_split(ids_bulge, nchunk)\n\n return id_chunks_halo, id_chunks_disk, id_chunks_bulge, id_chunks_star\n\ndef run(name, lvl, snap_idx, nchunk, basepath='../../runs/', data_dir='data/', tmp_dir='/tmp/'):\n\n print('running ', name, lvl, )\n\n name_lvl = name + '-' + lvl\n path = basepath + name + '/' + lvl\n\n nsnap = len(glob.glob(path+'/output/snapdir*/*.0.hdf5'))\n if snap_idx >= nsnap:\n print('dont have snap_idx ', snap_idx, 'quitting...')\n sys.exit(0)\n\n # Split up particle ids and snapshot indices into chunks to be processed individually\n id_chunks_halo, id_chunks_disk, id_chunks_bulge, id_chunks_star = get_id_indices_chunks(path, nchunk)\n\n # If output directory does not exist, make it\n if not os.path.isdir(data_dir+name_lvl):\n os.mkdir(data_dir+name_lvl)\n\n # Runs through each chunk of indices and reads the snapshot of each index. Each chunk of ids is written to a different temporary file.\n t0 = time.time()\n to_delete = _run_thread(path, name_lvl, snap_idx, id_chunks_halo, id_chunks_disk, id_chunks_bulge, id_chunks_star, data_dir, tmp_dir)\n t1 = time.time()\n print('First loop took', t1-t0, 's')\n\n shutil.rmtree(to_delete)\n\n return None\n\nif __name__ == '__main__':\n name = sys.argv[1]\n lvl = sys.argv[2]\n snap_idx = int(sys.argv[3])\n\n nchunk = 256\n\n run(name, lvl, snap_idx, nchunk)\n","repo_name":"gusbeane/gasbar","sub_path":"analysis/phase_space/compute_phase_space.py","file_name":"compute_phase_space.py","file_ext":"py","file_size_in_byte":9646,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"10566097826","text":"from django.conf.urls import *\n\n#from django.contrib import admin\n#admin.autodiscover()\nimport settings\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'CouchbaseCloud.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n\n url(r'^userlogin/$', 'auth.views.auth_user'),\n url(r'^getRamSize/$', 'auth.views.getRamSize'),\n url(r'^login/$','auth.views.login_user'),\n url(r'^home/$','auth.views.register_user'),\n url(r'^create_account/$','auth.views.create_account'),\n url(r'^couchdep/$','auth.views.couchdep'),\n url(r'^deploy/$','auth.views.save_deployment'),\n url(r'^mngcluster/$','auth.views.mngcluster'),\n url(r'^Add/$','auth.views.mngviewAdd'),\n url(r'^Del/$','auth.views.mngviewDel'),\n url(r'^installation/$','auth.views.install'),\n url(r'^conf/$','auth.views.conf_couchbase'),\n url(r'^poll_state/$', 'auth.views.poll_state'),\n url(r'^poll_ins_state/$', 'auth.views.poll_ins_state'),\n url(r'^gotoDeployments/$', 'auth.views.handleProgress'),\n url(r'^static/(?P.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}),\n url(r'^getDeployment/$','auth.views.getDeployment')\n)\n","repo_name":"couchbaselabs/cloudhosting","sub_path":"CouchbaseCloud_Settings/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"33595849636","text":"from django.urls import path\nfrom .views import *\n\nurlpatterns = [\n path('lists/', ToDoListView.as_view(), name='todolists'),\n path('lists/create/', ToDoListCreateView.as_view(), name='todolist-create'),\n path('lists//', ToDoListDetailView.as_view(), name='todolist_detail'), \n path('lists//update/', ToDoListUpdateView.as_view(), name='todolist-update'),\n path('lists//delete/', ToDoListDeleteView.as_view(), name='todolist-delete'),\n path('items/', ToDoItemView.as_view(), name='todoitems'),\n path('items/create/', ToDoItemCreateView.as_view(), name='todoitem-create'),\n path('items//', ToDoItemDetailView.as_view(), name='todoitem_detail'), \n path('items//update/', ToDoItemUpdateView.as_view(), name='todoitem-update'),\n path('items//delete/', ToDoItemDeleteView.as_view(), name='todoitem-delete'),\n path('items//toggle_done/', toggle_todo_done, name='todoitem-toggle_done'),\n]\n","repo_name":"adamhoke/ai-software-engineering","sub_path":"todo_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
    stepnameinputoutputtarget
    %d%s