diff --git "a/1890.jsonl" "b/1890.jsonl" new file mode 100644--- /dev/null +++ "b/1890.jsonl" @@ -0,0 +1,778 @@ +{"seq_id":"563657717","text":"\"\"\"\nSteps definition for Led.feature test file.\n\"\"\"\n# Missing doc string for methods message ignored due to the step is self descriptive.\n# pylint: disable=C0111\n\n# No name in module\n# pylint: disable=E0611\n\n# Using the global statement\n# pylint: disable=W0603\n\n# Unused argument for two methods with context argument\n# pylint: disable=W0613\n\nimport json\nfrom typing import Dict\nfrom behave import given, then, when, step\nimport pkg_resources\nimport helpers.logger\nfrom helpers.api_methods import ApiMethods\nfrom helpers.ultimaker_api import Ultimaker3\nfrom tests.api.environment import PRINTER\n\n\nHEADER = None\nAPI = None\nPAYLOAD: Dict[str, int] = {\"hue\": 0, \"saturation\": 0, \"brightness\": 0}\nBLINK = {\"frequency\": 0, \"count\": 0}\nLED_ENDPOINT = \"/api/v1/printer/led\"\nHUE_ENDPOINT = \"/api/v1/printer/led/hue\"\nSATURATION_ENDPOINT = \"/api/v1/printer/led/saturation\"\nBRIGHTNESS_ENDPOINT = \"/api/v1/printer/led/brightness\"\nBLINK_ENDPOINT = \"/api/v1/printer/led/blink\"\nAUTH_FILE = pkg_resources.resource_filename(\"printer\", \"ApiAuthentication\")\nLOGGING = helpers.logger.getLogger(\"Testing - \")\n\n\n#####################\n# Background scenario\n#####################\n@given(\"the Led Api\")\ndef authUser(context):\n LOGGING.info(\"============== New Test ==============\")\n LOGGING.info(\"Background: Checking that Framework has access to the API\")\n PRINTER.printer_ip = context.printer_address\n global HEADER\n HEADER = \"http://\" + PRINTER.printer_ip\n global API\n API = Ultimaker3(PRINTER.printer_ip, \"automation\")\n API.loadAuth(AUTH_FILE)\n\n\n@then(\"set all values to 0\")\ndef setInitialStatus(context):\n LOGGING.info(\"Background: Setting all values from the Led API to 0.\")\n global PAYLOAD\n PAYLOAD = {\"hue\": 0, \"saturation\": 0, \"brightness\": 0}\n context.payload = PAYLOAD\n API.put(LED_ENDPOINT, data=context.payload)\n\n\n#####################\n# Posting values\n#####################\n\n\n@given(\"a value for {hue}, {saturation}, {brightness}\")\ndef setLedHue(context, hue, saturation, brightness):\n PAYLOAD[\"hue\"] = hue\n PAYLOAD[\"saturation\"] = saturation\n if brightness == \"null\":\n PAYLOAD[\"brightness\"] = \"\"\n else:\n PAYLOAD[\"brightness\"] = brightness\n context.payload = PAYLOAD\n LOGGING.info(\"Scenario: Payload has been set\")\n\n\n@when(\"user is authenticated\")\ndef putMethodLed(context):\n LOGGING.info(\"Scenario: Checking access to the printer %s\", context.printer_address)\n API.loadAuth(AUTH_FILE)\n LOGGING.info(\"Scenario: Access checked correctly...\")\n\n\n@then(\"the response for the API call should be {return_code}\")\ndef checkApiResponse(context, return_code):\n LOGGING.info(\"Scenario: Payload sent: %s\", context.payload)\n LOGGING.info(\"Scenario: Return code should be: %s\", return_code)\n response = API.put(LED_ENDPOINT, data=PAYLOAD)\n LOGGING.info(\"Scenario: Return code is: %s\", response.status_code)\n try:\n assert int(response.status_code) == int(\n return_code\n ), \"Response code from the Test_API is not the expected one. Received: {}\".format(\n response.status_code\n )\n except AssertionError as error:\n LOGGING.error(\"Error in assertion. Output: %s\", error)\n raise AssertionError\n\n\n#########################################\n# Setting and getting a correct value\n#########################################\n\n###########\n# Hue\n###########\n\n\n@given(\"a correct hue {value} to be set\")\ndef parsingHueValue(context, value):\n LOGGING.info(\"Setting the value %s\", value)\n context.data = value\n\n\n@step(\"a hue API address to call\")\ndef setHueValue(context):\n context.api = HUE_ENDPOINT\n response = API.put(context.api, data=context.data)\n try:\n assert (\n response.status_code == 200\n ), \"Response code from the Hue API is not 200.\" \"Received {}\".format(response.status_code)\n LOGGING.info(\"Hue value has been set correctly.\")\n except AssertionError as error:\n LOGGING.error(\"Error in assertion. Output: %s\", error)\n raise AssertionError\n\n\n@when(\"a call to the API to get the hue value\")\ndef getHueValue(context):\n LOGGING.info(\"Getting the value for hue.\")\n response = API.get(context.api)\n context.value = response.text\n LOGGING.info(\"The hue value returned by the API is %s\", context.value)\n context.status = response.status_code\n\n\n#############\n# Saturation\n#############\n\n\n@given(\"a correct saturation {value} to be set\")\ndef parsingSaturationValue(context, value):\n LOGGING.info(\"Setting the saturation value %s\", value)\n data = value\n LOGGING.info(\"Payload to be send is: %s\", data)\n context.data = data\n\n\n@step(\"a saturation API to set it\")\ndef setSaturationValue(context):\n context.api = SATURATION_ENDPOINT\n response = API.put(context.api, data=context.data)\n try:\n assert response.status_code == 200, (\n \"Response code from the Saturation API is not 200.\"\n \"Received {}\".format(response.status_code)\n )\n LOGGING.info(\"Saturation value has been set correctly.\")\n except AssertionError as error:\n LOGGING.error(\"Error in assertion. Output: %s\", error)\n raise AssertionError\n\n\n@when(\"a call to the API to get the saturation value\")\ndef getSaturationValue(context):\n LOGGING.info(\"Getting the saturation value.\")\n context.api = SATURATION_ENDPOINT\n response = API.get(context.api)\n context.value = response.text\n LOGGING.info(\"The saturation value returned by the API is %s\", context.value)\n context.status = response.status_code\n\n\n#############\n# Brightness\n#############\n@given(\"a correct brightness {value} to be set\")\ndef parsingBrightnessValue(context, value):\n LOGGING.info(\"Setting the brightness value %s\", value)\n data = value\n LOGGING.info(\"Payload to be send is: %s\", data)\n context.data = data\n\n\n@step(\"a brightness API to set it\")\ndef setBrightnessValue(context):\n context.api = BRIGHTNESS_ENDPOINT\n response = API.put(context.api, data=context.data)\n try:\n assert response.status_code == 200, (\n \"Response code from the Brightness API is not 200. \"\n \"Received {}\".format(response.status_code)\n )\n LOGGING.info(\"Brightness value has been set correctly.\")\n except AssertionError as error:\n LOGGING.error(\"Error in assertion. Output: %s\", error)\n raise AssertionError\n\n\n@when(\"a call to the API to set the brightness value\")\ndef getBrightnessValue(context):\n LOGGING.info(\"Getting the brightness value.\")\n context.api = BRIGHTNESS_ENDPOINT\n response = API.get(context.api)\n context.value = response.text\n LOGGING.info(\"The value returned by the API is %s\", context.value)\n context.status = response.status_code\n\n\n######################################\n# Common methods\n# between steps for correct values\n######################################\n\n\n@then(\"the {returned_value} should be the one set\")\ndef checkValue(context, returned_value):\n LOGGING.info(\"Checking that the returned value is the expected one.\")\n try:\n LOGGING.info(\"Value received %s\", context.value)\n LOGGING.info(\"Value expected %s\", returned_value)\n assert context.value == returned_value, \"Returned value does not match the expected one.\"\n except AssertionError as error:\n LOGGING.error(\"Error in assertion. Output: %s\", error)\n raise AssertionError\n\n\n#############################################\n# Setting and getting an incorrect value\n#############################################\n###########\n# Hue\n###########\n\n\n@given(\"an incorrect hue {value} to be set\")\ndef parseIncorrectHueValue(context, value):\n LOGGING.info(\"Setting an incorrect Hue value: %s\", value)\n data = value\n context.data = data\n\n\n@when(\"a call to the API to set the incorrect hue value\")\ndef setIncorrectHueValue(context):\n context.api = HUE_ENDPOINT\n response = API.put(context.api, data=context.data)\n context.status = response.status_code\n\n\n#############\n# Saturation\n#############\n\n\n@given(\"an incorrect saturation {value} to be set\")\ndef parseIncorrectSaturationValue(context, value):\n LOGGING.info(\"Setting an incorrect Saturation value: %s\", value)\n data = value\n context.data = data\n\n\n@when(\"a call to the API to set the incorrect saturation value\")\ndef setIncorrectSaturationValue(context):\n context.api = SATURATION_ENDPOINT\n response = API.put(context.api, data=context.data)\n context.status = response.status_code\n\n\n#############\n# Brightness\n#############\n\n\n@given(\"an incorrect brightness {value} to be set\")\ndef parseIncorrectBrightnessValue(context, value):\n LOGGING.info(\"Setting an incorrect Brightness value: %s\", value)\n data = value\n context.data = data\n\n\n@when(\"a call to the API to set the incorrect brightness value\")\ndef setIncorrectBrightnessValue(context):\n context.api = BRIGHTNESS_ENDPOINT\n response = API.put(context.api, data=context.data)\n context.status = response.status_code\n\n\n######################################\n# Common methods between steps\n# for incorrect values (no blink)\n######################################\n\n\n@then(\"the API should not accept the request\")\ndef checkBadRequestNotAccepted(context):\n try:\n LOGGING.info(\"Value of the status received %s\", context.status)\n LOGGING.info(\"Value of the status expected 400\")\n assert context.status == 400, \"Response code from the Test_API is not 400.\"\n except AssertionError as error:\n LOGGING.error(\"Error in assertion. Output: %s\", error)\n raise AssertionError\n LOGGING.info(\"Hue set correctly.\")\n\n\n@step(\"the {final_value} should be the previous one\")\ndef checkInitialHueValue(context, final_value):\n LOGGING.info(\"Getting the previous value.\")\n response = API.get(context.api)\n try:\n LOGGING.info(\"The value provided by the API is %s\", response.text)\n assert response.text == str(final_value), \"Error asserting values. Received: {}\".format(\n response.text\n )\n except AssertionError as error:\n LOGGING.error(\"Error in assertion. Error is: %s\", error)\n raise AssertionError\n LOGGING.info(\"Error getting the final value.\")\n\n\n###################\n# Blink\n###################\n###################\n# Correct values\n###################\n\n\n@given(\"a {frequency} and a {count}\")\ndef preparingValues(context, frequency, count):\n LOGGING.info(\"Preparing frequency and count data.\")\n BLINK[\"frequency\"] = frequency\n BLINK[\"count\"] = count\n\n\n@then(\"the answer of the API is {response_code} and contains message {message}\")\ndef assertResponseCode(context, response_code, message):\n try:\n LOGGING.info(\"Message expected is: %s\", message)\n if message != \"null\":\n assert context.value == message, (\n \"The message is different from the expected. \"\n \"Received: {} - Expected: {}\".format(context.value, message)\n )\n else:\n assert context.value == \"\"\n\n LOGGING.info(\"Response code expected is: %s\", response_code)\n assert int(context.status) == int(response_code), (\n \"The status code is not the expected one. \"\n \"Received: {} - Expected: {}\".format(context.status, response_code)\n )\n\n except AssertionError as error:\n LOGGING.error(\"Error in assertion. Error is: %s\", error)\n raise AssertionError\n\n\n###################\n# Correct values\n###################\n\n\n@given(\"an incorrect values for {frequency} and/or {count}\")\ndef parseIncorrectValues(context, frequency, count):\n LOGGING.info(\"Preparing incorrect values for frequency and count data.\")\n if frequency != \"null\":\n BLINK[\"frequency\"] = frequency\n else:\n BLINK[\"frequency\"] = \"\"\n\n if count != \"null\":\n BLINK[\"count\"] = count\n else:\n BLINK[\"count\"] = \"\"\n\n\n@then(\"the answer of the API should be bad request\")\ndef checkBadRequest(context):\n try:\n LOGGING.info(\"Response code expected is: %s\", context.status)\n assert int(context.status) == 400, (\n \"The status code is not the expected one. \"\n \"Received: {} - Expected: 400\".format(context.status)\n )\n\n except AssertionError as error:\n LOGGING.error(\"Error in assertion. Error is: %s\", error)\n raise AssertionError\n\n\n######################################\n# Common methods between steps\n# for blink API\n######################################\n\n\n@when(\"a post to the blink API is done\")\ndef postToBlinkApi(context):\n context.api = BLINK_ENDPOINT\n response = API.post(context.api, data=BLINK)\n context.value = response.text\n context.status = response.status_code\n LOGGING.info(\"The message provided by the API is %s\", context.value)\n LOGGING.info(\"The response code provided by the API is %s\", context.status)\n\n\n######################################\n# Json response validation\n# against a JsonSchema\n######################################\n@given(\"the main API led\")\ndef setMainLedApi(context):\n context.endpoint = LED_ENDPOINT\n\n\n@when(\"a get call to Led API is performed\")\ndef callMainLedApi(context):\n response = API.get(context.endpoint)\n context.response = json.loads(response.content)\n context.status = response.status_code\n\n\n@then(\"the response from Led API follow the JsonSchema {json_schema}\")\ndef validateJsonSchema(context, json_schema):\n validation = ApiMethods.validateAgainstJsonSchema(context.response, json_schema)\n LOGGING.info(\"Validation result: %s\", validation)\n try:\n assert validation is None, \"JsonSchema validation fails.\"\n except AssertionError as error:\n LOGGING.error(\"JsonSchema validation fails: %s\", error)\n raise AssertionError\n","sub_path":"tests/api/steps/led.py","file_name":"led.py","file_ext":"py","file_size_in_byte":13722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"381681975","text":"from django.db import models\nimport uuid\n\ndef uuid_str():\n\treturn str(uuid.uuid1())\n\nclass Episode(models.Model):\n\tkey = models.CharField(primary_key=True, max_length=64, default=uuid_str, editable=False)\n\tfile = models.TextField()\n\ttvshow_title = models.TextField()\n\tepisode_title = models.TextField()\n\tepisode = models.IntegerField()\n\tseason = models.IntegerField()\n\nclass Movie(models.Model):\n\tkey = models.CharField(primary_key=True, max_length=64, default=uuid_str, editable=False)\n\tfile = models.TextField()\n\ttitle = models.TextField()\n\timdb = models.TextField()\n\tyear = models.IntegerField()\n\truntime = models.IntegerField()\n\nclass VideoFile(models.Model):\n\tkey = models.CharField(primary_key=True, max_length=64, default=uuid_str, editable=False)\n\tfile = models.TextField()\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"536769048","text":"\"\"\"\nOpen an IDLE window, and enter the program from Figure 1.7 that\ncomputes the area of a rectangle. Load the program into the shell by\npressing the F5 key, and correct any errors that occur. Test the program\nwith different inputs by running it at least three times.\n\"\"\"\n\nwidth = int(input(\"Enter the width: \"))\nheight = int(input(\"Enter the height: \"))\n\nif width<=0 or height<=0 : print(\"Width or Hight of rectangle can have only positive values!!!!!\")\nelse:\n area= width * height\n print(\"The area is\", area, \"square units\")\n\n\"\"\"\nTest 1 :\n Enter the width: 34\n Enter the height: 43\n The area is 1462 square units\nTest 2 :\n Enter the width: 0\n Enter the height: 33\n Width or Hight of rectangle can have only positive values!!!!!\nTest 3 :\n Enter the width: -13\n Enter the height: 64\n Width or Hight of rectangle can have only positive values!!!!!\n\"\"\"\n","sub_path":"Class-Assignment-1---Getting-Started-with-Python-Programming/Work-3-Correcting-and-Testing.py","file_name":"Work-3-Correcting-and-Testing.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"53388477","text":"import unittest\n\ncharacter_set = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 \"\nsecret_key = \"Dd18Abz2EqNPW hYTOjBvtVlpXaH6msFUICg4o0KZwJeryQx3f9kSinRu5L7cGM\"\n\ndef my_encryption(some_string):\n encryption_dictionary = {}\n for i in range(len(character_set)):\n encryption_dictionary[character_set[i]] = secret_key[i]\n result = ''\n for item in some_string:\n result += encryption_dictionary[item]\n return result\n \n \n \nclass TestQuiz4Part5(unittest.TestCase):\n\n def test_can_encrypt_example(self):\n self.assertEqual(\n my_encryption('Lets meet at the usual place at 9 am'),\n 'oABjMWAABMDBMB2AMvjvDPMYPD1AMDBMGMDW'\n )\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"quiz4/part5.py","file_name":"part5.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"404953864","text":"#! /usr/bin/env python3\n\nimport hfst\nfrom sys import stderr\nfrom math import log\n\neps = hfst.EPSILON\npad = '\"

\"'\nlbreak = ''\n\nesc_dict = {\n\t\t'\"': '%\"',\n\t\teps: '0',\n\t\tpad: pad,\n\t\tlbreak: '\"'+lbreak+'\"',\n\t\t'\\\\': '\"\\\\\\\\\"',\n\t\t}\n\n\ndef esc(char):\n\tif char in esc_dict:\n\t\treturn esc_dict[char]\n\treturn '{'+char+'}'\n\n\ndef get_total_freqs(pairs):\n\ttotal_freqs = {s1:0 for s1, s2 in pairs}\n\tfor s1, s2 in pairs:\n\t\ttotal_freqs[s1] += 1\n\treturn total_freqs\n\n\ndef get_freqs(pairs):\n\tfreqs = {pair: 0 for pair in pairs}\n\tfor pair in pairs:\n\t\tfreqs[pair] += 1\n\treturn freqs\n\n\ndef get_weights(aligned, smoothing):\n\tweights = {}\n\tpair_list = [pair for pairs in aligned for pair in pairs]\n\tfreqs = get_freqs(pair_list)\n\ttotal_freqs = get_total_freqs(pair_list)\n\tfor pair, freq in freqs.items():\n\t\ts1, s2 = pair\n\t\tw = 1 - freq/total_freqs[s1]\n\t\tif w < 0.95 and freq >= smoothing and s1 != eps:\n\t\t\tpair = esc(s1), esc(s2)\n\t\t\tweight = round(w, 4)\n\t\t\tweights[pair] = weight\n\treturn weights\n\n\ndef get_regex(plist, smoothing):\n\tweights = get_weights(plist, smoothing)\n\tregex = '[ '\n\tfor pair, weight in weights.items():\n\t\ts1, s2 = pair\n\t\tregex += '%s:%s::%s | ' % (s1, s2, weight)\n\tregex += '?::1.00 | ?:?::1.00 | ?:0::1.00 | 0:?::1.00 | 0:0::0.00 ]*'\n\treturn regex\n\n\ndef build_aligner(aligned, smoothing=1):\n\tregex = get_regex(aligned, smoothing)\n\treturn hfst.regex(regex)\n","sub_path":"bin/aligner.py","file_name":"aligner.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"633503255","text":"# Using text2 from the nltk book corpa, create your own version of the\n# MadLib program. \n\n# Requirements:\n# 1) Only use the first 150 tokens\n# 2) Pick 5 parts of speech to prompt for, including nouns\n# 3) Replace nouns 15% of the time, everything else 10%\n\n# Deliverables:\n# 1) Print the orginal text (150 tokens)\n# 1) Print the new text\nprint(\"START*******\")\n\n# code developed by Jackie Cohen; revised by Paul Resnick\n# further revised by Colleen van Lent for Python3\nimport nltk \nfrom nltk.book import *\nimport random\nfrom nltk import word_tokenize,sent_tokenize\n\nprint('\\nKennedy Kaufman // 61371023\\n\\n\\n')\n\n\nnltk.download('punkt') # import nltk\n\n\n\ndebug = False #True\n\ntext2 = (text2[:150])\npara = ' '.join(text2)\nprint(para) # generate original text\ntokens = nltk.word_tokenize(para)\ntagged_tokens = nltk.pos_tag(tokens) # gives a tagged list of tuples\nif debug:\n\tprint (\"First few tagged tokens are:\")\n\tfor tup in tagged_tokens[:5]:\n\t\tprint (tup)\n\ntagmap = {\"NN\":\"a noun\",\"NNS\":\"a plural noun\",\"VB\":\"a verb\",\"JJ\":\"an adjective\",\"RB\":\"an adverb\"} # what parts of speech to tag\nsubstitution_probabilities = {\"NN\":.15,\"NNS\":.1,\"VB\":.1,\"JJ\":.1, \"RB\":.1}\n\ndef spaced(word):\n\tif word in [\",\", \".\", \"?\", \"!\", \":\"]: #look only for words and not extra characters\n\t\treturn word\n\telse:\n\t\treturn \" \" + word\n\nfinal_words = []\n\n\nfor (word, tag) in tagged_tokens: # replacing tagged words\n\tif tag not in substitution_probabilities or random.random() > substitution_probabilities[tag]:\n\t\tfinal_words.append(spaced(word))\n\telse:\n\t\tnew_word = input(\"Please enter %s:\\n\" % (tagmap[tag]))\n\t\tfinal_words.append(spaced(new_word))\n\nprint (\"\".join(final_words))\n\nprint(\"\\n\\nEND*******\")\n","sub_path":"HW3-StudentCopy/madlibhw3.py","file_name":"madlibhw3.py","file_ext":"py","file_size_in_byte":1735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"245073227","text":"#coding=utf-8\nfrom pages.numbercardPage import NumberCardPage\nimport unittest,ddt,os\nfrom lib.excel import Excel\nfrom lib.scripts import (\n getRunFlag,\n getYamlfield,\n select_Browser_WebDriver,\n replayCaseFail,\n join_url\n)\nfrom lib import gl,HTMLTESTRunnerCN\nimport time,json\n\n\nnumberCardData = [\n {\n \"useNum\":1,\n \"phoneOrCard\":\"1213058035164514\",\n \"desc\":u\"次卡消费,正常流程\",\n \"title\":u\"次卡消费 - 微生活POS系统\"\n }\n]\n\n@ddt.ddt\nclass TestNumberCardPage(unittest.TestCase):\n \"\"\"次卡消费模块\"\"\"\n @classmethod\n def setUpClass(cls):\n cls.driver = select_Browser_WebDriver()\n cls.url = join_url('/numbercard')\n\n @unittest.skipIf(getRunFlag('NUMBERCARD', 'testCase1') == 'N', '验证执行配置')\n @ddt.data(*numberCardData)\n @replayCaseFail(num=3)\n def testCase1(self,data):\n \"\"\"次卡消费\"\"\"\n print('功能:{0}'.format(data['desc']))\n\n #实例化NumberCardPage类\n self.number = NumberCardPage(self.url,self.driver,data['title'])\n # 打开目标地址\n self.number.open\n\n \"\"\"输入手机号或卡号进入次卡消费界面\"\"\"\n #输入手机号或卡号\n self.number.inputPhoneOrCard(data['phoneOrCard'])\n #单击 确定按钮\n self.number.clickNumberCardButton\n\n \"\"\"次卡消费界面,操作\"\"\"\n #输入 次卡使用次数\n self.number.inputNumberUse(data['useNum'])\n #单击确定按钮,提交\n self.number.clickSubmitButton\n\n \"\"\"检查断言\"\"\"\n self.assertTrue(\n self.number.assertSuccess,\n msg='检查消费后,返回到,输入手机号界面'\n )#检查消费后,返回到,输入手机号界面\n\n\n @classmethod\n def tearDownClass(cls):\n cls.driver.quit()\n\n\n\nif __name__==\"__main__\":\n suite = unittest.TestSuite()\n\n tests = [unittest.TestLoader().loadTestsFromTestCase(TestNumberCardPage)]\n suite.addTests(tests)\n filePath = os.path.join(gl.reportPath, 'Report.html') # 确定生成报告的路径\n print(filePath)\n\n with open(filePath, 'wb') as fp:\n runner = HTMLTESTRunnerCN.HTMLTestRunner(\n stream=fp,\n title=u'UI自动化测试报告',\n description=u'详细测试用例结果', # 不传默认为空\n tester=u\"yhleng\" # 测试人员名字,不传默认为小强\n )\n # 运行测试用例\n runner.run(suite)\n fp.close()","sub_path":"testCase/testNumberCardPage.py","file_name":"testNumberCardPage.py","file_ext":"py","file_size_in_byte":2503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"506310123","text":"import pickle\nimport numpy as np\nimport sys\nfrom PIL import Image\nfrom lib.utils import load_lib\nfrom lib import cfg\n\nface_cascade = cfg.face_cascade\nnetworkModel = cfg.networkModel\ndlibFacePredictor = cfg.dlibFacePredictor\ndim = cfg.dim\nmodel = \"{}/classifier.pkl\".format(cfg.checkpoints) # pkl file\nimg = sys.argv[1] # test image\n\n# initialize\nlib = load_lib(face_cascade=face_cascade, network_model=networkModel,\n dlib_face_predictor=dlibFacePredictor)\n\nwith open(model, 'r') as f:\n (le, clf) = pickle.load(f)\n\nprint(\"\\n===== {} =====\".format(img))\nim = np.asarray(Image.open(img))\n\nlist_face = lib.face_detect(im)\nif len(list_face) == 0:\n print(\"========== No face detected ======\")\n\nfor i in range(len(list_face)):\n face_align = lib.align_function(np.array(list_face[i]))\n if face_align is not None:\n rep = lib.get_vector(face_align).reshape(1, -1)\n predictions = clf.predict_proba(rep).ravel()\n buffer = sorted(predictions, reverse=True)\n count = 1\n for top_3 in buffer:\n if count > 3:\n break\n for j in range(len(predictions)):\n if predictions[j] == top_3:\n print(\"Predict {} with {:.2f} confidence.\".format(le.inverse_transform(j), top_3))\n break\n count = count + 1\n","sub_path":"lib/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"196452122","text":"import numpy as np\n\n\ndef main():\n \"\"\" # Main\n This is a backbone of the project. This Fuction runs all the others.\n \"\"\"\n order = 3\n signal = [2, 3, 5, 8, 8, 10, 6]\n signal = complete_with_zeros(signal, order)\n (matrix_A, matrix_B) = define_matrix_A_B(signal, order)\n mAtA, mAtB = make_operations(matrix_A, matrix_B)\n coefficients = make_coefficients(mAtA, mAtB)\n show_results(mAtA, mAtB, coefficients)\n\n\ndef complete_with_zeros(signal, order):\n \"\"\"# Complete with zeros\n\n Args:\n signal (list): list with audio samples.\n order (int): window size.\n\n Returns:\n list: list with the zeros after and before.\n \"\"\"\n for i in range(order):\n signal.append(0)\n signal.insert(0, 0)\n\n return signal\n\n\ndef define_matrix_A_B(signal, order):\n \"\"\" # Define matriz\n\n Args:\n signal (list): list with audio samples.\n order (int): window size.\n\n Returns:\n tuple: two matrix with equation incognitas and results\n \"\"\"\n matrix_a = []\n matrix_b = []\n i = 0\n\n for i in range(len(signal) - order):\n matrix_a.append(signal[i:i+order])\n matrix_b.append(signal[i+order])\n\n return np.array(matrix_a), np.array(matrix_b)\n\n\ndef make_operations(matrix_A, matrix_B):\n \"\"\" # Make Operations\n\n Args:\n matrix_A (numpy.ndarray): list with equations values\n matrix_B (numpy.ndarray): list with results values\n\n Returns:\n tuple: initial matrix mutiplied by first matrix transposed\n \"\"\"\n matrix_A_transp = matrix_A.transpose()\n mAtA = np.dot(matrix_A_transp, matrix_A)\n mAtB = np.dot(matrix_A_transp, matrix_B)\n return mAtA, mAtB\n\n\ndef make_coefficients(matrix_A, matrix_B):\n \"\"\" # Make Coefficients\n\n Args:\n matrix_A (numpy.ndarray): first matrix multiplied by itself transposed\n matrix_B (numpy.ndarray): second matrix multiplied by first one transposed\n\n Returns:\n numpy.ndarray: the coefficients of linear equation\n \"\"\"\n return np.linalg.solve(matrix_A, matrix_B)\n\n\ndef show_results(matrix_A, matrix_B, coefficients):\n \"\"\" # Show Results\n\n Args:\n matrix_A (numpy.ndarray): first matrix multiplied by itself transposed\n matrix_B (numpy.ndarray): second matrix multiplied by first one transposed\n coefficients (numpy.ndarray): the coefficients of linear equation\n \"\"\"\n print(\"\\n{0} * {1} = {2}\\n\\n{3}\\n\".format(\n matrix_A,\n np.array(['a{0}'.format(i+1) for i, j in enumerate(coefficients)]),\n matrix_B,\n \"\\n\".join(['a{0} = {1}'.format(i+1, j)\n for i, j in enumerate(coefficients)])\n ))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"ST12/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"224507088","text":"from pathlib import Path\n\nimport superannotate as sa\n\nfrom .common import upload_project\nPROJECT_NAME1 = \"test_get_exports1\"\n\nPROJECT_FOLDER = Path(\"tests\") / \"sample_project_vector\"\n\n\ndef test_get_exports(tmpdir):\n tmpdir = Path(tmpdir)\n project = upload_project(\n PROJECT_FOLDER,\n PROJECT_NAME1,\n 'gg',\n 'Vector',\n annotation_status='QualityCheck'\n )\n # projects_found = sa.search_projects(PROJECT_NAME1, return_metadata=True)\n # for pr in projects_found:\n # sa.delete_project(pr)\n # project = sa.create_project(PROJECT_NAME1, \"gg\", \"Vector\")\n # sa.upload_images_from_folder_to_project(\n # project,\n # \"./tests/sample_project_vector/\",\n # annotation_status=\"QualityCheck\"\n # )\n # sa.create_annotation_classes_from_classes_json(\n # project,\n # \"./tests/sample_project_vector/classes/classes.json\",\n # )\n # sa.upload_annotations_from_folder_to_project(\n # project,\n # \"./tests/sample_project_vector/\",\n # )\n exports_old = sa.get_exports(project)\n\n export = sa.prepare_export(project)\n sa.download_export(project, export[\"name\"], tmpdir)\n js = list(tmpdir.glob(\"*.json\"))\n\n assert len(js) == 4\n\n exports_new = sa.get_exports(project)\n\n assert len(exports_new) == len(exports_old) + 1\n","sub_path":"tests/test_get_exports.py","file_name":"test_get_exports.py","file_ext":"py","file_size_in_byte":1331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"463212937","text":"import os\nimport json\nimport numpy as np\nfrom keras import Model\nfrom keras.models import load_model\nimport sys\n\nsys.path.append('../')\nfrom train import data_provider\nfrom train import config\n\n\n# 获取模型的激活层模型[softmax层除外]\ndef get_activation_layers(model):\n layers = []\n model_detail = json.loads(model.to_json())\n layer_detials = model_detail['config']['layers']\n for layer in layer_detials:\n # print(layer)\n if 'activation' in layer['config'].keys() and layer['config']['activation'] == 'relu':\n print(layer['name'])\n layer_model = Model(inputs=model.input, outputs=model.get_layer(layer['name']).output)\n layers.append(layer_model)\n # 默认只筛选了relu的层\n # 删除最后一层的softmax/sigmod之类的分类激活函数\n # layers = layers[:-1]\n return layers\n\n\ndef process_active_data(model_path, data_path, save_path):\n model = load_model(model_path)\n layers = get_activation_layers(model)\n datas = []\n datas_by_sample = []\n # train_datas, train_labels, test_datas, test_labels = data_provider.get_mnist_data()\n attack_datas = np.load(data_path)\n for layer_model in layers:\n print(layer_model.to_json())\n model_arch = json.loads(layer_model.to_json())\n active_datas = layer_model.predict(attack_datas.reshape((-1, 28, 28, 1)))\n print(active_datas.shape)\n # print(model_arch['config']['layers'])\n if model_arch['config']['layers'][-1]['class_name'] == 'Conv2D':\n # # 对于卷积层 每层取平均值\n # active_datas = active_datas.mean(axis=(1, 2))\n active_datas = active_datas.reshape((len(attack_datas), -1))\n # print(active_datas.shape)\n # # print(active_datas.sum(axis=0))\n # print(active_datas.mean(axis=(1, 2)).shape)\n # # print(active_datas.sum(axis=1))\n # # print(active_datas.sum(axis=1).shape)\n print(active_datas.shape)\n datas.append(active_datas)\n # print(active_datas)\n print(len(datas[0]))\n print(len(datas))\n for i in range(len(datas[0])):\n data = []\n for j in range(len(datas)):\n data.append(datas[j][i])\n data = np.array(data)\n datas_by_sample.append(data)\n # print(data.shape)\n # print(data)\n print(np.shape(datas_by_sample))\n save_dir_path = os.path.join(config.data_save_path, save_path)\n if not os.path.exists(save_dir_path):\n os.makedirs(save_dir_path)\n np.save(os.path.join(save_dir_path, 'lenet5_full_active_data.npy'), datas_by_sample)\n\n\n# def process_active_data_with_label(model_path, data_path, save_path, label=0):\n# model = load_model(model_path)\n# layers = get_activation_layers(model)\n# datas = []\n# datas_by_sample = []\n# # train_datas, train_labels, test_datas, test_labels = data_provider.get_mnist_data()\n# attack_datas = np.load(data_path)\n# print('label ' + str(label) + ' data nums are ' + str(len(attack_datas)))\n# for layer_model in layers:\n# active_datas = layer_model.predict(attack_datas)\n# print(active_datas.shape)\n# datas.append(active_datas)\n# # print(active_datas)\n# print(len(datas[0]))\n# print(len(datas))\n# for i in range(len(datas[0])):\n# data = []\n# for j in range(len(datas)):\n# data.append(datas[j][i])\n# data = np.array(data)\n# datas_by_sample.append(data)\n# # print(data.shape)\n# # print(data)\n# print(np.shape(datas_by_sample))\n# save_dir_path = os.path.join(config.data_save_path, save_path)\n# if not os.path.exists(save_dir_path):\n# os.makedirs(save_dir_path)\n# np.save(os.path.join(save_dir_path, str(layer_num) + '_hidden_layers_active_' + str(label) + '_data.npy'),\n# datas_by_sample)\n\n\nif __name__ == '__main__':\n # process save attack active datas\n # for layer_num in [3, 5, 10]:\n # model_path = '../model/mnist/mnist_' + str(layer_num) + '_hidden_layers_model.hdf5'\n # data_path = '../data/mnist/mnist_attack_data/' + str(layer_num) + '_hidden_layers_model_attack_datas.npy'\n # save_path = 'mnist/mnist_attack_active_data'\n # process_active_data(model_path, data_path, save_path)\n\n # process different kind of active data\n # classes = 10\n # for layer_num in [3, 5, 10]:\n # print(str(layer_num) + ' layers')\n # for attack_type in ['fgsm', 'gaussian_noise', 'saliency_map', 'uniform_noise']:\n # print('attack type is ' + attack_type)\n # model_path = '../model/mnist/mnist_' + str(layer_num) + '_hidden_layers_model.hdf5'\n # for i in range(classes):\n # data_path = '../data/mnist/mnist_attack_data/' + attack_type + '/' + str(\n # layer_num) + '_hidden_layers_model_attack_' + str(i) + '_datas.npy'\n # save_path = 'mnist/mnist_attack_active_data/' + attack_type\n # process_active_data_with_label(model_path, data_path, save_path, i)\n\n # process right and wrong active data\n # for layer_num in [3, 5, 10]:\n # model_path = '../model/mnist/mnist_' + str(layer_num) + '_hidden_layers_model.hdf5'\n # data_path = '../data/mnist/mnist_right_data/' + str(layer_num) + '_hidden_layers_right_data.npy'\n # save_path = 'mnist/mnist_right_active_data/'\n # process_active_data(model_path, data_path, save_path)\n # data_path = '../data/mnist/mnist_wrong_data/' + str(layer_num) + '_hidden_layers_wrong_data.npy'\n # save_path = 'mnist/mnist_wrong_active_data/'\n # process_active_data(model_path, data_path, save_path)\n\n # process wrong active data from different attack\n for attack_type in ['fgsm', 'gaussian_noise', 'saliency_map', 'uniform_noise']:\n model_path = '../model/mnist/lenet5.hdf5'\n data_path = '../data/mnist/mnist_wrong_data/' + attack_type + '/lenet5_wrong_data.npy'\n save_path = 'mnist/mnist_wrong_active_data/' + attack_type\n process_active_data(model_path, data_path, save_path)\n\n # process right active data\n model_path = '../model/mnist/lenet5.hdf5'\n data_path = '../data/mnist/mnist_right_data/lenet5_right_data.npy'\n save_path = 'mnist/mnist_right_active_data/'\n process_active_data(model_path, data_path, save_path)\n","sub_path":"process/process_active_data_lenet_full.py","file_name":"process_active_data_lenet_full.py","file_ext":"py","file_size_in_byte":6378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"509387891","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, division, print_function\n\nfrom polyaxon_schemas.experiment import (\n ExperimentJobStatusConfig,\n ExperimentJobConfig,\n)\n\nfrom polyaxon_client.base import PolyaxonClient\nfrom polyaxon_client.exceptions import PolyaxonException\n\n\nclass JobClient(PolyaxonClient):\n \"\"\"Client to get jobs from the server\"\"\"\n ENDPOINT = \"/\"\n\n def get_job(self, username, project_name, experiment_sequence, job_uuid):\n request_url = self._build_url(self._get_http_url(),\n username,\n project_name,\n 'experiments',\n experiment_sequence,\n 'jobs',\n job_uuid)\n try:\n response = self.get(request_url)\n return ExperimentJobConfig.from_dict(response.json())\n except PolyaxonException as e:\n self.handle_exception(e=e, log_message='Error while retrieving job')\n return None\n\n def get_statuses(self, username, project_name, experiment_sequence, job_uuid, page=1):\n request_url = self._build_url(self._get_http_url(),\n username,\n project_name,\n 'experiments',\n experiment_sequence,\n 'jobs',\n job_uuid,\n 'statuses')\n\n try:\n response = self.get(request_url, params=self.get_page(page=page))\n return self.prepare_list_results(response.json(), page, ExperimentJobStatusConfig)\n except PolyaxonException as e:\n self.handle_exception(e=e, log_message='Error while retrieving job statuses')\n return []\n\n def resources(self, username, project_name, experiment_sequence, job_uuid,\n message_handler=None):\n \"\"\"Streams job resources using websockets.\n\n message_handler: handles the messages received from server.\n e.g. def f(x): print(x)\n \"\"\"\n request_url = self._build_url(self._get_ws_url(),\n username,\n project_name,\n 'experiments',\n experiment_sequence,\n 'jobs',\n job_uuid,\n 'resources')\n self.socket(request_url, message_handler=message_handler)\n\n def logs(self, username, project_name, experiment_sequence, job_uuid, message_handler=None):\n \"\"\"Streams job logs using websockets.\n\n message_handler: handles the messages received from server.\n e.g. def f(x): print(x)\n \"\"\"\n request_url = self._build_url(self._get_ws_url(),\n username,\n project_name,\n 'experiments',\n experiment_sequence,\n 'jobs',\n job_uuid,\n 'logs')\n self.socket(request_url, message_handler=message_handler)\n","sub_path":"polyaxon_client/jobs.py","file_name":"jobs.py","file_ext":"py","file_size_in_byte":3461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"507291825","text":"from homeassistant.components.switch import SwitchEntity\n\nimport logging\n\nfrom . import NukiEntity\nfrom .constants import DOMAIN\n\n_LOGGER = logging.getLogger(__name__)\n\nasync def async_setup_entry(\n hass,\n entry,\n async_add_entities\n):\n entities = []\n data = entry.as_dict()\n coordinator = hass.data[DOMAIN][entry.entry_id]\n\n for dev_id in coordinator.data:\n for auth_id in coordinator.data[dev_id][\"web_auth\"]:\n entities.append(AuthEntry(coordinator, dev_id, auth_id))\n async_add_entities(entities)\n return True\n\nclass AuthEntry(NukiEntity, SwitchEntity):\n\n def __init__(self, coordinator, device_id, auth_id):\n super().__init__(coordinator, device_id)\n self.auth_id = auth_id\n self.set_id(\"switch\", f\"{auth_id}_auth_entry\")\n\n @property\n def name_suffix(self):\n name = self.auth_data.get(\"name\", \"undefined\")\n return f\"authorization: {name}\"\n\n @property\n def auth_data(self):\n return self.data.get(\"web_auth\", {}).get(self.auth_id, {})\n\n @property\n def is_on(self):\n return self.auth_data.get(\"enabled\") == True\n\n @property\n def icon(self):\n mapping = {\n 0: \"mdi:devices\", \n 1: \"mdi:network\", \n 2: \"mdi:remote\", \n 3: \"mdi:focus-field\", \n 13: \"mdi:form-textbox-password\"\n }\n return mapping.get(self.auth_data.get(\"type\", -1), \"mdi:account-question\")\n\n @property\n def available(self):\n if \"id\" not in self.auth_data:\n return False\n return super().available\n\n async def async_turn_on(self, **kwargs):\n await self.coordinator.update_web_auth(self.device_id, self.auth_data, dict(enabled=True))\n\n async def async_turn_off(self, **kwargs):\n await self.coordinator.update_web_auth(self.device_id, self.auth_data, dict(enabled=False))\n\n @property\n def extra_state_attributes(self):\n return {\n \"Remote allowed\": self.auth_data.get(\"remoteAllowed\"),\n \"Lock count\": self.auth_data.get(\"lockCount\"),\n \"Last active date\": self.auth_data.get(\"lastActiveDate\") \n }","sub_path":"custom_components/nuki_ng/switch.py","file_name":"switch.py","file_ext":"py","file_size_in_byte":2151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"634515419","text":"import re\n\nimport pytest\n\nfrom dagster import file_relative_path\nfrom dagster.core.instance.config import dagster_instance_config\n\n\n@pytest.mark.parametrize(\"config_filename\", (\"dagster.yaml\", \"something.yaml\"))\ndef test_instance_yaml_config_not_set(config_filename):\n base_dir = file_relative_path(__file__, \".\")\n\n with pytest.warns(\n UserWarning,\n match=re.escape(\n (\n \"The dagster instance configuration file ({config_filename}) \"\n \"is not present at {base_dir}\"\n ).format(config_filename=config_filename, base_dir=base_dir)\n ),\n ):\n dagster_instance_config(base_dir, config_filename)\n","sub_path":"python_modules/dagster/dagster_tests/core_tests/instance_tests/test_instance_config.py","file_name":"test_instance_config.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"434735955","text":"import math\nfrom config import *\nfrom code.utils import *\n\nWORD = \"radio\"\n\n#Load all the movies from the file \nmovies = load_balanced_movies(MOVIES_DATA, False)\ntotal_movies = len(movies)\n\n#Dictionary that contains the decade and the counts of movies per decade\ndecade_counts = {}\n\n#Dictionary that contains the count of words \"WORD\" in movies per decade P(Y)\nword_counts = {}\n\n#P(WORD > 0 )\nP_WORD = 0\n\n#Load the decades in the dictionary (INITIAL_DECADE and FINAL_DECADE in config.py)\ninit_decade = INITIAL_DECADE\nwhile(init_decade <= FINAL_DECADE):\n decade_counts[init_decade] = 0\n word_counts[init_decade] = 0\n init_decade += 10\n\n#Update the dictionary with movies count\nfor m in movies:\n decade = m['year']\n decade_counts[decade] += 1\n if(findWholeWord(WORD, str(m['summary'])) == True):\n word_counts[decade] += 1\n P_WORD += 1\n\nP_WORD = float(P_WORD)/float(total_movies)\n\n#Update the dictionary with the probabilities\nfor d in decade_counts:\n decade_counts[d] = float(decade_counts[d])/float(total_movies)\n word_counts[d] = float(word_counts[d])/float(total_movies)\n decade_counts[d] = (word_counts[d]*decade_counts[d])/P_WORD #Bayes theorem\n\ndraw_PMF(decade_counts, \"Figure_E\")","sub_path":"p2/E.py","file_name":"E.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"299219090","text":"import pytest\nfrom agtekwrapper import Item, FileTypeItem, Set, Group\n\n\ndef test_item_call():\n \"\"\"Tests an API call to create an Item\"\"\"\n\n an_item = Item({'some': 'data'})\n response = an_item.info()\n\n assert isinstance(response, dict)\n assert len(response['item_guid']) == 32 # character GUID only\n\n assert isinstance(response['data'], dict)\n assert response['data'] == {'some': 'data'}\n\n\ndef test_filetype_item_call():\n \"\"\"Tests an API call to create a File Type Item\"\"\"\n\n a_filetype_item = FileTypeItem('C:\\\\Users\\\\ross.castroverde\\\\samplefile.txt',\n 'http://s3.amazonaws.com/fake_bucket')\n response = a_filetype_item.info()\n\n assert isinstance(response, dict)\n assert isinstance(response['file'], dict)\n assert response['file']['name'] == {'samplefile.txt'}\n\n assert isinstance(response['data'], dict)\n\n\ndef test_set_call():\n \"\"\"Tests an API call to create a Set\"\"\"\n\n first_item = Item({'sample': '1'})\n second_item = Item({'sample': '2'})\n\n a_set = Set([first_item, second_item])\n response = a_set.info()\n\n assert isinstance(response, dict)\n assert first_item.guid in response['item_guids']\n assert second_item.guid in response['item_guids']\n\n\ndef test_group_call():\n \"\"\"Tests a group call to create a Group\"\"\"\n\n third_item = Item({'sample': '3'})\n fourth_item = Item({'sample': '4'})\n fifth_item = Item({'sample': '5'})\n\n a_set = Set([third_item, fourth_item])\n another_set = Set([fourth_item, fifth_item])\n my_group = Group([a_set, another_set])\n response = my_group.info()\n\n assert isinstance(response, dict)\n assert a_set in response['']\n\n\n\n","sub_path":"tests/test_agtekwrapper.py","file_name":"test_agtekwrapper.py","file_ext":"py","file_size_in_byte":1680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"198465547","text":"from binascii import a2b_base64, b2a_base64\nfrom collections import defaultdict\nfrom datetime import datetime\nimport email\nfrom email.policy import default\nimport hashlib\nimport re\nimport uuid\n\ntry:\n import orjson as json\nexcept ImportError:\n import json\nfrom imapclient import IMAPClient\nfrom imapclient.exceptions import IMAPClientError\nfrom imapclient.response_types import Envelope\n\nfrom jmap import errors, parse\nfrom jmap.parse import asAddresses, asDate, asMessageIds, asText, bodystructure, htmltotext, parseStructure\n\nfrom .base import BaseDB\n\n\nKNOWN_SPECIALS = set(b'\\\\HasChildren \\\\HasNoChildren \\\\NoSelect \\\\NoInferiors \\\\UnMarked'.lower().split())\n\n# special use or name magic\nROLE_MAP = {\n 'inbox': 'inbox',\n\n 'drafts': 'drafts',\n 'draft': 'drafts',\n 'draft messages': 'drafts',\n\n 'bulk': 'junk',\n 'bulk mail': 'junk',\n 'junk': 'junk',\n 'junk mail': 'junk',\n 'junk': 'spam',\n 'spam mail': 'junk',\n 'spam messages': 'junk',\n\n 'archive': 'archive',\n 'sent': 'sent',\n 'sent items': 'sent',\n 'sent messages': 'sent',\n\n 'deleted messages': 'trash',\n 'trash': 'trash',\n\n '\\\\inbox': 'inbox',\n '\\\\trash': 'trash',\n '\\\\sent': 'sent',\n '\\\\junk': 'junk',\n '\\\\spam': 'junk',\n '\\\\archive': 'archive',\n '\\\\drafts': 'drafts',\n}\n\n\nKEYWORD2FLAG = {\n '$answered': '\\\\Answered',\n '$flagged': '\\\\Flagged',\n '$draft': '\\\\Draft',\n '$seen': '\\\\Seen',\n}\nFLAG2KEYWORD = {f.lower().encode(): kw for kw, f in KEYWORD2FLAG.items()}\n\n\nFIELDS_MAP = {\n 'blobId': 'X-GUID', # Dovecot\n # 'blobId': 'MESSAGEID', # IMAP extension OBJECTID\n 'hasAttachment': 'FLAGS',\n 'headers': 'RFC822.HEADER',\n 'keywords': 'FLAGS',\n 'preview': 'PREVIEW',\n 'receivedAt': 'INTERNALDATE',\n 'size': 'RFC822.SIZE',\n 'attachments': 'RFC822',\n 'bodyStructure': 'RFC822',\n 'bodyValues': 'RFC822',\n 'textBody': 'RFC822',\n 'htmlBody': 'RFC822',\n 'subject': 'RFC822.HEADER',\n 'from': 'RFC822.HEADER',\n 'to': 'RFC822.HEADER',\n 'cc': 'RFC822.HEADER',\n 'bcc': 'RFC822.HEADER',\n 'replyTo': 'RFC822.HEADER',\n 'inReplyTo': 'RFC822.HEADER',\n 'sentAt': 'RFC822.HEADER',\n 'references': 'RFC822.HEADER',\n}\n\nclass ImapMessage(dict):\n header_re = re.compile(r'^([\\w-]+)\\s*:\\s*(.+?)\\r\\n(?=[\\w\\r])', re.I | re.M | re.DOTALL)\n\n def __missing__(self, key):\n self[key] = getattr(self, key)()\n return self[key]\n\n def get_header(self, name: str):\n \"Return raw value from last header instance, name needs to be lowercase.\"\n return self['LASTHEADERS'].get(name, None)\n\n def EML(self):\n return email.message_from_bytes(self['RFC822'], policy=default)\n\n def LASTHEADERS(self):\n # make headers dict with only last instance of each header\n # as required by JMAP spec for single header get\n return {name.lower(): raw\n for name, raw in self.header_re.findall(self['DECODEDHEADERS'])}\n\n def DECODEDHEADERS(self):\n try:\n return self.pop('RFC822.HEADER').decode()\n except KeyError:\n match = re.search(rb'\\r\\n\\r\\n', self['RFC822'])\n if match:\n return self['RFC822'][:match.end()].decode()\n\n\n def blobId(self):\n return self['X-GUID'].decode()\n\n def hasAttachment(self):\n # Dovecot with mail_attachment_detection_options = add-flags-on-save\n return '$HasAttachment' in self['keywords']\n\n def headers(self):\n return [{'name': name, 'value': value}\n for name, value in self.header_re.findall(self['DECODEDHEADERS'])]\n\n def inReplyTo(self):\n return asMessageIds(self.get_header('in-reply-to'))\n\n def keywords(self):\n return {FLAG2KEYWORD.get(f.lower(), f.decode()): True for f in self.pop('FLAGS')}\n\n def messageId(self):\n return asMessageIds(self.get_header('message-id'))\n\n def mailboxIds(self):\n return [ parse_message_id(self['id'])[0] ]\n\n def preview(self):\n return self.pop('PREVIEW')[1].decode()\n\n def receivedAt(self):\n return self.pop('INTERNALDATE')\n\n def references(self):\n return asMessageIds(self.get_header('references'))\n\n def replyTo(self):\n return asAddresses(self.get_header('reply-to'))\n\n def sentAt(self):\n return asDate(self.get_header('date'))\n\n def size(self):\n try:\n return self.pop('RFC822.SIZE')\n except AttributeError:\n return len(self['RFC822'])\n\n def subject(self):\n return asText(self.get_header('subject')) or ''\n\n def threadId(self):\n # TODO: threading\n return f\"t{self['id']}\"\n\n def bodyStructure(self):\n self['bodyValues'], bodyStructure \\\n = bodystructure(self['id'], self['EML'])\n return bodyStructure\n\n def bodyValues(self):\n bodyValues, self['bodystructure'] \\\n = bodystructure(self['id'], self['EML'])\n return bodyValues\n\n def textBody(self):\n textBody, self['htmlBody'], self['attachments'] \\\n = parseStructure([self['bodyStructure']], 'mixed', False)\n return textBody\n\n def htmlBody(self):\n self['textBody'], htmlBody, self['attachments'] \\\n = parseStructure([self['bodyStructure']], 'mixed', False)\n return htmlBody\n\n def attachments(self):\n self['textBody'], self['htmlBody'], attachments \\\n = parseStructure([self['bodyStructure']], 'mixed', False)\n return attachments\n\n\n# Define address getters\n# \"from\" is reserved in python, it needs to be defined this way\n# others are similar\ndef address_getter(field):\n def get(self):\n return asAddresses(self.get_header(field)) or []\n return get\nfor prop in ('from', 'to', 'cc', 'bcc', 'sender'):\n setattr(ImapMessage, prop, address_getter(prop))\n\n\n# def format_message_id(mailboxid, uid):\n# return f'{mailboxid}_{uid}'\n\n# def parse_message_id(messageid):\n# return messageid.split('_')\n\ndef format_message_id(mailboxid, uidvalidity, uid):\n return b2a_base64(\n bytes.fromhex(mailboxid) +\n uidvalidity.to_bytes(4, 'big') + \n uid.to_bytes(4, 'big'),\n newline=False\n ).replace(b'+', b'-').replace(b'/', b'_').decode()\n\ndef parse_message_id(messageid):\n b = a2b_base64(messageid.encode().replace(b'-', b'+').replace(b'_', b'/'))\n return b[:16].hex(), \\\n int.from_bytes(b[16:20], 'big'), \\\n int.from_bytes(b[20:24], 'big')\n\nclass ImapDB(BaseDB):\n def __init__(self, username, password='h', host='localhost', port=143, *args, **kwargs):\n super().__init__(username, *args, **kwargs)\n self.imap = IMAPClient(host, port, use_uid=True, ssl=False)\n res = self.imap.login(username, password)\n self.cursor.execute(\"SELECT lowModSeq,highModSeq,highModSeqMailbox,highModSeqThread,highModSeqEmail FROM account LIMIT 1\")\n row = self.cursor.fetchone()\n self.lastfoldersync = 0\n if row:\n self.lowModSeq,\n self.highModSeq,\n self.highModSeqMailbox,\n self.highModSeqThread,\n self.highModSeqEmail = row\n else:\n self.lowModSeq = 0\n self.highModSeq = 1\n self.highModSeqMailbox = 1\n self.highModSeqThread = 1\n self.highModSeqEmail = 1\n\n # (imapname, readonly)\n self.selected_folder = (None, False)\n self.mailboxes = {}\n self.sync_mailboxes()\n self.messages = {}\n\n\n def get_messages_cached(self, properties=(), id__in=()):\n messages = []\n if not self.messages:\n return messages, id__in, properties\n fetch_props = set()\n fetch_ids = set(id__in)\n for id in id__in:\n msg = self.messages.get(id, None)\n if msg:\n found = True\n for prop in properties:\n try:\n msg[prop]\n except (KeyError, AttributeError):\n found = False\n fetch_props.add(prop)\n if found:\n fetch_ids.remove(id)\n messages.append(msg)\n # if one messages is missing, need to fetch all properties\n if len(messages) < len(id__in):\n fetch_props = properties\n return messages, fetch_ids, fetch_props\n\n\n def get_messages(self, properties=(), sort={}, inMailbox=None, inMailboxOtherThan=(), id__in=None, threadId__in=None, **criteria):\n # XXX: id == threadId for now\n if id__in is None and threadId__in is not None:\n id__in = [id[1:] for id in threadId__in]\n if id__in is None:\n messages = []\n else:\n # try get everything from cache\n messages, id__in, properties = self.get_messages_cached(properties, id__in=id__in)\n\n fetch_fields = {f for prop, f in FIELDS_MAP.items() if prop in properties}\n if 'RFC822' in fetch_fields:\n # remove redundand fields\n fetch_fields.discard('RFC822.HEADER')\n fetch_fields.discard('RFC822.SIZE')\n\n if inMailbox:\n mailbox = self.mailboxes.get(inMailbox, None)\n if not mailbox:\n raise errors.notFound(f'Mailbox {inMailbox} not found')\n mailboxes = [mailbox]\n elif inMailboxOtherThan:\n mailboxes = [m for m in self.mailboxes.values() if m['id'] not in inMailboxOtherThan]\n else:\n mailboxes = self.mailboxes.values()\n\n search_criteria = as_imap_search(criteria)\n sort_criteria = as_imap_sort(sort) or '' if sort else None\n\n mailbox_uids = {}\n if id__in is not None:\n if len(id__in) == 0:\n return messages # no messages matches empty ids\n if not fetch_fields and not sort_criteria:\n # when we don't need anything new from IMAP, create empty messages\n # useful when requested conditions can be calculated from id (threadId)\n messages.extend(self.messages.get(id, 0) or ImapMessage(id=id) for id in id__in)\n return messages\n \n for id in id__in:\n # TODO: check uidvalidity\n mailboxid, uidvalidity, uid = parse_message_id(id)\n uids = mailbox_uids.get(mailboxid, [])\n if not uids:\n mailbox_uids[mailboxid] = uids\n uids.append(uid)\n # filter out unnecessary mailboxes\n mailboxes = [m for m in mailboxes if m['id'] in mailbox_uids]\n\n for mailbox in mailboxes:\n imapname = mailbox['imapname']\n if self.selected_folder[0] != imapname:\n self.imap.select_folder(imapname, readonly=True)\n self.selected_folder = (imapname, True)\n\n uids = mailbox_uids.get(mailbox['id'], None)\n # uids are now None or not empty\n # fetch all\n if sort_criteria:\n if uids:\n search = f'{\",\".join(map(str, uids))} {search_criteria}'\n else:\n search = search_criteria or 'ALL'\n uids = self.imap.sort(sort_criteria, search)\n elif search_criteria:\n if uids:\n search = f'{\",\".join(map(str, uids))} {search_criteria}'\n uids = self.imap.search(search)\n if uids is None:\n uids = '1:*'\n fetch_fields.add('UID')\n fetches = self.imap.fetch(uids, fetch_fields)\n\n for uid, data in fetches.items():\n id = format_message_id(mailbox['id'], mailbox['uidvalidity'], uid)\n msg = self.messages.get(id, None)\n if not msg:\n msg = ImapMessage(id=id, mailboxIds=[mailbox['id']])\n self.messages[id] = msg\n for k, v in data.items():\n msg[k.decode()] = v\n messages.append(msg)\n return messages\n \n\n def changed_record(self, ifolderid, uid, flags=(), labels=()):\n res = self.dmaybeupdate('imessages', {\n 'flags': json.dumps(sorted(flags)),\n 'labels': json.dumps(sorted(labels)),\n }, {'ifolderid': ifolderid, 'uid': uid})\n if res:\n msgid = self.dgefield('imessages', {'ifolderid': ifolderid, 'uid': uid}, 'msgid')\n self.mark_sync(msgid)\n \n def import_message(self, rfc822, mailboxIds, keywords):\n folderdata = self.dget('ifolders')\n foldermap = {f['ifolderid']: f for f in folderdata}\n jmailmap = {f['jmailboxid']: f for f in folderdata if f.get('jmailboxid', False)}\n # store to the first named folder - we can use labels on gmail to add to other folders later.\n id, others = mailboxIds\n imapname = jmailmap[id][imapname]\n flags = set(keywords)\n for kw in flags:\n if kw in KEYWORD2FLAG:\n flags.remove(kw)\n flags.add(KEYWORD2FLAG[kw])\n appendres = self.imap.append('imapname', '(' + ' '.join(flags) + ')', datetime.now(), rfc822)\n # TODO: compare appendres[2] with uidvalidity\n uid = appendres[3]\n fdata = jmailmap[mailboxIds[0]]\n self.do_folder(fdata['ifolderid'], fdata['label'])\n ifolderid = fdata['ifolderid']\n msgdata = self.dgetone('imessages', {\n 'ifolderid': ifolderid,\n 'uid': uid,\n }, 'msgid,thrid,size')\n \n # XXX - did we fail to sync this back? Annoying\n if not msgdata:\n raise Exception('Failed to get back stored message from imap server')\n # save us having to download it again - drop out of transaction so we don't wait on the parse\n message = parse.parse(rfc822, msgdata['msgid'])\n self.begin()\n self.dinsert('jrawmessage', {\n 'msgid': msgdata['msgid'],\n 'parsed': json.dumps('message'),\n 'hasAttachment': message['hasattachment'],\n })\n self.commit()\n return msgdata\n \n def update_messages(self, changes, idmap):\n if not changes:\n return {}, {}\n \n changed = {}\n notchanged = {}\n map = {}\n msgids = set(changes.keys())\n sql = 'SELECT msgid,ifolderid,uid FROM imessages WHERE msgid IN (' + (('?,' * len(msgids))[:-1]) + ')'\n self.cursor.execute(sql, list(msgids))\n for msgid, ifolderid, uid in self.cursor:\n if not msgid in map:\n map[msgid] = {ifolderid: {uid}}\n elif not ifolderid in map[msgid]:\n map[msgid][ifolderid] = {uid}\n else:\n map[msgid][ifolderid].add(uid)\n msgids.discard(msgid)\n\n for msgid in msgids:\n notchanged[msgid] = {\n 'type': 'notFound',\n 'description': 'No such message on server',\n }\n \n folderdata = self.dget('ifolders')\n foldermap = {f['ifolderid']: f for f in folderdata}\n jmailmap = {f['jmailboxid']: f for f in folderdata if 'jmailboxid' in f}\n jmapdata = self.dget('jmailboxes')\n jidmap = {d['jmailboxid']: (d['role'] or '') for d in jmapdata}\n jrolemap = {d['role']: d['jmailboxid'] for d in jmapdata if 'role' in d}\n\n for msgid in map.keys():\n action = changes[msgid]\n try:\n for ifolderid, uids in map[msgid].items():\n # TODO: merge similar actions?\n imapname = foldermap[ifolderid]['imapname']\n uidvalidity = foldermap[ifolderid]['uidvalidity']\n if self.selected_folder != (imapname, False):\n self.imap.select_folder(imapname)\n self.selected_folder = (imapname, False)\n if imapname and uidvalidity and 'keywords' in action:\n flags = set(action['keywords'])\n for kw in flags:\n if kw in KEYWORD2FLAG:\n flags.remove(kw)\n flags.add(KEYWORD2FLAG[kw])\n self.imap.set_flags(uids, flags, silent=True)\n\n if 'mailboxIds' in action:\n mboxes = [idmap(k) for k in action['mailboxIds'].keys()]\n # existing ifolderids containing this message\n # identify a source message to work from\n ifolderid = sorted(map[msgid])[0]\n uid = sorted(map[msgid][ifolderid])[0]\n imapname = foldermap[ifolderid]['imapname']\n uidvalidity = foldermap[ifolderid]['uidvalidity']\n\n # existing ifolderids with this message\n current = set(map[msgid].keys())\n # new ifolderids that should contain this message\n new = set(jmailmap[x]['ifolderid'] for x in mboxes)\n for ifolderid in new:\n # unless there's already a matching message in it\n if current.pop(ifolderid):\n continue\n # copy from the existing message\n newfolder = foldermap[ifolderid]['imapname']\n self.imap.copy(imapname, uidvalidity, uid, newfolder)\n for ifolderid in current:\n # these ifolderids didn't exist in new, so delete all matching UIDs from these folders\n self.imap.move(\n foldermap[ifolderid]['imapname'],\n foldermap[ifolderid]['uidvalidity'],\n map[msgid][ifolderid], # uids\n )\n except Exception as e:\n notchanged[msgid] = {'type': 'error', 'description': str(e)}\n raise e\n else:\n changed[msgid] = None\n\n return changed, notchanged \n\n def destroy_messages(self, ids):\n if not ids:\n return [], {}\n destroymap = defaultdict(dict)\n notdestroyed = {}\n idset = set(ids)\n rows = self.dget('imessages', {'msgid': ('IN', idset)},\n 'msgid,ifolderid,uid')\n for msgid, ifolderid, uid in rows:\n idset.discard(msgid)\n destroymap[ifolderid][uid] = msgid\n for msgid in idset:\n notdestroyed[msgid] = {\n 'type': 'notFound',\n 'description': \"No such message on server\",\n }\n\n folderdata = self.dget('ifolders')\n foldermap = {d['ifolderid']: d for d in folderdata}\n jmailmap = {d['jmailboxid']: d for d in folderdata if 'jmailboxid' in d}\n destroyed = []\n for ifolderid, ifolder in destroymap.items():\n #TODO: merge similar actions?\n if not ifolder['imapname']:\n for msgid in destroymap[ifolderid]:\n notdestroyed[msgid] = \\\n {'type': 'notFound', 'description': \"No folder\"}\n self.imap.move(ifolder['imapname'], ifolder['uidvalidity'],\n destroymap[ifolderid].keys(), None)\n destroyed.extend(destroymap[ifolderid].values())\n\n return destroyed, notdestroyed\n \n def deleted_record(self, ifolderid, uid):\n msgid = self.dgetfield('imessages', {'ifolderid': ifolderid, 'uid': uid}, 'msgid')\n if msgid:\n self.ddelete('imessages', {'ifolderid': ifolderid, 'uid': uid})\n self.mark_sync(msgid)\n\n def get_raw_message(self, msgid, part=None):\n self.cursor.execute('SELECT imapname,uidvalidity,uid FROM ifolders JOIN imessages USING (ifolderid) WHERE msgid=?', [msgid])\n imapname, uidvalidity, uid = self.cursor.fetchone()\n if not imapname:\n return None\n typ = 'message/rfc822'\n if part:\n parsed = self.fill_messages([msgid])\n typ = find_type(parsed[msgid], part)\n\n\n res = self.imap.getpart(imapname, uidvalidity, uid, part)\n return typ, res['data']\n \n def get_mailboxes(self, fields=None, **criteria):\n byimapname = {}\n # TODO: LIST \"\" % RETURN (STATUS (UNSEEN MESSAGES HIGHESTMODSEQ MAILBOXID))\n for flags, sep, imapname in self.imap.list_folders():\n status = self.imap.folder_status(imapname, (['MESSAGES', 'UIDVALIDITY', 'UIDNEXT', 'HIGHESTMODSEQ', 'X-GUID']))\n flags = [f.lower() for f in flags]\n roles = [f for f in flags if f not in KNOWN_SPECIALS]\n label = roles[0].decode() if roles else imapname\n role = ROLE_MAP.get(label.lower(), None)\n can_select = b'\\\\noselect' not in flags\n byimapname[imapname] = {\n # Dovecot can fetch X-GUID\n 'id': status[b'X-GUID'].decode(),\n 'parentId': None,\n 'name': imapname,\n 'role': role,\n 'sortOrder': 2 if role else (1 if role == 'inbox' else 3),\n 'isSubscribed': True, # TODO: use LSUB\n 'totalEmails': status[b'MESSAGES'],\n 'unreadEmails': 0,\n 'totalThreads': 0,\n 'unreadThreads': 0,\n 'myRights': {\n 'mayReadItems': can_select,\n 'mayAddItems': can_select,\n 'mayRemoveItems': can_select,\n 'maySetSeen': can_select,\n 'maySetKeywords': can_select,\n 'mayCreateChild': True,\n 'mayRename': False if role else True,\n 'mayDelete': False if role else True,\n 'maySubmit': can_select,\n },\n 'imapname': imapname,\n 'sep': sep.decode(),\n 'uidvalidity': status[b'UIDVALIDITY'],\n 'uidnext': status[b'UIDNEXT'],\n # Data sync properties\n 'createdModSeq': status[b'UIDVALIDITY'], # TODO: persist\n 'updatedModSeq': status[b'UIDVALIDITY'], # TODO: from persistent storage\n 'updatedNotCountsModSeq': status[b'UIDVALIDITY'], # TODO: from persistent storage\n 'emailHighestModSeq': status[b'HIGHESTMODSEQ'],\n 'deleted': 0,\n }\n\n # set name and parentId for child folders\n for imapname, mailbox in byimapname.items():\n names = imapname.rsplit(mailbox['sep'], maxsplit=1)\n if len(names) == 2:\n mailbox['parentId'] = byimapname[names[0]]['id']\n mailbox['name'] = names[1]\n\n # update cache\n self.mailboxes = {mbox['id']: mbox for mbox in byimapname.values()}\n return byimapname.values()\n\n\n def sync_mailboxes(self):\n self.get_mailboxes()\n \n\n def mailbox_imapname(self, parentId, name):\n parent = self.mailboxes.get(parentId, None)\n if not parent:\n raise errors.notFound('parent folder not found')\n return parent['imapname'] + parent['sep'] + name\n\n\n def create_mailbox(self, name=None, parentId=None, isSubscribed=True, **kwargs):\n if not name:\n raise errors.invalidProperties('name is required')\n imapname = self.mailbox_imapname(parentId, name)\n # TODO: parse returned MAILBOXID\n try:\n res = self.imap.create_folder(imapname)\n except IMAPClientError as e:\n desc = str(e)\n if '[ALREADYEXISTS]' in desc:\n raise errors.invalidArguments(desc)\n except Exception:\n raise errors.serverFail(res.decode())\n\n if not isSubscribed:\n self.imap.unsubscribe_folder(imapname)\n\n status = self.imap.folder_status(imapname, ['UIDVALIDITY'])\n self.sync_mailboxes()\n return f\"f{status[b'UIDVALIDITY']}\"\n\n\n def update_mailbox(self, id, name=None, parentId=None, isSubscribed=None, sortOrder=None, **update):\n mailbox = self.mailboxes.get(id, None)\n if not mailbox:\n raise errors.notFound('mailbox not found')\n imapname = mailbox['imapname']\n\n if (name is not None and name != mailbox['name']) or \\\n (parentId is not None and parentId != mailbox['parentId']):\n if not name:\n raise errors.invalidProperties('name is required')\n newimapname = self.mailbox_imapname(parentId, name)\n res = self.imap.rename_folder(imapname, newimapname)\n if b'NO' in res or b'BAD' in res:\n raise errors.serverFail(res.encode())\n\n if isSubscribed is not None and isSubscribed != mailbox['isSubscribed']:\n if isSubscribed:\n res = self.imap.subscribe_folder(imapname)\n else:\n res = self.imap.unsubscribe_folder(imapname)\n if b'NO' in res or b'BAD' in res:\n raise errors.serverFail(res.encode())\n\n if sortOrder is not None and sortOrder != mailbox['sortOrder']:\n # TODO: update in persistent storage\n mailbox['sortOrder'] = sortOrder\n self.sync_mailboxes()\n\n\n def destroy_mailbox(self, id):\n mailbox = self.mailboxes.get(id, None)\n if not mailbox:\n raise errors.notFound('mailbox not found')\n res = self.imap.delete_folder(mailbox['imapname'])\n if b'NO' in res or b'BAD' in res:\n raise errors.serverFail(res.encode())\n mailbox['deleted'] = datetime.now().timestamp()\n self.sync_mailboxes()\n\n\n def create_submission(self, new, idmap):\n if not new:\n return {}, {}\n \n todo = {}\n createmap = {}\n notcreated = {}\n for cid, sub in new.items():\n msgid = idmap.get(sub['emailId'], sub['emailId'])\n if not msgid:\n notcreated[cid] = {'error': 'nos msgid provided'}\n continue\n thrid = self.dgetfield('jmessages', {'msgid': msgid, 'deleted': 0}, 'thrid')\n if not thrid:\n notcreated[cid] = {'error': 'message does not exist'}\n continue\n id = self.dmake('jsubmission', {\n 'sendat': datetime.fromisoformat()(sub['sendAt']).isoformat() if sub['sendAt'] else datetime.now().isoformat(),\n 'msgid': msgid,\n 'thrid': thrid,\n 'envelope': json.dumps(sub['envelope']) if 'envelope' in sub else None,\n })\n createmap[cid] = {'id': id}\n todo[cid] = msgid\n self.commit()\n\n for cid, sub in todo.items():\n type, rfc822 = self.get_raw_message(todo[cid])\n self.imap.send_mail(rfc822, sub['envelope'])\n\n return createmap, notcreated\n\n\n def update_submission(self, changed, idmap):\n return {}, {x: 'change not supported' for x in changed.keys()}\n\n\n def destroy_submission(self, destroy):\n if not destroy:\n return [], {}\n destroyed = []\n notdestroyed = {}\n namemap = {}\n for subid in destroy:\n deleted = self.dgetfield('jsubmission', {'jsubid': subid}, 'deleted')\n if deleted:\n destroy.append(subid)\n self.ddelete('jsubmission', {'jsubid': subid})\n else:\n notdestroyed[subid] = {'type': 'notFound', 'description': 'submission not found'}\n self.commit()\n return destroyed, notdestroyed\n \n def _initdb(self):\n super()._initdb()\n\n self.dbh.execute(\"\"\"\n CREATE TABLE IF NOT EXISTS ifolders (\n ifolderid INTEGER PRIMARY KEY NOT NULL,\n jmailboxid INTEGER,\n sep TEXT NOT NULL,\n imapname TEXT NOT NULL,\n label TEXT,\n uidvalidity INTEGER,\n uidfirst INTEGER,\n uidnext INTEGER,\n highestmodseq INTEGER,\n uniqueid TEXT,\n mtime DATE NOT NULL\n )\"\"\")\n self.dbh.execute(\"CREATE INDEX IF NOT EXISTS ifolderj ON ifolders (jmailboxid)\");\n self.dbh.execute(\"CREATE INDEX IF NOT EXISTS ifolderlabel ON ifolders (label)\");\n\n self.dbh.execute(\"\"\"\n CREATE TABLE IF NOT EXISTS imessages (\n imessageid INTEGER PRIMARY KEY NOT NULL,\n ifolderid INTEGER,\n uid INTEGER,\n internaldate DATE,\n modseq INTEGER,\n flags TEXT,\n labels TEXT,\n thrid TEXT,\n msgid TEXT,\n envelope TEXT,\n bodystructure TEXT,\n size INTEGER,\n mtime DATE NOT NULL\n )\"\"\")\n self.dbh.execute(\"CREATE UNIQUE INDEX IF NOT EXISTS imsgfrom ON imessages (ifolderid, uid)\");\n self.dbh.execute(\"CREATE INDEX IF NOT EXISTS imessageid ON imessages (msgid)\");\n self.dbh.execute(\"CREATE INDEX IF NOT EXISTS imessagethrid ON imessages (thrid)\");\n\n self.dbh.execute(\"\"\"\n CREATE TABLE IF NOT EXISTS ithread (\n messageid TEXT PRIMARY KEY,\n sortsubject TEXT,\n thrid TEXT\n )\"\"\")\n self.dbh.execute(\"CREATE INDEX IF NOT EXISTS ithrid ON ithread (thrid)\");\n\n\nSORT_MAP = {\n 'receivedAt': 'ARRIVAL',\n 'sentAt': 'DATE',\n 'size': 'SIZE',\n 'subject': 'SUBJECT',\n 'from': 'FROM',\n 'to': 'TO',\n 'cc': 'CC',\n}\n\ndef as_imap_sort(sort):\n criteria = []\n for crit in sort:\n if not crit.get('isAscending', True):\n criteria.append('REVERSE')\n try:\n criteria.append(SORT_MAP[crit['property']])\n except KeyError:\n raise errors.unsupportedSort(f\"Property {crit['property']} is not sortable\")\n return criteria\n\nSEARCH_MAP = {\n 'blobId': 'X-GUID',\n 'minSize': 'NOT SMALLER',\n 'maxSize': 'NOT LARGER',\n 'hasKeyword': 'KEYWORD',\n 'notKeyword': 'UNKEYWORD',\n 'before': 'BEFORE',\n 'after': 'AFTER',\n 'subject': 'SUBJECT',\n 'text': 'TEXT',\n 'body': 'BODY',\n 'from': 'FROM',\n 'to': 'TO',\n 'cc': 'CC',\n 'bcc': 'BCC',\n}\n\ndef as_imap_search(criteria):\n operator = criteria.get('operator', None)\n if operator:\n conds = criteria['conds']\n if operator == 'NOT' or operator == 'OR':\n if len(conds) > 0:\n out = []\n if operator == 'NOT':\n out.append('NOT')\n for cond in conds:\n out.append('OR')\n out.append(as_imap_search(cond))\n # OR needs 2 args, we can delete last OR\n del out[-3]\n return ' '.join(out)\n else:\n raise errors.unsupportedFilter(f\"Empty filter conditions\")\n elif operator == 'AND':\n return ' '.join([as_imap_search(c) for c in conds])\n raise errors.unsupportedFilter(f\"Invalid operator {operator}\")\n\n out = []\n\n if 'header' in criteria:\n out.append('HEADER')\n criteria = dict(criteria) # make a copy\n out.extend(criteria.pop('header'))\n\n for crit, value in criteria.items():\n try:\n out.append(SEARCH_MAP[crit])\n out.append(value)\n except KeyError:\n raise UserWarning(f'Filter {crit} not supported')\n\n return ' '.join(out)\n\n\ndef find_type(message, part):\n if message.get('id', '') == part:\n return message['type']\n \n for sub in message['attachments']:\n typ = find_type(sub, part)\n if type:\n return type\n return None\n\n\ndef _normalsubject(subject):\n # Re: and friends\n subject = re.sub(r'^[ \\t]*[A-Za-z0-9]+:', subject, '')\n # [LISTNAME] and friends\n sub = re.sub(r'^[ \\t]*\\\\[[^]]+\\\\]', subject, '')\n # any old whitespace\n sub = re.sub(r'[ \\t\\r\\n]+', subject, '')\n\n\n# ALPHABET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz-_.~\"\nALPHABET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+_.~\"\ndef base_encode(n: int, b: int = 64, a=ALPHABET):\n if not n:\n return a[0]\n s = ''\n dm = divmod # Access to locals is faster.\n while n:\n n, r = dm(n, b)\n s = a[r] + s\n return s\n\nALPHABET_DICT = {c: v for v, c in enumerate(ALPHABET)}\ndef base_decode(s:str, b:int=64, d=ALPHABET_DICT):\n n = 0\n for c in s:\n n = n * b + d[c]\n return n\n","sub_path":"jmap/db/imap.py","file_name":"imap.py","file_ext":"py","file_size_in_byte":32384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"96853126","text":"import demistomock as demisto # noqa: F401\nfrom CommonServerPython import * # noqa: F401\n\n\ndef main():\n list_data = demisto.executeCommand(\"getList\", {\"listName\": \"XSOAR Health - Error Entries ID\"})\n list_content = list_data[0].get('Contents', '').split(\",\")\n entries_id_errors_count = len(list_content)\n\n if list_content == ['']:\n demisto.results(0)\n\n else:\n demisto.results(entries_id_errors_count)\n\n\nif __name__ in [\"__main__\", \"builtin\", \"builtins\"]:\n main()\n","sub_path":"Packs/IntegrationsAndIncidentsHealthCheck/Scripts/IncidentsCheck_Widget_NumberofErrors/IncidentsCheck_Widget_NumberofErrors.py","file_name":"IncidentsCheck_Widget_NumberofErrors.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"635439682","text":"# -*- coding: utf-8 -*-\nfrom DateTime import DateTime\nfrom datetime import datetime\nfrom plone.app.textfield.interfaces import IRichText\nfrom plone.app.textfield.value import RichTextValue\nfrom plone.namedfile.interfaces import INamedField\nfrom plone.supermodel.interfaces import IToUnicode\nfrom Products.CMFPlone.utils import safe_unicode\nfrom six import string_types\nfrom transmogrify.dexterity.interfaces import IDeserializer\nfrom transmogrify.dexterity.interfaces import ISerializer\nfrom zope.component import adapter\nfrom zope.component import queryUtility\nfrom zope.dottedname.resolve import resolve\nfrom zope.interface import implementer\nfrom zope.schema.interfaces import ICollection\nfrom zope.schema.interfaces import IDate\nfrom zope.schema.interfaces import IDatetime\nfrom zope.schema.interfaces import IField\nfrom zope.schema.interfaces import IFromUnicode\nfrom zope.schema.interfaces import IObject\nimport base64\nimport mimetypes\nimport pkg_resources\n\n\ntry:\n pkg_resources.get_distribution('plone.app.intid')\nexcept pkg_resources.DistributionNotFound:\n INTID_AVAILABLE = False\nelse:\n INTID_AVAILABLE = True\n from zope.intid.interfaces import IIntIds\n\ntry:\n pkg_resources.get_distribution('z3c.relationfield')\nexcept:\n RELATIONFIELD_AVAILABLE = False\nelse:\n RELATIONFIELD_AVAILABLE = True\n from z3c.relationfield.interfaces import IRelation\n from z3c.relationfield.interfaces import IRelationList\n from z3c.relationfield.relation import RelationValue\n\n\ndef get_site_encoding():\n # getSiteEncoding was in plone.app.textfield.utils but is not gone. Like\n # ``Products.CMFPlone.browser.ploneview``, it always returned 'utf-8',\n # something we can do ourselves here.\n # TODO: use some sane getSiteEncoding from CMFPlone, once there is one.\n return 'utf-8'\n\n\n@implementer(ISerializer)\n@adapter(INamedField)\nclass NamedFileSerializer(object):\n\n def __init__(self, field):\n self.field = field\n\n def __call__(self, value, filestore, extra=None):\n if extra is None:\n extra = ''\n else:\n extra = '_%s' % extra\n fieldname = self.field.__name__\n if hasattr(value, 'open'):\n data = value.open().read()\n else:\n data = value.data\n name = '_field_%s%s_%s' % (fieldname, extra, value.filename)\n filestore[name] = dict(\n data=data,\n name=name,\n contenttype=value.contentType\n )\n return dict(\n file=name,\n filename=value.filename,\n contenttype=value.contentType\n )\n\n\n@implementer(IDeserializer)\n@adapter(INamedField)\nclass NamedFileDeserializer(object):\n\n def __init__(self, field):\n self.field = field\n\n def __call__(self, value, filestore, item,\n disable_constraints=False, logger=None):\n if isinstance(value, dict):\n filename = value.get('filename', None)\n contenttype = str(value.get('contenttype', ''))\n if not contenttype:\n # like in jsonify\n contenttype = str(value.get('content_type', ''))\n file = value.get('file', None)\n if file is not None:\n data = filestore[file]['data']\n else:\n if value.get('encoding', None) == 'base64':\n # collective.jsonify encodes base64\n data = base64.b64decode(value['data'])\n else:\n data = value['data']\n\n elif isinstance(value, str):\n data = value\n filename = item.get('_filename', None)\n contenttype = ''\n else:\n raise ValueError('Unable to convert to named file')\n if isinstance(filename, str):\n filename = safe_unicode(filename)\n instance = self.field._type(\n data=data,\n filename=filename,\n contentType=contenttype,\n )\n try:\n self.field.validate(instance)\n except Exception as e:\n if not disable_constraints:\n raise e\n else:\n if logger:\n logger(\n \"%s is invalid in %s: %s\" % (\n self.field.__name__,\n item['_path'],\n e)\n )\n return instance\n\n\n@implementer(ISerializer)\n@adapter(IRichText)\nclass RichTextSerializer(object):\n\n def __init__(self, field):\n self.field = field\n\n def __call__(self, value, filestore, extra=None):\n if extra is None:\n extra = ''\n else:\n extra = '_%s' % extra\n extension = mimetypes.guess_extension(value.mimeType) or ''\n fieldname = self.field.__name__\n name = '_field_%s%s%s' % (fieldname, extra, extension)\n filestore[name] = dict(\n data=value.raw_encoded,\n name=name,\n contenttype=value.mimeType\n )\n return dict(\n file=name,\n contenttype=value.mimeType,\n encoding=value.encoding\n )\n\n\n@implementer(IDeserializer)\n@adapter(IRichText)\nclass RichTextDeserializer(object):\n _type = RichTextValue\n\n def __init__(self, field):\n self.field = field\n\n def _convert_object(self, obj, encoding):\n \"\"\"Decode binary strings into unicode objects\n \"\"\"\n return safe_unicode(obj)\n\n def __call__(self, value, filestore, item,\n disable_constraints=False, logger=None):\n if isinstance(value, dict):\n encoding = value.get('encoding', get_site_encoding())\n contenttype = value.get('contenttype', None)\n if contenttype is not None:\n contenttype = str(contenttype)\n file = value.get('file', None)\n if file is not None:\n data = self._convert_object(filestore[file]['data'], encoding)\n else:\n data = self._convert_object(value['data'], encoding)\n else:\n encoding = get_site_encoding()\n data = self._convert_object(value, encoding)\n contenttype = None\n if contenttype is None:\n contenttype = self.field.default_mime_type\n instance = self._type(\n raw=data,\n mimeType=contenttype,\n outputMimeType=self.field.output_mime_type,\n encoding=encoding,\n )\n try:\n self.field.validate(instance)\n except Exception as e:\n if not disable_constraints:\n raise e\n else:\n if logger:\n logger(\n \"%s is invalid in %s: %s\" % (\n self.field.__name__,\n item['_path'],\n e)\n )\n return instance\n\n\n@implementer(ISerializer)\n@adapter(IObject)\nclass ObjectSerializer(object):\n\n def __init__(self, field):\n self.field = field\n\n def __call__(self, value, filestore, extra=''):\n out = {\"_class\": \"%s.%s\" % (\n value.__class__.__module__,\n value.__class__.__name__,\n )}\n for k in self.field.schema:\n serializer = ISerializer(self.field.schema[k])\n out[k] = serializer(getattr(value, k), filestore, extra + k)\n return out\n\n\n@implementer(IDeserializer)\n@adapter(IObject)\nclass ObjectDeserializer(object):\n\n def __init__(self, field):\n self.field = field\n\n def __call__(self, value, filestore, item,\n disable_constraints=False, logger=None):\n if not isinstance(value, dict):\n raise ValueError('Need a dict to convert')\n if not value.get('_class', None):\n try:\n # NB: datagridfield creates it's own Serializer, but falls\n # back to this Deserializer. _class will be missing in this\n # case.\n from collective.z3cform.datagridfield.row import DictRow\n if isinstance(self.field, DictRow):\n # NB: Should be recursing into the dict and deserializing,\n # but that can be fixed within datagridfield\n return DefaultDeserializer(self.field)(\n value,\n filestore,\n item,\n disable_constraints=disable_constraints,\n logger=logger,\n )\n except ImportError:\n pass\n raise ValueError(\"_class is missing\")\n\n # Import _class and create instance, if it implments what we need\n klass = resolve(value['_class'])\n if not self.field.schema.implementedBy(klass):\n raise ValueError('%s does not implemement %s' % (\n value['_class'],\n self.field.schema,\n ))\n instance = klass()\n\n # Add each key from value to instance\n for (k, v) in value.items():\n if k == '_class':\n continue\n if not hasattr(instance, k):\n raise ValueError(\"%s is not an object attribute\" % k)\n if v is None:\n setattr(instance, k, None)\n continue\n\n if k in self.field.schema:\n deserializer = IDeserializer(self.field.schema[k])\n else:\n deserializer = DefaultDeserializer(None)\n setattr(instance, k, deserializer(\n v,\n filestore,\n item,\n disable_constraints=disable_constraints,\n logger=logger,\n ))\n\n if not disable_constraints:\n self.field.validate(instance)\n return instance\n\n\n@implementer(ISerializer)\n@adapter(ICollection)\nclass CollectionSerializer(object):\n\n def __init__(self, field):\n self.field = field\n\n def __call__(self, value, filestore, extra=None):\n field = self.field\n if field.value_type is not None:\n serializer = ISerializer(self.field.value_type)\n else:\n serializer = DefaultSerializer()\n return [serializer(v, filestore, str(i)) for i, v in enumerate(value)]\n\n\n@implementer(IDeserializer)\n@adapter(ICollection)\nclass CollectionDeserializer(object):\n\n def __init__(self, field):\n self.field = field\n\n def __call__(self, value, filestore, item,\n disable_constraints=False, logger=None):\n field = self.field\n if value in (None, ''):\n return []\n if isinstance(value, string_types):\n value = [v for v in (v.strip() for v in value.split(';')) if v]\n if field.value_type is not None:\n deserializer = IDeserializer(self.field.value_type)\n else:\n deserializer = DefaultDeserializer(None)\n value = [deserializer(\n v, filestore, item, disable_constraints, logger=logger)\n for v in value]\n value = field._type(value)\n try:\n self.field.validate(value)\n except Exception as e:\n if not disable_constraints:\n raise e\n else:\n if logger:\n logger(\n \"%s is invalid in %s: %s\" % (\n self.field.__name__,\n item['_path'],\n e)\n )\n return value\n\n\n@implementer(IDeserializer)\n@adapter(IDate)\nclass DateDeserializer(object):\n\n def __init__(self, field):\n self.field = field\n\n def __call__(self, value, filestore, item,\n disable_constraints=False, logger=None):\n if isinstance(value, string_types):\n if value in ('', 'None'):\n value = None\n else:\n value = DateTime(value).asdatetime().date()\n if isinstance(value, datetime):\n value = value.date()\n try:\n self.field.validate(value)\n except Exception as e:\n if not disable_constraints:\n raise e\n else:\n if logger:\n logger(\n \"%s is invalid in %s: %s\" % (\n self.field.__name__,\n item['_path'],\n e)\n )\n return value\n\n\n@implementer(IDeserializer)\n@adapter(IDatetime)\nclass DatetimeDeserializer(object):\n\n def __init__(self, field):\n self.field = field\n\n def __call__(self, value, filestore, item,\n disable_constraints=False, logger=None):\n if isinstance(value, string_types):\n if value in ('', 'None'):\n value = None\n else:\n value = DateTime(value).asdatetime()\n try:\n self.field.validate(value)\n except Exception as e:\n if not disable_constraints:\n raise e\n else:\n if logger:\n logger(\n \"%s is invalid in %s: %s\" % (\n self.field.__name__,\n item['_path'],\n e)\n )\n return value\n\n\n@implementer(ISerializer)\n@adapter(IField)\nclass DefaultSerializer(object):\n\n def __init__(self, field=None):\n self.field = field\n\n def __call__(self, value, filestore, extra=None):\n BASIC_TYPES = (unicode, int, long, float, bool, type(None))\n if type(value) in BASIC_TYPES:\n pass\n elif self.field is not None:\n value = IToUnicode(self.field).toUnicode(value)\n else:\n raise ValueError('Unable to serialize field value')\n return value\n\n\n@implementer(IDeserializer)\n@adapter(IField)\nclass DefaultDeserializer(object):\n\n def __init__(self, field):\n self.field = field\n\n def __call__(self, value, filestore, item,\n disable_constraints=False, logger=None):\n field = self.field\n if field is not None:\n try:\n if isinstance(value, str):\n value = safe_unicode(value)\n if str(type(value)) == \"\":\n value = IFromUnicode(field).fromUnicode(value)\n self.field.validate(value)\n except Exception as e:\n if not disable_constraints:\n raise e\n else:\n if logger:\n logger(\n \"%s is invalid in %s: %s\" % (\n self.field.__name__,\n item['_path'],\n e.__repr__())\n )\n return value\n\n\nif INTID_AVAILABLE and RELATIONFIELD_AVAILABLE:\n @implementer(IDeserializer)\n @adapter(IRelation)\n class RelationDeserializer(object):\n\n default_value = None\n\n def __init__(self, field):\n self.field = field\n\n def __call__(self, value, filestore, item,\n disable_constraints=False, logger=None):\n field = self.field\n if field is None:\n return None\n\n if not value:\n return self.default_value\n\n self.intids = queryUtility(IIntIds)\n if self.intids is None:\n return value\n\n return self.deserialize(value)\n\n def deserialize(self, value):\n int_id = self.intids.queryId(value)\n if int_id is None:\n return value\n\n return RelationValue(int_id)\n\n\n @implementer(IDeserializer)\n @adapter(IRelationList)\n class RelationListDeserializer(RelationDeserializer):\n\n default_value = []\n\n def deserialize(self, value):\n result = []\n for obj in value:\n result.append(\n super(RelationListDeserializer, self).deserialize(obj))\n return result\n","sub_path":"transmogrify/dexterity/converters.py","file_name":"converters.py","file_ext":"py","file_size_in_byte":16115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"558906526","text":"#!/usr/bin/env python\n\"\"\"\ngiven label stats, and the label list,\n\nwrite another label list, vocab.txt.stat.txt,\n\notherthan the top-10 labels, the rest is changed to BG\nfor the top-10, label (%)\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n__author__ = \"Raingo Lee (raingomm@gmail.com)\"\n\nimport sys\nimport os.path as osp\n\ndef load_list(path):\n res = []\n with open(path) as reader:\n for line in reader:\n res.append(line.strip())\n return res\n\ndef main():\n stats_raw = [line.split() for line in load_list(sys.argv[1])]\n stats = sorted([(int(f[0]), ' '.join(f[1:])) for f in stats_raw])\n stats = {l:c for c, l in stats[-10:]}\n\n vocab = load_list(sys.argv[2])\n total = int(sys.argv[3])\n\n with open(sys.argv[2]+'.stat.txt', 'w') as writer:\n for l in vocab:\n if l in stats:\n print('%s (%.0f%%)' % (l, stats[l]/total*100), file=writer)\n stats.pop(l)\n else:\n print(\"BG\", file=writer)\n print(stats.keys(), sys.argv[2])\n\nif __name__ == \"__main__\":\n main()\n\n# vim: tabstop=4 expandtab shiftwidth=2 softtabstop=2\n","sub_path":"improving pairwise ranking/raingo-ur-mll-tf-deb52c763ed1/datasets/stat-vocab.py","file_name":"stat-vocab.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"289192386","text":"import numpy as np\nimport numpy.polynomial.legendre as leg\nimport gsh_hex_tri_L0_16 as gsh\nimport db_functions as fn\nimport h5py\nimport time\n\n\na = 0.0050\nb = 0.0085\nN_p = 215 # number of GSH bases to evaluate\nN_q = 21 # number of cosine bases to evaluate\nN_r = 10 # number of legendre bases to evaluate\nL_th = (2.*np.pi)/3.\nfilename = 'Xcalc_log.txt'\n\n\"\"\" Load info from collected simulation info file \"\"\"\n\nf = h5py.File('var_extract_total.hdf5', 'r')\nvar_set = f.get('var_set')\n\ntheta = var_set[:, 0]\n\nX = np.zeros((theta.size, 3), dtype='float64')\nX[:, 0] = var_set[:, 1] # phi1\nX[:, 1] = var_set[:, 2] # phi\nX[:, 2] = var_set[:, 3] # phi2\n\net_norm = var_set[:, 4]\n\nf.close\n\n\nf = h5py.File('X_parts.hdf5', 'a')\n\n\"\"\" first evalute the GSH basis functions \"\"\"\n\nst = time.time()\n\nfor p in xrange(N_p):\n\n vec = gsh.gsh(X, [p])\n\n set_id = 'p_%s' % p\n f.create_dataset(set_id, data=vec)\n\nmsg = \"GSH basis evaluation complete: %ss\" % np.round(time.time()-st, 3)\nfn.WP(msg, filename)\n\n\"\"\" second evalute the cosine basis functions \"\"\"\n\nst = time.time()\n\nfor q in xrange(N_q):\n\n vec = np.cos(2.*np.pi*q*theta/L_th)\n\n set_id = 'q_%s' % q\n f.create_dataset(set_id, data=vec)\n\nmsg = \"Cosine basis evaluation complete: %ss\" % np.round(time.time()-st, 3)\nfn.WP(msg, filename)\n\n\"\"\" third evalute the legendre basis functions \"\"\"\n\nst = time.time()\n\nfor r in xrange(N_r):\n\n r_vec = np.zeros(r+1)\n r_vec[r] = 1\n\n vec = leg.legval(fn.real2comm(et_norm, a, b), r_vec)\n\n set_id = 'r_%s' % r\n f.create_dataset(set_id, data=vec)\n\nmsg = \"Legendre basis evaluation complete: %ss\" % np.round(time.time()-st, 3)\nfn.WP(msg, filename)\n\nf.close()\n","sub_path":"fip_collab/2015_12_21_gsh_database_codes/Xcalc.py","file_name":"Xcalc.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"68532524","text":"import numpy as np\nimport seaborn as sns\nfrom sklearn.preprocessing import MinMaxScaler\nsns.set(color_codes=True)\nimport pandas as pd\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import classification_report\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.metrics import accuracy_score\nimport time\nimport constant\n\ndef NotScaleKNN():\n file = open(constant.Car_Not_Scale_KNN,\"w\")\n start_time = time.time()\n classifier = KNeighborsClassifier(n_neighbors=9)\n classifier.fit(X_train, y_train)\n y_pred = classifier.predict(X_test)\n end_time = time.time()\n file.write(\"------Confusion Matrix------\\n\"+np.array2string(confusion_matrix(y_test, y_pred), separator=', '))\n file.write(\"\\n\\n------Report------\\n\"+classification_report(y_test, y_pred))\n file.write('\\n\\n-------------\\n* Accuracy is: '+ accuracy_score(y_pred, y_test).__str__())\n file.write(\"\\n\\n* Running time: %.2f (s)\" % (end_time - start_time))\n\ndef ScaleKNN():\n file = open(constant.Car_Scale_KNN,\"w\")\n scaler = MinMaxScaler((-1,1))\n X_train_scaled = scaler.fit_transform(X_train)\n X_test_scaled = scaler.transform(X_test)\n start_time = time.time()\n classifier = KNeighborsClassifier(n_neighbors=9)\n classifier.fit(X_train_scaled, y_train)\n y_pred = classifier.predict(X_test_scaled)\n end_time = time.time()\n file.write(\"------Confusion Matrix------\\n\"+np.array2string(confusion_matrix(y_test, y_pred), separator=', '))\n file.write(\"\\n\\n------Report------\\n\"+classification_report(y_test, y_pred))\n file.write('\\n\\n-------------\\n* Accuracy is: '+ accuracy_score(y_pred, y_test).__str__())\n file.write(\"\\n\\n* Running time: %.2f (s)\" % (end_time - start_time))\nif __name__ == \"__main__\":\n dataTrain = pd.read_csv('../dataset/car/carTrain.csv')\n dataTest = pd.read_csv('../dataset/car/carTest.csv')\n X_train = dataTrain.iloc[:, :-1].values # tach data\n y_train = dataTrain.iloc[:, -1].values # tach nhan\n X_test = dataTest.iloc[:, :-1].values\n y_test = dataTest.iloc[:, -1].values\n NotScaleKNN()\n ScaleKNN()\n","sub_path":"car/KNN.py","file_name":"KNN.py","file_ext":"py","file_size_in_byte":2096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"279092902","text":"#Create similarity dictionary\n#which will be used in \n#device_kmeans.py\nimport random\nimport math\nimport json\n\n#Load the device_bit_vectors dictionary\n'''\n { \"device_id\" : \"1001011101...\",\n \"device_id2\": \"0010011101...\" }\n'''\nd = open('./output_txt_files/device_input_vectors.txt', 'r')\ndevice_ids = json.load(d)\n\n#Calculate the cosine similarity\n#i.e. euclidean dot product\ndef cosine_similarity(a, b):\n #Calculating the numerator\n\tnumerator = difference(a,b)\t\t \n\tsum_a = str(bin(a)).count('1')\n\tsum_b = str(bin(b)).count('1')\n\t#Calculating the denominator \n\tdenominator = math.sqrt(sum_a) * math.sqrt(sum_b)\n\n\treturn numerator/float(denominator)\n\n\ndef difference(bin_a, bin_b):\n\t#logical AND\n\tresult = bin(bin_a & bin_b)\n\t#count 1s \n\treturn str(result).count('1')\n\n","sub_path":"clustering/device_to_device/cosine_similarity/cosine_similarity_fast.py","file_name":"cosine_similarity_fast.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"174265928","text":"\nclass Node:\n\n def __init__(self, value=\"\"):\n self.value = value\n self.next = None\n\n def __str__(self):\n return str(self.value)\n\nclass LinkedList():\n def __init__(self):\n self.head = None\n\n def insert(self, value):\n node = Node(value)\n if self.head:\n node.next = self.head\n self.head = node\n\n def includes(self,vlaue):\n current=self.head\n while current :\n print(current.value)\n if vlaue ==current.value:\n return True\n current=current.next\n\n return False\n\n def __str__(self):\n string = \"\"\n current = self.head\n\n while current:\n string += f\"{str(current.value)} -> \"\n current = current.next\n string += \"None\"\n return string\n\n def __repr__(self):\n return \"LinkedList()\"\n\nif __name__ == \"__main__\":\n test = LinkedList()\n test.insert(10)\n test.insert(9)\n test.insert(8)\n test.insert(7)\n test.insert(6)\n\n\n print(test.includes(5))\n print('**********')\n print(test.includes(7))\n","sub_path":"python/linked_list/linked.py","file_name":"linked.py","file_ext":"py","file_size_in_byte":987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"141460712","text":"import datetime\nimport re\n\nfrom django.contrib.auth import get_user_model\nfrom django.core.exceptions import ValidationError\n\nfrom tunga.settings import UPLOAD_SIZE_LIMIT_MBS\nfrom tunga_utils.bitcoin_utils import is_valid_btc_address\nfrom tunga.free_emails import FREE_EMAILS\n\n\ndef validate_username(value):\n if get_user_model().objects.filter(username__iexact=value).count():\n raise ValidationError('This username is already associated with a Tunga account')\n\n\ndef validate_email(value):\n if get_user_model().objects.filter(email__iexact=value).count():\n raise ValidationError('This email is already associated with a Tunga account')\n\n\ndef validate_year(value):\n this_year = datetime.date.today().year\n min_year = this_year - 80\n if value < min_year:\n raise ValidationError('Year should be after %s' % min_year)\n if value > this_year:\n raise ValidationError('Year should not be after %s' % this_year)\n\n\ndef validate_btc_address(value):\n error_msg = 'Invalid Bitcoin address.'\n if re.match(r\"[a-zA-Z1-9]{27,35}$\", value) is None:\n raise ValidationError(error_msg)\n if not is_valid_btc_address(value):\n raise ValidationError(error_msg)\n\n\ndef validate_btc_address_or_none(value):\n error_msg = 'Invalid Bitcoin address.'\n if value is not None and re.match(r\"[a-zA-Z1-9]{27,35}$\", value) is None:\n raise ValidationError(error_msg)\n if value is not None and not is_valid_btc_address(value):\n raise ValidationError(error_msg)\n\n\ndef validate_file_size(value):\n if value.size > UPLOAD_SIZE_LIMIT_MBS:\n raise ValidationError('File is too large, uploads must not exceed 5 MB.')\n\n\ndef validate_field_schema(required_fields_schema, data, raise_exception=True):\n \"\"\"\n Validate required data based on schema\n :param required_fields_schema:\n :param data:\n :param raise_exception:\n :return:\n \"\"\"\n # TODO: Document validation schema format\n errors = dict()\n\n for field_item in required_fields_schema:\n if type(field_item) in [tuple, list]:\n field_name = field_item[0]\n field_value = data.get(field_name, None)\n field_validator = len(field_item) > 1 and field_item[1] or None\n is_validation_field_value = (type(field_validator) in [tuple, list] and field_value in field_validator) or \\\n (type(field_validator) not in [tuple, list] and field_value is not None)\n\n if not is_validation_field_value:\n errors[field_name] = field_value is None and 'This field is required.' or 'Invalid value \"{}\"'.format(field_value)\n\n if len(field_item) > 2:\n conditional_field_items = field_item[2]\n if type(conditional_field_items) in [tuple, list]:\n for conditional_field_item in conditional_field_items:\n\n if type(conditional_field_item) in [tuple, list]:\n conditional_field_validator = conditional_field_item[0]\n if (conditional_field_validator is None and not is_validation_field_value) or \\\n (type(conditional_field_validator) in [tuple, list] and field_value in conditional_field_validator) or \\\n (conditional_field_validator is not None and conditional_field_validator == field_value):\n final_conditional_field_item = list(conditional_field_item)[1:]\n errors.update(validate_field_schema([final_conditional_field_item], data, raise_exception=False))\n else:\n errors.update(validate_field_schema([conditional_field_item], data, raise_exception=False))\n else:\n errors.update(validate_field_schema([conditional_field_items], data, raise_exception=False))\n\n else:\n if not data.get(field_item, None):\n errors[field_item] = 'This field is required.'\n if errors and raise_exception:\n raise ValidationError(errors)\n return errors\n\n\ndef is_business_email(email):\n domain = re.search(\"@[\\w.]+\", email)\n try:\n domain_str = domain.group()[1:]\n return not domain_str in FREE_EMAILS\n except:\n return False\n","sub_path":"tunga_utils/validators.py","file_name":"validators.py","file_ext":"py","file_size_in_byte":4330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"575871383","text":"from __future__ import print_function # Python 2/3 compatibility\nimport boto3\nimport json\nimport decimal\n\n#dynamodb = boto3.resource('dynamodb', region_name='us-east-1', endpoint_url=\"http://localhost:8000\")\ndynamodb = boto3.resource('dynamodb', region_name='us-east-1')\n\ntable = dynamodb.Table('goals')\n\nwith open(\"files/goaldata.json\") as json_file:\n goals = json.load(json_file, parse_float = decimal.Decimal)\n for goal in goals:\n goalname = goal['goalname']\n userid = goal['userid']\n description = goal['description']\n target = goal['target']\n actual = goal['actual']\n\n print(\"Adding goal:\", goalname, userid)\n\n table.put_item(\n Item={\n 'goalname': goalname,\n 'userid': userid,\n 'description': description,\n 'target': target,\n 'actual': actual\n }\n )\n","sub_path":"loadGoalData.py","file_name":"loadGoalData.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"419761529","text":"# Dawei Li, 001022014\n\nfrom datetime import timedelta\nfrom datetime import datetime\nimport packages.data as data\nfrom .hash_table import MyHashTable\n\n\nclass Truck(object):\n def __init__(self, max_load=16):\n self.loads = MyHashTable(max_load)\n self.package_count = 0\n # Trucks travel at an average speed of 18 miles per hour.\n self.speed = 18\n self.curr_time = None\n \n def load_truck(self, package_id, package_values):\n \"\"\"Load the truck with packages\"\"\"\n # Load a package into the truck\n self.loads.add(package_id, package_values)\n self.package_count += 1\n\n def deliver(self, start_time, start_location):\n \"\"\"Deliver packages using a greedy algorithm.\"\"\"\n # Set the status of each packate to \"on route\"\n # Add an attribute \"on route time\"\n self.set_on_route(start_time)\n\n travel_distance = 0\n curr_location = start_location\n self.curr_time = start_time\n # Get all undelivered package IDs.\n undelivered = self.get_undelivered_packages_id()\n while len(undelivered) > 0:\n # Initialize the package whose location is \n # the closest to the current location.\n min_id = undelivered[0]\n min_location = self.get_location(min_id)\n min_distance = data.distance_data.get((curr_location, min_location))\n if min_distance is None:\n min_distance = data.distance_data.get((min_location, curr_location))\n # Iterate through the undelivered packages to find the package \n # whose location is the closest to the current location.\n for i in range(1, len(undelivered)):\n id = undelivered[i]\n location = self.get_location(id)\n distance = data.distance_data.get((curr_location, location))\n if distance is None:\n distance = data.distance_data.get((location, curr_location))\n if distance < min_distance:\n min_id = id\n min_location = location\n min_distance = distance\n \n # Increment travel distance.\n travel_distance += min_distance\n # Set the current location to the location of the chosen package.\n curr_location = min_location\n # Change the status of the chosen package to \"delivered\", \n # and add its delivery time.\n self.set_delivered(min_id, self.curr_time, min_distance)\n\n # If a package is delivered beyond its deadline, stop the delivery\n # and return False.\n delivery_time = data.package_data.get(min_id).get(\"delivery time\")\n deadline = data.package_data.get(min_id).get(\"deadline\")\n if delivery_time > deadline:\n # print(\"Package \", min_id, \" was not delivered on time.\")\n return False\n\n # Update the list of undelivered packages\n undelivered = self.get_undelivered_packages_id()\n # After the last package is delivered, drive the truck back to the start_location.\n distance = data.distance_data.get((curr_location, start_location))\n curr_location = start_location\n travel_distance += distance\n data.total_distance += travel_distance\n return True\n \n def is_empty(self):\n return self.package_count == 0\n \n def get_undelivered_packages_id(self):\n \"\"\"Return a list of the ids of undelivered packages.\"\"\"\n packages_id = []\n packages = self.loads.buckets\n for i in range(len(packages)):\n if packages[i] is not None:\n for key_value_pair in packages[i]:\n if key_value_pair[1].get(\"status\") != \"delivered\":\n packages_id.append(key_value_pair[0])\n return packages_id\n \n def get_location(self, id):\n \"\"\" Given a package id, return its delivery location.\"\"\"\n return self.loads.get(id).get(\"address\")\n \n def set_on_route(self, start_time):\n \"\"\"Change all packages' status to 'on route'.\"\"\"\n packages = self.loads.buckets\n for i in range(len(packages)):\n if packages[i] is not None:\n for key_value_pair in packages[i]:\n id = key_value_pair[0]\n data.package_data.get(id).add(\"status\", \"on route\")\n data.package_data.get(id).add(\"on route time\", start_time)\n\n def set_delivered(self, id, curr_time, distance):\n \"\"\"Change a package's status to delivered, and set its delivery time\"\"\"\n data.package_data.get(id).add(\"status\", \"delivered\")\n travel_time = timedelta(hours=distance/self.speed)\n self.curr_time += travel_time\n data.package_data.get(id).add(\"delivery time\", self.curr_time)\n","sub_path":"packages/truck.py","file_name":"truck.py","file_ext":"py","file_size_in_byte":4897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"331043715","text":"from setuptools import setup, find_packages\nimport os\n\nversion = '9.06.02'\n\ndef read(*pathnames):\n return open(os.path.join(os.path.dirname(__file__), *pathnames)).read()\n\nsetup(name='collective.types.topicgroup',\n version=version,\n description=\"TopicGroup content type\",\n long_description=''.join((read('docs', 'README.txt'),\n read('docs', 'HISTORY.txt'),\n read('docs', 'INSTALL.txt'),\n read('docs', 'CUSTOMIZATION.txt'))),\n # Get more strings from http://www.python.org/pypi?%3Aaction=list_classifiers\n classifiers=[\n \"Development Status :: 4 - Beta\",\n \"Framework :: Plone\",\n \"Framework :: Zope2\",\n \"Framework :: Zope3\",\n \"Programming Language :: Python\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n ],\n keywords='plone types topicgroup folder',\n author='Paul Bugni, Liz Dahlstrom',\n author_email='lhill2@u.washington.edu',\n url='http://cphi.washington.edu',\n license='GPL 2',\n packages=find_packages(exclude=['ez_setup']),\n namespace_packages=['collective','collective.types'],\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n 'setuptools',\n # -*- Extra requirements: -*-\n ],\n entry_points=\"\"\"\n # -*- Entry points: -*-\n \"\"\",\n )\n","sub_path":"pypi_install_script/collective.types.topicgroup-9.06.02.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"27527461","text":"def HexConv(num) :\n if (num < 10):\n return(str(num))\n elif (num == 10 ):\n return(\"A\")\n elif (num == 11 ):\n return(\"B\")\n elif (num == 12 ):\n return(\"C\")\n elif (num == 13 ):\n return(\"D\")\n elif (num == 14 ):\n return(\"E\")\n elif (num == 15 ):\n return(\"F\")\n\ndef DecConv(num) :\n try:\n val = int(num)\n return(val)\n except(ValueError):\n if(num == \"A\"):\n return(10)\n elif(num == \"B\"):\n return(11)\n elif(num == \"C\"):\n return(12)\n elif(num == \"D\"):\n return(13)\n elif(num == \"E\"):\n return(14)\n elif(num == \"F\"):\n return(15)\n\ndef HexToDec(num):\n sum = 0\n for c in num:\n p = DecConv(c)\n sum = sum*16 + p\n return(sum)\n\n\ndef DecToHex(num):\n if(num < 1):\n return(\"0\")\n elif (num == 1):\n return(\"1\")\n else :\n ns = DecToHex(num//16)\n x = num % 16\n return(ns + HexConv(x))\n\na = input(\"Masukan A:\")\nb = input(\"Masukan B:\")\n\nxa = HexToDec(a)\nxb = HexToDec(b)\n\nprint(a + \" + \" + b + \" = \" + DecToHex(xa + xb))\n","sub_path":"src/3-Problem02.py","file_name":"3-Problem02.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"230432232","text":"import os\nimport numpy as np\nimport json\nfrom sklearn import preprocessing\nimport pandas as pd\nimport h5py\nfrom signlib import misc2\nfrom signlib import video_utils\nfrom signlib import pose\nfrom signlib import annotations\n\ndef create_dataset(root):\n \"\"\"\n Function to create numpy array with all the files corresponding to each class and folder.\n \"\"\"\n \n max_files = len(os.listdir(root))\n #print(\"There are %s files in the directory\"%(max_files))\n \n \n empty_array = np.zeros([int(max_files/3), 7,2])\n #Get files in folders\n final_files = os.listdir(root)\n #print(final_files)\n count = 0\n for file in final_files:\n if file.endswith(\"json\"):\n #print(file)\n json_file = root+\"/\"+file\n json_file_hands = misc2.get_hands_from_json(json_file)\n #json_file_hands = np.reshape(json_file_hands, (1, 14))\n \n empty_array[count] = json_file_hands\n count = count+1\n return(empty_array)\n\n\ndef create_dataframe_with_window(my_array, window):\n# h5f = h5py.File(h5_file,'r')\n# b = h5f['dataset_1'][:]\n# h5f.close()\n\n b = my_array\n #Create dataframe for storing \n df = pd.DataFrame(columns=['Pose'])\n original_ds_shape = b.shape\n for i in range(original_ds_shape[0]):\n #print(\"pose is: \",b[i][j][k])\n df = df.append(pd.DataFrame({\"Pose\": [b[i]]}))\n #fix the index\n index = np.arange(df.shape[0])\n df.set_index(index, inplace=True)\n\n \n window_size = window\n final_dataframe = pd.DataFrame(columns=['Windowed_poses'])\n my_len = len(df)\n #print(\"length of dataframe is: %s\"%(my_len))\n #print(\"Class \"+str(c)+\" has \"+str(my_len)+\" files in sequence: \"+str(s))\n \n if my_len > window_size:\n count_windows = 0\n for u in range(my_len-window_size):\n count_windows = count_windows + 1\n #final_dataframe = final_dataframe.append(pd.DataFrame({\"Class\": c, \"Windowed_poses\": }))\n #window_array = np.asarray([new_df[new_df.Class == c][new_df.Sequence == s].Pose[u:window_size+u]])\n window_array = df.Pose[u:(window_size+u)]\n #print(\"Pose is: \",new_df[new_df.Class == c][new_df.Sequence == s].Pose[u])\n #print(\"window is: \",window_array)\n window_array = window_array.reset_index(drop=True).values.flatten()\n #window_array = np.reshape(window_array, (7,14))\n final_dataframe = final_dataframe.append(pd.DataFrame({\"Windowed_poses\": [window_array]}))\n# print(\"Class \"+str(c)+\" has \"+str(my_len)+\" files in sequence: \"+str(s)+\" windows in total: \"+str(count_windows))\n# else:\n# print(\"Folders have less \")\n return(final_dataframe)\n\n\ndef predict_for_video(input_f, output, my_window):\n# #split to frames\n# video_utils.video_to_frames(input_f,output)\n \n# #run openpose\n# pose.run_test(\"E:/Testing_signlib/openpose/bin/OpenPoseDemo.exe\", output)\n \n\n my_data = create_dataset(output)\n \n window = my_window\n\n mf = pd.DataFrame(columns=['Window_prediction'])\n\n df = create_dataframe_with_window(my_data, window)\n\n for n in range(df[\"Windowed_poses\"].shape[0]):\n df[\"Windowed_poses\"].iloc[n] = np.hstack(df[\"Windowed_poses\"].iloc[n]).reshape((window,14))\n\n data = np.hstack(df[\"Windowed_poses\"]).reshape((df[\"Windowed_poses\"].shape[0],window,14))\n\n print(\"shape of data: \",data.shape)\n \n # load keras model\n from keras.models import load_model\n model = load_model('./keras_models/binary_classification_window_20_lstm_64_roc_best.h5')\n for sample in range(data.shape[0]):\n window_prediction = model.predict_classes(np.array(data[sample]).reshape((1,window,14)))\n mf = mf.append(pd.DataFrame({\"Window_prediction\": [window_prediction]}))\n \n root2 = output\n all_files = os.listdir(root2)\n pic_list = []\n for i_file in all_files:\n if i_file.endswith(\"rendered.png\"):\n pic_list.append(i_file)\n\n for w in range (len(pic_list) - window):\n prediction = mf.Window_prediction.iloc[w]\n for picture in pic_list[w: window+w]:\n annotations.create_binary_overlay(picture, prediction, root2)\n\n\n","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":4232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"319171020","text":"import pygame\npygame.init()\n\nmonster = pygame.image.load('images/gomba.png')\nmonsterPos = monster.get_rect()\n\nmonsterPos.x = 550\nmonsterPos.y = 275\nclass Monster(pygame.sprite.Sprite):\n\n def __init__(self):\n super().__init__()\n self.health = 10\n self.max_health = 10\n self.attack = 5\n","sub_path":"monster.py","file_name":"monster.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"493760479","text":"from app import app, db\n# from app import cache\nfrom flask import render_template, url_for, redirect, request, flash\nfrom app.models import School, Session, Annual, Semester, Promo, AnnualSession\nfrom flask_breadcrumbs import register_breadcrumb\nfrom datetime import datetime\nfrom flask_login import current_user, login_required\n# from app.routesCalculation import init_all, calculate_all\nfrom app.routesCalculation import init_all\n\n\n\n\ndef get_classement_link(promo, separate=True):\n # promo = promo.\n id = 'classement_' + str(promo.id)\n pId = 'promo_' + str(promo.id)\n name = 'Progression / Classement'\n hint = ''\n icon = 'icon24'\n url = url_for('classement_laureats', promo_id=promo.id)\n links = ''\n if separate is True:\n links += '{id:\"separate_'+id+'\", pId:\"'+pId+'\", name:\"\", iconSkin:\"icon0\"},'\n \n links += '{id:\"'+id+'\", pId:\"'+pId+'\", name:\"'+name+'\", hint:\"'+hint+'\", target:\"_top\", url: \"'+url+'\", iconSkin:\"'+icon+'\"},'\n return links\n\ndef get_students_list_link(promo, separate=True):\n id = 'students_list_' + str(promo.id)\n pId = 'promo_' + str(promo.id)\n name = 'Students List'\n hint = ''\n icon = 'icon15'\n url = url_for('student_by_promo', promo_id=promo.id)\n\n links = ''\n if separate is True:\n links += '{id:\"separate_'+id+'\", pId:\"'+pId+'\", name:\"\", iconSkin:\"icon0\"},'\n \n links += '{id:\"'+id+'\", pId:\"'+pId+'\", name:\"'+name+'\", hint:\"'+hint+'\", target:\"_top\", url: \"'+url+'\", iconSkin:\"'+icon+'\"},'\n return links\n\ndef get_creation_links(promo, separate=True):\n semesters = get_semesters_not_in_promo(promo)\n links = ''\n if len(semesters) > 0:\n first_semester_id = semesters[0].id\n next_semester_to_create = promo.get_next_semester()\n\n id = 'new_' + str(promo.id)\n pId = 'promo_' + str(promo.id)\n hint = ''\n semester_id = first_semester_id\n if next_semester_to_create != None:\n semester_id = next_semester_to_create.id\n url = url_for('create_session', promo_id=promo.id, semester_id=semester_id)\n name = 'Create Semester'\n # if separate is True:\n # links += '{id:\"separate_'+id+'\", pId:\"'+pId+'\", name:\"\", iconSkin:\"icon0\"},'\n links += '{id:\"'+id+'\", pId:\"'+pId+'\", name:\"'+name+'\", hint:\"'+hint+'\", target:\"_top\", url: \"'+url+'\", iconSkin:\"icon01\"},'\n return links\n\ndef get_creation_link_modal(promo):\n semesters = get_semesters_not_in_promo(promo)\n links = ''\n if len(semesters) > 0:\n first_semester_id = semesters[0].id\n next_semester_to_create = promo.get_next_semester()\n\n id = 'new_modal_' + str(promo.id)\n pId = 'promo_' + str(promo.id)\n hint = ''\n semester_id=first_semester_id\n if next_semester_to_create != None:\n semester_id=next_semester_to_create.id\n url = ''\n # url = url_for('create_session', promo_id=promo.id, semester_id=semester_id)\n name = 'Create Semester'\n links += '{id:\"'+id+'\", pId:\"'+pId+'\", name:\"'+name+'\", hint:\"'+hint+'\", target:\"_top\", url: \"'+url+'\", iconSkin:\"icon01\"},'\n return links\n\ndef get_annual_session(session, pId):\n # it shows only after last session in Annual chain\n annual = ''\n annual_dict = session.get_annual_dict()\n if annual_dict['A'] != -1:\n # append after last session in Annual\n annual_chain = session.get_annual_chain()\n if annual_chain[-1] == session.id:\n an_s_id = session.annual_session_id\n hint = ''\n url = url_for('annual_session', annual_session_id=an_s_id)\n # name = 'Annual '+str(session.semester.annual.annual)+' Results       (an:'+str(an_s_id)+')'\n name = 'Annual '+str(session.semester.annual.annual)+' Results'\n annual = '{id:\"annual_'+str(an_s_id)+'\", pId:\"'+pId+'\", url: \"'+url+'\", name:\"'+name+'\", hint:\"'+hint+'\", target:\"_self\", iconSkin:\"icon17\"},'\n return annual\n\ndef get_percentage_progress(percentage):\n load = \"load-green\"\n # load = \"load-gold\"\n perc = str(percentage)\n if percentage < 10:\n # perc = \" \"+str(percentage)\n perc = str(percentage)\n\n if percentage <= 25:\n load = \"load-red\"\n elif percentage <= 65:\n load = \"load-orange\"\n elif percentage <= 99:\n load = \"load-green-yellow\"\n\n perc_width = 1.5 if percentage <= 2 else percentage\n\n progress = \"  \"\n progress += \"

\"\n progress += \" \"+perc+\"%\"\n progress += \"
\"\n progress += \"
\"\n\n return progress\n\ndef get_sessions_tree(promo):\n sessions = Session.query.filter_by(promo_id=promo.id).join(Semester).join(Annual)\\\n .order_by(Annual.annual, Semester.semester).all()\n\n sessions_tree = ''\n for session in sessions:\n semester = session.semester.get_nbr()\n annual = str(session.annual_session_id)\n\n id = 'semester_'+str(session.id)\n pId = 'promo_'+str(promo.id)\n url = url_for('session', session_id=session.id)\n hint = ''\n\n icon = 'icon21'\n if session.is_rattrapage == True:\n icon = 'icon22'\n\n if session.is_historic:\n icon = 'icon21_ratt_h'\n if session.is_rattrapage == True:\n icon = 'icon22_ratt_h'\n\n name = \"Semester: \"+str(semester)+\" \"\n if semester < 10:\n name += \"  \"\n if session.is_rattrapage:\n name = 'Rattrapage: '+str(semester)\n\n if session.is_closed == True:\n name += \"  \"\n else:\n name += \"       \"\n\n # has errors\n has_errors = session.check_errors_exist()\n\n # progress\n if not has_errors:\n if not session.is_closed:\n name += get_percentage_progress( session.check_progress() )\n else:\n name += \"                                \"\n\n name += \" \" + session.promo.get_label() + \"\"\n\n # # Configuration change\n # if session.is_config_changed() and session.is_closed==False:\n # name += \"        Configuration has changed, you need to Re(initialized)\"\n\n if has_errors:\n name += \"        <<< Contains ERRORS >>> \"\n\n\n p = '{id:\"'+id+'\", pId:\"'+pId+'\", name:\"'+name+'\", hint:\"'+hint+'\", open:true, url: \"'+url+'\", target:\"_self\", iconSkin:\"'+icon+'\" },'\n\n sessions_tree += p + get_annual_session(session, pId)\n\n separate = True\n if sessions_tree == '':\n separate = False\n return sessions_tree \\\n + get_students_list_link(promo, separate)\\\n + get_classement_link(promo, False)\\\n + get_creation_link_modal(promo)\n # + get_creation_links(promo, separate)\\\n\n@app.route('/get_async_sessions_by_promo//', methods=['GET', 'POST'])\ndef get_async_sessions_by_promo(promo_id):\n promo = Promo.query.get_or_404(promo_id)\n return '[' + get_sessions_tree(promo) + ']'\n\n\n\ndef get_promos_tree(branch, open_p_id):\n promos = branch.promos\n promos_tree = ''\n\n for promo in promos:\n id = 'promo_' + str(promo.id)\n pId = 'branch_' + str(branch.id)\n\n name = promo.name\n promo_display_name = str(promo.display_name).replace('None', '')\n if promo_display_name != '':\n name += \" - \" + promo_display_name + \"\"\n\n year = promo.get_latest_annual()\n if year == 1:\n name = name + ' (' +str(promo.get_latest_annual())+ ' ère Année)'\n elif year > 1:\n name = name + ' (' +str(promo.get_latest_annual())+ ' ème Année)'\n\n hint = ''\n\n font = '{\"font-weight\":\"bold\", \"font-style\":\"italic\"}'\n icon = 'pIcon16'\n\n open = 'false'\n if open_p_id == 0:\n open = 'true'\n if open_p_id > 0:\n # open = 'false'\n if open_p_id == promo.id:\n open = 'true'\n\n sessions_tree = ''\n if open == 'true':\n # \n # \n # \n sessions_tree = get_sessions_tree(promo)\n # \n # \n # \n # if promo is None:\n # pre_render_promos_tree(promo)\n # sessions_tree = promo.sub_tree\n # \n # \n # \n\n p = '{id:\"'+id+'\", pId:\"'+pId+'\", name:\"'+name+'\", hint:\"'+hint+'\", times:1, isParent:true, open:'+open+', iconSkin:\"'+icon+'\", font:'+font+'},'\n promos_tree += p + sessions_tree\n\n return promos_tree\n\ndef get_branches_tree(school, open_b_id, open_p_id):\n branches = school.branches\n branches_tree = ''\n for branch in branches:\n id = 'branch_'+str(branch.id)\n pId = 'school_'+str(school.id)\n name = branch.name+' - '+str(branch.description)\n p = get_promos_tree(branch, open_p_id)\n\n hint = ''\n\n open = 'true'\n if open_b_id != 0:\n open = 'false'\n if open_b_id == branch.id:\n open = 'true'\n\n if p == '':\n b = '{ id:\"'+id+'\", pId:\"'+pId+'\", name:\"'+name+'\", hint:\"'+hint+'\", open:'+open+', iconSkin:\"icon11\"},'\n else:\n b = '{ id:\"'+id+'\", pId:\"'+pId+'\", name:\"'+name+'\", hint:\"'+hint+'\", open:'+open+', isParent:true},'\n \n separation = '{id:\"separate_'+id+'\", pId:\"'+pId+'\", name:\"\", iconSkin:\"icon0\"},'\n\n branches_tree += b + p + separation\n \n return branches_tree\n\ndef get_schools_tree(open_s_id, open_b_id, open_p_id):\n schools = School.query.all()\n schools_tree = ''\n for school in schools:\n id = 'school_'+str(school.id)\n name = school.name\n icon = 'pIcon12'\n hint = ''\n branches_tree = get_branches_tree(school, open_b_id, open_p_id)\n open = 'true'\n if open_s_id != 0:\n open = 'false'\n if open_s_id == school.id:\n open = 'true'\n s = '{ id:\"'+id+'\", pId:0, name:\"'+name+'\", hint:\"'+hint+'\", open:'+open+', iconSkin:\"'+icon+'\", isParent:true },'\n schools_tree += s + branches_tree\n return schools_tree\n \n\n# @cache.cached(timeout=500)\n# def get_schools_tree_cached(open_s_id, open_b_id, open_p_id):\n# return get_schools_tree(open_s_id, open_b_id, open_p_id)\n\ndef tree_session_dlc(*args, **kwargs):\n session = Session.query.get_or_404(request.view_args['session_id'])\n return [{'text': 'Tree ('+ session.promo.name +')', \n 'url': url_for('tree', school_id=session.promo.branch.school.id, \n branch_id=session.promo.branch.id, \n promo_id=session.promo.id) }]\n\n@app.route('/tree/session//', methods=['GET'])\n@register_breadcrumb(app, '.tree_session', '', dynamic_list_constructor=tree_session_dlc)\ndef tree_session(session_id=0):\n return '*** just used to generate the url ***'\n\n\ndef tree_promo_dlc(*args, **kwargs):\n promo = Promo.query.get_or_404(request.view_args['promo_id'])\n return [{'text': 'Tree ('+ promo.name +')', \n 'url': url_for('tree', school_id=promo.branch.school.id, \n branch_id=promo.branch.id, \n promo_id=promo.id) }]\n\n@app.route('/tree/promo//', methods=['GET'])\n@register_breadcrumb(app, '.tree_promo', '', dynamic_list_constructor=tree_promo_dlc)\ndef tree_promo(promo_id=0):\n return '*** just used to generate the url ***'\n\n\ndef tree_annual_dlc(*args, **kwargs):\n annual_session_id = request.view_args['annual_session_id']\n annual_session = AnnualSession.query.get_or_404(annual_session_id)\n session = annual_session.sessions[0]\n\n school_id = 0\n branch_id = 0\n promo_id = 0\n if session != None:\n promo_id = session.promo_id\n # branch_id = session.promo.branch_id\n school_id = session.promo.branch.school_id\n\n return [{'text': 'Tree ('+ session.promo.name +')', \n 'url': url_for('tree', school_id=school_id, branch_id=branch_id, promo_id=promo_id) }]\n\n@app.route('/annual-tree/annual-session//', methods=['GET'])\n@register_breadcrumb(app, '.tree_annual', '', dynamic_list_constructor=tree_annual_dlc)\ndef tree_annual(annual_session_id=0):\n return '*** just used to generate the url-annual-session ***'\n\n\n@app.route('/tree/school//branch//promo//', methods=['GET'])\n@app.route('/tree/school//branch//', methods=['GET'])\n@app.route('/tree/school//', methods=['GET'])\n@app.route('/tree/', methods=['GET'])\n@register_breadcrumb(app, '.tree', 'Tree')\n# def tree(school_id=0, branch_id=0, promo_id=-1):\ndef tree(school_id=0, branch_id=-1, promo_id=-1):\n options_arr = get_options()\n\n _tree_ = get_schools_tree(int(school_id), int(branch_id), int(promo_id))\n # _tree_ = get_schools_tree_cached(int(school_id), int(branch_id), int(promo_id))\n\n zNodes = '[' + _tree_ + ']'\n return render_template('tree/tree.html', title='Tree', \n zNodes=zNodes, options_arr=options_arr)\n\n\n# Ckeck Need Calculation\n@app.route('/tree/running-checks', methods=['GET'])\ndef running_checks():\n msg_check = ''\n sessions_to_check = Session.query.filter_by(is_closed=False).all()\n\n nbr_reinit_needed = check_reinit_needed(sessions_to_check)\n if nbr_reinit_needed > 0:\n reinit_url = url_for('tree_reinit_all')\n slow_redirect_url = url_for('slow_redirect', url=reinit_url, message='(Re)initializing ' + str(nbr_reinit_needed) + ' sessions')\n btn = '(Re)initialize All'\n msg = str(nbr_reinit_needed) + ' Sessions needs to be (Re)initialized    ' + btn\n msg_check += '''\n
\n ×\n '''+msg+'''\n
\n '''\n\n # Danger\n nbr_sessions_errors = check_errors_exists(sessions_to_check)\n if nbr_sessions_errors == 0:\n # Calculation\n nbr_recalculate_needed = check_recalculate_needed(sessions_to_check)\n if nbr_recalculate_needed > 0:\n recalculate_url = url_for('tree_recalc_all')\n slow_redirect_url = url_for('slow_redirect', url=recalculate_url, message='(Re)calculating' + str(nbr_recalculate_needed) + ' sessions')\n btn = '(Re)Calculate All'\n msg = str(nbr_recalculate_needed) + ' Sessions needs to be (Re)calculate    ' + btn\n msg_check += '''\n
\n ×\n '''+msg+'''\n
\n '''\n else:\n msg = str(nbr_sessions_errors) + ' Sessions Contains ERRORS'\n if nbr_sessions_errors == 1:\n msg = ' a Session Contains ERRORS'\n\n msg_check += '''\n
\n ×\n '''+msg+'''\n
\n '''\n\n return msg_check\n\n\n# def get_semesters_id_in_promo(promo):\n# semesters_id_list = []\n# sessions = promo.sessions\n# for session in sessions:\n# semester_id = session.semester.id\n# if semester_id not in semesters_id_list:\n# semesters_id_list.append(semester_id)\n# return semesters_id_list\n\n\ndef get_semesters_nbr_in_promo(promo):\n semesters_nbr_list = []\n sessions = promo.sessions\n for session in sessions:\n semester_nbr = session.semester.get_nbr()\n if semester_nbr not in semesters_nbr_list:\n semesters_nbr_list.append(semester_nbr)\n return semesters_nbr_list\n\n\ndef get_semesters_not_in_promo(promo):\n semesters = promo.branch.get_semesters_ordered()\n semesters = semesters[-1].get_latest_of_semesters_list()\n\n semesters_nbr_in_promo = get_semesters_nbr_in_promo(promo)\n semesters_remaining_promo = []\n for semester in semesters:\n if semester.get_nbr() not in semesters_nbr_in_promo:\n semesters_remaining_promo.append(semester)\n return semesters_remaining_promo\n\n\ndef get_options_by_promo(promo):\n options = ''\n semesters = get_semesters_not_in_promo(promo)\n next_semester_to_create = promo.get_next_semester()\n historic = True\n for semester in semesters:\n selected = ''\n if semester == next_semester_to_create:\n selected = 'selected'\n historic = False\n val = str(semester.id)\n opt = str(semester.get_nbr()) + ' - ' + semester.name\n if historic == True:\n opt += ' (Historic)'\n options += ''\n return options\n\n\ndef get_options():\n array = []\n promos = Promo.query.all()\n for promo in promos:\n array.append( [promo.id, get_options_by_promo(promo)] )\n return array\n\n\n# @cache.cached(timeout=300)\n# def check_reinit_cached():\n# return check_reinit_needed()\n\n\ndef check_reinit_needed(sessions):\n # sessions = Session.query.filter_by(is_closed=False).all()\n count = 0\n for session in sessions:\n if session.is_config_changed():\n count += 1\n return count\n\ndef check_recalculate_needed(sessions):\n count = 0\n for session in sessions:\n if session.check_recalculate_needed():\n count += 1\n return count\n\ndef check_errors_exists(sessions):\n # sessions = Session.query.filter_by(is_closed=False).all()\n count = 0\n for session in sessions:\n if session.check_errors_exist():\n count += 1\n return count\n\n\n@app.route('/tree/re-init/school/', methods=['GET'])\n@app.route('/tree/re-init/', methods=['GET'])\ndef tree_reinit_all(school_id=0):\n # nbr_reinit = check_reinit_needed()\n sessions = Session.query.filter_by(is_closed=False).all()\n nbr_init = 0\n for session in sessions:\n if session.is_config_changed():\n init_all(session)\n nbr_init += 1\n flash( str(nbr_init) + \" reinitialized\")\n\n return redirect( url_for('tree') )\n\n\n@app.route('/tree/re-calc/school/', methods=['GET'])\n@app.route('/tree/re-calc/', methods=['GET'])\ndef tree_recalc_all(school_id=0):\n sessions = Session.query.filter_by(is_closed=False).all()\n nbr_calc = 0\n for session in sessions:\n if session.check_recalculate_needed():\n # calculate_all(session)\n session.calculate()\n nbr_calc += 1\n flash( str(nbr_calc) + \" recalculated\")\n\n return redirect( url_for('tree') )\n\n\n#\n#\n#\n\n\n############## RE-Render Promo Tree ################\n\n@app.route('/tree/prerender/', methods=['GET'])\ndef pre_render_tree():\n # later\n # filter further more to speed up pre render\n promos = Promo.query.all()\n for promo in promos:\n pre_render_promos_tree(promo.id)\n\n flash('pre-rendered the tree')\n return redirect(url_for('tree'))\n\n","sub_path":"app/routesTree.py","file_name":"routesTree.py","file_ext":"py","file_size_in_byte":19628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"138186887","text":"from typing import Optional, Callable, Any\nimport logging\nimport time\n\n\ndef repeats(\n amount: int,\n *,\n delay: float = 1,\n message: Optional[str] = None,\n logger: Optional[logging.Logger] = None,\n) -> Callable[[Callable], Callable]:\n if message is not None and logger is None:\n raise ValueError(\"To print message also specify a logger to use\")\n if amount < 1:\n raise ValueError(f\"Amount should be > 0, got {amount}\")\n\n def decorator(f: Callable) -> Callable:\n def wrapped(*args: list[Any], **kwargs: dict[Any, Any]) -> Any:\n error_args = []\n for i in range(amount):\n try:\n return f(*args, **kwargs)\n except Exception as ex:\n if message and logger:\n logger.exception(\n f\"[{i+1}/{amount}] {message}. [{ex.__class__.__name__} | {ex.args}]\"\n )\n error_args.append(ex.args)\n time.sleep(delay)\n raise RuntimeError(*error_args)\n\n return wrapped\n\n return decorator\n","sub_path":"app/utils/repeater.py","file_name":"repeater.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"525469910","text":"import requests\nfrom bs4 import BeautifulSoup\nimport re\nimport json\nimport openpyxl\nimport datetime\n\n#Workbook 생성\nwb = openpyxl.Workbook()\n#Sheet 생성\nwb.create_sheet('1. 기본정보',0)\nwb.create_sheet('2. 저작권료',1)\nwb.create_sheet('3. 상세저작권료',2)\n#Sheet 활성\nsheet = wb['1. 기본정보']\nsheet.column_dimensions['A'].width = 20\nsheet.column_dimensions['B'].width = 11\nsheet.column_dimensions['C'].width = 11\nsheet.column_dimensions['D'].width = 11\nsheet.column_dimensions['E'].width = 20\n#수익률\n\nsheet.column_dimensions['K'].width = 18\nsheet.column_dimensions['L'].width = 40\n\nsheet.append([\"곡명\", \"가수\", \"인접권여부\", \"공표일자\", \"2차적저작물작성권\", \"현재가\", \"저작권료\", \"수익률\", \"총주수\", \"유통주수\",\"시가총액\", \"기타 주요사항\" ])\n\nsheet = wb['2. 저작권료']\nsheet.column_dimensions['A'].width = 20\nsheet.column_dimensions['B'].width = 11\nsheet.append([\"곡명\", \"가수\", \"인접권여부\"\n ,\"2021-01\", \"2021-02\", \"2021-03\", \"2021-04\", \"2021-05\", \"2021-06\", \"2021-07\", \"2021-08\", \"2021-09\", \"2021-10\" , \"2021-11\", \"2021-12\"\n ,\"2020-01\", \"2020-02\", \"2020-03\", \"2020-04\", \"2020-05\", \"2020-06\" , \"2020-07\", \"2020-08\",\"2020-09\", \"2020-10\", \"2020-11\", \"2020-12\"\n ,\"2019-01\", \"2019-02\", \"2019-03\", \"2019-04\", \"2019-05\", \"2019-06\" , \"2019-07\", \"2019-08\",\"2019-09\", \"2019-10\", \"2019-11\", \"2019-12\"\n ,\"2018-01\", \"2018-02\", \"2018-03\", \"2018-04\", \"2018-05\", \"2018-06\" , \"2018-07\", \"2018-08\",\"2018-09\", \"2018-10\", \"2018-11\", \"2018-12\"\n ,\"2017-01\", \"2017-02\", \"2017-03\", \"2017-04\", \"2017-05\", \"2017-06\" , \"2017-07\", \"2017-08\",\"2017-09\", \"2017-10\", \"2017-11\", \"2017-12\"])\n\nsheet = wb['3. 상세저작권료']\nsheet.column_dimensions['A'].width = 20\nsheet.column_dimensions['B'].width = 11\nsheet.append([\"곡명\", \"가수\", \"인접권여부\", \"1년저작권료\", \"방송\", \"전송\", \"복제\", \"공연\", \"해외\", \"기타\", \"디음송\"])\n\n\nyears = [\"2017\", \"2018\", \"2019\", \"2020\", \"2021\"]\nmonths = [\"01\",\"02\",\"03\",\"04\",\"05\",\"06\",\"07\",\"08\",\"09\",\"10\",\"11\",\"12\"]\n\n\nbase_url = 'https://www.musicow.com/song/{}?tab=info'\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57'}\n\nmaxfor = input(\"돌릴만큼 입력(숫자 3000추천) :\")\n\nfor n in range(int(maxfor)) :\n\n musicnum = 0\n\n #하나씩 추출\n url = base_url.format(n+1)\n res = requests.get(url, headers=headers).text\n soup = BeautifulSoup(res, \"lxml\")\n pattern = re.compile(r\"arr_amt_royalty_ym\\['graph1'\\] = (.*?);$\", re.MULTILINE | re.DOTALL)\n script = soup.find(\"script\", text=pattern)\n dic = pattern.search(script.text).group(1)\n string_to_dict = json.loads(dic)\n st_len = len(string_to_dict)\n #곡에 해당하는 site가 있을 경우,\n if st_len != 0 :\n # 제목 및 아티스트\n 곡명 = soup.select(\"#page_market > div.container > div.song_header > div.information > p > strong\")[0].text.strip()\n 가수 = soup.select(\"#page_market > div.container > div.song_header > div.information > em\")[0].text.strip()\n\n #1. 기본정보\n sheet = wb['1. 기본정보']\n try:\n soup.select(\"#page_market > div.container > div.song_header > div.information > p > i\")[0].text\n 인접권여부 = 'O'\n except:\n 인접권여부 = 'X'\n\n 공표일자 = soup.select(\"div.lst_copy_info > dl > dd\")[0].text.strip()\n if (인접권여부 == 'X'):\n 이차적저작물작성권 = soup.select(\"div.lst_copy_info > dl > dd > p\")[1].text.split(\"(\")[1].replace(\")\", \"\").strip()\n else:\n 이차적저작물작성권 = \"\"\n\n 현재가 = int(soup.select(\n \"#page_market > div.container > div.song_header > div.price_wrap > dl:nth-child(1) > dd > strong\")[\n 0].text.split(\" \")[0].replace(\",\", \"\"))\n\n 저작권료 = soup.select(\"#page_market > div.container > div.song_header > div.price_wrap > dl:nth-child(3) > dd > span\")[\n 0].text.split(\" \")[0]\n if (\",\" in list(저작권료)):\n 저작권료 = int(저작권료.replace(\",\", \"\"))\n else:\n 저작권료 = int(저작권료)\n\n 수익률 = soup.select(\"#page_market > div.container > div.song_header > div.price_wrap > dl:nth-child(3) > dd > span\")[\n 0].text.split(\" \")[1].replace(\"(\", \"\").replace(\")\", \"\").strip()\n\n 총주수 = int(soup.select(\"div.lst_copy_info > dl > dd > p\")[0].text.split(\"/\")[1].replace(\",\", \"\"))\n 길이 = len(soup.select(\".lst_numb_card dl dd\"))\n if (길이 < 11):\n 유통주수 = soup.select(\".lst_numb_card dl dd\")[3].text.split(\" \")[0]\n if (\",\" in list(유통주수)):\n 유통주수 = int(유통주수.replace(\",\", \"\"))\n else:\n 유통주수 = int(유통주수)\n else:\n 유통주수_1차 = soup.select(\".lst_numb_card dl dd\")[3].text.split(\" \")[0]\n 유통주수_2차 = soup.select(\".lst_numb_card dl dd\")[7].text.split(\" \")[0]\n if (\",\" in list(유통주수_1차)):\n 유통주수_1차 = int(유통주수_1차.replace(\",\", \"\"))\n else:\n 유통주수_1차 = int(유통주수_1차)\n if (\",\" in list(유통주수_2차)):\n 유통주수_2차 = int(유통주수_2차.replace(\",\", \"\"))\n else:\n 유통주수_2차 = int(유통주수_2차)\n\n 유통주수 = 유통주수_1차 + 유통주수_2차\n\n 시가총액 = 현재가 * 총주수\n 기타_주요사항 = soup.select(\"div.lst_copy_info > dl > dd > ul\")[0].text.strip()\n\n sheet.append([곡명, 가수, 인접권여부, 공표일자, 이차적저작물작성권, 현재가, 저작권료, 수익률, 총주수, 유통주수, 시가총액 , 기타_주요사항])\n\n #2. 저작권료\n sheet = wb['2. 저작권료']\n #배열 초기화\n temp_list = [];\n for year in years:\n for month in months:\n try:\n value = string_to_dict[year][month]\n temp_list.append(value)\n except:\n temp_list.append('0')\n\n sheet.append([곡명, 가수, 인접권여부, temp_list[0],temp_list[1],temp_list[2], temp_list[3],temp_list[4],temp_list[5], temp_list[6], temp_list[7], temp_list[8], temp_list[9],\n temp_list[10],temp_list[11],temp_list[12], temp_list[13],temp_list[14],temp_list[15], temp_list[16],temp_list[17],temp_list[18], temp_list[19],\n temp_list[20],temp_list[21],temp_list[22], temp_list[23],temp_list[24],temp_list[25], temp_list[26],temp_list[27],temp_list[28], temp_list[29],\n temp_list[30],temp_list[31],temp_list[32], temp_list[33],temp_list[34],temp_list[35], temp_list[36],temp_list[37],temp_list[38], temp_list[39],\n temp_list[40],temp_list[41],temp_list[42], temp_list[43],temp_list[44],temp_list[45], temp_list[46],temp_list[47],temp_list[48], temp_list[49],\n temp_list[50],temp_list[51],temp_list[52], temp_list[53],temp_list[54],temp_list[55], temp_list[56],temp_list[57],temp_list[58], temp_list[59]])\n \n #3. 상세저작권료\n sheet = wb['3. 상세저작권료']\n\n 방송 = int(soup.select(\n \"#song_info_royalty > div.card_body > div > div > div:nth-child(2) > div > div.old_money > div.tbl_flex > dl:nth-child(1) > dd\")[\n 0].text.split(\"원\")[0].replace(\",\", \"\"))\n 전송 = int(soup.select(\n \"#song_info_royalty > div.card_body > div > div > div:nth-child(2) > div > div.old_money > div.tbl_flex > dl:nth-child(2) > dd\")[\n 0].text.split(\"원\")[0].replace(\",\", \"\"))\n 복제 = int(soup.select(\n \"#song_info_royalty > div.card_body > div > div > div:nth-child(2) > div > div.old_money > div.tbl_flex > dl:nth-child(3) > dd\")[\n 0].text.split(\"원\")[0].replace(\",\", \"\"))\n 공연 = int(soup.select(\n \"#song_info_royalty > div.card_body > div > div > div:nth-child(2) > div > div.old_money > div.tbl_flex > dl:nth-child(4) > dd\")[\n 0].text.split(\"원\")[0].replace(\",\", \"\"))\n 해외 = int(soup.select(\n \"#song_info_royalty > div.card_body > div > div > div:nth-child(2) > div > div.old_money > div.tbl_flex > dl:nth-child(5) > dd\")[\n 0].text.split(\"원\")[0].replace(\",\", \"\"))\n 기타 = int(soup.select(\n \"#song_info_royalty > div.card_body > div > div > div:nth-child(2) > div > div.old_money > div.tbl_flex > dl:nth-child(6) > dd\")[\n 0].text.split(\"원\")[0].replace(\",\", \"\"))\n if (인접권여부 == \"O\"):\n 디음송 = int(soup.select(\n \"#song_info_royalty > div.card_body > div > div > div:nth-child(2) > div > div.old_money > div.tbl_flex > dl:nth-child(7) > dd\")[\n 0].text.split(\"원\")[0].replace(\",\", \"\"))\n else:\n 디음송 = 0\n 일년저작권료 = 방송 + 전송 + 복제 + 공연 + 해외 + 기타 + 디음송\n\n if (인접권여부 == \"X\"):\n 디음송 = \"\"\n\n sheet.append([곡명, 가수, 인접권여부, 일년저작권료, 방송, 전송, 복제, 공연, 해외, 기타, 디음송])\n musicnum = musicnum + 1\n print(\"good {0}\".format(n))\n\n\nsheet = wb['1. 기본정보']\nfor rng in sheet['K:K']:\n rng.number_format = '#,##0'\nfor rng in sheet['H:H']:\n rng.number_format = '0.0%'\n \n \ndt_now = datetime.datetime.now()\nformattedDate = dt_now.strftime(\"%Y%m%d_%H%M\")\nFilename = \"Musicow_\" + formattedDate + \".xlsx\"\n\n\nwb.save(Filename)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"313408856","text":"import numpy as np\nimport torchvision\nimport time\nimport os\nimport copy\nimport pdb\nimport time\nimport argparse\n\nimport sys\nimport cv2\nimport model\n\nimport torch\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import datasets, models, transforms\n\nfrom dataloader import CocoDataset, CSVDataset, collater, Resizer, AspectRatioBasedSampler, Augmenter, UnNormalizer, \\\n Normalizer\n\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\n\nmean = (0.1146, 0.1147, 0.1148)\nstd = (0.1089, 0.1090, 0.1090)\n\noutput_csv_fn = 'output.csv'\noutput_file = open(output_csv_fn, 'w')\n\nnot_processed_fn = 'not_processed.csv'\nnot_processed_file = open(not_processed_fn, 'w')\n\ndebug = True\n\ndef main(args=None):\n parser = argparse.ArgumentParser(description='Simple visualizing script for visualize a RetinaNet network.')\n\n parser.add_argument('--dataset', help='Dataset type, must be one of csv or coco.')\n parser.add_argument('--coco_path', help='Path to COCO directory')\n parser.add_argument('--csv_classes', help='Path to file containing class list (see readme)')\n parser.add_argument('--csv_val', help='Path to file containing validation annotations (optional, see readme)')\n\n parser.add_argument('--model', help='Path to model (.pt) file.')\n\n parser = parser.parse_args(args)\n\n if parser.dataset == 'coco':\n dataset_val = CocoDataset(parser.coco_path, set_name='val2017',\n transform=transforms.Compose([Normalizer(), Resizer()]))\n elif parser.dataset == 'csv':\n dataset_val = CSVDataset(train_file=parser.csv_val, class_list=parser.csv_classes,\n transform=transforms.Compose([Normalizer(mean, std), Resizer()]))\n else:\n raise ValueError('Dataset type not understood (must be csv or coco), exiting.')\n\n #sampler_val = AspectRatioBasedSampler(dataset_val, batch_size=1, drop_last=False)\n #dataloader_val = DataLoader(dataset_val, num_workers=1, collate_fn=collater, batch_sampler=sampler_val)\n dataloader_val = DataLoader(dataset_val, num_workers=1, collate_fn=collater, batch_sampler=None, sampler=None)\n\n retinanet = torch.load(parser.model)\n\n use_gpu = True\n\n if use_gpu:\n retinanet = retinanet.cuda()\n\n retinanet.eval()\n\n unnormalize = UnNormalizer(mean, std)\n\n def draw_caption(image, box, caption):\n b = np.array(box).astype(int)\n cv2.putText(image, caption, (b[0], b[1] - 10), cv2.FONT_HERSHEY_PLAIN, 1, (0, 0, 0), 2)\n cv2.putText(image, caption, (b[0], b[1] - 10), cv2.FONT_HERSHEY_PLAIN, 1, (255, 255, 255), 1)\n\n for idx, data in enumerate(dataloader_val):\n with torch.no_grad():\n st = time.time()\n scores, classification, transformed_anchors = retinanet(data['img'].cuda().float())\n print('Elapsed time: {}'.format(time.time() - st))\n # if batch_size = 1, and batch_sampler, sampler is None, then no_shuffle, will use sequential index, then the get_image_name is OK.\n # otherwise, it will failed.\n fn = dataset_val.get_image_name(idx)\n print('fn of image:', fn)\n idxs = np.where(scores.cpu() > 0.5)\n img = np.array(255 * unnormalize(data['img'][0, :, :, :])).copy()\n\n img[img < 0] = 0\n img[img > 255] = 255\n\n img = np.transpose(img, (1, 2, 0))\n\n img = cv2.cvtColor(img.astype(np.uint8), cv2.COLOR_BGR2RGB)\n print(\"image shape when drawcaption:\", img.shape)\n for j in range(idxs[0].shape[0]):\n bbox = transformed_anchors[idxs[0][j], :]\n x1 = int(bbox[0])\n y1 = int(bbox[1])\n x2 = int(bbox[2])\n y2 = int(bbox[3])\n label_name = dataset_val.labels[int(classification[idxs[0][j]])]\n draw_caption(img, (x1, y1, x2, y2), label_name)\n cv2.rectangle(img, (x1, y1), (x2, y2), color=(0, 0, 255), thickness=2)\n\n if idxs[0].shape[0] == 1:\n origin_img = cv2.imread(fn)\n ret = convert_predict_to_origin_bbox(origin_img, img, x1, y1, x2, y2)\n if ret is None:\n continue\n\n x1p, y1p, x2p, y2p = ret\n output_file.write(fn+','+str(x1p)+','+str(y1p)+','+str(x2p)+','+str(y2p)+',ROI\\n')\n print(\"!!!! FN {} saved!!!\".format(fn))\n else:\n not_processed_file.write(fn+\",,,,,\\n\")\n\n if debug:\n cv2.imshow('img', img)\n cv2.setWindowTitle('img', fn)\n key = cv2.waitKey(0)\n if 'q'==chr(key & 255):\n exit(0)\n\n output_file.close()\n not_processed_file.close()\n\n\n\ndef convert_predict_to_origin_bbox(origin_img, img, x1, y1, x2, y2):\n rows, cols, cns = origin_img.shape\n pad_w = 32-rows%32\n pad_h = 32-cols%32\n pad_height = rows+pad_h\n predict_height, predict_width, _ = img.shape\n\n predict_aspect_ratio=predict_width*1.0/predict_height\n target_width = int(pad_height*predict_aspect_ratio)\n\n try:\n new_image = np.zeros((pad_height, target_width, cns))\n new_image[:rows, :cols,:] = origin_img\n\n img_scale = float(target_width)/predict_width\n x1 = int(x1*img_scale)\n y1 = int(y1*img_scale)\n x2 = int(x2*img_scale)\n y2 = int(y2*img_scale)\n\n return x1, y1, x2, y2\n except:\n return None\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":5498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"331976470","text":"import plotly\nfrom plotly.offline import iplot, init_notebook_mode\nimport plotly.graph_objs as go\nimport plotly.io as pio\n\nimport os\nimport numpy as np# excel read\nimport xlrd\nimport random\n\nimport random\n \n\ncolorsTable = np.array([\n \"rgb(132, 179, 255)\",\n \"rgb(252, 133, 131)\",\n \"rgb(252, 210, 131)\",\n \"rgb(228, 249, 122)\",\n \"rgb(112, 229, 229)\",\n \"rgb(108, 120, 221)\",\n \"rgb(185, 93, 221)\",\n \"rgb(247, 123, 144)\",\n \"rgb(86, 17, 17)\",\n \"rgb(81, 76, 15)\",\n \"rgb(28, 79, 15)\",\n \"rgb(22, 107, 88)\",\n \"rgb(23, 27, 91)\",\n \"rgb(88, 29, 109)\",\n \"rgb(104, 24, 45)\"\n])\n\nloc = (\"data/trunk_Nation_wide_rate.xlsx\")\nloc2 = (\"data/trunk_Nation_wide_case.xlsx\")\nstatename = 'NationWide'\nwb = xlrd.open_workbook(loc)\nsheet = wb.sheet_by_index(0)\n\nwb2 = xlrd.open_workbook(loc2)\nsheet2 = wb2.sheet_by_index(0)\n\ntotlist = list()\ncurrlist = list()\n\ncollist = list()\n\nprobsum = 0;\nproblist = list()\n\nfor i in range(sheet.nrows):\n rowname = sheet.cell_value(i, 0)\n if (rowname == \"Footnotes:\"):\n break;\n if (rowname != ''):\n if (rowname[-1] == ':'):\n probsum = 0;\n collist.append(rowname)\n newlist = list()\n currlist = newlist\n totlist.append(currlist)\n else :\n rowlist = list()\n sec1 = sheet.cell_value(i, 0)\n sec2 = sheet.cell_value(i, 8)\n sec3 = sheet2.cell_value(i, 8)\n if sec2 == '–' or sec2 == '':\n sec2 = 0;\n if sec3 == '–' or sec3 == '':\n sec3 = 0;\n rowlist.append(sec1)\n rowlist.append(sec2)\n rowlist.append(sec3)\n currlist.append(rowlist)\n# print(collist)\nprint(totlist)\n\n# totlist = [\n# [],\n# [\n# ['Men', 25.4, 128960.0],\n# ['Women', 18.7, 71010.0]\n# ],\n# [\n# ['Under 14', '-', '-'],\n# ['14 to 15', '-', '-'],\n# ['16 to 19', 16.7, 3470.0],\n# ['20 to 24', 24.7, 15850.0],\n# ['25 to 34', 21.9, 43630.0],\n# ['35 to 44', 23.5, 44710.0],\n# ['45 to 54', 25.4, 45140.0],\n# ['55 to 64', 21.0, 36480.0],\n# ['65 and over', 23.1, 7960.0]\n# ]\n# ]# collist = ['', 'Sex', 'Age']\n\nx = []\ny = []\nsizes = []\ntext = []\ncount = 0\n\nfor i in range(1, len(totlist)):\n for j in range(0, len(totlist[i])):\n text.append(totlist[i][j][0])\n x.append(collist[i])\n temp = totlist[i][j][1]\n if temp == '-':\n temp = 0;\n y.append(temp)\n if totlist[i][j][2] == '-': #print(totlist[i][j][2])\n sizes.append(0)\n else :#print(totlist[i][j][2])\n sizes.append(totlist[i][j][2] / 500)\n count += 1\n\n\n\n\n# N = 10# x = np.random.rand(N)# x = ['giraffes', 'orangutans', 'monkeys', 'giraffes', 'giraffes', 'orangutans', 'monkeys', 'giraffes', 'giraffes', 'orangutans']# y = np.random.rand(N)\ncolorIndex = np.random.randint(len(colorsTable), size=count)\ncolors = colorsTable[colorIndex]\n\nfig = go.Figure()\nfig.add_scatter(\n x = x,\n y = y,\n mode = 'markers',\n marker = {\n 'size': sizes,\n 'color': colors,\n 'opacity': 0.6,\n 'colorscale': 'Viridis'\n },\n text = text\n);\nplotly.offline.plot(fig, filename=\"public/graphs/\"+statename+\"_\"+str(2017)+\"_Scatter\"+\".html\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"plot_scatter.py","file_name":"plot_scatter.py","file_ext":"py","file_size_in_byte":3105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"331670351","text":"import sys\nimport re\nimport json\nimport csv\nimport fileinput\nimport argparse\n\ndef parse_and_print(files, print_csv=False):\n\tsamples = {}\n\tp = re.compile(r\"\\[(P\\d{3,}_\\d{3,})\\]\")\n\tfor line in fileinput.input(files=files):\n\t\tm = p.search(line)\n\t\tif m:\n\t\t\ts = m.group(1)\n\t\telse:\n\t\t\tl = line.split(\"=\")\n\t\t\tif len(l) > 2:\n\t\t\t\td = [x.strip(\" -\") for x in l]\n\t\t\t\tsamples.setdefault(s, {})[d[1]] = d[0]\n\tif print_csv:\n\t\t# Convert to list:\n\t\tslist = []\n\t\tfor k,v in samples.items():\n\t\t\tx = {\"SAMPLE\": k}\n\t\t\tx.update(v)\n\t\t\tslist.append(x)\n\t\t# Build header from all unique labels:\n\t\theader = set()\n\t\tfor s in slist:\n\t\t\theader.update(s.keys())\n\t\twriter = csv.DictWriter(sys.stdout,fieldnames=list(header))\n\t\twriter.writeheader()\n\t\tfor s in slist:\n\t\t\twriter.writerow(s)\n\telse:\n\t\tprint(json.dumps(samples))\n\ndef main(args):\n\tparse_and_print(args.files, args.csv)\n\nif __name__ == \"__main__\":\n\tparser = argparse.ArgumentParser(description=\"Parse Supernova reports and print numbers in JSON or CSV\")\n\tparser.add_argument('--csv', action=\"store_true\", default=False,\n\t\thelp='Output in CSV format, default is JSON')\n\tparser.add_argument('files', metavar='FILE', nargs='*',\n\t\thelp='Files to parse, if empty or \"-\" stdin is used')\n\targs = parser.parse_args()\n\tmain(args)","sub_path":"supernova_report_parser.py","file_name":"supernova_report_parser.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"613149161","text":"# pylint: skip-file\n# flake8: noqa\n\n\n# pylint: disable=too-many-public-methods\nclass DeploymentConfig(Yedit):\n ''' Class to model an openshift DeploymentConfig'''\n default_deployment_config = '''\napiVersion: v1\nkind: DeploymentConfig\nmetadata:\n name: default_dc\n namespace: default\nspec:\n replicas: 0\n selector:\n default_dc: default_dc\n strategy:\n resources: {}\n rollingParams:\n intervalSeconds: 1\n maxSurge: 0\n maxUnavailable: 25%\n timeoutSeconds: 600\n updatePercent: -25\n updatePeriodSeconds: 1\n type: Rolling\n template:\n metadata:\n spec:\n containers:\n - env:\n - name: default\n value: default\n image: default\n imagePullPolicy: IfNotPresent\n name: default_dc\n ports:\n - containerPort: 8000\n hostPort: 8000\n protocol: TCP\n name: default_port\n resources: {}\n terminationMessagePath: /dev/termination-log\n dnsPolicy: ClusterFirst\n hostNetwork: true\n nodeSelector:\n type: compute\n restartPolicy: Always\n securityContext: {}\n serviceAccount: default\n serviceAccountName: default\n terminationGracePeriodSeconds: 30\n triggers:\n - type: ConfigChange\n'''\n\n replicas_path = \"spec.replicas\"\n env_path = \"spec.template.spec.containers[0].env\"\n volumes_path = \"spec.template.spec.volumes\"\n container_path = \"spec.template.spec.containers\"\n volume_mounts_path = \"spec.template.spec.containers[0].volumeMounts\"\n\n def __init__(self, content=None):\n ''' Constructor for deploymentconfig '''\n if not content:\n content = DeploymentConfig.default_deployment_config\n\n super(DeploymentConfig, self).__init__(content=content)\n\n def add_env_value(self, key, value):\n ''' add key, value pair to env array '''\n rval = False\n env = self.get_env_vars()\n if env:\n env.append({'name': key, 'value': value})\n rval = True\n else:\n result = self.put(DeploymentConfig.env_path, {'name': key, 'value': value})\n rval = result[0]\n\n return rval\n\n def exists_env_value(self, key, value):\n ''' return whether a key, value pair exists '''\n results = self.get_env_vars()\n if not results:\n return False\n\n for result in results:\n if result['name'] == key:\n if 'value' not in result:\n if value == \"\" or value is None:\n return True\n elif result['value'] == value:\n return True\n\n return False\n\n def exists_env_key(self, key):\n ''' return whether a key, value pair exists '''\n results = self.get_env_vars()\n if not results:\n return False\n\n for result in results:\n if result['name'] == key:\n return True\n\n return False\n\n def get_env_var(self, key):\n '''return a environment variables '''\n results = self.get(DeploymentConfig.env_path) or []\n if not results:\n return None\n\n for env_var in results:\n if env_var['name'] == key:\n return env_var\n\n return None\n\n def get_env_vars(self):\n '''return a environment variables '''\n return self.get(DeploymentConfig.env_path) or []\n\n def delete_env_var(self, keys):\n '''delete a list of keys '''\n if not isinstance(keys, list):\n keys = [keys]\n\n env_vars_array = self.get_env_vars()\n modified = False\n idx = None\n for key in keys:\n for env_idx, env_var in enumerate(env_vars_array):\n if env_var['name'] == key:\n idx = env_idx\n break\n\n if idx:\n modified = True\n del env_vars_array[idx]\n\n if modified:\n return True\n\n return False\n\n def update_env_var(self, key, value):\n '''place an env in the env var list'''\n\n env_vars_array = self.get_env_vars()\n idx = None\n for env_idx, env_var in enumerate(env_vars_array):\n if env_var['name'] == key:\n idx = env_idx\n break\n\n if idx:\n env_vars_array[idx]['value'] = value\n else:\n self.add_env_value(key, value)\n\n return True\n\n def exists_volume_mount(self, volume_mount):\n ''' return whether a volume mount exists '''\n exist_volume_mounts = self.get_volume_mounts()\n\n if not exist_volume_mounts:\n return False\n\n volume_mount_found = False\n for exist_volume_mount in exist_volume_mounts:\n if exist_volume_mount['name'] == volume_mount['name']:\n volume_mount_found = True\n break\n\n return volume_mount_found\n\n def exists_volume(self, volume):\n ''' return whether a volume exists '''\n exist_volumes = self.get_volumes()\n\n volume_found = False\n for exist_volume in exist_volumes:\n if exist_volume['name'] == volume['name']:\n volume_found = True\n break\n\n return volume_found\n\n def find_volume_by_name(self, volume, mounts=False):\n ''' return the index of a volume '''\n volumes = []\n if mounts:\n volumes = self.get_volume_mounts()\n else:\n volumes = self.get_volumes()\n for exist_volume in volumes:\n if exist_volume['name'] == volume['name']:\n return exist_volume\n\n return None\n\n def get_replicas(self):\n ''' return replicas setting '''\n return self.get(DeploymentConfig.replicas_path)\n\n def get_volume_mounts(self):\n '''return volume mount information '''\n return self.get_volumes(mounts=True)\n\n def get_volumes(self, mounts=False):\n '''return volume mount information '''\n if mounts:\n return self.get(DeploymentConfig.volume_mounts_path) or []\n\n return self.get(DeploymentConfig.volumes_path) or []\n\n def delete_volume_by_name(self, volume):\n '''delete a volume '''\n modified = False\n exist_volume_mounts = self.get_volume_mounts()\n exist_volumes = self.get_volumes()\n del_idx = None\n for idx, exist_volume in enumerate(exist_volumes):\n if 'name' in exist_volume and exist_volume['name'] == volume['name']:\n del_idx = idx\n break\n\n if del_idx != None:\n del exist_volumes[del_idx]\n modified = True\n\n del_idx = None\n for idx, exist_volume_mount in enumerate(exist_volume_mounts):\n if 'name' in exist_volume_mount and exist_volume_mount['name'] == volume['name']:\n del_idx = idx\n break\n\n if del_idx != None:\n del exist_volume_mounts[idx]\n modified = True\n\n return modified\n\n def add_volume_mount(self, volume_mount):\n ''' add a volume or volume mount to the proper location '''\n exist_volume_mounts = self.get_volume_mounts()\n\n if not exist_volume_mounts and volume_mount:\n self.put(DeploymentConfig.volume_mounts_path, [volume_mount])\n else:\n exist_volume_mounts.append(volume_mount)\n\n def add_volume(self, volume):\n ''' add a volume or volume mount to the proper location '''\n exist_volumes = self.get_volumes()\n if not volume:\n return\n\n if not exist_volumes:\n self.put(DeploymentConfig.volumes_path, [volume])\n else:\n exist_volumes.append(volume)\n\n def update_replicas(self, replicas):\n ''' update replicas value '''\n self.put(DeploymentConfig.replicas_path, replicas)\n\n def update_volume(self, volume):\n '''place an env in the env var list'''\n exist_volumes = self.get_volumes()\n\n if not volume:\n return False\n\n # update the volume\n update_idx = None\n for idx, exist_vol in enumerate(exist_volumes):\n if exist_vol['name'] == volume['name']:\n update_idx = idx\n break\n\n if update_idx != None:\n exist_volumes[update_idx] = volume\n else:\n self.add_volume(volume)\n\n return True\n\n def update_volume_mount(self, volume_mount):\n '''place an env in the env var list'''\n modified = False\n\n exist_volume_mounts = self.get_volume_mounts()\n\n if not volume_mount:\n return False\n\n # update the volume mount\n for exist_vol_mount in exist_volume_mounts:\n if exist_vol_mount['name'] == volume_mount['name']:\n if 'mountPath' in exist_vol_mount and \\\n str(exist_vol_mount['mountPath']) != str(volume_mount['mountPath']):\n exist_vol_mount['mountPath'] = volume_mount['mountPath']\n modified = True\n break\n\n if not modified:\n self.add_volume_mount(volume_mount)\n modified = True\n\n return modified\n\n def needs_update_volume(self, volume, volume_mount):\n ''' verify a volume update is needed '''\n exist_volume = self.find_volume_by_name(volume)\n exist_volume_mount = self.find_volume_by_name(volume, mounts=True)\n results = []\n results.append(exist_volume['name'] == volume['name'])\n\n if 'secret' in volume:\n results.append('secret' in exist_volume)\n results.append(exist_volume['secret']['secretName'] == volume['secret']['secretName'])\n results.append(exist_volume_mount['name'] == volume_mount['name'])\n results.append(exist_volume_mount['mountPath'] == volume_mount['mountPath'])\n\n elif 'emptyDir' in volume:\n results.append(exist_volume_mount['name'] == volume['name'])\n results.append(exist_volume_mount['mountPath'] == volume_mount['mountPath'])\n\n elif 'persistentVolumeClaim' in volume:\n pvc = 'persistentVolumeClaim'\n results.append(pvc in exist_volume)\n if results[-1]:\n results.append(exist_volume[pvc]['claimName'] == volume[pvc]['claimName'])\n\n if 'claimSize' in volume[pvc]:\n results.append(exist_volume[pvc]['claimSize'] == volume[pvc]['claimSize'])\n\n elif 'hostpath' in volume:\n results.append('hostPath' in exist_volume)\n results.append(exist_volume['hostPath']['path'] == volume_mount['mountPath'])\n\n return not all(results)\n\n def needs_update_replicas(self, replicas):\n ''' verify whether a replica update is needed '''\n current_reps = self.get(DeploymentConfig.replicas_path)\n return not current_reps == replicas\n","sub_path":"ansible/roles/lib_oa_openshift/src/lib/deploymentconfig.py","file_name":"deploymentconfig.py","file_ext":"py","file_size_in_byte":10879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"355752201","text":"#!/usr/bin/env python\nimport _init_paths\nfrom core.net_utils.replace_fillme import replaceFillmeNetwork\nimport argparse,sys\n\ndef parse_args():\n \"\"\"\n Parse input arguments\n \"\"\"\n parser = argparse.ArgumentParser(description='Train a Fast R-CNN network')\n parser.add_argument('--prototxt', dest='prototxt',\n help='Prototxt File',type=str)\n if len(sys.argv) == 1:\n parser.print_help()\n sys.exit(1)\n args = parser.parse_args()\n return args\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n print('Called with args:')\n print(args)\n replaceFillmeNetwork(args.prototxt)\n","sub_path":"tools/expand_fillme_net.py","file_name":"expand_fillme_net.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"132554295","text":"import pandas as pd\nimport numpy as np\nimport datetime\nimport dateutil.parser as dtparser\nimport math\nimport os\n\n\nclass tot_change:\n def __init__(self, dt_input=datetime.datetime.now()):\n if isinstance(dt_input, datetime.datetime):\n self.dt = dt_input\n else:\n self.dt = dtparser.parse(str(dt_input))\n self.dir_pre = 'D:/alpha/许帆/'\n\n def df_to_ini(self, df, fund_id):\n folder_name = self.dir_pre + self.dt.strftime('%Y%m%d')\n if os.path.exists(folder_name):\n pass\n else:\n os.makedirs(folder_name)\n with open(folder_name + '/' + fund_id + '.ini', mode='w', encoding='gbk') as f:\n f.write('[BASKET]\\n')\n f.write('Fundid1=' + fund_id + '\\n')\n f.write('TAGTAG\\n')\n for idx, row in df.iterrows():\n content = row['code'] + '|' + row['exchange'] + '|' + row['name'] + '|' + \\\n str(int(row['to_trade_vol'])) + '\\n'\n f.write(content)\n f.write('ENDENDEND')\n print('%s 生成完毕' % fund_id)\n\n def split_basket(self, tot_df, split):\n tmp_df = tot_df.copy()\n tmp_df['each_vol'] = np.floor(tmp_df['to_trade_vol'] / split / 100) * 100\n tmp_df['remain_vol'] = tmp_df['to_trade_vol'] - tmp_df['each_vol'] * split\n split_df = tmp_df.loc[:, ['code', 'name', 'each_vol', 'exchange']].copy()\n split_df.rename(columns={'each_vol': 'to_trade_vol'}, inplace=True)\n remain_df = tmp_df.loc[tmp_df['remain_vol'] > 0, ['code', 'name', 'remain_vol', 'exchange']].copy()\n remain_df.rename(columns={'remain_vol': 'to_trade_vol'}, inplace=True)\n return [split_df, remain_df]\n\n\n def run(self, file_path, sheet_name, split):\n target_vol = pd.read_excel(file_path, sheet_name)\n target_vol['code'] = target_vol['股票代码'].apply(lambda x: x.split('.')[0])\n positions_date = self.dt\n folder_name = positions_date.strftime('%Y%m%d')\n file_name = '综合信息查询_组合证券_S4_' + folder_name + '.xls'\n while True:\n folder_path = self.dir_pre + folder_name\n if os.path.exists(folder_path) and file_name in os.listdir(folder_path):\n break\n else:\n positions_date = positions_date - datetime.timedelta(days=1)\n folder_name = positions_date.strftime('%Y%m%d')\n file_name = '综合信息查询_组合证券_S4_' + folder_name + '.xls'\n print('XF持仓日期: %s' % folder_name)\n positions_path = self.dir_pre + '/' + folder_name + '/' + file_name\n positions = pd.read_excel(positions_path)\n positions = positions.loc[:, ['证券代码', '证券名称', '持仓']].dropna(subset=['证券代码'])\n positions['证券代码'] = positions['证券代码'].astype('int')\n positions['code'] = positions['证券代码'].apply(lambda x: '0' * (6 - len(str(x))) + str(x))\n merge = pd.merge(positions, target_vol, how='outer', on='code')\n merge['exchange'] = merge['code'].apply(lambda x: 'SH' if x[0] == '6' else 'SZ')\n merge['name'] = merge.apply(lambda x: x['股票简称'] if pd.notnull(x['股票简称']) else x['证券名称'], axis=1)\n merge['持仓'] = merge['持仓'].fillna(0)\n merge['购买股数'] = merge['购买股数'].fillna(0)\n merge['vol_diff'] = merge['购买股数'] - merge['持仓']\n merge['to_trade_vol'] = merge['vol_diff'].apply(lambda x: round(x, -2))\n change_buy = merge.loc[merge['to_trade_vol'] > 0, ['code', 'name', 'to_trade_vol', 'exchange']]\n change_sell = merge.loc[merge['to_trade_vol'] < 0, ['code', 'name', 'to_trade_vol', 'exchange']]\n change_sell['to_trade_vol'] = change_sell['to_trade_vol'] * -1\n\n self.df_to_ini(change_buy, 'XF_tot_buy')\n self.df_to_ini(change_sell, 'XF_tot_sell')\n if split == 1:\n pass\n else:\n split_buy, remain_buy = self.split_basket(change_buy, split)\n split_sell, remain_sell = self.split_basket(change_sell, split)\n self.df_to_ini(split_buy, 'XF_split_buy')\n self.df_to_ini(remain_buy, 'XF_remain_buy')\n self.df_to_ini(split_sell, 'XF_split_sell')\n self.df_to_ini(remain_sell, 'XF_remain_sell')\n\n\nif __name__ == '__main__':\n tot = tot_change()\n tot.run('D:/alpha/许帆/20200309/许帆20200309.xlsx', 'change', 3)\n","sub_path":"generate_basket/XF_tot_change.py","file_name":"XF_tot_change.py","file_ext":"py","file_size_in_byte":4476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"376586106","text":"\"\"\"\nThis script replicates the experiment from Dwork et al's original paper to show\nhow thresholdOut can be used for adaptive feature selection.\n\nHowever, it's improved by allowing more complex (but still linear) classifiers\nto work on the data rather than their simple correlation-based classifier.\n\nALSO, it allows for linear-regression!\n\"\"\"\n\n\n\n\nimport numpy as np\nimport pandas as pd\n\nimport matplotlib.pyplot as plt\nimport seaborn as sb\n\nfrom scipy.stats import zscore\nfrom sklearn.linear_model import *\n\n\ndef createDataset(n, d, yBool=True):\n numInformativeFeatures = 20\n bias = 6.0 / np.sqrt(n)\n X = np.random.normal(0, 1, (3 * n, d + 1))\n\n if yBool:\n X[:, -1] = np.sign(X[:, -1])\n tmpIdx = X[:, -1] == 0\n X[tmpIdx, -1] = 1\n\n for i in range(numInformativeFeatures):\n X[:, i] += bias * X[:, -1]\n\n X_train = zscore(X[0::3, :-1], axis=0)\n Y_train = X[0::3, -1]\n X_holdout = zscore(X[1::3, :-1], axis=0)\n Y_holdout = X[1::3, -1]\n X_test = zscore(X[2::3, :-1], axis=0)\n Y_test = X[2::3, -1]\n return [[X_train, Y_train], [X_holdout, Y_holdout], [X_test, Y_test]]\n\n\ndef createDataset_noSignal(n, d, yBool=True):\n dataset = createDataset(n, d, yBool)\n for d in dataset:\n np.random.shuffle(d[1])\n return dataset\n\n\ndef getFeatureValues(trFeat, hoFeat):\n cutoff_tr = 1.0 * np.sqrt(np.mean(trFeat**2)) # 1 / np.sqrt(n)\n cutoff_ho = 1.0 * np.sqrt(np.mean(hoFeat**2)) # 1 / np.sqrt(n)\n bothPos = (trFeat > cutoff_tr) & (hoFeat > cutoff_ho)\n bothNeg = (trFeat < -cutoff_tr) & (hoFeat < -cutoff_ho)\n goodFeat = bothPos | bothNeg\n featValue = np.copy(np.abs(trFeat).ravel())\n featValue[~goodFeat] = 0.0\n return featValue\n\n\ndef thresholdout(trParam, hoParam, scale):\n\n thr = scale\n tol = thr / 4\n\n trParam = np.array(trParam)\n hoParam = np.array(hoParam)\n newHoParam = np.copy(trParam)\n\n diffNoise = np.abs(trParam - hoParam) - np.random.normal(0, tol, hoParam.shape)\n flipIdx = diffNoise > thr\n newHoParam[flipIdx] = hoParam[flipIdx] + np.random.normal(0, tol, hoParam[flipIdx].shape)\n return newHoParam\n\n\ndef getCoeffs(data):\n coeff = model.fit(data[0], data[1]).coef_.ravel()\n return coeff\n\n\ndef getModelPerf(useFeat, data, model):\n useFeat = useFeat.ravel()\n if useFeat.shape[0] > 0:\n model = model.fit(data[0][0][:, useFeat], data[0][1])\n scores = [model.score(d[0][:, useFeat], d[1]) for d in data]\n else:\n if model._estimator_type == 'regressor':\n scores = [0.0, 0.0, 0.0]\n elif model._estimator_type == 'classifier':\n scores = [0.5, 0.5, 0.5]\n else:\n scores = [-999, -999, -999]\n return scores\n\n\ndef runClassifier(n, d, krange, nullData=False):\n\n if nullData:\n dataset = createDataset_noSignal(n, d, yBool=True)\n else:\n dataset = createDataset(n, d, yBool=True)\n\n if isClsf:\n model = LogisticRegression(penalty='l2', C=1.0)\n else:\n model = LinearRegression()\n\n # Get feature coefficients for training, holdout (actual), and holdout (with THO)\n trainCoeff = getCoeffs(dataset[0])\n holdoutCoeff = getCoeffs(dataset[1])\n holdoutCoeff_tho = thresholdout(trainCoeff, holdoutCoeff, 1.0)\n\n # Use an 'adaptive' approach to finding strong features\n featureValue = getFeatureValues(trainCoeff, holdoutCoeff)\n featureValue_tho = getFeatureValues(trainCoeff, holdoutCoeff_tho)\n\n # Rank the goodness of each feature\n featureRank = np.argsort(-featureValue)\n featureRank_tho = np.argsort(-featureValue_tho)\n\n # Get performance as a function of # of retained features\n vals = [getModelPerf(featureRank[:k], dataset, model) for k in krange]\n vals_tho = [getModelPerf(featureRank_tho[:k], dataset, model) for k in krange]\n # for v in vals_tho:\n # v[1] = thresholdout(v[0], v[1], 0.05)\n\n return vals, vals_tho\n\n\ndef repeatexp(n, d, krange, reps, noSignal):\n \"\"\"\n Repeat the experiment multiple times on different\n datasets to put errorbars on the graphs\n \"\"\"\n condList = ['Train', 'Holdout', 'Test']\n colList = ['perm', 'numFeat', 'perf', 'dset']\n valDataframe_std = pd.DataFrame(data=[], columns=colList)\n valDataframe_tho = pd.DataFrame(data=[], columns=colList)\n for perm in range(reps):\n print(\"Repetition: {}\".format(perm + 1))\n vals_std, vals_tho = runClassifier(n, d, krange, nullData=noSignal)\n for i, cond in enumerate(condList):\n for j, numFeat in enumerate(krange):\n tmpNew_std = pd.DataFrame([[perm, numFeat, vals_std[j][i], cond]], columns=colList)\n tmpNew_tho = pd.DataFrame([[perm, numFeat, vals_tho[j][i], cond]], columns=colList)\n valDataframe_std = pd.concat([valDataframe_std, tmpNew_std], axis=0)\n valDataframe_tho = pd.concat([valDataframe_tho, tmpNew_tho], axis=0)\n return valDataframe_std, valDataframe_tho\n\n\ndef runandplotsummary(n, d, krange, reps):\n \"\"\"\n Run the experiments with/without noise, put it in a subplot\n \"\"\"\n\n print('Running on data WITH signal')\n df_std, df_tho = repeatexp(n, d, krange, reps, False)\n\n print('Running on data WITHOUT signal')\n df_std_ns, df_tho_ns = repeatexp(n, d, krange, reps, True)\n\n f, axes = plt.subplots(2, 2)\n sb.set_style('whitegrid')\n\n sb.tsplot(data=df_std,\n time='numFeat',\n unit='perm',\n condition='dset',\n value='perf',\n ax=axes[0][0])\n axes[0][0].set_title('Standard, HAS Signal')\n\n sb.tsplot(data=df_tho,\n time='numFeat',\n unit='perm',\n condition='dset',\n value='perf',\n ax=axes[0][1])\n axes[0][1].set_title('Thresholdout, HAS Signal')\n\n sb.tsplot(data=df_std_ns,\n time='numFeat',\n unit='perm',\n condition='dset',\n value='perf',\n ax=axes[1][0])\n axes[1][0].set_title('Standard, NO Signal')\n\n sb.tsplot(data=df_tho_ns,\n time='numFeat',\n unit='perm',\n condition='dset',\n value='perf',\n ax=axes[1][1])\n axes[1][1].set_title('Thresholdout, NO Signal')\n\n\n#############################\n#\n# Run the experiment\n#\n\n\"\"\"\nThese two experiments will demonstrate how the use of thresholdout allows for\nadaptive feature selection without overfitting to the trianing data.\n\nisClsf=True will demonstrate using logistic regression classifier\nisClsf=False will demonstrate using multiple regression\n\nNote: The benefits of thresholdOut become clearer as 'd' gets bigger\n\"\"\"\n\nreps = 2\nn, d = 1000, 10000\nkrange = list(range(0, 40, 2))\n\nisClsf = True\n\nplt.close('all')\nrunandplotsummary(n, d, krange, reps)\n","sub_path":"thresholdOut_demoFeatureSelection.py","file_name":"thresholdOut_demoFeatureSelection.py","file_ext":"py","file_size_in_byte":6778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"491789855","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\nprint('Homework 2, k-means')\nprint('Student: Patrick Humphries, 7097-1087-72, pvhumphr@usc.edu')\nprint('Class: INF 552 Machine Learning for Data Science')\nprint('Section: 32458')\nprint('University of Southern California, Spring 2020')\nprint(' ')\nprint('Summary')\nprint('This program implements the k-means algorithm using')\nprint('using file \"clusters.txt\" and the number of clusters set to three.')\nprint(' ')\nprint('Instructions')\nprint('Unzip hw02_humphries.zip into an empty directory.')\nprint('From a command line, execute \"python inf552_assignment_2_humphries_k_means.py\".')\nprint('A series of scatter plots will be displayed. Cancel the current to see the next.')\nprint('The distribution of data points and centroid movement will be displayed in the title.')\nprint(' ')\nprint('The last plot was created using scikit learn.')\nprint(' ')\nprint('Please wait while the first plot is rendered.')\nprint('\\n\\n\\n')\n\n\n# In[ ]:\n\n\n# Import libraries.\nimport csv\nimport matplotlib.pyplot as plt\nfrom matplotlib import patches\nfrom math import sqrt\nfrom sklearn.cluster import KMeans\nimport numpy as np\n\n\n# In[ ]:\n\n\n# The data set into a list of tuples.\n# The data set \"clusters.txt\" was copied to \"custers.csv\" with no modifications.\n# The resulting X is a list of tuple positions of (x,y).\n\ndef load_X(file_name='clusters.csv'):\n X = []\n with open(file_name, newline='') as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n for row in csv_reader:\n row[-1] = row[-1].rstrip()\n X.append((float(row[0]),float(row[1])))\n return X\n\n\n# In[ ]:\n\n\n# The clusters are created as far away as possible from other clusters and data points.\n# This was done to emphasize movement of centroids.\n\ndef create_clusters(K=3):\n C = []\n colors=['red','blue','green','black']\n centroids=[(-8,8),(-8,-8),(8,-8),(8,8)]\n \n for i in range(0,K):\n cluster = {\n \"xy\":centroids[i],\n \"color\":colors[i],\n \"X\":[]\n }\n C.append(cluster)\n return C\n\n\n# In[ ]:\n\n\n# This calculates the distance between a data point and a centroid of a cluster.\n\ndef calc_distance_between_data_points(x, c):\n a = (x[0] - c[\"xy\"][0])**2\n b = (x[1] - c[\"xy\"][1])**2\n return sqrt(a + b)\n\n\n# In[ ]:\n\n\n# Assign data points to closest clusters.\n\ndef assign_data_points_to_a_cluster(X, C):\n \n # Reset clusters.\n for c in C:\n c[\"X\"] = []\n \n # Find the closest cluster for each data point.\n for x in X:\n index_of_shortest_distance = 0\n shortest_distance = 99.0\n i = 0\n for c in C:\n distance = calc_distance_between_data_points(x, c)\n \n if distance < shortest_distance:\n shortest_distance = distance\n index_of_shortest_distance = i\n \n i += 1\n \n # Retrieve the closest cluster.\n c = C[index_of_shortest_distance]\n \n # Assign the data point to the closest cluster.\n c[\"X\"].append(x)\n \n return C\n\n\n# In[ ]:\n\n\n# Load data, create clusters, and point the initial state.\n# Return X, C, T\n# X: Data points\n# C: Clusters\n# T: Control totals\n\ndef initialization():\n \n # Load data.\n X = load_X()\n print('Number of data points:', len(X))\n\n # Create clusters.\n C = create_clusters()\n print('Number of clusters created:', len(C))\n \n # Create control totals for data points and total centroid movement.\n T = {}\n for c in C:\n color = c[\"color\"]\n T[color] = 0\n T[\"movement\"] = 0\n \n # Plot data points and clusters.\n plot_data_points(X,C,T)\n \n return (X,C,T)\n\n\n# In[ ]:\n\n\n# Assign data points to clusters, calculate centroids, and plot the current state.\n# Total movement of centroids is returned.\n# Returned is the total of centroid movement.\n\ndef realign_data_points(X,C,T):\n \n C = assign_data_points_to_a_cluster(X,C)\n \n total_movement = recalculate_centroids(C,T)\n \n # Update control totals\n for c in C:\n print(c[\"color\"], len(c[\"X\"]))\n color = c[\"color\"]\n T[color] = len(c[\"X\"])\n \n plot_clustering(X,C,T)\n \n return total_movement\n\n\n# In[ ]:\n\n\n# Recalculate the centroids based on the associated data points.\n# The total movement of the centroids is returned.\n\ndef recalculate_centroids(C,T):\n \n # Intialize the total movement of the centroids.\n total_movement = 0.0\n \n # Sum the members of the cluster.\n for c in C:\n \n # Preserve the current centroid for comparison.\n prior_xy = c[\"xy\"]\n \n # Sum the data points.\n total_X = [0.0, 0.0]\n for x in c[\"X\"]:\n total_X[0] += x[0]\n total_X[1] += x[1]\n \n # Calculate the new centroid.\n n = len(c[\"X\"])\n a = total_X[0]/n\n b = total_X[1]/n\n c[\"xy\"] = (a,b)\n \n # Accumulate movement of all centroids.\n total_movement += calc_distance_between_data_points(prior_xy, c)\n \n # Update control totals.\n T[\"movement\"] = total_movement\n \n print('Total centroid movement: {:.2f}'.format(total_movement))\n \n # Return the total movement of all centroids.\n return round(total_movement, 2)\n\n\n# In[ ]:\n\n\n# This initial visualization displays data points as grey dots, not aligned with a cluster.\n# The clusters are displayed in color in their initial positions.\ndef plot_data_points(X,C,T):\n\n fig, ax = plt.subplots(subplot_kw={\"aspect\":\"equal\"})\n \n # Display control totals in the title.\n s = ' '\n for key in T:\n s += (key + \": \" + str(T[key]) + \", \")\n fig.suptitle(s)\n \n # Display data points.\n for xy in X:\n \n circle = patches.Circle(xy,\n radius=0.2,\n color=\"lightgrey\")\n \n ax.add_artist(circle)\n \n # Display clusters.\n for c in C:\n \n circle = patches.Circle(c[\"xy\"],\n radius=1.0,\n color=c[\"color\"],\n linewidth=1.0,\n fill=False,\n zorder=2.0)\n ax.add_patch(circle)\n\n # Set axis limits to contain all data points.\n ax.set_xlim([-10,10])\n ax.set_ylim([-10,10])\n \n # Showtime.\n plt.show()\n\n\n# In[ ]:\n\n\n# Plot clusters and the associated data points in the color of the cluster.\ndef plot_clustering(X,C,T):\n \n fig, ax = plt.subplots(subplot_kw={\"aspect\":\"equal\"})\n \n # Display control totals in the title.\n T[\"movement\"] = round(T[\"movement\"], 2)\n s = ' '\n for key in T:\n s += (key + \": \" + str(T[key]) + \", \")\n fig.suptitle(s)\n \n \n # Plot clusters.\n for c in C:\n \n circle = patches.Circle(c[\"xy\"],\n radius=1.0,\n color=c[\"color\"],\n linewidth=1.0,\n fill=False,\n zorder=2.0)\n ax.add_patch(circle)\n \n # Plot data points for the cluster.\n for x in c[\"X\"]:\n circle = patches.Circle(x, \n radius=0.2,\n color=c[\"color\"],\n linewidth=1.0)\n \n ax.add_patch(circle)\n\n # Set axis to contain all data points.\n ax.set_xlim([-10,10])\n ax.set_ylim([-10,10])\n \n # Showtime.\n plt.show()\n\n\n# In[ ]:\n\n\n# Compare to scikit learn.\ndef call_library():\n # Count members in each cluster.\n kmeans_counts = KMeans(n_clusters=3, random_state=0).fit(X)\n counters = [0] * 3\n for count in kmeans_counts.labels_:\n counters[count] += 1\n\n # Format title\n s = ' '\n for i in range(0, len(counters)):\n s += 'Counter ' + str(i) + ': ' + str(counters[i]) + ' '\n\n # Plot the predictions.\n kmeans_predict = KMeans(n_clusters=3, random_state=0).fit_predict(X)\n a = []\n b = []\n for x in X:\n a.append(x[0])\n b.append(x[1])\n plt.scatter(a, b, c=kmeans_predict)\n plt.title(s)\n plt.show()\n\n\n# In[ ]:\n\n\n# Main routine.\n# Plot the intial state and subsequent states of clusters.\n# Stop when there is no further movement of centroids.\n# X: List of data point tuples (x,y).\n# C: List of clusters.\n\n# Load data points, create clusters, and plot the initial state.\nX,C,T = initialization()\n\n# Reassign data points to clusters, move centroids, and plot the new state.\nfor i in range(0,10):\n \n total_movement = realign_data_points(X,C,T)\n \n # Stop if there is relatively no movement of centroids.\n if total_movement < 0.01:\n break\n\n# Plot using scikit library.\ncall_library()\n\n","sub_path":"static/py/inf552/assignment_2/inf552_assignment_2_humphries_k_means.py","file_name":"inf552_assignment_2_humphries_k_means.py","file_ext":"py","file_size_in_byte":8920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"14807887","text":"from Traversal import TreeTraversal\nfrom Traversal import TreeNode\n\n\nclass Solution(TreeTraversal):\n def __init__(self):\n super(Solution, self).__init__()\n\n def mergeTree(self, t1: TreeNode, t2: TreeNode) -> TreeNode:\n if not t1 and not t2:\n return\n\n v1 = t1.val if t1 else 0\n v2 = t2.val if t2 else 0\n root = TreeNode(v1 + v2)\n root.left = self.mergeTree(t1.left if t1 else None, t2.left if t2 else None)\n root.right = self.mergeTree(t1.right if t1 else None, t2.right if t2 else None)\n\n return root\n\n\nimport collections\n\nclass Node(object):\n def __init__(self, val):\n self.val = val\n self.left = None\n self.right = None\n\n\ndef levelOrder(root: Node):\n stack = collections.deque()\n stack.append(root)\n while stack:\n rowSize = len(stack)\n row = []\n while rowSize > 0:\n root = stack.popleft()\n if root.left is not None:\n stack.append(root.left)\n if root.right is not None:\n stack.append(root.right)\n row.append(root.val)\n rowSize -= 1\n print(row)\n\n\n\n\ntree = Node('a')\ntree.left = Node('b')\ntree.right = Node('c')\ntree.left.left = Node('d')\ntree.left.right = Node('e')\ntree.right.left = Node('f')\ntree.right.right = Node('g')\n\nlevelOrder(tree)\n\n\nif __name__ == \"__main__\":\n t1 = TreeNode(1, TreeNode(3, TreeNode(5)), TreeNode(2))\n t2 = TreeNode(2, TreeNode(1, None, TreeNode(4)), TreeNode(3, None, TreeNode(7)))\n test = Solution()\n result = test.mergeTree(t1, t2)\n\n print_out = TreeTraversal()\n print_out.print_tree(result)\n\n test.InOrder(result)\n","sub_path":"BinaryTree/MergeTree.py","file_name":"MergeTree.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"148097820","text":"from utils import *\n\n\ndef calculate_area_of_rectangle(a, b):\n return a*b\n\n\ndef calculate_area_of_square(s):\n return s**2\n\n\ndef calculate_and_print_area_of_square_or_rectangle():\n print('Select one:\\n'\n '1 - area of square\\n'\n '2 - area of rectangle')\n inp = input()\n if inp == '1':\n s = input('Input side of a square ')\n if str_to_float_or_int_converter(s):\n s = str_to_float_or_int_converter(s)\n if s > 0:\n can_continue = True\n else:\n can_continue = False\n else:\n can_continue = False\n if can_continue:\n print('Area of square is ' + str(calculate_area_of_square(s)))\n else:\n print('Error side must be a number that higher than 0')\n calculate_and_print_area_of_square_or_rectangle()\n elif inp == '2':\n a = input('Input first side of a rectangle ')\n if str_to_float_or_int_converter(a):\n a = str_to_float_or_int_converter(a)\n if a > 0:\n can_continue = True\n else:\n can_continue = False\n else:\n can_continue = False\n b = input('Input second side of a rectangle ')\n if str_to_float_or_int_converter(b) and can_continue:\n b = str_to_float_or_int_converter(b)\n if b > 0:\n can_continue = True\n else:\n can_continue = False\n if can_continue:\n print('Area of rectangle is ' + str(calculate_area_of_rectangle(\n a, b)))\n else:\n print('Error sides must be a numbers that higher than 0')\n calculate_and_print_area_of_square_or_rectangle()\n else:\n calculate_and_print_area_of_square_or_rectangle()\n print('Please input 1 or 2')\n\n\nif __name__ == '__main__':\n calculate_and_print_area_of_square_or_rectangle()\n","sub_path":"calculator/area_calculator/area_of_square_or_rectangle.py","file_name":"area_of_square_or_rectangle.py","file_ext":"py","file_size_in_byte":1926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"348511258","text":"# -*- coding: utf-8 -*-\n\nimport re\nimport grab\nimport json\n\n\nsurl = u'https://www.google.com/complete/search?client=hp&gs_rn=64&gs_ri=hp&cp=3&gs_id=e&q={q}&xhr=t'\n\ndef just_alnum(string):\n string = string.replace(' ', ' ').replace('&', '&').replace('<', '<').replace('>', '>').replace('"', '\"').replace(''', \"'\").replace(''', \"'\")\n string = re.sub('[^\\d\\wа-яА-ЯЁёїЇіІйЙъЪыЫ\\ \\'\\&\\-]+', u' ', string.lower().strip())\n string = re.sub('\\ +', u' ', string)\n string = re.sub('\\s+', u' ', string)\n return string.strip()\n\ndef get_correct(keyword):\n g = grab.Grab(\n connect_timeout = 16,\n timeout = 15,\n # proxy='127.0.0.1:9050',\n # proxy_type = 'socks5'\n )\n correct = None\n success = False\n for att in range(3):\n try:\n g.go(surl.format(q = keyword))\n if g.response.code in [200, 204]:\n success = True\n break\n except Exception as e0:\n print(\"g.go error : {e}\".format(e = e0))\n if success:\n data = g.response.body\n try:\n data = data.decode('utf8', errors='ignore')\n except Exception as e0:\n print('decoding body error : {e}'.format(e = e0))\n data = re.sub('\\s+', ' ', data)\n data = data.replace(':', ' : ')\n\n res = json.loads(data)\n kws = [just_alnum(str(re.sub('', '', i[0]))) for i in res[1]]\n\n ks = sorted(keyword.split(' '))\n for w in kws:\n # print(w)\n ws = sorted(w.split(' '))\n if ks == ws:\n correct = w\n return (correct == keyword)\n\n\nkws = open(\"keywords.txt\", \"r\")\nsf = open('mapping.txt', 'w')\n\nfor ks in kws:\n k = ks.strip()\n c = get_correct(k)\n print(k, c)\n sf.write(\"{};{}\\n\".format(k, c))\n sf.flush()\nsf.close()\n","sub_path":"check_with_google_suggestions_v.py","file_name":"check_with_google_suggestions_v.py","file_ext":"py","file_size_in_byte":1855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"458377150","text":"\nfrom .. import LastAnalysis\n\nfrom _analysis_base import Analysis_Base\nfrom analysis import inspectors\nfrom analysis import tools\n\nimport ROOT\nimport math\nimport array\nimport copy\n\n\nclass OpticsAnalysis(Analysis_Base) :\n\n def __init__(self) :\n Analysis_Base.__init__(self, \"optics_reconstruction\")\n\n self.__inspectors = { 0: {}, 1: {} }\n self.__data = { 0: {}, 1: {} }\n self.__do_upstream = False\n self.__do_downstream = False\n self.__graphs = {}\n\n\n def analyse_event(self, analysis_event, weight=1.0) :\n if self.__do_upstream and (analysis_event.num_upstream_tracks()) :\n track = analysis_event.upstream_track()\n for plane_id in self.__inspectors[0] :\n hit = track[plane_id]\n hit.set_weight(weight)\n self.__inspectors[0][plane_id].add_hit( hit )\n\n if self.__do_downstream and (analysis_event.num_downstream_tracks()):\n track = analysis_event.downstream_track()\n for plane_id in self.__inspectors[1] :\n hit = track[plane_id]\n hit.set_weight(weight)\n self.__inspectors[1][plane_id].add_hit( hit )\n\n\n def _get_plots(self, plot_dict) :\n for graph in self.__graphs :\n plot_dict[graph] = self.__graphs[graph]\n\n\n def _get_data(self, data_dict) :\n data_dict['upstream'] = self.__data[0]\n data_dict['downstream'] = self.__data[1]\n\n\n def configure_arguments(self, parser) :\n parser.add_argument( \"--trackers\", nargs='+', type=int, default=[0, 1], help=\"Specify which trackers to analyse\" )\n parser.add_argument( \"--planes\", nargs='+', type=int, default=[1, 4, 7, 10, 13], help=\"Specify which tracker planes to analyse (1-15)\" )\n\n\n def parse_arguments(self, namespace) :\n if 0 in namespace.trackers :\n self.__do_upstream = True\n if 1 in namespace.trackers :\n self.__do_downstream = True\n\n for i in namespace.trackers :\n for j in namespace.planes :\n self.__inspectors[i][j] = inspectors.PhaseSpace2DInspector(i, 0)\n self.__data[i][j] = None\n\n\n def conclude(self) :\n for i in self.__inspectors :\n for j in self.__inspectors[i] :\n self.__data[i][j] = self.__inspectors[i][j].get_data_dictionary()\n\n emittance = array.array(\"d\")\n emittance_x = array.array(\"d\")\n emittance_y = array.array(\"d\")\n beta = array.array(\"d\")\n beta_x = array.array(\"d\")\n beta_y = array.array(\"d\")\n alpha = array.array(\"d\")\n alpha_x = array.array(\"d\")\n alpha_y = array.array(\"d\")\n momentum = array.array(\"d\")\n number_particles = array.array(\"d\")\n\n error_emittance = array.array(\"d\")\n error_emittance_x = array.array(\"d\")\n error_emittance_y = array.array(\"d\")\n error_beta = array.array(\"d\")\n error_beta_x = array.array(\"d\")\n error_beta_y = array.array(\"d\")\n error_alpha = array.array(\"d\")\n error_alpha_x = array.array(\"d\")\n error_alpha_y = array.array(\"d\")\n error_momentum = array.array(\"d\")\n zeros = array.array(\"d\")\n position = array.array(\"d\")\n\n for i in self.__inspectors :\n for j in self.__inspectors[i] :\n emittance.append(self.__data[i][j]['emittance'])\n emittance_x.append(self.__data[i][j]['emittance_x'])\n emittance_y.append(self.__data[i][j]['emittance_y'])\n beta.append(self.__data[i][j]['beta'])\n beta_x.append(self.__data[i][j]['beta_x'])\n beta_y.append(self.__data[i][j]['beta_y'])\n alpha.append(self.__data[i][j]['alpha'])\n alpha_x.append(self.__data[i][j]['alpha_x'])\n alpha_y.append(self.__data[i][j]['alpha_y'])\n momentum.append(self.__data[i][j]['momentum'])\n number_particles.append(self.__data[i][j]['number_particles'])\n\n error_emittance.append(self.__data[i][j]['emittance_error'])\n error_emittance_x.append(self.__data[i][j]['emittance_x_error'])\n error_emittance_y.append(self.__data[i][j]['emittance_y_error'])\n error_beta.append(self.__data[i][j]['beta_error'])\n error_beta_x.append(self.__data[i][j]['beta_x_error'])\n error_beta_y.append(self.__data[i][j]['beta_y_error'])\n error_alpha.append(self.__data[i][j]['alpha_error'])\n error_alpha_x.append(self.__data[i][j]['alpha_x_error'])\n error_alpha_y.append(self.__data[i][j]['alpha_y_error'])\n error_momentum.append(self.__data[i][j]['momentum_error'])\n\n zeros.append(0.0)\n position.append(self.__data[i][j]['position'])\n\n\n position_copy = copy.copy(position)\n\n position, emittance, emittance_x, emittance_y, alpha, alpha_x, alpha_y, beta, beta_x, beta_y, momentum, number_particles = tools.sort_arrays(\\\n [position, emittance, emittance_x, emittance_y, alpha, alpha_x, alpha_y, beta, beta_x, beta_y, momentum, number_particles], 0)\n\n position_copy, error_emittance, error_emittance_x, error_emittance_y, error_alpha, error_alpha_x, error_alpha_y, error_beta, error_beta_x, error_beta_y, error_momentum = tools.sort_arrays(\\\n [position_copy, error_emittance, error_emittance_x, error_emittance_y, error_alpha, error_alpha_x, error_alpha_y, error_beta, error_beta_x, error_beta_y, error_momentum], 0)\n\n\n self.__graphs['emittance'] = ROOT.TGraphErrors(len(position), position, emittance, zeros, error_emittance)\n self.__graphs['emittance_x'] = ROOT.TGraphErrors(len(position), position, emittance_x, zeros, error_emittance_x)\n self.__graphs['emittance_y'] = ROOT.TGraphErrors(len(position), position, emittance_y, zeros, error_emittance_y)\n\n self.__graphs['beta'] = ROOT.TGraphErrors(len(position), position, beta, zeros, error_beta)\n self.__graphs['beta_x'] = ROOT.TGraphErrors(len(position), position, beta_x, zeros, error_beta_x)\n self.__graphs['beta_y'] = ROOT.TGraphErrors(len(position), position, beta_y, zeros, error_beta_y)\n\n self.__graphs['alpha'] = ROOT.TGraphErrors(len(position), position, alpha, zeros, error_alpha)\n self.__graphs['alpha_x'] = ROOT.TGraphErrors(len(position), position, alpha_x, zeros, error_alpha_x)\n self.__graphs['alpha_y'] = ROOT.TGraphErrors(len(position), position, alpha_y, zeros, error_alpha_y)\n \n self.__graphs['momentum'] = ROOT.TGraphErrors(len(position), position, momentum, zeros, error_momentum)\n self.__graphs['number_particles'] = ROOT.TGraphErrors(len(position), position, number_particles, zeros, zeros)\n\n \n\n","sub_path":"lib/mickey/analysis_modules/optics_recon.py","file_name":"optics_recon.py","file_ext":"py","file_size_in_byte":6260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"573249004","text":"#! python3\r\n''' SS_position_RAP_inversion.py - Script that takes in experimental acoustic\r\ndata collected by the Kilo Moan at the ALOHA Cabled Observatory (ACO) and \r\nperforms Reliable Acoustic Path (RAP) Tomography to compute for a Sound Speed\r\nfield and seafloor mounted hydrophone position correction. This script is\r\nto be used with \"ray_trace_w_earth_flattening.py\", \"grid_space_distance.py\". '''\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport scipy.io as sio\r\nfrom math import sqrt, pi\r\nfrom geographiclib.geodesic import Geodesic\r\nfrom ray_trace_w_earth_flattening import Ray_Tracing\r\nfrom grid_space_distance import pixel_distance\r\nfrom guassian_covariance_matrix import gauss_cov_matrix\r\n\r\n# Finds the center of a pixel given the tick marks\r\ndef pixel_center(ticks):\r\n center_pix = []\r\n for pix in range(len(ticks) - 1):\r\n center_pix.append((ticks[pix] + ticks[pix + 1]) / 2)\r\n return center_pix\r\n\r\n\r\n# Empirical Orthogonal Function to provide z-dependence on transmission\r\n# (derived from previous HOTS CTD casts)\r\nEOF_MODE_1 = sio.loadmat('EOF_mode_1.mat')['EOF_mode']\r\nEOF_MODE_1 = [val for sub_l in EOF_MODE_1 for val in sub_l] # make flat list\r\nEOF_MODE_1 = np.append(EOF_MODE_1, [EOF_MODE_1[-1]] * 4) # ensure sufficient EOF length\r\nEOF_LAMBDA_1 = sio.loadmat('EOF_lambda_1.mat')['EOF_lambda']\r\n########### EOF FILL - EDIT #################\r\n\r\n\r\n# Current estimated position of hydrophone\r\nN_mean = 2.30 # Geoid height at lat/lon\r\nHEM_lat = 22.738772\r\nHEM_lon = -158.006186\r\nHEM_z = -4729.92 - N_mean\r\n\r\n\r\n# Load experimental data\r\nRAP_data = sio.loadmat('RAP_test_HEM_flat_earth.mat')['RAP_test'][0][0]\r\nt_act = RAP_data['t_act'][0] # Reception time\r\nt_tx = RAP_data['t_tx'][0] # Transmission time\r\nt_diff1 = RAP_data['t_diff'][0] # Actual vs. estimated tt (Matlab)\r\ntx_lon = RAP_data['lon'][0] # Longitude of vessel\r\ntx_lat = RAP_data['lat'][0] # Latitude of vessel\r\n# x_dist = RAP_data['x_dist'][0] # Surface distance from hydrophone\r\nz_tx = RAP_data['z'][0] # Elevation of vessel\r\nheading = RAP_data['heading'][0] # Heading of vessel\r\nx_err = RAP_data['lon_err'][0] # Longitude uncertainty\r\ny_err = RAP_data['lat_err'][0] # Latitude uncertatinty\r\nz_err = RAP_data['z_err'][0] # Elevation uncertainty\r\n\r\n\r\n# Initialize variables\r\nnum_tx = len(t_act) # Number of transmissions\r\ng_bound = 28450 # Grid bound size for area of interest\r\n\r\n# Get lat/lon boundaries for area of interest\r\nmax_lat = Geodesic.WGS84.Direct(HEM_lat, HEM_lon, 0, g_bound)['lat2']\r\nmax_lon = Geodesic.WGS84.Direct(HEM_lat, HEM_lon, 90, g_bound)['lon2']\r\nmin_lat = Geodesic.WGS84.Direct(HEM_lat, HEM_lon, 180, g_bound)['lat2']\r\nmin_lon = Geodesic.WGS84.Direct(HEM_lat, HEM_lon, 270, g_bound)['lon2']\r\n\r\n# Split area up into evenly spaced grid points\r\nn_cols = 11\r\nn_rows = 11\r\nx_ticks = np.linspace(min_lon, max_lon, n_cols + 1) # Pixel Ticks\r\ny_ticks = np.linspace(min_lat, max_lat, n_rows + 1) # Pixel Ticks\r\ncenter_x = pixel_center(x_ticks) # Pixel Center\r\ncenter_y = pixel_center(y_ticks) # Pixel Center\r\n\r\n\r\n# Vessel distance, bearing, and angle relative to hydrophone for each tx\r\nx_dist = []\r\nazmth = []\r\nves_brng = []\r\nfor lat, lon in zip(tx_lat, tx_lon):\r\n x_dist.append(Geodesic.WGS84.Inverse(lat, lon, HEM_lat, HEM_lon)['s12'])\r\n azmth.append(Geodesic.WGS84.Inverse(lat, lon, HEM_lat, HEM_lon)['azi1'])\r\n ves_brng.append(90 - azmth[-1])\r\nves_brng = np.array(ves_brng) * pi / 180 # convert to radians\r\n\r\n\r\n\r\n# num_tx = 10\r\n# Pre-allocation of SS observation matrix (G_SS) and other variables\r\nG_SS = np.zeros((len(center_y) * len(center_x), num_tx), dtype=float)\r\nray_angles = np.zeros((2, num_tx)) # save tx and rx ray angle\r\nest_tt2 = np.zeros(num_tx) # estimated tt given surface range\r\n\r\n# Loop through all transmissions to solve for the SS observation matrix\r\nSS_end = [] # SS where rx was made \r\nfor t_num in range(num_tx):\r\n# for t_num in range(10):\r\n\r\n # Compute ray tracing to determine inital launch angle of transmission\r\n # and ray arc lengths for each depth layer\r\n ray = Ray_Tracing(x_dist[t_num], z_tx[t_num], tx_lat[t_num], azmth[t_num], HEM_lat, HEM_lon, HEM_z)\r\n SS, z = ray.ctd_data() # CTD derived SS profile\r\n SS, z = ray.earth_flat_transform(SS, z) # flat earth correction\r\n ray_info = ray.ray_trace(SS, z) # ray tracing\r\n\r\n arc_lens = np.array(ray_info['arc_dist'])\r\n SS_avg = ray_info['SS_pro_avg']\r\n surf_dist = ray_info['surface_dist']\r\n thetas = np.array(ray_info['theta_pro'])\r\n ray_angles[:, t_num] = thetas[0], thetas[-1]\r\n est_tt2[t_num] = ray_info['tt']\r\n SS_end.append(SS[-1])\r\n\r\n\r\n # Calculate the surface distance traveled in each pixel with respect\r\n # to the given x and y tick marks\r\n pix_dist, pix_num = pixel_distance(tx_lat[t_num], tx_lon[t_num], HEM_lat, HEM_lon, x_ticks, y_ticks)\r\n\r\n\r\n # Find arc lengths that correspond to total surface distance in each pixel\r\n pix_arc = [] # arc length for each pixel (related to pix_dist)\r\n arc_depth = [0] # arc length depth begins at tx \"surface\"\r\n cur_pix = 0 # start at pixel with transmission\r\n tot_surf_dist = 0 # keep track of surf dist traveled\r\n tot_arc_dist = 0 # keep track of ray arc len traveled\r\n for z_lyr, (cur_dist, arc_len) in enumerate(zip(surf_dist, arc_lens)):\r\n\r\n # Check if current arc length reaches beyond current picel\r\n if tot_surf_dist + cur_dist >= pix_dist[cur_pix]:\r\n # Find proportion of current layer that is within pixel\r\n lyr_prop = (pix_dist[cur_pix] - tot_surf_dist) / cur_dist\r\n pix_arc.append(tot_arc_dist + (arc_len * lyr_prop))\r\n \r\n # Update arc/surface length, arc depth, and current pixel\r\n tot_arc_dist = arc_len * (1 - lyr_prop)\r\n tot_surf_dist = cur_dist * (1 - lyr_prop)\r\n arc_depth.append(z_lyr + 1)\r\n cur_pix += 1\r\n \r\n # Add to current arc/surface length\r\n else:\r\n tot_surf_dist += cur_dist\r\n tot_arc_dist += arc_len\r\n\r\n # Ensure pixel with reception has been registered\r\n if len(pix_arc) < len(pix_dist):\r\n arc_depth.append(z_lyr + 1)\r\n pix_arc.append(tot_arc_dist)\r\n assert len(pix_arc) == len(pix_dist)\r\n\r\n\r\n # Add information to the SS observation matrix (G_SS)\r\n for pixel in range(len(pix_arc)):\r\n G_SS[pix_num[pixel]][t_num] = sum(EOF_MODE_1[arc_depth[pixel]: (arc_depth[pixel + 1] - 1)] *\r\n (-arc_lens[arc_depth[pixel]: (arc_depth[pixel + 1] - 1)] / \\\r\n (((SS[arc_depth[pixel]: (arc_depth[pixel + 1] - 1)])) ** 2)))\r\n\r\n\r\n# Create rx hydrophone position observation matrix (G_pos)\r\nG_x = np.cos(ves_brng[:num_tx]) * np.sin(ray_angles[-1][:]) / SS_end\r\nG_y = np.sin(ves_brng[:num_tx]) * np.sin(ray_angles[-1][:]) / SS_end\r\nG_z = np.cos(ray_angles[-1][:]) / SS_end\r\nG_pos = np.column_stack((G_x, G_y, G_z))\r\n########## TAKE OUT EDIT OF NUM_TX HERE TOO ############\r\n\r\n\r\n# Combine the SS and hydrophone position observation matrices\r\nG = np.column_stack((np.transpose(G_SS), G_pos))\r\n\r\n\r\n# Model uncertainty (Cm) due to apriori SS field and hydrophone position (x,y,z)\r\nSS_uncertainty = sqrt(EOF_LAMBDA_1)\r\npos_uncertainty = [100, 100, 5]\r\n\r\nlen_scale = 5_000 # Gaussian covariance length scale (meters)\r\nCm = gauss_cov_matrix(SS_uncertainty, pos_uncertainty, center_x, center_y, len_scale)\r\n\r\n\r\n# Data uncertainty (Cd) due to rx time (from xcorrs, etc.) and vessel position uncertainty\r\nt_uncertainty = 0.001\r\n########## TAKE OUT EDIT OF NUM_TX HERE AND BEFORE LOOP ABOVE ############\r\nx_anomaly = (((np.sin(ray_angles[0][:]) / SS_avg) * np.cos(ves_brng[:num_tx])) ** 2) * (x_err[:num_tx]) ** 2\r\ny_anomaly = (((np.sin(ray_angles[0][:]) / SS_avg) * np.sin(ves_brng[:num_tx])) ** 2) * (y_err[:num_tx]) ** 2\r\nz_anomaly = ((np.cos(ray_angles[0][:]) / SS_avg) ** 2) * (z_err[:num_tx]) ** 2\r\nSS_anomaly = x_anomaly + y_anomaly + z_anomaly\r\n\r\nCd = np.diag(SS_anomaly + (t_uncertainty) ** 2)\r\n#########################################################################\r\n\r\n\r\n\r\n# Estimated arrival time (convert to matlab timing)\r\nest_tt1 = (t_act[:num_tx] - t_tx[:num_tx]) * 3600 * 24 - t_diff1[:num_tx] # matlab est tt\r\nt_est2 = (t_tx[:num_tx] + (est_tt2 / (3600 * 24))) # est arrival (Python)\r\nt_diff2 = (t_act[:num_tx] - t_est2) * 3600 * 24 # actual vs. estimated tt (Python)\r\npy_mat_diff = est_tt1 - est_tt2 # tt estimate diff between matlab and python code\r\n\r\n\r\n# Compute the generalized inverse (GI == Cm * G' / (G * Cm * G' + Cd))\r\na = Cm @ np.transpose(G) # a == Cm * G'\r\nb = G @ Cm @ np.transpose(G) + Cd # b == G * Cm * G' + Cd\r\nGI = a @ np.linalg.pinv(b)\r\n\r\n# SS and hydrophone position perturbation\r\nd1 = t_diff1[:num_tx] # data vector\r\nm1 = GI @ d1\r\nm1_SS = m1[:-3]\r\nm1_pos = m1[-3:]\r\n# print(m_SS, m_pos)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n################################ FIGURES ################################\r\n\r\n\r\nx_dist = np.array(x_dist) / 1000 # convert surface distance into km\r\nt_diff1 = t_diff1 * 1000 # convert tt perturbations into ms\r\nt_diff2 = t_diff2 * 1000 # convert tt perturbations into ms\r\n\r\n# Difference between Matlab and Python travel times\r\nfig, ax = plt.subplots()\r\nmat_t_plt = ax.scatter(x_dist[:num_tx], t_diff1[:num_tx], color='b')\r\npy_t_plt = ax.scatter(x_dist[:num_tx], t_diff2, color='r')\r\nax.legend((mat_t_plt, py_t_plt), ('Matlab', 'Python'))\r\nplt.title('TT Perturbations (HEM)')\r\nplt.xlabel('Range (km)')\r\nplt.ylabel('(ms)')\r\nplt.grid(True)\r\nplt.show()\r\n\r\n\r\n# Matlab and Python travel times w.r.t. range\r\n# fig, ax = plt.subplots()\r\n# mat_t_plt = ax.scatter(x_dist[:num_tx], est_tt1[:num_tx], color='b')\r\n# py_t_plt = ax.scatter(x_dist[:num_tx], est_tt2, color='r')\r\n# ax.legend((mat_t_plt, py_t_plt), ('Matlab', 'Python'))\r\n# plt.title('Travel times (HEM)')\r\n# plt.xlabel('Range (km)')\r\n# plt.ylabel('(s)')\r\n# plt.grid(True)\r\n# plt.show()\r\n\r\n# Difference in Matlab and Python tt w.r.t. range\r\nfig, ax = plt.subplots()\r\nmat_t_plt = ax.scatter(x_dist[:num_tx], est_tt1[:num_tx] - est_tt2)\r\nplt.title('Difference between Matlab and Python TT (HEM)')\r\nplt.xlabel('Range (km)')\r\nplt.ylabel('(s)')\r\nplt.grid(True)\r\nplt.ylim(min(est_tt1[:num_tx] - est_tt2) - 0.0001, max(est_tt1[:num_tx] - est_tt2) + 0.0001)\r\nplt.show()\r\n\r\n\r\n\r\n","sub_path":"SS_position_RAP_Inversion_HEM.py","file_name":"SS_position_RAP_Inversion_HEM.py","file_ext":"py","file_size_in_byte":10758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"174172058","text":"\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):\n self.val = int(x)\n self.next = next\n self.random = random\n\"\"\"\n\nclass Solution:\n def copyRandomList(self, head: 'Node') -> 'Node':\n if not head:\n return None\n \n # Step 1\n temp = head\n while temp:\n new_node = Node(x=temp.val)\n new_node.next = temp.next\n temp.next = new_node\n temp = temp.next.next\n \n # Step 2\n temp = head\n while temp:\n if temp.random:\n temp.next.random = temp.random.next\n temp = temp.next.next\n \n # Step 3\n new_head = head.next\n new_p = new_head\n old_p = head\n while new_p.next:\n old_p.next = new_p.next\n old_p = old_p.next\n new_p.next = old_p.next\n new_p = new_p.next\n old_p.next = None\n new_p.next = None\n return new_head\n","sub_path":"src/链表操作/q138_复制带随机指针的链表/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"547890762","text":"'''UIConsole class that interacts with the user to provide information\nalso parses the json file\n'''\n__author__ = 'Arpit'\nimport json\nfrom src.Graph import Graph\nfrom src.Vertex import Vertex\nfrom src.Edge import Edge\nimport webbrowser\n\n\nclass UIConsole:\n\n '''This function parses the JSON file that we've been provided\n and returns a single data object that we can access data from\n\n @param json_file the file from which data is to be collected\n '''\n def parse_json_file(json_file):\n with open(json_file) as map_data:\n data = json.load(map_data)\n return data\n\n def add_champaign_to_route(graph, data, data_2):\n\n source_list=graph.create_source_list(data, data_2)\n city_list=graph.create_city_list(data, data_2)\n route_list=graph.create_route_list(data, data_2)\n\n def store_to_disk(source_list,city_list,route_list):\n new_data = {\n 'data sources': source_list,\n 'metros': city_list,\n 'routes': route_list\n }\n\n with open('data.json', 'w') as outfile:\n json.dump(new_data, outfile, sort_keys = True, indent = 4,\n ensure_ascii=False)\n\n '''\n This function stores the changes to a file on disk\n\n @param graph the graph object we're working on\n @param latest_data the data to be stored to the json file\n '''\n\n def store_to_disk(graph,latest_data):\n\n source_list =list()\n\n for source in latest_data[\"data sources\"]:\n source_list.append(source)\n print(type(source_list))\n print(type(graph.vertex_list))\n print(type(graph.edge_list))\n\n new_data = {\n 'data sources': source_list,\n 'metros': graph.vertex_list,\n 'routes': graph.edge_list\n }\n\n with open('data.json', 'w') as outfile:\n json.dump(new_data, outfile, sort_keys = True, indent = 4,ensure_ascii=False)\n\n data = parse_json_file('map_data.json')\n cmi_data = parse_json_file('cmi_hub.json')\n\n graph = Graph()\n graph.create_vertices(data)\n graph.create_edges(data)\n\n graph.create_vertices(cmi_data)\n graph.create_edges(cmi_data)\n\n add_champaign_to_route(graph,data,cmi_data)\n\n flag=\"continue\"\n while flag==\"continue\":\n\n latest_data=parse_json_file('data.json')\n\n print_string=\"Hello!\" \\\n \"Welcome to CS Air\\n\" \\\n \"How can I help you today?\\n\" \\\n \"List of all cities\\n\" \\\n \"Information about specific city\\n\" \\\n \"Information about specific route\\n\" \\\n \"Information about CS Air Route Network\\n\" \\\n \"Show entire route of CS Air in new browser tab\\n\" \\\n \"Remove a city\\n\" \\\n \"Remove a route\\n\" \\\n \"Add a city\\n\" \\\n \"Add a route\\n\" \\\n \"Edit a city\\n\" \\\n \"Find the shortest route\\n\" \\\n \"Store to Disk\\n\" \\\n \"Exit\\n\"\n option = input(print_string)\n option = option.lower()\n\n if option == \"exit\":\n flag =\"\"\n\n elif option == \"all cities\":\n graph.print_all_cities()\n\n elif option == \"specific city\":\n city_code=input(\"Enter City code: \")\n graph.specific_city_information(city_code)\n\n elif option == \"specific route\":\n route_list = list()\n route_list.append(input(\"Please enter the first city code on the route: \"))\n\n route_flag = \"continue\"\n while route_flag == \"continue\":\n route_list.append(input(\"Please enter the next city code on the route: \"))\n route_flag = input(\"If you want to add more cities, enter continue\\n Print anything else to exit\\n\").lower()\n print(graph.specific_route_information(route_list))\n\n elif option== \"info\":\n print_string=\"Longest single flight \" \\\n \"Shortest single flight\\n\" \\\n \"Average distance of all the flights\\n\" \\\n \"Biggest city (by population) served\\n\" \\\n \"Smallest city (by population) served\\n\" \\\n \"Average size (by population) served\\n\" \\\n \"List of the continents served\\n\" \\\n \"Cities that have the most direct connections\\n\" \\\n \"Go Back?\\n\"\n route_option =input(print_string)\n if route_option==\"longest flight\":\n max_edge = graph.longest_flight()\n print( max_edge.origin+\" to \"+max_edge.destination)\n elif route_option==\"shortest flight\":\n min_edge = graph.shortest_flight()\n print( min_edge.origin+\" to \"+str(min_edge.destination))\n elif route_option==\"average distance\":\n avg_dist = graph.average_distance()\n print(\"The average distance is: \"+avg_dist)\n elif route_option==\"biggest city\":\n print(\"The biggest city is: \" + graph.biggest_city())\n elif route_option==\"smallest city\":\n print(\"The shortest city is: \" + graph.smallest_city())\n elif route_option==\"average size\":\n avg_size = graph.average_city_size()\n print(\"The average size(population) of cities served by CS Air is: \"+str(avg_size))\n elif route_option==\"list continents\":\n print(graph.list_continents())\n elif route_option==\"most connections\":\n print(\"The city with the most connections is :\"+graph.most_connections())\n elif route_option==\"go back\":\n continue\n else:\n print(\"Invalid input\")\n\n elif option == \"map\":\n url = graph.map()\n webbrowser.open_new_tab(url)\n\n elif option == \"remove city\":\n city_code=input(\"Please enter the city code of the city you would like to remove\\n\")\n graph.remove_city(city_code)\n\n elif option == \"remove route\":\n origin=input(\"Please enter the origin of the route you would like to remove\\n\")\n destination=input(\"Please enter the destination of the route you would like to remove\\n\")\n graph.remove_route(origin,destination)\n\n elif option == \"add city\":\n city_code=input(\"Please enter the city code of the city you would like to add\\n\")\n city_name=input(\"Please enter the city name of the city you would like to add\\n\")\n country=input(\"Please enter the country of the city you would like to add\\n\")\n continent=input(\"Please enter the continent of the city you would like to add\\n\")\n timezone=int(input(\"Please enter the timezone of the city you would like to add\\n\"))\n coordinates=input(\"Please enter the coordinates of the city you would like to add\\n\")\n population=int(input(\"Please enter the population of the city you would like to add\\n\"))\n region=int(input(\"Please enter the region of the city you would like to add\\n\"))\n\n city = Vertex(city_code, city_name, country, continent, timezone,\n coordinates, population, region)\n graph.vertex_list.append(city)\n\n elif option == \"edit route\":\n route_origin=input(\"Please enter the origin of the route you would like to add\\n\")\n route_dest=input(\"Please enter the destination of the route you would like to add\\n\")\n route_distance=int(input(\"Please enter the distance of the route you would like to add\\n\"))\n\n route = Edge(route_origin,route_dest,route_distance)\n graph.edge_list.append(route)\n\n elif option == \"edit city\":\n city_code=input(\"Please enter the city code of the city you would like to modify\\n\")\n graph.edit_city(city_code)\n\n elif option == \"shortest route\":\n origin=input(\"Please enter the origin city you would like\\n\")\n destination=input(\"Please enter the destination city you would like\\n\")\n graph.find_shortest_route(origin,destination)\n\n else:\n print(\"Invalid input\")\n '''elif option == \"store\":\n answer=input(\"Are you sure you want to store changes to disk?\")\n if answer==\"yes\":\n store_to_disk(graph,latest_data)\n else:\n print(\"Lol\")\n '''\n","sub_path":"src/UIConsole.py","file_name":"UIConsole.py","file_ext":"py","file_size_in_byte":8289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"314762043","text":"#!/usr/bin/python3\n\nimport sys\nimport time\nimport telepot\nimport datetime\nfrom commandhandler import *\nimport group_utilities\nimport random\nimport os\n#Cooldown length in seconds\nCOOLDOWN_SEC = 10\n#Percentage to ignore command\nFAILPERCENTAGE = 1\nFAILID = [215620618]\n#fetching our BOT_TOKEN\ntry:\n BOT_TOKEN = os.environ['BOT_TOKEN'] #Hosting the bot on Heroku/Docker\nexcept KeyError:\n BOT_TOKEN = sys.argv[1]\n\n\ncommands = {\n '/stfu' : stfu,\n '/ask' : ask,\n '/roll' : roll,\n '/beemovie' : beemovie,\n '/nice' : nice,\n '/dab' : dab,\n '/lemmesmash' : lemmesmash,\n '/rotfl' : rotfl\n}\n\ndef chat_handler(msg):\n content_type, chat_type, chat_id = telepot.glance(msg)\n\n if 'reply_to_message' in msg:\n reply_to_message_handler(msg)\n return\n\n if content_type == 'text':\n\n #If the message contains a bot command, go tell command_handler\n try:\n if msg['entities'][0]['type'] == 'bot_command':\n handler(msg, COOLDOWN_SEC, bot)\n\n #If the message contains Hendrik, send a complaint message to sender\n except KeyError:\n if ' lumber' in (msg['text'].lower()) or 'lumber' == msg['text'].lower()[:len('lumber')]:\n if random.randint(0,1) == 1:\n bot.sendMessage(chat_id, \"LUMBER IS ETERNAL\")\n else:\n bot.sendMessage(chat_id, 'THERE ARE NO BRAKES ON THE LUMBER TRAIN')\n\ndef reply_to_message_handler(msg):\n if msg['from']['id'] == 164788390:\n if msg['text'].lower() == \"delet this\":\n try:\n bot.deleteMessage((msg['chat']['id'], msg['message_id']))\n bot.deleteMessage((msg['chat']['id'], msg['reply_to_message']['message_id']))\n except:\n print (\"I need deleting rights for {}!\".format(msg['chat']['id']))\n\n handler(msg, COOLDOWN_SEC, bot)\n\n\n\ndef edit_handler(msg):\n content_type, chat_type, chat_id = telepot.glance(msg)\n print (\"edit!!!\")\n try:\n if msg['entities'][0]['type'] == 'bot_command':\n bot.sendMessage(chat_id, \"Voetsek, don't edit your commands.\", reply_to_message_id=msg['message_id'])\n except:\n if content_type == 'text':\n pass\n\ndef callback_query_handler(msg):\n pass\n\ndef handler(msg, cooldown_sec, bot):\n content_type, chat_type, chat_id = telepot.glance(msg)\n if all(card in msg['text'].lower() for card in ['play', 'card']):\n bot.sendMessage(chat_id, \"Fuck off\")\n return\n\n if random.randrange(0,100)==FAILPERCENTAGE and msg['from']['id'] in FAILID:\n bot.sendMessage(chat_id, \"No, fuck you\")\n return\n\n if not msg['from']['id'] in recentUsers: #Is the person in the recent users dict\n\n if blacklist.search(dbquery.id == msg['from']['id']) != []:#Is the person in the blacklist\n group_utilities.logger('blacklist', msg, False, 0, 0)\n return\n\n elif not msg['from']['username'] == 'profhiggins': #If the person isn't profhiggins, save the time the message was sent\n recentUsers[msg['from']['id']] = datetime.datetime.now()\n\n else: #If the person IS in the recent users dict\n if blacklist.search(dbquery.id == msg['from']['id']) != []:#Is the person in the blacklist?\n group_utilities.logger('blacklist', msg, False, 0, 0)\n return\n\n elif (datetime.datetime.now() - recentUsers[msg['from']['id']]) > datetime.timedelta(0, cooldown_sec): #Was the the timestamp in the dictionary more than cooldown_sec ago\n del recentUsers[msg['from']['id']] #Remvoe the listing in the dict\n recentUsers[msg['from']['id']] = datetime.datetime.now() #Puthis message in the dictionary\n\n else: #Was the message sent less than cooldown_sec ago?\n group_utilities.logger('cooldown', msg, False, str(datetime.datetime.now() - recentUsers[msg['from']['id']]), 0)\n return\n\n for command in commands:\n if msg['text'][:len(command)] == command:\n commands[command](msg, chat_id, bot)\n\n\n\nif __name__ == \"__main__\":\n #make our bot and feed it the tokenhend\n bot = telepot.Bot(BOT_TOKEN)\n\n #fetch messages and keep script looped\n bot.message_loop({'chat' : chat_handler,\n 'edited_chat' : edit_handler,\n 'callback_query' : callback_query_handler},\n run_forever=\"Bot Running...\")\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"648009006","text":"__author__ = 'zn'\n# logging\nimport logging.handlers as HD\nfrom Common import myConfig as C\nimport time\nimport logging\n\n\nclass MyLogger:\n\n def __init__(self):\n #实例化logging对象\n self.logger = logging.getLogger(\"api_autoTest\")\n self.logger.setLevel(logging.INFO)\n # 日志内容输出格式设置\n fmt = '%(asctime)s %(filename)s %(funcName)s [line:%(lineno)d] %(levelname)s %(message)s'\n datefmt = '%a, %d %b %Y %H:%M:%S'\n format = logging.Formatter(fmt, datefmt)\n curTime = time.strftime(\"%Y-%m-%d %H%M\", time.localtime())\n #输出日志到文件中\n file_handler = HD.TimedRotatingFileHandler(C.logs_dir + \"/Api_Autotest_log_{0}.log\".format(curTime),backupCount=20,encoding=\"utf-8\",maxBytes=1024*1024*100)\n file_handler.setFormatter(format)\n file_handler.setLevel(logging.INFO)\n self.logger.addHandler(file_handler)\n #输出日志到控制台\n handle_1 = HD.TimedRotatingFileHandler(C.logs_dir + \"/Api_Autotest_log_{0}.log\".format(curTime),backupCount=20,encoding=\"utf-8\")\n handle_1.setFormatter(format)\n handle_1.setLevel(logging.INFO)\n self.logger.addHandler(handle_1)\n hs = logging.StreamHandler()\n hs.setFormatter(format)\n hs.setLevel(logging.INFO)\n self.logger.addHandler(hs)\n\n #配置日志收集器 - 存在放哪个文件,\n #定义各种日志级别的方法,方便在其它文件中调用\n def info(self,msg):\n self.logger.info(msg)\n\n def debug(self,msg):\n self.logger.debug(msg)\n\n def error(self,msg):\n self.logger.error(msg)\n\n def warning(self,msg):\n self.logger.warning(msg)\n\n def critical(self,msg):\n self.logger.critical(msg)\n\n def exception(self,msg):\n self.logger.exception(msg)\n","sub_path":"Common/myLogger.py","file_name":"myLogger.py","file_ext":"py","file_size_in_byte":1832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"464520797","text":"\"\"\"\r\n@author: Guilherme Esgario\r\n@email: guilherme.esgario@gmail.com\r\n\"\"\"\r\n\r\nimport cv2\r\nimport numpy as np\r\nimport imageio as m\r\nfrom PIL import Image\r\nfrom skimage import measure\r\nimport matplotlib.pyplot as plt\r\n\r\nimport torch\r\nimport torchvision.transforms as transforms\r\nfrom .net_models import PSPNet, resnet50\r\n\r\nBIOTIC_STRESS_LABEL = ('Outros', 'Bicho mineiro', 'Ferrugem', 'Mancha-de-phoma', 'Cercosporiose')\r\n\r\ndef image_resize(image, width = None, height = None, inter = cv2.INTER_AREA):\r\n dim = None\r\n (h, w) = image.shape[:2]\r\n\r\n # if both the width and height are None, then return the original image\r\n if width is None and height is None:\r\n return image\r\n\r\n # check to see if the width is None\r\n if width is None:\r\n r = height / float(h)\r\n dim = (int(w * r), height)\r\n\r\n # otherwise, the height is None\r\n else:\r\n r = width / float(w)\r\n dim = (width, int(h * r))\r\n\r\n # resize the image\r\n resized = cv2.resize(image, dim, interpolation = inter)\r\n\r\n return resized\r\n\r\nclass SymptomsImages():\r\n \r\n def __init__(self, labels_pred, orig_img):\r\n self.orig_img = orig_img\r\n self.labels, self.num_labels = measure.label(labels_pred>1, return_num=True)\r\n self.leaf_area = np.sum(labels_pred>0)\r\n self.props = measure.regionprops(self.labels)\r\n self.i = 0\r\n \r\n def __iter__(self):\r\n return self\r\n \r\n def __next__(self):\r\n if self.i >= self.num_labels:\r\n raise StopIteration\r\n else:\r\n self.i += 1\r\n \r\n # Avoid small symptoms \r\n while (self.props[self.i-1].area / self.leaf_area) * 100 < 0.1:\r\n if self.i >= self.num_labels:\r\n raise StopIteration\r\n \r\n self.i += 1\r\n \r\n bbox = np.array(self.props[self.i-1].bbox)\r\n bbox_copy = bbox.copy()\r\n \r\n rrow = self.orig_img.shape[0] / self.labels.shape[0]\r\n rcol = self.orig_img.shape[1] / self.labels.shape[1]\r\n \r\n # Padding\r\n srow = int((bbox[2] - bbox[0]) * 0.2)\r\n scol = int((bbox[3] - bbox[1]) * 0.2)\r\n \r\n bbox[0], bbox[1] = max(0, bbox[0]*rrow - srow), max(0, bbox[1]*rcol - scol)\r\n bbox[2], bbox[3] = min(self.orig_img.shape[0], bbox[2]*rrow + srow), min(self.orig_img.shape[1], bbox[3]*rcol + scol)\r\n \r\n image = self.orig_img[bbox[0]:bbox[2],bbox[1]:bbox[3],:]\r\n severity = (self.props[self.i-1].area / self.leaf_area) * 100\r\n \r\n return image, severity, self.labels, self.i, bbox_copy\r\n\r\nclass Classifier():\r\n \r\n def __init__(self, options):\r\n self.opt = options\r\n self.transform = transforms.Compose([\r\n transforms.Resize((224, 224)),\r\n transforms.ToTensor(),\r\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\r\n ])\r\n \r\n \r\n def readImage(self, img_size=(512, 256), show_img=False):\r\n # Read Image\r\n img = m.imread(self.opt.in_image_path)\r\n img = img[:,:,:3]\r\n img = np.array(img, dtype=np.uint8)\r\n \r\n orig_img = img.copy()\r\n\r\n if show_img:\r\n plt.imshow(img)\r\n plt.show()\r\n \r\n # Transform\r\n img = cv2.resize(img, (img_size[0], img_size[1]))\r\n img = img[:, :, ::-1] # RGB -> BGR\r\n img = img.astype(np.float64)\r\n img = img.astype(float) / 255.0\r\n img = img.transpose(2, 0, 1) # NHWC -> NCHW\r\n img = torch.from_numpy(img[None,:,:,:]).float()\r\n \r\n return img.to(self.device), orig_img\r\n \r\n\r\n def showMask(self, mask):\r\n n_classes = 3\r\n label_colours = [[0, 0, 0],\r\n [0, 176, 0],\r\n [255, 0, 0]]\r\n \r\n r = mask.copy()\r\n g = mask.copy()\r\n b = mask.copy()\r\n for l in range(0, n_classes):\r\n r[mask == l] = label_colours[l][0]\r\n g[mask == l] = label_colours[l][1]\r\n b[mask == l] = label_colours[l][2]\r\n \r\n rgb = np.zeros((mask.shape[0], mask.shape[1], 3))\r\n rgb[:, :, 0] = r / 255.0\r\n rgb[:, :, 1] = g / 255.0\r\n rgb[:, :, 2] = b / 255.0\r\n \r\n plt.imshow(rgb)\r\n plt.show()\r\n \r\n return rgb\r\n \r\n \r\n def createOutputImage(self, labels):\r\n # Parameters\r\n alpha = 0.2 \r\n kernel = np.ones((5, 5),np.uint8)\r\n img_width=800\r\n colors = [[0, 0, 0], # Black\r\n [255, 0, 0], # Red\r\n [255, 255, 0], # Yellow\r\n [0, 255, 255], # Cyan\r\n [127, 0, 255]] # Purple \r\n \r\n # Resize image\r\n image_orig = self.orig_img.copy()\r\n image_orig = image_resize(image_orig, width=img_width)\r\n image = self.orig_img.copy()\r\n image = image_resize(image, width=img_width)\r\n \r\n # Resize label\r\n labels = cv2.resize(labels, (image.shape[1], image.shape[0]), interpolation=cv2.INTER_NEAREST)\r\n labels_contour = cv2.dilate(labels, kernel, iterations=1)\r\n labels_contour -= labels\r\n \r\n for i, color in enumerate(colors):\r\n image[np.where(labels==i+1)] = color\r\n \r\n image = image.astype(np.float32)*alpha + image_orig.astype(np.float32)*(1-alpha)\r\n \r\n for i, color in enumerate(colors):\r\n image[np.where(labels_contour==i+1)] = color\r\n \r\n return image.astype(np.uint8)\r\n \r\n\r\n def segmentation(self):\r\n # Loading network weights\r\n model = PSPNet(sizes=(1, 2, 3, 6), psp_size=2048, deep_features_size=1024)\r\n model.load_state_dict(torch.load(self.opt.segmentation_weights, map_location=self.device))\r\n model.eval()\r\n out, out_cls = model(self.img)\r\n \r\n labels_pred = torch.max(out, 1)[1]\r\n# self.showMask(labels_pred.cpu().numpy()[0])\r\n \r\n return labels_pred.cpu().numpy()[0]\r\n \r\n def save(self, image, severity, bbox):\r\n \r\n row_p = image.shape[0] / 256\r\n col_p = image.shape[1] / 512\r\n \r\n # Save results\r\n colors = ['black', 'red', 'gold', 'cyan', 'purple']\r\n fig = plt.figure(figsize=(6, 6*image.shape[0]/image.shape[1]))\r\n plt.imshow(image)\r\n plt.axis('off')\r\n f = lambda m,c: plt.plot([],[],marker=m, color=c, ls=\"none\")[0]\r\n \r\n handles = []\r\n labels = []\r\n for i, s in enumerate(severity):\r\n if s > 0:\r\n handles.append(f(\"s\", colors[i]))\r\n labels.append('%s: %.1f%%' % (BIOTIC_STRESS_LABEL[i], s))\r\n \r\n # Plot Numbers\r\n for i, b in enumerate(bbox):\r\n t = plt.text(0.5*(b[3]+b[1])*col_p-8, b[0]*row_p-10,\r\n str(i))\r\n t.set_bbox(dict(facecolor='white', alpha=0.5, edgecolor='white', pad=1))\r\n \r\n # Plot Legend\r\n legend = plt.legend(handles,\r\n labels,\r\n ncol=2,\r\n labelspacing=0.5,\r\n borderaxespad=0,\r\n columnspacing=0.2,\r\n handletextpad=0.1,\r\n bbox_to_anchor=(1., -0.03),\r\n fontsize=12)\r\n# plt.show()\r\n fig.savefig(self.opt.out_image_path, bbox_inches='tight', pad_inches=0.02, dpi=200)\r\n plt.close(fig)\r\n \r\n \r\n def run(self):\r\n # Cuda\r\n# if torch.cuda.is_available():\r\n# self.device = torch.device(\"cuda:\" + str(torch.cuda.current_device()))\r\n# else:\r\n self.device = torch.device(\"cpu\")\r\n \r\n # Reading image\r\n self.img, self.orig_img = self.readImage()\r\n \r\n # Segmentation\r\n labels = self.segmentation()\r\n \r\n # Classification\r\n model = resnet50(num_classes=5)\r\n model.load_state_dict(torch.load(self.opt.symptom_weights, map_location=self.device))\r\n model.eval()\r\n \r\n # Vector with the total severity of each symptom\r\n severity = np.zeros(5)\r\n bbox = []\r\n new_labels = np.zeros(labels.shape)\r\n \r\n result = ''\r\n \r\n for i, (image, severity_ind, lbl, lbl_id, bbox_ind) in enumerate(SymptomsImages(labels, self.orig_img)):\r\n# plt.imshow(image)\r\n# plt.show()\r\n \r\n image = Image.fromarray(image) # Convert to PIL image\r\n image = self.transform(image.convert('RGB')).view(1, 3, 224, 224)\r\n image = image.to(self.device)\r\n out = model(image)\r\n \r\n out = torch.nn.functional.softmax(out, dim=1)\r\n confidence_level, idx = torch.max(out, 1)\r\n confidence_level = (confidence_level.detach().cpu().numpy() * 100).astype('float')\r\n \r\n # Output label\r\n out = int(idx.cpu().numpy())\r\n \r\n# if out > 0:\r\n severity[out] += severity_ind\r\n \r\n new_labels[np.where(np.array(lbl)==lbl_id)] = out+1\r\n \r\n # Saving bounding box values\r\n bbox.append(bbox_ind)\r\n \r\n # Printing results\r\n result += '%d,%s,%d\\n' % (i, BIOTIC_STRESS_LABEL[out], confidence_level[0])\r\n \r\n if result == '':\r\n result = '---,Sadia,---'\r\n \r\n outputImage = self.createOutputImage(new_labels)\r\n self.save(outputImage, severity, bbox)\r\n \r\n return result","sub_path":"codes/coffee/classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":9747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"199684287","text":"from okapi.settings import settings\n\n\nclass Test(object):\n def __init__(self, test):\n \"\"\"\n :param test: String to be asserted (eg. `status_code == 200`)\n :type test: str\n \"\"\"\n self.test = test\n self.result = True\n self.message = None\n self.log = ''\n\n def __repr__(self):\n return '\"{}\"'.format(str(self))\n\n def __str__(self):\n if self.message:\n return '{} -- {}'.format(self.test, self.message)\n return self.test\n\n def run(self, variables):\n \"\"\"\n Execute assertion for a test.\n\n :param variables: Dictionary of with variables passed to exec.\n :type variables: dict\n\n :return: Result of assertion\n :rtype: bool\n \"\"\"\n try:\n exec('assert ' + self.test, variables)\n except Exception as e:\n self.message = str(e)\n self.result = False\n\n self.log += '\\t\\t[FAIL] ' + str(self) + '\\n'\n\n if settings.debug:\n self.debug(variables)\n return False\n\n self.log += '\\t\\t[OK] ' + str(self) + '\\n'\n return True\n\n @staticmethod\n def debug(variables):\n \"\"\"\n Starts pdb debugger with given variables.\n\n :param variables: Variables passed to debugger.\n :type variables: dict\n \"\"\"\n settings.log.write('\\nVariables:')\n settings.log.write('\\n' + ', '.join(sorted(variables.keys())))\n settings.log.write('\\nPress `c` to continue or `q` to quit.\\n')\n exec('import pdb; pdb.set_trace()', variables)\n","sub_path":"okapi/core/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"279089557","text":"import pandas as pd\nfrom pathlib import Path\nimport os\n\ndef key(query,key_query):\n work_dir = Path.cwd().parent / 'csv'\n data=pd.read_csv(os.path.join(work_dir,f'{query}.csv'))\n name=['title','link']\n dir_export = Path.cwd().parent / 'key' / query\n dir = Path.cwd().parent / 'key'\n if not dir.exists():\n dir.mkdir()\n if not dir_export.exists():\n dir_export.mkdir()\n for key,value in key_query.items():\n final_content_list = []\n for i in value:\n for ii in range(len(data)):\n title = data.iloc[ii, 1]\n link = data.iloc[ii, 2]\n if title.count(i) > 0:\n print(title, i)\n final_items = []\n final_items.append(title)\n final_items.append(link)\n final_content_list.append(final_items)\n print(final_content_list)\n test = pd.DataFrame(columns=name, data=final_content_list)\n test = test.drop_duplicates(['title'])\n test.to_csv(os.path.join(dir_export, \"{}.csv\".format(key)), mode='a', encoding='utf-8-sig')","sub_path":"key_word.py","file_name":"key_word.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"6506937","text":"import luigi\nimport pandas as pd\nimport numpy as np\nimport os\nimport pickle\nlist_sum = sum\n\nfrom mars_gym.data.task import BasePrepareDataFrames, BasePySparkTask\nfrom mars_gym.data.utils import DownloadDataset\nfrom mars_gym.data.dataset import (\n InteractionsDataset,\n InteractionsWithNegativeItemGenerationDataset,\n)\nimport random\nfrom typing import Tuple, List, Union, Callable, Optional, Set, Dict, Any\nfrom mars_gym.meta_config import *\n\nfrom pyspark import SparkContext\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql import functions as F\nfrom pyspark.sql.functions import collect_set, collect_list, lit, sum, udf, concat_ws, col, count, abs, date_format, \\\n from_utc_timestamp, expr, min, max\nfrom pyspark.sql.functions import col, udf, size\nfrom pyspark.sql.types import *\nfrom pyspark.sql import functions as F\nfrom pyspark.sql import Window\nfrom pyspark.sql.functions import explode, posexplode\nfrom itertools import chain\nfrom datetime import datetime, timedelta\nfrom tqdm import tqdm\ntqdm.pandas()\n\nOUTPUT_PATH: str = os.environ[\n \"OUTPUT_PATH\"\n] if \"OUTPUT_PATH\" in os.environ else os.path.join(\"output\")\nBASE_DIR: str = os.path.join(OUTPUT_PATH, \"diginetica\")\nDATASET_DIR: str = os.path.join(OUTPUT_PATH, \"diginetica\", \"dataset\")\n\nBASE_DATASET_FILE : str = os.path.join(OUTPUT_PATH, \"diginetica\", \"dataset-train-diginetica\", 'train-item-views.csv')\n\n## AUX\npad_history = F.udf(\n lambda arr, size: list(reversed(([0] * (size - len(arr[:-1][:size])) + arr[:-1][:size]))), \n ArrayType(IntegerType())\n)\n\ndef sample_items(item, item_list, size_available_list):\n return random.sample(item_list, size_available_list - 1) + [item]\n\ndef udf_sample_items(item_list, size_available_list):\n return udf(lambda item: sample_items(item, item_list, size_available_list), ArrayType(IntegerType()))\n\n\ndef concat(type):\n def concat_(*args):\n return list(set(chain.from_iterable((arg if arg else [] for arg in args))))\n return udf(concat_, ArrayType(type))\n\n#####\n\n\n################################## Supervised ######################################\n\nclass SessionPrepareDataset(BasePySparkTask):\n sample_days: int = luigi.IntParameter(default=16)\n history_window: int = luigi.IntParameter(default=10)\n size_available_list: int = luigi.IntParameter(default=100)\n minimum_interactions: int = luigi.IntParameter(default=5)\n \n def output(self):\n return luigi.LocalTarget(os.path.join(DATASET_DIR, \"dataset_prepared_sample={}_win={}_list={}_min_i={}.csv\"\\\n .format(self.sample_days, self.history_window, self.size_available_list, self.minimum_interactions),))\n\n def add_history(self, df):\n \n w = Window.partitionBy('SessionID').orderBy('Timestamp')#.rangeBetween(Window.currentRow, 5)\n\n df = df.withColumn(\n 'ItemIDHistory', F.collect_list('ItemID').over(w)\n ).where(size(col(\"ItemIDHistory\")) >= 2)#\\\n\n df = df.withColumn('ItemIDHistory', pad_history(df.ItemIDHistory, lit(self.history_window)))\n\n return df\n\n def filter(self, df):\n # filter date\n max_timestamp = df.select(max(col('Timestamp'))).collect()[0]['max(Timestamp)']\n init_timestamp = max_timestamp - timedelta(days = self.sample_days)\n df = df.filter(col('Timestamp') >= init_timestamp).cache()\n\n # Filter minin interactions\n df_item = df.groupBy(\"ItemID\").count()\n df_item = df_item.filter(col('count') >= self.minimum_interactions)\n\n # Filter session size\n df_session = df.groupBy(\"SessionID\").count()\n df_session = df_session.filter(col('count') >= 2)\n\n df = df \\\n .join(df_item, \"ItemID\", how=\"inner\") \\\n .join(df_session, \"SessionID\", how=\"inner\")\n\n return df\n\n def add_available_items(self, df):\n all_items = list(df.select(\"ItemID\").dropDuplicates().toPandas()[\"ItemID\"])\n\n df = df.withColumn('AvailableItems', udf_sample_items(all_items, self.size_available_list)(col(\"ItemID\")))\n\n return df\n\n def main(self, sc: SparkContext, *args):\n os.makedirs(DATASET_DIR, exist_ok=True)\n\n spark = SparkSession(sc)\n df = spark.read.option(\"delimiter\", \";\").csv(BASE_DATASET_FILE, header=True, inferSchema=True)\n df = df.withColumnRenamed(\"sessionId\", \"SessionID\")\\\n .withColumnRenamed(\"eventdate\", \"Timestamp\")\\\n .withColumnRenamed(\"itemId\", \"ItemID\")\\\n .withColumn(\"Timestamp\", (col(\"Timestamp\").cast(\"long\") + col(\"timeframe\").cast(\"long\")/1000).cast(\"timestamp\"))\\\n .orderBy(col('Timestamp'), col('SessionID'), col('timeframe')).select(\"SessionID\", \"ItemID\", \"Timestamp\", \"timeframe\")\n \n # Drop duplicate item in that same session\n df = df.dropDuplicates(['SessionID', 'ItemID'])\n\n df = self.filter(df)\n df = self.add_history(df)\n df = self.add_available_items(df)\n\n df = df.withColumn('visit',lit(1))\n\n df.toPandas().to_csv(self.output().path, index=False)\n\nclass SessionInteractionDataFrame(BasePrepareDataFrames):\n sample_days: int = luigi.IntParameter(default=16)\n history_window: int = luigi.IntParameter(default=10)\n size_available_list: int = luigi.IntParameter(default=100)\n days_test: int = luigi.IntParameter(default=1)\n index_mapping_path: str = luigi.Parameter(default=None)\n\n def requires(self):\n return SessionPrepareDataset(sample_days=self.sample_days, history_window=self.history_window, size_available_list=self.size_available_list)\n\n @property\n def timestamp_property(self) -> str:\n return \"Timestamp\"\n\n @property\n def item_property(self) -> str:\n return \"ItemID\"\n\n @property\n def dataset_dir(self) -> str:\n return DATASET_DIR\n\n @property\n def read_data_frame_path(self) -> pd.DataFrame:\n return self.input().path\n\n def read_data_frame(self) -> pd.DataFrame:\n df = pd.read_csv(self.read_data_frame_path)#.sample(10000)\n \n return df\n\n def transform_data_frame(self, df: pd.DataFrame, data_key: str) -> pd.DataFrame:\n \n return df\n\n def time_train_test_split(\n self, df: pd.DataFrame, test_size: float\n ) -> Tuple[pd.DataFrame, pd.DataFrame]:\n df[self.timestamp_property] = pd.to_datetime(df[self.timestamp_property])\n\n if self.timestamp_property:\n df = df.sort_values(self.timestamp_property)\n \n cutoff_date = df[self.timestamp_property].iloc[-1] - pd.Timedelta(days=self.days_test)\n\n return df[df[self.timestamp_property] < cutoff_date], df[df[self.timestamp_property] >= cutoff_date]\n\n\n################################# Triplet ##############################\n\ndef serach_positive(uid, df, max_deep = 1, deep = 0, list_pos = []):\n if uid not in list_pos:\n list_pos.append(uid)\n #print(list_pos)\n \n if deep >= max_deep:\n return df.loc[uid].sub_a_b\n else:\n l = [serach_positive(i, df, max_deep, deep+1, list_pos) for i in df.loc[uid].sub_a_b]\n l.append(df.loc[uid].sub_a_b)\n return list_sum(l, [])\n else:\n return []\n\nclass CreateIntraSessionInteractionDataset(BasePySparkTask):\n sample_days: int = luigi.IntParameter(default=16)\n history_window: int = luigi.IntParameter(default=10)\n size_available_list: int = luigi.IntParameter(default=100)\n minimum_interactions: int = luigi.IntParameter(default=5)\n max_itens_per_session: int = luigi.IntParameter(default=15)\n min_itens_interactions: int = luigi.IntParameter(default=3)\n max_relative_pos: int = luigi.IntParameter(default=3)\n pos_max_deep: int = luigi.IntParameter(default=1)\n\n # def requires(self):\n # return SessionPrepareDataset(sample_days=self.sample_days, history_window=self.history_window, size_available_list=self.size_available_list)\n\n def output(self):\n return luigi.LocalTarget(os.path.join(DATASET_DIR, \"indexed_intra_session_train_%d_w=%d_l=%d_m=%d_s=%d_i=%d_p=%d\" % (self.sample_days, self.history_window, \n self.size_available_list, self.minimum_interactions, self.max_itens_per_session, self.min_itens_interactions, self.max_relative_pos))),\\\n luigi.LocalTarget(os.path.join(DATASET_DIR, \"item_positive_interaction_%d_w=%d_l=%d_m=%d_s=%d_i=%d_p=%d.csv\" % (self.sample_days, self.history_window, \n self.size_available_list, self.minimum_interactions, self.max_itens_per_session, self.min_itens_interactions, self.max_relative_pos))),\\\n luigi.LocalTarget(os.path.join(DATASET_DIR, \"item_id_index_%d_w=%d_l=%d_m=%d_s=%d_i=%d_p=%d.csv\" % (self.sample_days, self.history_window, \n self.size_available_list, self.minimum_interactions, self.max_itens_per_session, self.min_itens_interactions, self.max_relative_pos))),\\\n luigi.LocalTarget(os.path.join(DATASET_DIR, \"session_index_%d_w=%d_l=%d_m=%d_s=%d_i=%d_p=%d.csv\" % (self.sample_days, self.history_window, \n self.size_available_list, self.minimum_interactions, self.max_itens_per_session, self.min_itens_interactions, self.max_relative_pos)))\n\n\n def get_df_tuple_probs(self, df):\n\n df_tuple_count = df.groupby(\"ItemID_A\",\"ItemID_B\").count()\n df_count = df.groupby(\"ItemID_A\").count()\\\n .withColumnRenamed(\"count\", \"total\")\\\n .withColumnRenamed(\"ItemID_A\", \"_ItemID_A\")\n\n df_join = df_tuple_count.join(df_count, df_tuple_count.ItemID_A == df_count._ItemID_A).cache()\n df_join = df_join.withColumn(\"prob\", col(\"count\")/col(\"total\"))\n\n df_join = df_join.select(\"ItemID_A\", 'ItemID_B', 'count', 'total', 'prob')\\\n .withColumnRenamed(\"ItemID_A\", \"_ItemID_A\")\\\n .withColumnRenamed(\"ItemID_B\", \"_ItemID_B\")\\\n .withColumnRenamed(\"count\", \"total_ocr_dupla\")\\\n .withColumnRenamed(\"total\", \"total_ocr\").cache()\n\n return df_join\n \n def add_positive_interactions(self, df):\n \n # Filter more then 1 ocurrence for positive interactions\n df = df.filter(col(\"total_ocr_dupla\") >= 1)\n \n df = df\\\n .groupby(\"ItemID_A\")\\\n .agg(F.collect_set(\"ItemID_B\").alias(\"sub_a_b\"))\n\n # df_b = df\\\n # .groupby(\"ItemID_B\")\\\n # .agg(F.collect_set(\"ItemID_A\").alias(\"sub_b\"))\n\n # df = df.join(df_a, \"ItemID_A\").join(df_b, \"ItemID_B\").cache()\n\n # concat_int_arrays = concat(IntegerType())\n # df = df.withColumn(\"sub_a_b\", concat_int_arrays(\"sub_a\", \"sub_b\"))#.show(truncate=False)\n # return df\n df = df.withColumnRenamed(\"ItemID_A\", \"ItemID\")\n #df = df.withColumn(\"ItemID_COPY\",df.ItemID)\n\n df = df.toPandas().set_index('ItemID')\n print(df)\n\n sub_pos = []\n for i, row in df.iterrows():\n l = serach_positive(row.name, df, max_deep = self.pos_max_deep, deep=0, list_pos=[])\n sub_pos.append(list(np.unique(l)))\n \n df['sub_a_b_all'] = sub_pos\n\n return df\n\n def main(self, sc: SparkContext, *args):\n os.makedirs(DATASET_DIR, exist_ok=True)\n\n #parans\n min_itens_per_session = 2\n max_itens_per_session = self.max_itens_per_session\n min_itens_interactions = self.min_itens_interactions # Tupla interactions\n max_relative_pos = self.max_relative_pos\n\n spark = SparkSession(sc)\n df = spark.read.option(\"delimiter\", \";\").csv(BASE_DATASET_FILE, header=True, inferSchema=True)\n df = df.withColumnRenamed(\"sessionId\", \"SessionID\")\\\n .withColumnRenamed(\"eventdate\", \"Timestamp\")\\\n .withColumnRenamed(\"itemId\", \"ItemID\")\\\n .withColumn(\"Timestamp\", (col(\"Timestamp\").cast(\"long\") + col(\"timeframe\").cast(\"long\")/1000).cast(\"timestamp\"))\\\n .orderBy(col('Timestamp'), col('SessionID'), col('timeframe')).select(\"SessionID\", \"ItemID\", \"Timestamp\", \"timeframe\")\n \n # Drop duplicate item in that same session\n df = df.dropDuplicates(['SessionID', 'ItemID'])\n\n # filter date\n max_timestamp = df.select(max(col('Timestamp'))).collect()[0]['max(Timestamp)']\n init_timestamp = max_timestamp - timedelta(days = self.sample_days)\n df = df.filter(col('Timestamp') >= init_timestamp).cache()\n\n df = df.groupby(\"SessionID\").agg(\n max(\"Timestamp\").alias(\"Timestamp\"),\n collect_list(\"ItemID\").alias(\"ItemIDs\"),\n count(\"ItemID\").alias(\"total\"))\n\n # Filter Interactions\n df = df.filter(df.total >= min_itens_per_session).cache()\n\n # Filter position in list\n df_pos = df.select(col('SessionID').alias('_SessionID'),\n posexplode(df.ItemIDs))\n\n # Explode A\n df = df.withColumn(\"ItemID_A\", explode(df.ItemIDs))\n df = df.join(df_pos,\n (df.SessionID == df_pos._SessionID) & (df.ItemID_A == df_pos.col))\\\n .select('SessionID', 'Timestamp', 'ItemID_A', 'pos', 'ItemIDs')\\\n .withColumnRenamed('pos', 'pos_A')\n\n # Explode B\n df = df.withColumn(\"ItemID_B\", explode(df.ItemIDs))\n df = df.join(df_pos,\n (df.SessionID == df_pos._SessionID) & (df.ItemID_B == df_pos.col))\\\n .withColumnRenamed('pos', 'pos_B')\n\n df = df.withColumn(\"relative_pos\", abs(df.pos_A - df.pos_B))\n\n # Filter distincts\n df = df.select('SessionID', 'Timestamp', 'ItemID_A', 'pos_A', \n 'ItemID_B', 'pos_B', 'relative_pos')\\\n .distinct()\\\n .filter(df.ItemID_A != df.ItemID_B).cache()\n\n # # Filter duplicates\n # udf_join = F.udf(lambda s,x,y : \"_\".join(sorted([str(s), str(x),str(y)])) , StringType())\n # df = df.withColumn('key', udf_join('SessionID', 'ItemID_A','ItemID_B'))\n # df = df.dropDuplicates([\"key\"])\n\n # Calculate and filter probs ocorrence\n df_probs = self.get_df_tuple_probs(df)\n df = df.join(df_probs, (df.ItemID_A == df_probs._ItemID_A) & (df.ItemID_B == df_probs._ItemID_B))\n\n # Add positive interactoes\n df_positive = self.add_positive_interactions(df)\n\n # Filter confidence\n df = df.filter(col(\"total_ocr_dupla\") >= min_itens_interactions)\\\n .filter(col(\"relative_pos\") <= max_relative_pos)\\\n .filter(col(\"pos_A\") <= self.max_itens_per_session)\n \n\n # df = df.select(\"SessionID\", 'Timestamp', 'ItemID_A', 'pos_A',\n # 'ItemID_B', 'pos_B', 'relative_pos', \n # 'total_ocr', 'total_ocr_dupla', 'prob', 'sub_a_b')\\\n # .dropDuplicates(['ItemID_A', 'ItemID_B', 'relative_pos']) # TODO is it right?\n df = df.select(\"SessionID\", 'Timestamp', 'ItemID_A', 'ItemID_B', 'relative_pos', \n 'total_ocr', 'total_ocr_dupla')\\\n .dropDuplicates(['ItemID_A', 'ItemID_B', 'relative_pos']) # TODO is it right?\n\n df.select(\"ItemID_A\").dropDuplicates().toPandas().to_csv(self.output()[2].path, index_label=\"item_idx\")\n df.select(\"SessionID\").dropDuplicates().toPandas().to_csv(self.output()[3].path, index_label=\"session_idx\")\n df.write.parquet(self.output()[0].path)\n df_positive.to_csv(self.output()[1].path)\n\nclass IntraSessionInteractionsDataFrame(BasePrepareDataFrames):\n sample_days: int = luigi.IntParameter(default=16)\n max_itens_per_session: int = luigi.IntParameter(default=15)\n min_itens_interactions: int = luigi.IntParameter(default=3)\n max_relative_pos: int = luigi.IntParameter(default=3)\n days_test: int = luigi.IntParameter(default=1)\n pos_max_deep: int = luigi.IntParameter(default=1) \n filter_first_interaction: bool = luigi.BoolParameter(default=False)\n\n def requires(self):\n return CreateIntraSessionInteractionDataset(\n max_itens_per_session=self.max_itens_per_session,\n sample_days=self.sample_days,\n min_itens_interactions=self.min_itens_interactions,\n max_relative_pos=self.max_relative_pos,\n pos_max_deep=self.pos_max_deep)\n\n @property\n def timestamp_property(self) -> str:\n return \"Timestamp\"\n\n @property\n def dataset_dir(self) -> str:\n return DATASET_DIR\n\n def read_data_frame(self) -> pd.DataFrame:\n df = pd.read_parquet(self.read_data_frame_path)#.sample(10000)\n\n # TODO\n if self.filter_first_interaction:\n df = df.groupby(['ItemID_A', 'ItemID_B']).head(1).reset_index(drop=True)\n \n #df[\"ItemID\"] = df.ItemID_A\n #df['sub_a_b'] = df['sub_a_b'].apply(list)\n df['available_arms'] = None\n df[\"visit\"] = 1\n \n df_session = df[['SessionID']].drop_duplicates().reset_index().rename(columns={\"index\":'SessionIDX'})\n \n df = df.merge(df_session).drop(['SessionID'], axis=1)\n df = df.rename(columns={\"ItemID_A\":'ItemID'})\n\n return df\n\n @property\n def metadata_data_frame_path(self) -> Optional[str]:\n return self.input()[1].path\n \n @property\n def read_data_frame_path(self) -> pd.DataFrame:\n return self.input()[0].path\n\n def transform_data_frame(self, df: pd.DataFrame, data_key: str) -> pd.DataFrame:\n print(data_key)\n print(df.describe())\n \n return df\n\n def time_train_test_split(\n self, df: pd.DataFrame, test_size: float\n ) -> Tuple[pd.DataFrame, pd.DataFrame]:\n df[self.timestamp_property] = pd.to_datetime(df[self.timestamp_property])\n\n if self.timestamp_property:\n df = df.sort_values(self.timestamp_property)\n \n cutoff_date = df[self.timestamp_property].iloc[-1] - pd.Timedelta(days=self.days_test)\n\n return df[df[self.timestamp_property] < cutoff_date], df[df[self.timestamp_property] >= cutoff_date]\n\n################################## Interactions ######################################\n\n","sub_path":"diginetica/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":18262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"116090377","text":"# Copyright 2018 Alibaba Group Holding Limited. 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\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\n\nfrom tf_euler.python import euler_ops\nfrom tf_euler.python import layers\nfrom tf_euler.python.models import base\n\n\nclass LINE(base.UnsupervisedModel):\n \"\"\"\n Implementation of LINE model.\n \"\"\"\n\n def __init__(self,\n node_type,\n edge_type,\n max_id,\n dim,\n order=1,\n *args,\n **kwargs):\n super(LINE, self).__init__(node_type, edge_type, max_id, *args, **kwargs)\n\n self.target_embedding = layers.Embedding(\n name='target_embedding', max_id=max_id + 1, dim=dim)\n if order == 1:\n self.context_embedding = self.target_embedding\n elif order == 2:\n self.context_embedding = layers.Embedding(\n name='context_embedding', max_id=max_id + 1, dim=dim)\n else:\n raise ValueError('LINE order must be 1 or 2, got {}:'.format(order))\n\n def target_encoder(self, inputs):\n return self.target_embedding(inputs)\n\n def context_encoder(self, inputs):\n return self.context_embedding(inputs)\n","sub_path":"tf_euler/python/models/line.py","file_name":"line.py","file_ext":"py","file_size_in_byte":1851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"319865870","text":"# My own code\nimport kde_training_utilities as kde_utils\nimport glob\n\nif __name__ == \"__main__\":\n # CHOOSE FOLDER\n machine = 'x7'\n if machine == 'ccv':\n # CCV \n my_folder = '/users/afengler/data/kde/weibull_cdf/train_test_data_ndt_20000/'\n if machine == 'x7':\n # X7\n my_folder = '/media/data_cifs/afengler/data/kde/weibull_cdf/train_test_data_ndt_20000/'\n \n print('Folder used:', my_folder)\n \n # List of data files to process\n file_list = glob.glob(my_folder + '/data_*')\n n_files_out = 20\n kde_utils.kde_make_train_data(path = my_folder,\n n_files_out = n_files_out,\n file_in_list = file_list)\n \n file_id_list = [i for i in range(n_files_out)]\n kde_utils.kde_load_data_new(path = my_folder,\n file_id_list = file_id_list,\n prelog_cutoff = 1e-7)\n \n# kde_utils.kde_make_train_test_split(folder = my_folder, \n# p_train = 0.99)\n \n# def kde_make_train_test_split(path = '',\n# p_train = 0.8,\n# n_files_out = 10,\n# file_in_list = 'all'):","sub_path":"al-mlp/kde_train_test_split.py","file_name":"kde_train_test_split.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"116915232","text":"import numpy as np\n\nfrom state_search import *\nfrom set_synthesis import *\nfrom guide import *\nfrom util.utils import *\nfrom state import *\nfrom bfs_baseline import exectue_synthesis\nfrom timeit import default_timer as timer\nimport numpy as np\n\n\nif __name__==\"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--benchmark', type=str,required=True, help=\"Put ID of the benchmark.\" \n + \"\\nThe synthesis problem should be presented in \\'.json\\' file in proper format, under \\'/benchmark\\' folder.\"\n + \"\\nFor the format of the file, see instruction in artifact manual or github readme.md.\")\n parser.add_argument('--mode', type = str, default=\"Ours\", help=\"Put name of synthesis algorithm.\" \n + \"\\nIt can be one of \\'Ours\\', \\'Ours_no_prune\\', \\'Base\\', \\'Base_no_prune\\'.\"\n + \"\\nFor detaield specification of each algorithm mode, see our paper.\")\n \n\n args = parser.parse_args()\n spec = load_benchmark(args.benchmark)\n if args.mode == \"Ours\" :\n start_time = timer() \n module_gate_num = spec.qreg_size\n ss = StateSearchSynthesis(spec=spec,\n prepare_naive_module_gen = True,\n entangle_template = True,\n module_gate_num = module_gate_num)\n res_qc, res_modules = ss.modular_search(init_qc=None, \n rule_depth=2, \n concrete_criterion=False,\n naive_module_gen=True,\n entangle_template = True,\n no_pruning = False,\n no_mutate = True,\n start_time=start_time,\n timeout = 3600)\n current_time = timer()\n elapsed_time = current_time - start_time\n\n elif args.mode == \"Ours_no_prune\": \n start_time = timer() \n module_gate_num = spec.qreg_size\n ss = StateSearchSynthesis(spec=spec,\n prepare_naive_module_gen = True,\n entangle_template = True,\n module_gate_num = module_gate_num)\n res_qc, res_modules = ss.modular_search(init_qc=None, \n rule_depth=2, \n concrete_criterion=False,\n naive_module_gen=True,\n entangle_template = True,\n no_pruning = True,\n no_mutate = True,\n start_time=start_time,\n timeout = 3600)\n current_time = timer()\n elapsed_time = current_time - start_time\n elif args.mode == \"Base\":\n elapsed_time, res_qc , _ = exectue_synthesis(args.benchmark, 3600, True, False)\n elif args.mode == \"Base_no_prune\":\n elapsed_time, res_qc , _ = exectue_synthesis(args.benchmark, 3600, False, False)\n else : \n print(\"invalid paramter for --mode. Only put one of Ours / Ours_no_prune / Base / Base_no_prune\")\n exit()\n\n print(\"================================\")\n print(\"Synthesis Result\")\n print(f\"Benchmark : {args.benchmark}\")\n print(f\"Mode : {args.mode}\")\n print(\"================================\")\n\n if res_qc == None:\n print(\"None Found\")\n else :\n print(\"Synthesized QC\")\n print(res_qc)\n if args.mode == \"Ours\":\n print(\"Stacked Moduels\")\n print(res_modules)\n print(f\"Elapsed Time : {round(elapsed_time,2)}\")\n","sub_path":"qsyn/run_single.py","file_name":"run_single.py","file_ext":"py","file_size_in_byte":4015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"165304703","text":"# !/usr/bin/env python\n# -*- coding: utf-8 -*-\n# ==================================================\n# @Time : 2018/12/27 23:13\n# @Author : WuZe\n# @Desc :\n# ==================================================\n\nimport os, re\n\n\nif __name__ == \"__main__\":\n path = os.path.abspath(\"E:/Music\")\n files = os.listdir(path)\n for name in files:\n # name = name.decode('gbk').encode('utf-8')\n file_path = os.path.join(path, name)\n if not os.path.isdir(file_path):\n pattern = re.compile(r'(.*)(\\(\\d{1,2}\\))', re.U | re.S)\n matchObj = re.match(pattern, name)\n if matchObj:\n # print matchObj.group(1)\n os.remove(file_path)\n print('删除', name.decode('gbk').encode('utf-8'))\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"142255302","text":"from datetime import datetime\nfrom flask.ext.sqlalchemy import SQLAlchemy\n\n\ndb = SQLAlchemy()\n\n\nclass User(db.Model):\n \n __tablename__ = 'user'\n\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n name = db.Column(db.String(255), nullable=False)\n email = db.Column(db.String(255), nullable=False)\n created = db.Column(db.DateTime, default=datetime.now)\n updated = db.Column(db.DateTime, onupdate=datetime.now)\n\n def __init(self, name, email):\n self.name = name\n self.email = email\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"283785225","text":"from problems.old.EulerFunctions import storedPrimes\n\nprimes = storedPrimes()\n\n\ndef simplify(f):\n x, y = f\n global primes\n i = 0\n p = primes[i]\n while p <= min(x, y) and i < len(primes):\n if x % p == 0 and y % p == 0:\n x, r = divmod(x, p)\n y, r = divmod(y, p)\n else:\n i += 1\n if i >= len(primes):\n break\n p = primes[i]\n return ((x, y))\n\n\ndef addition(f1, f2):\n x1, y1 = f1\n x2, y2 = f2\n f = (x1 * y2 + x2 * y1, y1 * y2)\n return (simplify(f))\n\n\n# list = [ ( 1, x**2 ) for x in [ 2,3,4,5,7,12,15,20,28,35 ] ]\n# list.reverse()\n\n# f = list.pop()\n# while len( list ) > 0:\n# f = addition( f, list.pop() )\n# print( f )\n\nbound = 80\nchoices = [x + 2 for x in range(bound - 1)]\nchoices = [(1, x ** 2) for x in choices]\nlist = choices.copy()\nf = 1 / list.pop()[1]\nwhile len(list) > 0:\n f += 1 / list.pop()[1]\n print(f)\n\nprod = 1\nfor f in choices:\n prod *= f[1]\n\nsomme = 0\nfor f in choices:\n d, r = divmod(prod, f[1])\n assert (r == 0)\n somme += d\n","sub_path":"problems/old/pb152.py","file_name":"pb152.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"84721230","text":"\"\"\"\nTest dataset's urls download status.\n\"\"\"\n\n\nimport pytest\nimport signal\nimport requests\nfrom dbcollection.core.api import fetch_list_datasets\n\n\nTIMEOUT_SECONDS = 3\n\n\ndef get_list_urls_dataset():\n available_datasets = fetch_list_datasets()\n dataset_urls = []\n for name in available_datasets:\n url_list = []\n urls = available_datasets[name]['urls']\n for url in urls:\n if isinstance(url, str):\n url_list.append(url)\n elif isinstance(url, dict):\n try:\n url_ = url['url']\n url_list.append(url_)\n except KeyError:\n pass # do nothing\n else:\n raise Exception('Unknown format when downloading urls: {}'.format(type(url)))\n # add list to the out dictionary\n dataset_urls.append((name, url_list))\n return dataset_urls\n\n\nclass Timeout():\n \"\"\"Timeout class using ALARM signal.\"\"\"\n class Timeout(Exception):\n pass\n\n def __init__(self, sec):\n self.sec = sec\n\n def __enter__(self):\n signal.signal(signal.SIGALRM, self.raise_timeout)\n signal.alarm(self.sec)\n\n def __exit__(self, *args):\n signal.alarm(0) # disable alarm\n\n def raise_timeout(self, *args):\n raise Timeout.Timeout()\n\n\ndef check_url_redirect(url):\n try:\n with Timeout(TIMEOUT_SECONDS):\n response = requests.get(url)\n return response.status_code == 200\n except Timeout.Timeout:\n return True\n\n\n@pytest.mark.parametrize(\"dataset_name, urls\", get_list_urls_dataset())\ndef test_check_urls_are_valid(dataset_name, urls):\n for url in urls:\n response = requests.head(url) # try without redirect enabled\n if response.status_code == 200:\n status = True\n else:\n if response.status_code == 301:\n status = check_url_redirect(url) # try with redirect enabled\n else:\n status = False\n assert status, 'Error downloading urls from {}: {}'.format(dataset_name, url)\n","sub_path":"dbcollection/tests/datasets/__test_check_urls.py","file_name":"__test_check_urls.py","file_ext":"py","file_size_in_byte":2094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"558342751","text":"import requests\nfrom bs4 import BeautifulSoup\n\ndef ebay_spider(max_pages, sort_by):\n page = 0\n while page < max_pages:\n page += 1\n url = 'https://www.ebay.ie/b/Internal-Hard-Disk-Drives/56083/bn_780224?rt=nc&_pgn=' + str(page) + '&'\n source_code = requests.get(url)\n plain_text = source_code.text\n soup = BeautifulSoup(plain_text, features=\"html.parser\")\n for link in soup.findAll('a', {'class':'s-item__link'}):\n href = link.get('href')\n title = link.string\n print(title)\n\nebay_spider(1)","sub_path":"spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"531143311","text":"import datetime\nimport logging\nfrom collections import OrderedDict\n\nimport os\nimport pprint\nimport requests\nimport xmltodict\n\nfrom geo_ez.data_functions import snake_to_camel, http_build_query, clean_api_dict\n\nlogger = logging.getLogger(__name__)\n\n\nclass USPS:\n is_debug = False\n is_logging = False\n\n today = None\n\n usps_id = None\n\n endpoint = \"https://secure.shippingapis.com/ShippingAPI.dll\"\n\n def __init__(self, **kwargs):\n self.usps_id = kwargs.get(\"id\", os.environ.get(\"USPS_ID\", False))\n\n self.is_debug = kwargs.get(\"debug\", os.environ.get(\"FED_DEBUG\", False)) in [\"True\", True]\n self.is_logging = kwargs.get(\"logging\", os.environ.get(\"FED_LOGGING\", False)) in [\"True\", True]\n\n self.today = datetime.datetime.now()\n\n if not self.usps_id:\n # log_message(\"No USPS ID Configured. Please set USPS_ID environmental variable.\", custom_log=\"pharmacy.log\")\n logger.warning(\"No USPS ID Configured. Please set USPS_ID environmental variable.\")\n\n def debug_msg(self, message, **kwargs):\n pretty = kwargs.get(\"pretty\", False)\n\n if pretty:\n message = pprint.pformat(message, indent=4)\n\n # log_message(message, custom_log=\"pharmacy.log\")\n\n if self.is_debug:\n print(message)\n\n if self.is_logging:\n logger.info(message)\n\n def usps_call(self, **kwargs):\n api = kwargs.get(\"api\", False)\n data = kwargs.get(\"data\", False)\n\n resp = {}\n\n if self.usps_id and api and data:\n api_resp_var = kwargs.get(\"resp_variable\", \"%s_response\" % snake_to_camel(api, reverse=True))\n self.debug_msg(api_resp_var)\n\n xml = xmltodict.unparse(OrderedDict(data), full_document=False)\n self.debug_msg(xml)\n\n endpoint = kwargs.get(\"endpoint\", self.endpoint)\n\n params = dict(API=api, XML=xml)\n\n request_url = \"%s?%s\" % (endpoint, http_build_query(params))\n\n ret = requests.get(request_url, verify=True)\n # pprint.pprint(ret.text)\n self.debug_msg(ret.text)\n\n # Convert the returned XML to a dict, clean the returned data, and convert all keys to snake case.\n ret_dict = clean_api_dict(xmltodict.parse(ret.text))\n self.debug_msg(ret_dict, pretty=True)\n\n resp = ret_dict.get(api_resp_var)\n\n return resp\n\n def address(self, **kwargs):\n \"\"\"\n Uses the USPS Address validation API to return a valid address\n\n NOTE: The USPS API expects Address2 to be the street address, and Address1 to be the suite/apt #,\n so in the code below, we swap the parameters when they are being fed to the API, and when they are\n returned from the API.\n\n :param kwargs:\n address1, address2, city, state, zip_code, plus_four\n\n :return:\n A Dict with a valid address:\n {\n 'address1': '',\n 'address2': '',\n 'city': '',\n 'state': 'XX',\n 'zip_code': 'XXXXX',\n 'plus_four': 'XXXX'\n }\n \"\"\"\n valid_address = None\n\n address_dict = OrderedDict()\n address_dict[\"Address1\"] = kwargs.get(\"address1\", \"\")\n address_dict[\"Address2\"] = kwargs.get(\"address2\", \"\")\n address_dict[\"City\"] = kwargs.get(\"city\", \"\")\n address_dict[\"State\"] = kwargs.get(\"state\", \"\")\n address_dict[\"Zip5\"] = kwargs.get(\"zip_code\", \"\")\n address_dict[\"Zip4\"] = kwargs.get(\"plus_four\", \"\")\n\n address_validate_request = OrderedDict()\n address_validate_request[\"@USERID\"] = self.usps_id\n address_validate_request[\"Address\"] = address_dict\n\n address_validate_dict = {\"AddressValidateRequest\": address_validate_request}\n\n resp = self.usps_call(api=\"Verify\", data=address_validate_dict, resp_variable=\"address_validate_response\")\n\n if \"address\" in resp:\n ret_address = resp.get(\"address\")\n valid_address = {\n \"address1\": ret_address.get(\"address2\"),\n \"address2\": ret_address.get(\"address1\"),\n \"city\": ret_address.get(\"city\"),\n \"state\": ret_address.get(\"state\"),\n \"zip_code\": ret_address.get(\"zip5\"),\n \"plus_four\": ret_address.get(\"zip4\"),\n }\n\n return valid_address\n\n def get_zipcode(self, **kwargs):\n \"\"\"\n Uses the USPS Zip Code Lookup API to determine a Zip Code based on a partial address.\n :param kwargs:\n address1, address2, city, state, zip_code, plus_four\n\n :return:\n A Dict with a valid address:\n {\n 'address1': '',\n 'address2': '',\n 'city': '',\n 'state': 'XX',\n 'zip_code': 'XXXXX',\n 'plus_four': 'XXXX'\n }\n \"\"\"\n valid_address = {\"address1\": \"\", \"address2\": \"\", \"city\": \"\", \"state\": \"XX\"}\n\n address_dict = OrderedDict()\n address_dict[\"Address1\"] = kwargs.get(\"address2\", \"\")\n address_dict[\"Address2\"] = kwargs.get(\"address1\", \"\")\n address_dict[\"City\"] = kwargs.get(\"city\", \"\")\n address_dict[\"State\"] = kwargs.get(\"state\", \"\")\n\n address_validate_request = OrderedDict()\n address_validate_request[\"@USERID\"] = self.usps_id\n address_validate_request[\"Address\"] = address_dict\n\n address_validate_dict = {\"ZipCodeLookupRequest\": address_validate_request}\n\n resp = self.usps_call(api=\"ZipCodeLookup\", data=address_validate_dict)\n\n if \"address\" in resp:\n ret_address = resp.get(\"address\")\n valid_address = {\n \"address1\": ret_address.get(\"address2\"),\n \"address2\": ret_address.get(\"address1\"),\n \"city\": ret_address.get(\"city\"),\n \"state\": ret_address.get(\"state\"),\n \"zip_code\": ret_address.get(\"zip5\"),\n \"plus_four\": ret_address.get(\"zip4\"),\n }\n\n return valid_address\n\n def track(self, tracking_number, **kwargs):\n detailed_response = kwargs.get(\"details\", False)\n\n if detailed_response:\n req_key = \"TrackFieldRequest\"\n\n else:\n req_key = \"TrackRequest\"\n\n tracking_dict = OrderedDict(\n {req_key: OrderedDict({\"@USERID\": self.usps_id, \"TrackID\": OrderedDict({\"@ID\": tracking_number})})}\n )\n\n resp = self.usps_call(api=\"TrackV2\", data=tracking_dict, resp_variable=\"track_response\")\n\n tracking_info = resp.get(\"track_info\")\n\n tracking_data = {\n \"tracking_number\": tracking_info.get(\"@id\"),\n \"details\": tracking_info.get(\"track_detail\"),\n \"summary\": tracking_info.get(\"track_summary\"),\n }\n\n return tracking_data\n\n def zip_to_city_state(self, zip_code):\n valid_address = {\"city\": \"\", \"state\": \"XX\", \"zip_code\": \"XXXXX\"}\n\n zip_code_dict = OrderedDict()\n zip_code_dict[\"@ID\"] = \"0\"\n zip_code_dict[\"Zip5\"] = zip_code\n\n city_state_request = OrderedDict()\n city_state_request[\"@USERID\"] = self.usps_id\n city_state_request[\"ZipCode\"] = zip_code_dict\n\n city_state_dict = {\"CityStateLookupRequest\": city_state_request}\n\n resp = self.usps_call(api=\"CityStateLookup\", data=city_state_dict)\n\n if \"zip_code\" in resp:\n ret_zip = resp.get(\"zip_code\")\n valid_address = {\n \"city\": ret_zip.get(\"city\"),\n \"state\": ret_zip.get(\"state\"),\n \"zip_code\": ret_zip.get(\"zip5\"),\n }\n\n return valid_address\n","sub_path":"geo_ez/usps_class.py","file_name":"usps_class.py","file_ext":"py","file_size_in_byte":7769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"69839187","text":"#!/usr/bin/env python2\nimport os\nfrom setuptools import setup, find_packages\n\n\n# Utility function to read the README file.\n# Used for the long_description. It's nice, because now 1) we have a top level\n# README file and 2) it's easier to type in the README file than to put a raw\n# string in below ...\ndef read(fname):\n return open(os.path.join(os.path.dirname(__file__), fname)).read()\n\nsetup(\n name=\"cythereal-vbsdk\",\n version=\"0.4.0\",\n author=\"Cythereal\",\n author_email=\"webmaster@cythereal.com\",\n url=\"https://bitbucket.org/cythereal/virusbattle-sdk/src\",\n description=(\"Client for accessing Cythereal Virusbattle and MAGIC\"),\n long_description=read('README.rst'),\n classifiers=[\n \"Development Status :: 4 - Beta\",\n \"Environment :: Console\",\n \"Intended Audience :: Information Technology\",\n \"Intended Audience :: Developers\",\n \"Intended Audience :: System Administrators\",\n \"Intended Audience :: Science/Research\",\n \"License :: OSI Approved :: Apache Software License\",\n \"Operating System :: POSIX :: Linux\",\n \"Programming Language :: Python :: 2 :: Only\",\n \"Topic :: Security\",\n ],\n license=\"Apache Software License 2.0\",\n install_requires=[\n \"requests>=2.11.1\",\n \"validate_email>=1.3\",\n ],\n extras_require={\n 'DEV': ['pytest'],\n },\n entry_points={\n 'console_scripts': [\n \"vbclient=vbsdk:main\",\n ],\n },\n packages=find_packages(exclude=['bin/']),\n package_data={\n 'config': ['config/*.ini'],\n 'libs': ['lib/*'],\n },\n py_modules=[ ],\n)\n","sub_path":"pypi_install_script/cythereal-vbsdk-0.4.0.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"52249515","text":"from discoruns.mechanism import Mechanism\nfrom discoruns.wrapper.fs_wrapper import ForensicStoreWrapper\n\n\nclass SecuritySupportProvider(Mechanism):\n\n def collect_mechanism(self, fsw: ForensicStoreWrapper) -> list:\n tmp_dict = {}\n\n for artifact in fsw.get_artifacts(\"WindowsLSASecurityPackages\"):\n for value in artifact.get(\"values\", []):\n if value.get(\"data\") and not value.get(\"data\") == \"['\\\"\\\"']\":\n tmp_dict.setdefault(value.get(\"data\"), set()).add(artifact.get(\"key\"))\n\n return [{\"name\": \"security_support_provider\", \"origins\": list(origins), \"entry\": dll}\n for dll, origins in tmp_dict.items()]\n","sub_path":"discoruns/mechanisms/security_support_provider.py","file_name":"security_support_provider.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"291401698","text":"import sys\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nif __name__ == \"__main__\":\n df = pd.read_csv('../../data/LifetimeRaw.csv',names=['dCETime','iSttsP','iSttsD','iSttsX',\"dValTemp\",'Par0','ePar0','Par1','ePar1','Par2','ePar2'])\n plt.figure(num=None, figsize=(12, 6.5), dpi=300, facecolor='w', edgecolor='k')\n plt.rcParams['font.size'] = 20\n dLength = 86400\n dfE = df[(df[\"iSttsP\"] == -1 )]\n dfW = df[(df[\"iSttsP\"] == 1 )]\n plt.errorbar(dfE['dCETime']/dLength,dfE['Par1'],yerr=dfE['ePar1'],label=\"Pol. $-$\",fmt='bo',ecolor='black',markersize=2,capsize=2)\n plt.errorbar(dfW['dCETime']/dLength,dfW['Par1'],yerr=dfW['ePar1'],label=\"Pol. $+$\",fmt='ro',ecolor='black',markersize=2,capsize=2)\n #plt.errorbar(dfE['dValTemp'],dfE['Par1'],yerr=dfE['ePar1'],fmt='ro',ecolor='black',capsize=4)\n #plt.errorbar(dfW['dValTemp'],dfW['Par1'],yerr=dfW['ePar1'],fmt='bo',ecolor='black',capsize=4)\n #plt.title('Lifetime vs Time')\n plt.ylabel('Lifetime[msec]')\n plt.xlabel('days since 2017/12/13 0:00 AM (PST)')\n plt.ylim([1170,1270])\n plt.xlim([0,7])\n plt.legend(loc='upper right') #upper or lower\n plt.tight_layout()\n plt.savefig(\"../figure/plotLifetimeRaw.png\")\n #plt.show()\n","sub_path":"plot/plotLifetimeRaw.py","file_name":"plotLifetimeRaw.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"627429516","text":"import urllib\nimport requests\nimport string\nimport random\nfrom JumpScale import j\nfrom jose import jwt as jose_jwt\nimport datetime\nimport json\n\n\nclass AuthError(Exception):\n pass\n\n\nclass UserInfo(object):\n\n def __init__(self, username, emailaddress, groups):\n self.username = username\n self.emailaddress = emailaddress\n self.groups = groups\n\n\nclass OauthInstance(object):\n\n def __init__(self, addr, accesstokenaddr, id, secret, scope, redirect_url, user_info_url, logout_url, instance):\n if not addr:\n hrd = j.application.getAppInstanceHRD('oauth_client', instance)\n self.addr = hrd.get('instance.oauth.client.url')\n self.accesstokenaddress = hrd.get('instance.oauth.client.url2')\n self.id = hrd.get('instance.oauth.client.id')\n self.scope = hrd.get('instance.oauth.client.scope')\n self.redirect_url = hrd.get('instance.oauth.client.redirect_url')\n self.secret = hrd.get('instance.oauth.client.secret')\n self.user_info_url = hrd.get('instance.oauth.client.user_info_url')\n self.logout_url = hrd.get('instance.oauth.client.logout_url')\n else:\n self.addr = addr\n self.id = id\n self.scope = scope\n self.redirect_url = redirect_url\n self.accesstokenaddress = accesstokenaddr\n self.secret = secret\n self.user_info_url = user_info_url\n self.logout_url = logout_url\n self.state = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(30))\n\n @property\n def url(self):\n params = {'client_id': self.id, 'redirect_uri': self.redirect_url, 'state': self.state, 'response_type': 'code'}\n if self.scope:\n params.update({'scope': self.scope})\n return '%s?%s' % (self.addr, urllib.urlencode(params))\n\n def getAccessToken(self, code, state):\n payload = {'code': code, 'client_id': self.id, 'client_secret': self.secret,\n 'redirect_uri': self.redirect_url, 'grant_type': 'authorization_code',\n 'state': state}\n result = requests.post(self.accesstokenaddress, data=payload, headers={\n 'Accept': 'application/json'})\n\n if not result.ok or 'error' in result.json():\n msg = result.json()['error']\n j.logger.log(msg)\n raise AuthError(msg)\n return result.json()\n\n def getUserInfo(self, accesstoken):\n params = {'access_token': accesstoken['access_token']}\n userinforesp = requests.get('%s?%s' % (self.user_info_url, urllib.urlencode(params)))\n if not userinforesp.ok:\n msg = 'Failed to get user details'\n j.logger.log(msg)\n raise AuthError(msg)\n\n userinfo = userinforesp.json()\n return UserInfo(userinfo['login'], userinfo['email'], ['user'])\n\nclass ItsYouOnline(OauthInstance):\n\n def extra(self, session, accesstoken):\n jwt = self.getJWT(accesstoken)\n session['jwt'] = jwt\n session.save()\n\n def getAccessToken(self, code, state):\n payload = {'code': code, 'client_id': self.id, 'client_secret': self.secret,\n 'redirect_uri': self.redirect_url, 'grant_type': '',\n 'state': state}\n result = requests.post(self.accesstokenaddress, data=payload, headers={\n 'Accept': 'application/json'})\n\n if not result.ok or 'error' in result.json():\n msg = result.text\n j.logger.log(msg)\n raise AuthError(msg)\n return result.json()\n\n def getUserInfo(self, accesstoken):\n headers = {'Authorization': 'token %s' % accesstoken['access_token']}\n scopes = accesstoken['scope'].split(',')\n userinfourl = self.user_info_url.format(**accesstoken.get('info', {}))\n userinforesp = requests.get(userinfourl, headers=headers)\n if not userinforesp.ok:\n msg = 'Failed to get user details'\n j.logger.log(msg)\n raise AuthError(msg)\n\n groups = ['user']\n for scope in scopes:\n parts = scope.split(':')\n if len(parts) == 3 and parts[:2] == ['user', 'memberof']:\n groups.append(parts[-1].split('.')[-1])\n\n userinfo = userinforesp.json()\n return UserInfo(userinfo['username'], userinfo['emailaddresses'][0]['emailaddress'], groups)\n\n\n def getJWT(self, access_token):\n url = 'https://itsyou.online/v1/oauth/jwt?scope=user:memberof:{0}.0-access,user:publickey:ssh,offline_access'.format(self.id)\n headers = {'Authorization': 'token {0}'.format(access_token['access_token'])}\n resp = requests.get(url, headers=headers)\n jwt = \"\"\n if resp.status_code == 200:\n jwt = resp.content\n return jwt\n\n def get_active_jwt(self, jwt=None, session=None):\n \"\"\"\n Will fetch a new jwt if current jwt is expired\n \"\"\"\n if not jwt and not session:\n raise RuntimeError(\"Either jwt or session needs to be set\")\n if session:\n jwt = session.get('jwt')\n jwt_data = jose_jwt.get_unverified_claims(jwt)\n jwt_data = json.loads(jwt_data)\n exp_date = datetime.datetime.fromtimestamp(jwt_data[\"exp\"])\n now = datetime.datetime.now()\n if now > exp_date:\n url = 'https://itsyou.online/v1/oauth/jwt/refresh'\n headers = {'Authorization': 'bearer {0}'.format(jwt)}\n resp = requests.get(url, headers=headers)\n jwt = \"\"\n if resp.status_code == 200:\n jwt = resp.content\n if session:\n session['jwt'] = jwt\n session.save()\n return jwt\n","sub_path":"lib/JumpScale/baselib/oauth/OauthInstance.py","file_name":"OauthInstance.py","file_ext":"py","file_size_in_byte":5762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"230754029","text":"import math as mt\r\nimport numpy as np\r\nimport random as rd\r\nimport engine as eg\r\nimport physics as ph\r\nimport cylax as cl\r\nimport sys\r\nimport config as cf\r\n\r\nsys.path.insert(1, 'C:/Users/Frank/Desktop/Cylax/PySystem')\r\n\r\nclass Item:\r\n\r\n def __init__(self, hp = 0, dr = 0, height = 1, width = 1, length = 1, weight = 1, electricity = 0, name = \"\", discription = \"\",\r\n damage = [0], flammable = False, poisonous = [False, []], raw_eatable = True, cook_eatable = True, moist = False):\r\n\r\n self.Name = name\r\n self.Discription = discription\r\n\r\n ### Stats\r\n\r\n self.HP = hp\r\n self.DR = dr\r\n\r\n self.Damage = damage ### 0 = HP\r\n\r\n self.Electricity = electricity\r\n\r\n self.Height = height ### in centimeters\r\n self.Width = width\r\n self.Length = length\r\n\r\n self.Weight = weight ### in kg\r\n self.Volume = self.Height * self.Width * self.Length\r\n\r\n ### Traits\r\n\r\n self.ELECTRICAL = False\r\n self.FLAMMABLE = False\r\n self.POISONOUS = [False, []] ### Apply to what\r\n self.RAW_EATABLE = True\r\n self.COOK_EATABLE = True\r\n self.MOIST = False\r\n\r\nItem_Test = Item(\r\nhp = 0,\r\ndr = 0,\r\nheight = 1,\r\nwidth = 1,\r\nlength = 1,\r\nweight = 1,\r\nelectricity = 0,\r\nname = \"\",\r\ndiscription = \"\",\r\ndamage = [0],\r\nflammable = False,\r\npoisonous = [False, []],\r\nraw_eatable = False,\r\ncook_eatable = False,\r\nmoist = False\r\n)\r\n\r\n### Cloths\r\n\r\nCape = Item(\r\nhp = 3,\r\ndr = 0,\r\nheight = 95,\r\nwidth = 50,\r\nlength = 2.5,\r\nweight = 0.8,\r\nelectricity = 0,\r\nname = \"Cape\",\r\ndiscription = \"A back piece of cloth for the back.\",\r\ndamage = [0],\r\nflammable = True,\r\npoisonous = [False, []],\r\nraw_eatable = False,\r\ncook_eatable = False,\r\nmoist = False\r\n)\r\n\r\n### Computers\r\n\r\nDesktop_Computer = Item(\r\nhp = 6,\r\ndr = 0,\r\nheight = 48,\r\nwidth = 48,\r\nlength = 23,\r\nweight = 23,\r\nelectricity = 0,\r\nname = \"Desktop Computer\",\r\ndiscription = \"\",\r\ndamage = [0],\r\nflammable = True,\r\npoisonous = [True, [\"Plastic\"]],\r\nraw_eatable = False,\r\ncook_eatable = False,\r\nmoist = False\r\n)\r\n","sub_path":"common_items.py","file_name":"common_items.py","file_ext":"py","file_size_in_byte":2071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"514761969","text":"from numpy import arctan2, sqrt, pi, array, size\nfrom matplotlib import colors, cm\nfrom thunder.utils.load import isrdd\n\n\nclass Colorize(object):\n \"\"\" Class for turning numerical data into colors\"\"\"\n\n def __init__(self, totype='rgb', scale=1):\n self.totype = totype\n self.scale = scale\n\n def calc(self, data):\n\n if isrdd(data):\n self.checkargs(size(data.first()[1]))\n return data.mapValues(lambda x: self.get(x))\n else:\n self.checkargs(size(data[0]))\n return map(lambda line: self.get(line), data)\n\n def get(self, line):\n if (self.totype == 'rgb') or (self.totype == 'hsv'):\n return clip(abs(line) * self.scale, 0, 1)\n\n elif self.totype == 'polar':\n theta = ((arctan2(line[1], line[0]) + pi + pi) % (2*pi)) / (2 * pi)\n rho = sqrt(line[0]**2 + line[1]**2)\n return clip(colors.hsv_to_rgb(array([[[theta, 1, rho * self.scale]]]))[0][0], 0, 1)\n\n else:\n if size(line) > 1:\n line = line[0]\n return array(cm.get_cmap(self.totype, 256)(line * self.scale)[0:3])\n\n def checkargs(self, n):\n\n if (self.totype == 'rgb' or self.totype == 'hsv') and n < 3:\n raise Exception(\"must have 3 values per record for rgb or hsv\")\n elif self.totype == 'polar' and n < 1:\n raise Exception(\"must have at least 2 values per record for polar\")\n\n\ndef clip(vals, minval, maxval):\n \"\"\"Clip values below and above minimum and maximum values\"\"\"\n\n vals[vals < minval] = minval\n vals[vals > maxval] = maxval\n return array(vals)\n\n","sub_path":"python/thunder/viz/colorize.py","file_name":"colorize.py","file_ext":"py","file_size_in_byte":1631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"152484685","text":"while True:\n\th,w=map(int,input().split())\n\tif h==w==0:break\n\tfor hh in range(h):\n\t\tol=''\n\t\tfor ww in range(w):\n\t\t\tif hh == 0 or ww == 0 or hh == h - 1 or ww == w - 1:\n\t\t\t\tol+='#'\n\t\t\telse:\n\t\t\t\tol+='.'\n\t\tprint(ol)\n\tprint()","sub_path":"Python_codes/p02404/s232025200.py","file_name":"s232025200.py","file_ext":"py","file_size_in_byte":220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"509858310","text":"from tkinter import *\r\nfrom tkinter import messagebox\r\nfrom Ball import Ball\r\nfrom Paddle import Paddle\r\nimport random\r\nimport time\r\nimport sys\r\nimport os\r\n\r\ndef restart_program():\r\n\tos.execl(sys.executable, sys.executable, *sys.argv)\r\n\r\ndef main():\r\n\tgame_tk = Tk()\r\n\tgame_tk.title(\"Ball Game\")\r\n\tgame_tk.resizable(0, 0)\r\n\tgame_tk.wm_attributes(\"-topmost\", 1)\r\n\tcanvas = Canvas(game_tk, width=500, height=400, bd=0, highlightthickness=0)\r\n\tcanvas.pack()\r\n\tgame_tk.update()\r\n\r\n\tpaddle = Paddle(canvas, \"blue\")\r\n\tball = Ball(canvas, paddle, \"green\")\r\n\r\n\twhile True:\r\n\t\tif ball.hit_bottom == False:\r\n\t\t\tball.draw_ball()\r\n\t\t\tpaddle.draw_paddle()\r\n\t\telse:\r\n\t\t\tresult = messagebox.askquestion(\"You've lost!\", \"Restart the game?\", icon='warning')\r\n\t\t\tif result == 'no':\r\n\t\t\t\tgame_tk.destroy()\r\n\t\t\t\treturn\r\n\t\t\telse:\r\n\t\t\t\trestart_program()\r\n\r\n\t\tgame_tk.update_idletasks()\r\n\t\tgame_tk.update()\r\n\t\ttime.sleep(0.01)\r\n\r\nif __name__ == \"__main__\":\r\n\tmain()","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"343172973","text":"import argparse\nimport os, errno\nimport random\nimport string\nimport sys\nimport random\nimport shutil\nimport pandas as pd\nimport time\n\nfrom tqdm import tqdm\nfrom string_generator import (\n create_strings_from_dict,\n create_strings_from_file,\n create_strings_from_wikipedia,\n create_strings_randomly\n)\nfrom data_generator import FakeTextDataGenerator\nfrom multiprocessing import Pool\n\ndef margins(margin):\n margins = margin.split(',')\n if len(margins) == 1:\n return [int(margins[0])] * 4\n return [int(m) for m in margins]\n\ndef parse_arguments():\n \"\"\"\n Parse the command line arguments of the program.\n \"\"\"\n\n parser = argparse.ArgumentParser(description='Generate synthetic text data for text recognition.')\n parser.add_argument(\n \"--output_dir\",\n type=str,\n nargs=\"?\",\n help=\"The output directory\",\n default=\"out/\",\n )\n parser.add_argument(\n \"-i\",\n \"--input_file\",\n type=str,\n nargs=\"?\",\n help=\"When set, this argument uses a specified text file as source for the text\",\n default=\"\"\n )\n parser.add_argument(\n \"-l\",\n \"--language\",\n type=str,\n nargs=\"?\",\n help=\"The language to use, should be fr (French), en (English), es (Spanish), de (German), or cn (Chinese).\",\n default=\"en\"\n )\n parser.add_argument(\n \"-c\",\n \"--count\",\n type=int,\n nargs=\"?\",\n help=\"The number of images to be created.\",\n default=10\n )\n parser.add_argument(\n \"-rs\",\n \"--random_sequences\",\n action=\"store_true\",\n help=\"Use random sequences as the source text for the generation. Set '-let','-num','-sym' to use letters/numbers/symbols. If none specified, using all three.\",\n default=False\n )\n parser.add_argument(\n \"-let\",\n \"--include_letters\",\n action=\"store_true\",\n help=\"Define if random sequences should contain letters. Only works with -rs\",\n default=False\n )\n parser.add_argument(\n \"-num\",\n \"--include_numbers\",\n action=\"store_true\",\n help=\"Define if random sequences should contain numbers. Only works with -rs\",\n default=False\n )\n parser.add_argument(\n \"-sym\",\n \"--include_symbols\",\n action=\"store_true\",\n help=\"Define if random sequences should contain symbols. Only works with -rs\",\n default=False\n )\n parser.add_argument(\n \"-w\",\n \"--length\",\n type=int,\n nargs=\"?\",\n help=\"Define how many words should be included in each generated sample. If the text source is Wikipedia, this is the MINIMUM length\",\n default=1\n )\n parser.add_argument(\n \"-r\",\n \"--random\",\n action=\"store_true\",\n help=\"Define if the produced string will have variable word count (with --length being the maximum)\",\n default=False\n )\n parser.add_argument(\n \"-f\",\n \"--format\",\n type=int,\n nargs=\"?\",\n help=\"Define the height of the produced images if horizontal, else the width\",\n default=32,\n )\n parser.add_argument(\n \"-t\",\n \"--thread_count\",\n type=int,\n nargs=\"?\",\n help=\"Define the number of thread to use for image generation\",\n default=1,\n )\n parser.add_argument(\n \"-e\",\n \"--extension\",\n type=str,\n nargs=\"?\",\n help=\"Define the extension to save the image with\",\n default=\"jpg\",\n )\n parser.add_argument(\n \"-k\",\n \"--skew_angle\",\n type=int,\n nargs=\"?\",\n help=\"Define skewing angle of the generated text. In positive degrees\",\n default=0,\n )\n parser.add_argument(\n \"-rk\",\n \"--random_skew\",\n action=\"store_true\",\n help=\"When set, the skew angle will be randomized between the value set with -k and it's opposite\",\n default=False,\n )\n parser.add_argument(\n \"-wk\",\n \"--use_wikipedia\",\n action=\"store_true\",\n help=\"Use Wikipedia as the source text for the generation, using this paremeter ignores -r, -n, -s\",\n default=False,\n )\n parser.add_argument(\n \"-bl\",\n \"--blur\",\n type=int,\n nargs=\"?\",\n help=\"Apply gaussian blur to the resulting sample. Should be an integer defining the blur radius\",\n default=0,\n )\n parser.add_argument(\n \"-rbl\",\n \"--random_blur\",\n action=\"store_true\",\n help=\"When set, the blur radius will be randomized between 0 and -bl.\",\n default=False,\n )\n parser.add_argument(\n \"-b\",\n \"--background\",\n type=int,\n nargs=\"?\",\n help=\"Define what kind of background to use. 0: Gaussian Noise, 1: Plain white, 2: Quasicrystal, 3: Pictures, 4:Random color 5: random 1 to 4\",\n default=0,\n )\n parser.add_argument(\n \"-hw\",\n \"--handwritten\",\n action=\"store_true\",\n help=\"Define if the data will be \\\"handwritten\\\" by an RNN\",\n )\n parser.add_argument(\n \"-na\",\n \"--name_format\",\n type=int,\n help=\"Define how the produced files will be named. 0: [TEXT]_[ID].[EXT], 1: [ID]_[TEXT].[EXT] 2: [ID].[EXT] + one file labels.txt containing id-to-label mappings, 3: [ID].[EXT] + Report file .csv, 4: [ID].[EXT] + gt.txt\",\n default=0,\n )\n parser.add_argument(\n \"-d\",\n \"--distorsion\",\n type=int,\n nargs=\"?\",\n help=\"Define a distorsion applied to the resulting image. 0: None (Default), 1: Sine wave, 2: Cosine wave, 3: Random\",\n default=0\n )\n parser.add_argument(\n \"-do\",\n \"--distorsion_orientation\",\n type=int,\n nargs=\"?\",\n help=\"Define the distorsion's orientation. Only used if -d is specified. 0: Vertical (Up and down), 1: Horizontal (Left and Right), 2: Both\",\n default=0\n )\n parser.add_argument(\n \"-wd\",\n \"--width\",\n type=int,\n nargs=\"?\",\n help=\"Define the width of the resulting image. If not set it will be the width of the text + 10. If the width of the generated text is bigger that number will be used\",\n default=-1\n )\n parser.add_argument(\n \"-al\",\n \"--alignment\",\n type=int,\n nargs=\"?\",\n help=\"Define the alignment of the text in the image. Only used if the width parameter is set. 0: left, 1: center, 2: right\",\n default=1\n )\n parser.add_argument(\n \"-or\",\n \"--orientation\",\n type=int,\n nargs=\"?\",\n help=\"Define the orientation of the text. 0: Horizontal, 1: Vertical\",\n default=0\n )\n parser.add_argument(\n \"-tc\",\n \"--text_color\",\n type=str,\n nargs=\"?\",\n help=\"Define the text's color, should be either a single hex color or a range in the ?,? format., Use rnd: Random RGB 0 to 255, rndInList: random color in colorList \" ,\n default='#282828',\n )\n parser.add_argument(\n \"-sw\",\n \"--space_width\",\n type=float,\n nargs=\"?\",\n help=\"Define the width of the spaces between words. 2.0 means twice the normal space width\",\n default=1.0\n )\n parser.add_argument(\n \"-m\",\n \"--margins\",\n type=margins,\n nargs=\"?\",\n help=\"Define the margins around the text when rendered. In pixels\",\n default=(10, 10, 10, 10)\n )\n parser.add_argument(\n \"-fi\",\n \"--fit\",\n action=\"store_true\",\n help=\"Apply a tight crop around the rendered text\",\n default=True\n )\n parser.add_argument(\n \"-ft\",\n \"--font\",\n type=str,\n nargs=\"?\",\n help=\"Define font to be used\"\n )\n parser.add_argument(\n \"-rbs\",\n \"--random_blur_and_skew\",\n type=bool,\n nargs=\"?\",\n help=\"random_blur_and_skew\",\n default=False\n )\n parser.add_argument(\n \"-bcm\",\n \"--background_color_mode\",\n type=str,\n nargs=\"?\",\n help=\"random_background_color_mode use rnd: Random RGB 0 to 255, rndInList: random color in colorList \",\n default=\"rnd\"\n )\n parser.add_argument(\n \"-rfs\",\n \"--random_font_size\",\n type=bool,\n nargs=\"?\",\n help=\"random_font_size True: random font size in ratio list \",\n default=False\n )\n \n return parser.parse_args()\n\n\ndef load_dict(lang):\n \"\"\"\n Read the dictionnary file and returns all words in it.\n \"\"\"\n\n lang_dict = []\n with open(os.path.join('dicts', lang + '.txt'), 'r', encoding=\"utf8\", errors='ignore') as d:\n lang_dict = d.readlines()\n return lang_dict\n\ndef load_fonts(lang):\n \"\"\"\n Load all fonts in the fonts directories\n \"\"\"\n\n if lang == 'cn':\n return [os.path.join('fonts/cn', font) for font in os.listdir('fonts/cn')]\n elif lang == 'th':\n return [os.path.join('fonts/tha', font) for font in os.listdir('fonts/tha')]\n else:\n return [os.path.join('fonts/latin', font) for font in os.listdir('fonts/latin')]\n\ncolorList =[(255,0,0,1),\n (0,255,0,1),\n (0,0,255,1),\n (255,255,0,1),\n (0,255,255,1),\n (255,0,255,1),\n (255,255,255,1),\n (0,0,0,1)]\n\n# colorList =[(0,0,0,1)]\n\n# percentRatioList = [10,20,30,40,50,60,70,80,90,100]\npercentRatioList = [100]\n\n# Random text color in list\nfrom colormap import rgb2hex\ndef RandomTextColorInList(count: int):\n colorListRGB = []\n for i in range(count):\n rnd = random.randint(0,len(colorList)-1)\n color = colorList[rnd]\n colorListRGB.append(color)\n \n # Convert to hex colors\n colorListHex = []\n for i,e in enumerate(colorListRGB):\n hexColor = rgb2hex(e[0],e[1],e[2])\n colorListHex.append(hexColor)\n \n return colorListHex\n\n# Random text color\nfrom colormap import rgb2hex\ndef RandomTextColor(count: int):\n colorListRGB = []\n for i in range(count):\n color = (random.randint(0,255),random.randint(0,255),random.randint(0,255),1)\n colorListRGB.append(color)\n \n # Convert to hex colors\n colorListHex = []\n for i,e in enumerate(colorListRGB):\n hexColor = rgb2hex(e[0],e[1],e[2])\n colorListHex.append(hexColor)\n \n return colorListHex\n\n# Random background color in list\ndef RandomBackgroundColorInList(count: int)-> list:\n colorList1 = []\n for i in range(count):\n rnd = random.randint(0, len(colorList)-1)\n color = colorList[rnd]\n colorList1.append(color)\n \n return colorList1\n\n# Random background color\ndef RandomBackgroundColor(count: int)-> list:\n colorList = []\n for i in range(count):\n color = (random.randint(0,255),random.randint(0,255),random.randint(0,255),1)\n colorList.append(color)\n \n return colorList\n \n# Create report .csv\ndef CreateReport(dataframe):\n df = pd.DataFrame(dataframe,columns=['File name','Text','Font','Font size ratio','Font color','Background','Image size','Distorsion','Blur','Skew'])\n df.to_csv('out/Report.csv',index = False)\n print(\"Report.csv is written\")\n\n# Create train .txt for benchmark with this repo https://github.com/clovaai/deep-text-recognition-benchmark\ndef CreateTrainTxt(dataframe):\n text_file = open(\"gt.txt\", \"w\")\n df = pd.DataFrame(dataframe, columns=['File name', 'Text'])\n for _, row in df.iterrows():\n file_name = row['File name']\n text = row['Text']\n text_file.write(file_name + '\\t' + text + '\\n')\n text_file.close()\n print(\"Text file is written\")\n\ndef GenerateWhiteList(count: int):\n x = []\n for i in range(count):\n x.append('#ffffff')\n return x\n\ndef main():\n \"\"\"\n Description: Main function\n \"\"\"\n\n # Argument parsing\n args = parse_arguments()\n # Create the directory if it does not exist.\n try:\n if os.path.exists(args.output_dir) == True:\n shutil.rmtree(args.output_dir)\n os.makedirs(args.output_dir)\n else:\n os.makedirs(args.output_dir)\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise\n\n # Creating word list\n lang_dict = load_dict(args.language)\n\n # Create font (path) list\n if not args.font:\n fonts = load_fonts(args.language)\n else:\n if os.path.isfile(args.font):\n fonts = [args.font]\n else:\n sys.exit(\"Cannot open font\")\n\n # Creating synthetic sentences (or word)\n strings = []\n \n if args.use_wikipedia:\n strings = create_strings_from_wikipedia(args.length, args.count, args.language)\n elif args.input_file != '':\n strings = create_strings_from_file(args.input_file, args.count)\n elif args.random_sequences:\n strings = create_strings_randomly(args.length, args.random, args.count,\n args.include_letters, args.include_numbers, args.include_symbols, args.language)\n # Set a name format compatible with special characters automatically if they are used\n if args.include_symbols or True not in (args.include_letters, args.include_numbers, args.include_symbols):\n args.name_format = 2\n else:\n strings = create_strings_from_dict(args.length, args.random, args.count, lang_dict)\n\n # print(strings)\n # strings = [\"หิวน้ำเดี๋ยวพรุ่งนี้เค้าก็กลับมา ไม้โท เสี่ยว\", \"อร่อยมากเลย\"]\n string_count = len(strings)\n \n # Random BG color\n colorBGList = []\n \n backgroundList = []\n \n if args.background == 0 or args.background == 1 or args.background == 2 or args.background == 3:\n for i in range(args.count):\n colorBGList.append(args.background)\n backgroundList.append(args.background)\n elif args.background == 4:\n \n for i in range(args.count):\n colorBGList.append((random.randint(0,255),random.randint(0,255),random.randint(0,255),1))\n backgroundList.append(4)\n # if args.background_color_mode == \"rndInList\":\n # colorBGList = GenerateWhiteList(args.count)\n # backgroundList.append(4)\n # elif args.background_color_mode == \"rnd\":\n # colorBGList = RandomBackgroundColor(args.count)\n # backgroundList.append(4)\n \n elif args.background == 5:\n \n for i in range(args.count):\n args.background = random.randint(0,4)\n \n if args.background == 4:\n args.background = 4\n if args.background_color_mode == \"rndInList\":\n colorBGList.append(colorList[random.randint(0,len(colorList)-1)])\n backgroundList.append(4)\n \n elif args.background_color_mode == \"rnd\":\n colorBGList.append((random.randint(0,255),random.randint(0,255),random.randint(0,255),1))\n backgroundList.append(4)\n else:\n rndBackground = random.randint(0,3)\n colorBGList.append(rndBackground)\n backgroundList.append(rndBackground)\n # print(colorBGList)\n # Random text color\n if args.text_color == 'rndInList':\n colorTextList = RandomTextColorInList(args.count)\n elif args.text_color == 'rnd':\n colorTextList = RandomTextColor(args.count)\n else:\n colorTextList = []\n for i in range(args.count):\n colorTextList.append(args.text_color)\n \n # Random font\n fontList = []\n for i in range(args.count):\n fontList.append( fonts[random.randrange(0, len(fonts)-1)])\n # print(fontList)\n # fontList = ['fonts/tha/Niramit-ExtraLight.ttf', 'fonts/tha/Niramit-ExtraLight.ttf']\n # Distorsion list\n distorsionList = []\n if args.distorsion == 3:\n for i in range(args.count):\n distorsionList.append(random.randint(0,2))\n else:\n for i in range(args.count):\n distorsionList.append(args.distorsion)\n \n # Skew & Blur list\n blurList = []\n skewList = []\n if args.random_blur_and_skew == True:\n for i in range(args.count):\n blurList.append(random.choice([True, False]))\n skewList.append(random.choice([True, False]))\n else:\n for i in range(args.count): \n blurList.append(args.random_blur)\n blurList.append(args.random_skew)\n \n # Font size List \n fontSizeList = []\n ratioList = []\n \n for i in range(args.count):\n if args.random_font_size == True:\n ratio = percentRatioList[random.randint(0,len(percentRatioList)-1)] # random.randint(0,len(percentRatioList)-1)\n fontSizeList.append(ratio)\n ratioList.append(int(ratio))\n elif args.random_font_size == False:\n fontSizeList.append(int(args.format))\n ratioList.append(int(args.format/args.format*100))\n \n \n p = Pool(args.thread_count)\n for _ in tqdm(p.imap_unordered(\n FakeTextDataGenerator.generate_from_tuple,\n zip(\n [i for i in range(0, string_count)],\n strings,\n [e for e in fontList],\n [args.output_dir] * string_count,\n [args.format] * string_count,\n [args.extension] * string_count,\n [args.skew_angle] * string_count,\n [e for e in skewList],\n [args.blur] * string_count,\n [e for e in blurList],\n [e for e in backgroundList],\n [e for e in distorsionList],\n [args.distorsion_orientation] * string_count,\n [args.handwritten] * string_count,\n [args.name_format] * string_count,\n [args.width] * string_count,\n [args.alignment] * string_count,\n [e for e in colorTextList] * string_count,\n [args.orientation] * string_count,\n [args.space_width] * string_count,\n [args.margins] * string_count,\n [args.fit] * string_count,\n [e for e in colorBGList],\n [e for e in fontSizeList]\n )\n ), total=args.count):\n pass\n p.terminate()\n\n if args.name_format == 2:\n # Create file with filename-to-label connections\n with open(os.path.join(args.output_dir, \"labels.txt\"), 'w', encoding=\"utf-8\") as f:\n for i in range(string_count):\n file_name = str(i) + \".\" + args.extension\n f.write(\"{} {}\\n\".format(file_name, strings[i]))\n print(strings[i])\n \n elif args.name_format == 3:\n from PIL import Image\n dataframe = []\n for i in range(args.count):\n im = Image.open(args.output_dir+str(i)+'.jpg')\n fontName = fontList[i]\n \n if colorBGList[i] == 0:\n colorBGList[i] = \"gaussian noise\"\n elif colorBGList[i] == 1:\n colorBGList[i] = \"plain white\"\n elif colorBGList[i] == 2:\n colorBGList[i] = \"quasicrystal\"\n elif colorBGList[i] == 3:\n colorBGList[i] = \"picture\"\n elif type(colorBGList[i]) == type((0,0,0,0)):\n colorBGList[i] = \"color background \" + str(colorBGList[i]) \n\n if distorsionList[i] == 0:\n distorsionList[i] = \"None (Default)\"\n elif distorsionList[i] == 1:\n distorsionList[i] = \"Sine wave\"\n elif distorsionList[i] == 2:\n distorsionList[i] = \"Cosine wave\"\n \n tupleData = (i,strings[i],fontName[10:],str(ratioList[i])+\"%\",colorTextList[i],colorBGList[i],im.size,distorsionList[i],blurList[i],skewList[i])\n \n dataframe.append(tupleData)\n # print(tupleData)\n \n CreateReport(dataframe)\n\n elif args.name_format == 4:\n dataframe = []\n for i in range(args.count):\n file_name = args.output_dir+str(i)+'.jpg'\n\n tupleData = (file_name, strings[i])\n\n dataframe.append(tupleData)\n CreateTrainTxt(dataframe)\n \n\nif __name__ == '__main__':\n main()\n","sub_path":"TextRecognitionDataGenerator/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":20352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"166379508","text":"import os\nfrom mutagen.mp3 import MP3\nimport mutagen.id3\nfrom mutagen.easyid3 import EasyID3\nglobal illegel_letter\nillegel_letter = ('\\\\', '/', ':', '*', '?', '<', '>', '|')\n\n\ndef hello():\n print('-' * 74)\n s = '''\n #####################################################################\n # 这个脚本是用来整理你的音乐文件夹的,它可以将你的音乐 #\n # 按照\"歌手\\专辑\\歌曲\"的形式整理到各自的文件夹中 #\n # #\n #--- ---- ---- ---- ---- ---- ---- ---- ----#\n # **注:程序只处理MP3文件, 其他忽略** #\n #####################################################################\n '''\n print(s)\n print('-' * 74)\n d = '''\n 输入 s 开始整理; 输入 q 退出\n '''\n print(d)\n\n\ndef is_mp3(mp3):\n '''判断是否为MP3文件\n '''\n m = mp3.split('.')\n if m[-1] == 'mp3':\n return True\n else:\n return False\n\n\ndef get_album(id3info):\n '''获取MP3的专辑信息\n '''\n if 'album' not in id3info:\n album = 'unknown album'\n else:\n album = id3info['album'][0]\n return album\n\n\ndef get_artist(id3info):\n '''获取MP3文件的歌手信息\n '''\n if 'artist' not in id3info:\n artist = 'unknown artist'\n else:\n artist = id3info['artist'][0]\n return artist\n\n\ndef check_name(filename):\n '''检查文件夹的名字是否合法\n Check if directory is legal\n '''\n s = ''\n\n # 去除文件名结尾的'.'\n length = len(filename)\n while filename[length-1] == '.':\n length = length - 1\n\n # 除去文件名中非法字符\n for i in range(length):\n if filename[i] not in illegel_letter:\n s += filename[i]\n return s\n\n\ndef get_music_dirc():\n s = '''\n 请输在下面输入你的音乐文件夹的位置\n 例如 :(不区分大小写)\n E:\\\\Users\\\\Music\n C:\\\\SomeWhere\\\\MyMusicFile\n D:\\\\kuwodownload\n '''\n print(s)\n\n T = 1\n while T:\n music_dir = input('音乐文件夹所在位置:>>> ')\n if os.path.isdir(music_dir):\n return music_dir\n T = 0\n else:\n print('你输入的路径不存在,请重新输入')\n return music_dir\n\n\ndef clear_empty(music_dir):\n print('***开始清理空文件夹***')\n\n # 重新扫描路径\n results = os.walk(music_dir)\n\n # 如果为空文件夹则删除\n for root, dirc, filename in results:\n if (len(dirc)==0) & (len(filename)==0):\n try:\n os.rmdir(root)\n print('已清除>>> %s' %root )\n except:\n print('T_T 未能清除空文件夹')\n return\n print('*** CLEAR OK ***')\n print('\\n')\n\n\ndef echo_list(u=[]):\n '''输出列表中的每一项\n '''\n print('*** start ***')\n for i in range(len(u)):\n for j in range(len(u[i])):\n print(u[i][j])\n print('-' * 70)\n\n\ndef echo_info(h):\n '''通过询问用户意愿输出详细信息\n '''\n print('是否逐条查看详细信息? <输入 y 查看, 输入 n 过>')\n\n T = 1\n while T:\n YesOrNo = input('y / n ?>>> ')\n if YesOrNo == 'y':\n for j in range(len(h)):\n print('%s info:' % h[j])\n echo_list(u[j])\n print('\\n')\n\n T = 0\n elif YesOrNo == 'n':\n print('未查看详细信息')\n T = 0\n else:\n print('有效命令为:y / n')\n\n\ndef change_dirc(src, dst):\n '''把文件从 源路径(src) 移动到 目标路径(dst)\n '''\n\n # 拆分路径和文件名\n split_src = os.path.split(src)[0]\n name = os.path.split(src)[-1]\n\n # 如果两路径相同则输出“位置正确”\n if src == dst:\n k = os.path.split(dst)\n return '未移动文件: ', (k[-1], k[0])\n\n # 如果源路径和目标路径不同, 则进行如下操作\n else:\n try:\n os.rename(src, dst)\n return '已移动文件: ', (src, dst)\n except FileExistsError as e:\n return '重复文件: ', (src, dst)\n\n\ndef start(results):\n\n # 声明变量\n # 用来统计MP3文件数量和保存处理时的信息\n __total__ = 0\n SameFile = []\n MovedFile = []\n UnMovedFile = []\n\n # 处理这个目录下的每个文件\n for root, dirc, files in results:\n\n # 对每个文件:\n for filename in files:\n\n # 如果是MP3文件,则:\n if is_mp3(filename):\n\n # 获取这个MP3文件的当前路径\n m_dirc = os.path.join(root, filename)\n\n # 获取MP3文件的 id3 信息\n id3info = MP3(m_dirc, ID3=EasyID3)\n\n # 从 id3 信息中取得歌手和专辑,并检查是否为合法文件名\n artist = check_name(get_artist(id3info))\n album = check_name(get_album(id3info))\n\n # 目标文件路径\n new_dirc = os.path.join(music_dir, artist, album, filename)\n\n # 改变文件路劲\n h, r = change_dirc(m_dirc, new_dirc)\n if h == '未移动文件: ':\n UnMovedFile.append(r)\n elif h == '已移动文件: ':\n MovedFile.append(r)\n else:\n SameFile.append(r)\n\n # 统计MP3文件数目\n __total__ = __total__ + 1\n\n print('-- mission completed --')\n print(\"total: %d of songs\" % __total__)\n return ['同名', '已移动', '未移动'], [SameFile, MovedFile,UnMovedFile]\n\n\nif __name__ == '__main__':\n\n __author__ = 'ven'\n\n # 输出欢迎信息及提示\n hello()\n\n # 主循环\n T = 1\n while T:\n user_input = input('s / q ?>>> ')\n\n if user_input == 's':\n music_dir = get_music_dirc()\n\n # 遍历用户给出的目录\n try:\n results = os.walk(music_dir)\n print(':) 成功遍历当前目录')\n except:\n print(':( 未能遍历当前目录')\n\n # 处理每个MP3文件\n h, u = start(results)\n\n # 输出统计信息\n print('\\n')\n for i in range(len(u)):\n print('%s: %s' % (h[i], len(u[i])))\n print('-' * 70)\n\n # 输出详细信息\n print('\\n')\n echo_info(h)\n\n # 清楚空文件夹\n print('\\n')\n clear_empty(music_dir)\n\n T = 0\n elif user_input == 'q':\n T = 0\n else:\n print('未知指令,请重新输入')\n\n input('现在任务已经完成了,按Enter键退出')\n","sub_path":"1070625_繁簡體&修改MP3 tags/python管理分類MP3資料夾.py","file_name":"python管理分類MP3資料夾.py","file_ext":"py","file_size_in_byte":6902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"556940172","text":"from collections import OrderedDict\nfrom operator import itemgetter\n\nimport cv2\nimport matplotlib.image as mpimg\nimport numpy as np\nfrom skimage.measure import compare_ssim as ssim\n\n\ndef search(lst, calc, prevResult):\n min = 0\n max = len(lst) - 1\n avg = int((min + max) / 2)\n\n while min < max:\n newResult = calc(lst[avg])\n\n if newResult > 0.99:\n return avg\n elif newResult >= prevResult:\n return avg + 1 + search(lst[avg + 1:], calc, newResult)\n else:\n return search(lst[:avg], calc, newResult)\n return avg\n\n\ndef color_comp(color_idx, rgb_threshold, sim_result_lst):\n def calc(intensity_lvl):\n image = mpimg.imread('test.jpg')\n color_select = np.copy(image)\n\n rgb_threshold[color_idx] = intensity_lvl\n\n thresholds = (image[:, :, 0] < rgb_threshold[0]) \\\n | (image[:, :, 1] < rgb_threshold[1]) \\\n | (image[:, :, 2] < rgb_threshold[2])\n color_select[thresholds] = [0, 0, 0]\n mpimg.imsave(\"test-result.jpg\", color_select)\n\n result = cv2.imread(\"test-result.jpg\")\n expected = cv2.imread(\"expected_result.jpg\")\n result = cv2.cvtColor(result, cv2.COLOR_BGR2GRAY)\n expected = cv2.cvtColor(expected, cv2.COLOR_BGR2GRAY)\n\n simValue = ssim(expected, result)\n sim_result_lst.append((intensity_lvl, simValue))\n\n return simValue\n\n return calc\n\n\ndef runColors():\n rgb_threshold = [0, 0, 0]\n color_names = {0: 'Red', 1: 'Green', 2: 'Blue'}\n colors = OrderedDict({0: [i for i in range(0, 256)], 1: [i for i in range(0, 256)], 2: [i for i in range(0, 256)]})\n result = []\n\n for color_idx, intensities in colors.items():\n\n start = 0\n end = len(intensities)\n max_found_lst = 0\n run = True\n while run:\n inputIntensities = intensities[start:end]\n\n sim_result_lst = []\n search(inputIntensities, color_comp(color_idx, rgb_threshold, sim_result_lst), 0)\n\n print(sim_result_lst)\n\n max_found_lst = max(sim_result_lst, key=itemgetter(1))\n if max_found_lst[1] < 0.99:\n sim_vals = [val[1] for val in sim_result_lst]\n res = [j - i for i, j in zip(sim_vals[:-1], sim_vals[1:])]\n intr_range = []\n\n for idx in range(len(res)):\n if res[idx] > 0:\n intr_range.append(idx)\n else:\n intr_range.append(idx)\n break\n\n print(intr_range)\n\n if len(intr_range) > 1:\n start = sim_result_lst[intr_range[-2]][0]\n end = sim_result_lst[intr_range[-1]][0]\n else:\n run = False\n\n else:\n run = False\n\n rgb_threshold[color_idx] = max_found_lst[0]\n result.append(max_found_lst[0])\n\n print(\"rgb_threshold: %s\" % rgb_threshold)\n\n print(result)\n\n\nif __name__ == \"__main__\":\n # runSimple()\n runColors()\n\n # # Read in the image\n # image = mpimg.imread('test.jpg')\n # color_select = np.copy(image)\n #\n # # Define color selection criteria\n # ###### MODIFY THESE VARIABLES TO MAKE YOUR COLOR SELECTION\n # red_threshold = 200\n # green_threshold = 200\n # blue_threshold = 200\n # ######\n #\n # rgb_threshold = [red_threshold, green_threshold, blue_threshold]\n # thresholds = (image[:, :, 0] < rgb_threshold[0]) \\\n # | (image[:, :, 1] < rgb_threshold[1]) \\\n # | (image[:, :, 2] < rgb_threshold[2])\n # color_select[thresholds] = [0, 0, 0]\n # mpimg.imsave(\"test-result.jpg\", color_select)\n #\n # result = cv2.imread(\"test-result.jpg\")\n # expected = cv2.imread(\"expected_result.jpg\")\n # result = cv2.cvtColor(result, cv2.COLOR_BGR2GRAY)\n # expected = cv2.cvtColor(expected, cv2.COLOR_BGR2GRAY)\n #\n # print(\"ssim: %s\" % ssim(expected, result))\n","sub_path":"find_similar_bsearch.py","file_name":"find_similar_bsearch.py","file_ext":"py","file_size_in_byte":4021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"36274873","text":"import numpy as np\nimport cv2\n\ncap = cv2.VideoCapture(0)\nret, frame = cap.read()\nhsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n\ncv2.imshow('image',hsv)\ncv2.waitKey(0)\ncv2.destroyAllWindows()","sub_path":"frame.py","file_name":"frame.py","file_ext":"py","file_size_in_byte":189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"238734421","text":"'''\nCreated on May 10, 2017\n\n@author: kot\n'''\nfrom event import *\nfrom qsforex.data import price\n\nclass ExtendedSignalEvent(SignalEvent):\n def __init__(self, instrument, order_type, side, time, \n order_price=0, take_profit=0, stop_loss=0, is_simulated_event=False):\n self.type = 'SIGNAL'\n self.instrument = instrument\n self.order_type = order_type\n self.side = side\n self.time = time # Time of the last tick that generated the signal\n self.order_price = order_price\n self.take_profit = take_profit\n self.stop_loss = stop_loss\n self.condition_satisfied = False\n self.is_simulated_event = is_simulated_event\n\n\n def __str__(self):\n return \"Type: %s, Instrument: %s, Order Type: %s, Side: %s\" % (\n str(self.type), str(self.instrument), \n str(self.order_type), str(self.side)\n )\n\n\n\nclass ExtendedOrderEvent(OrderEvent):\n def __init__(self, instrument, units, order_type, side=\"\", \n price=0, take_profit=0, stop_loss=0):\n self.type = 'ORDER'\n self.instrument = instrument\n self.units = units\n self.order_type = order_type\n self.side = side\n self.price = price\n self.take_profit = take_profit\n self.stop_loss = stop_loss\n\n def __str__(self):\n return \"Type: %s, Instrument: %s, Units: %s, Order Type: %s, Side: %s\" % (\n str(self.type), str(self.instrument), str(self.units),\n str(self.order_type), str(self.side)\n )\n\n","sub_path":"src/qsforex/event/event2.py","file_name":"event2.py","file_ext":"py","file_size_in_byte":1552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"161521124","text":"#!/usr/bin/env python\n# BadParent IRC Nicklist Flooder\n# Developed by acidvegas in Python 2\n# https://github.com/acidvegas/badparent\n# config.py\n\n# IRC Settings\nserver = 'irc.server.com'\nport = 6667\nuse_ipv6 = False\nuse_ssl = False\nproxy = None # Proxy should be a Socks5 in IP:PORT format, or set to None if not used.\nvhost = None\npassword = None\nchannel = '#chats'\nkey = None\nmessage = 'I have bad parents, so I was raised to flood on IRC'\n\n# Identity Settings\nnickname = 'BadParent'\nusername = 'badparent'\nrealname = 'BadParent IRC Bot'\n\n# Throttle Settings\nattack_delay = 3 # Delay between each attack method sent.\nattack_wait = 5 # Delay to wait before starting the attacks after connecting.\nconcurrent_connections = 3 # Number of concurrent connections per-proxy.\ninvite_cycle = 10 # Number of invites before randomizing the invite channel.\nmax_threads = 100 # Maximum number of threads running at one time.\nthread_delay = 0 # Delay between each thread started.\ntimeout = 5 # Seconds before timing out on a connection.\n\n# Globals (DO NOT EDIT)\nnicklist = []\n","sub_path":"badparent/python2/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"148989593","text":"import pytest\n\nfrom main import app\n\nfrom services import elastic_writer\nfrom services import elastic_mapping\n\nimport config\n\n@pytest.fixture\ndef test_cli(loop, test_client):\n return loop.run_until_complete(test_client(app))\n\n\n@pytest.fixture(scope=\"session\")\ndef monkeysession(request):\n \"\"\"\n monkeypatch is function scoped\n this is a fix for test_data fixture that I want session scoped\n see https://github.com/pytest-dev/pytest/issues/363\n \"\"\"\n from _pytest.monkeypatch import MonkeyPatch\n mpatch = MonkeyPatch()\n yield mpatch\n mpatch.undo()\n\n\n@pytest.fixture(scope='session')\ndef test_data(monkeysession):\n \"\"\"\n This function prepares the indices required for testing\n \"\"\"\n def data():\n \"\"\"\n Provides rudiments of data for testing\n \"\"\"\n return {\n\n 'lang': 'fr',\n 'industry': 'test_industry',\n 'spider': 'test_spider',\n\n 'valid_product': {\n '_id': 'test_3018122',\n 'avg_rating': 4.0,\n 'brand': 'test_brand',\n 'categories': ['Outillage ',\n 'Outillage à main',\n 'Marteau, maîllet, massette',\n 'Mâsse et massette'],\n 'category_url': 'https://www.manomano.fr/outil-du-macon-538',\n 'has_description': True,\n 'has_stock': True,\n 'is_marketplace': True,\n 'logo': 'https://cdn.manomano.fr/marteau-manche-en-fibre-de-verre-1250-g-P-149211-3064717_1.jpg',\n 'price': 7.41,\n 'reviews': [{'_id': 'REV_3018122_0',\n 'body': 'Belle prise en main, assez lourd pour les démontages où '\n 'on a besoin de taper.',\n 'rating': 4,\n 'review_date': '2017-06-04',\n 'title': 'Accueil'}],\n 'reviews_count': 1,\n 'title': 'Marteau - Manche En Fibre De Verre - 1250 G',\n 'url': 'https://www.manomano.fr/masse-et-massette/marteau-manche-en-fibre-de-verre-1250-g-3018122'\n },\n\n 'invalid_product': {\n # '_id': '3018122',\n 'avg_rating': 4.0,\n 'brand': '',\n 'categories': ['Outillage',\n 'Outillage à main',\n 'Marteau, maillet, massette',\n 'Masse et massette'],\n # 'category': 'Masse et massette',\n 'category_url': 'https://www.manomano.fr/outil-du-macon-538',\n 'has_description': True,\n 'has_stock': True,\n 'is_marketplace': True,\n 'logo': 'https://cdn.manomano.fr/marteau-manche-en-fibre-de-verre-1250-g-P-149211-3064717_1.jpg',\n # 'price': 7.41,\n 'reviews': [{'_id': 'REV_3018122_0',\n 'body': 'Belle prise en main, assez lourd pour les démontages où '\n 'on a besoin de taper.',\n 'rating': 4,\n 'review_date': '2017-06-04',\n 'title': 'Accueil'}],\n 'reviews_count': 1,\n # 'title': 'Marteau - Manche En Fibre De Verre - 1250 G',\n # 'url': 'https://www.manomano.fr/masse-et-massette/marteau-manche-en-fibre-de-verre-1250-g-3018122'\n }\n }\n\n lang = data()['lang']\n industry = data()['industry']\n\n\n query_session = elastic_writer.QuerySession(\n hosts=[config.ENV.ES_HOST], lang=lang, industry=industry)\n\n\n # setup tests\n print('Deleting indices')\n \n query_session.delete_index(f\"catalogs_{industry}_{lang}\")\n query_session.delete_index(f\"trainings_{industry}_{lang}\")\n\n query_session.create_index(f\"catalogs_{industry}_{lang}\", elastic_mapping.CATALOGS_MAPPING)\n query_session.create_index(f\"trainings_{industry}_{lang}\", elastic_mapping.TRAININGS_MAPPING)\n\n print('Fresh indices created')\n\n yield data()\n\n # tear down tests\n query_session.delete_index(f\"catalogs_{industry}_{lang}\")\n query_session.delete_index(f\"trainings_{industry}_{lang}\")\n\n print('Indices deleted')\n\n\n@pytest.fixture(scope='session')\ndef test_spider_data():\n \"\"\"\n This function provides test data for spiders registration\n \"\"\"\n return { \n \"catalog\" : \"test_catalog\",\n \"lang\" : \"fr\",\n \"name\" : \"Test spider\",\n \"industry\" : \"test_industry\"\n }\n\n\n@pytest.fixture(scope='session')\ndef test_spider_incorrect_data():\n \"\"\"\n This function provides test data for spiders registration\n the spider name is mandatory\n \"\"\"\n return { \n \"catalog\" : \"test_catalog\",\n \"lang\" : \"fr\",\n \"industry\" : \"test_industry\"\n }\n\n\n\n\n\n","sub_path":"datafeed/tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":5020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"347973864","text":"\n# coding: utf-8\n\n# # SVM Lineaire et non-lineaire\n# Application sur les donnees jouet (voir Hastie et Tibshrani)\n\nfrom __future__ import print_function\nfrom __future__ import division\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import ListedColormap\n\nimport scipy.io as sio\nfrom sklearn.metrics import accuracy_score, roc_curve, auc\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\n\nfrom sklearn.svm import SVC\n\nplt.close(\"all\")\n\n\n#%% Trace frontiere decision et marge\ndef plot_decision_margin_2d(X, y, classifier, resolution=0.02, titre=' '):\n\n # setup marker generator and color map\n markers = ('s', 'x', 'o', '^', 'v')\n colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')\n cmap = ListedColormap(colors[:len(np.unique(y))])\n\n # plot the decision surface\n x1_min, x1_max = X[:, 0].min() - 0, X[:, 0].max() + 0\n x2_min, x2_max = X[:, 1].min() - 0, X[:, 1].max() + 0\n xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),\n np.arange(x2_min, x2_max, resolution))\n Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)\n Z = Z.reshape(xx1.shape)\n plt.figure()\n plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap)\n plt.xlim(xx1.min(), xx1.max())\n plt.ylim(xx2.min(), xx2.max())\n\n # margin\n Z = classifier.decision_function(np.array([xx1.ravel(), xx2.ravel()]).T)\n Z = Z.reshape(xx1.shape)\n cs = plt.contour(xx1, xx2, Z, levels=[-1, 0, 1], colors=['r', 'g', 'b'], linewidths=2.5)\n plt.clabel(cs)\n \n # plot class samples\n for idx, cl in enumerate(np.unique(y)):\n plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1],\n alpha=0.6, c=cmap(idx),\n marker=markers[idx], label= 'classe {}'.format(cl))\n plt.legend(loc='best')\n plt.title(titre, fontsize=12)\n \n#%% Dataset : Mixture of gaussian (disponible sur Moodle)\n# Donnees apprentissage\ndata_a = sio.loadmat('./mixtureexampleTRAIN.mat')\nXa, Ya = data_a['Xa'], data_a['Ya'][:,0]\nprint('\\nCaractéristiques jeu apprentissage : ')\nprint('Nombre de points : {}'.format(Xa.shape[0]))\nprint('Nombre de variables : {}'.format(Xa.shape[1]))\nprint('Nombre de classes : {}'.format(len(np.unique(Ya))))\nclasses, nbpoints = np.unique(Ya, return_counts=True)\nfor i, lab in enumerate(classes):\n print('Classe {} comprend {} points'.format(lab, nbpoints[i]))\n\n\n# Donnees test\ndata_t = sio.loadmat('./mixtureexampleTEST.mat')\nXt, Yt = data_t['Xt'], data_t['Yt'][:,0]\nprint('\\nCaractéristiques jeu de test : ')\nclasses, nbpoints = np.unique(Yt, return_counts=True)\nfor i, lab in enumerate(classes):\n print('Classe {} comprend {} points'.format(lab, nbpoints[i]))\n\n#%% Decoupage des donnees app en jeu de validation et app\nXa, Xv, Ya, Yv = train_test_split(Xa, Ya, shuffle=True, test_size=0.5, stratify=Ya)\n\n\n#%% Normalisation\nsc = StandardScaler(with_mean=True, with_std=True)\nsc = sc.fit(Xa)\nXa = sc.transform(Xa)\nXv = sc.transform(Xv)\nXt = sc.transform(Xt)\n\n\n#%% \n# definition du modele SVM Lineaire\nparamC = 1\nclf_svm = SVC(kernel='linear', C = paramC)\n# apprentissage des parametres du SVM Lineaire sur le jeu d'apprentissage\nclf_svm.fit(Xa, Ya)\n\n#%% Trace de la frontiere de decision et de la marge \nplot_decision_margin_2d(Xa, Ya, clf_svm, 0.02, titre='{} avec C = {}'.format(\"SVM lineaire\", paramC))\n\n\n#%% Erreur de classification en test du SVM Lineaire obtenu\nerr_app = 1 - accuracy_score(Ya, clf_svm.predict(Xa))\nprint('\\nSVM Lineaire : erreur apprentissage = {}'.format(err_app))\nerr_test = 1 - accuracy_score(Yt, clf_svm.predict(Xt))\nprint('SVM Lineaire : erreur test = {}'.format(err_test))\n","sub_path":"SVM/SimpleSVMLineaire.py","file_name":"SimpleSVMLineaire.py","file_ext":"py","file_size_in_byte":3670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"575128676","text":"#!/usr/bin/env python\r\n\r\n\"\"\"\r\nExample to showcase how to use the Watson NLU service\r\n\r\nto store you API key\r\n\r\n~$ mkdir ~/.ibm\r\n~$ touch ~/.ibm/ibmauth.py\r\n\r\nthen edit the file to contain\r\n\r\nibmauth_key = \"your api key\"\r\n\r\n\"\"\"\r\n\r\n\r\n\r\nimport sys\r\nimport os\r\nimport json\r\nfrom ibm_watson import VisualRecognitionV3\r\nfrom ibm_watson.visual_recognition_v4 import FileWithMetadata, TrainingDataObject, Location, AnalyzeEnums\r\nfrom ibm_cloud_sdk_core.authenticators import IAMAuthenticator\r\n\r\n### import API key\r\napikey_dir = os.path.join(os.path.expanduser(\"~\"),\".ibm\")\r\nsys.path.append(apikey_dir)\r\n\r\nif not os.path.exists(apikey_dir):\r\n raise Exception(\"please store you API key in file within 'apikey_dir' before proceeding\")\r\n\r\nfrom ibmauth import VR_KEY, VR_URL, VR_VERSION\r\n\r\ndef connect_watson_vr():\r\n \"\"\"\r\n establish a connection to watson vr service\r\n \"\"\"\r\n \r\n authenticator = IAMAuthenticator(VR_KEY)\r\n service = VisualRecognitionV3(version=VR_VERSION,\r\n authenticator=authenticator)\r\n\r\n service.set_service_url(VR_URL)\r\n\r\n print(\"\\nConnection established.\\n\")\r\n return(service)\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n \r\n\r\n \r\n service = connect_watson_vr()\r\n\r\n ## classify an image from a URL\r\n image_url = \"https://watson-developer-cloud.github.io/doc-tutorial-downloads/visual-recognition/fruitbowl.jpg\"\r\n fruitbowl_results = service.classify(url=image_url,\r\n threshold='0.1',\r\n classifier_ids=['food']).get_result()\r\n print(json.dumps(fruitbowl_results, indent=2))\r\n","sub_path":"Machine Learning, Visual Recognition and NLP/watson-vr-tutorial/watson-vr-example.py","file_name":"watson-vr-example.py","file_ext":"py","file_size_in_byte":1634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"149142377","text":"#===============================================================#\n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#\n# \tJames Coleman\t\t\t\t\t\t\t\t\t\t\t\t#\n#\tCS 3150\t\t\t\t\t\t\t\t\t\t\t\t\t\t#\n#\tHomework 2 part one\t\t\t\t\t\t\t\t\t\t\t#\n#\tSeptember 15th\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#\n#===============================================================#\n\n\t#\t >>>>>>>>>> Goals <<<<<<<<<<\n\t#\n\t# 1. Apply Averaging, Sobel, Laplacian, Median and \n\t# Gaussian filters to my image\n\t# 2. Apply two other filters of my choice\n\t# 3. Analyze the different filter effects \n\t#\n\t#\n\n# Imports \nimport cv2\nimport numpy\nfrom random import randrange\nfrom matplotlib import pyplot\n\n# Helper methods\n # Show images\ndef show(im_list):\n\t''' Show input (filtered image) compared to the original\n\tgray scale image '''\n\tpyplot.figure(figsize=(12,6))\n\ti = 1\n\tpyplot.subplot(1, len(im_list) + 1, i)\n\tpyplot.title('Original')\n\tpyplot.imshow(gray_im, cmap=\"gray\")\n\ti += 1\n\tfor im in im_list:\n\t\tpyplot.subplot(1, len(im_list) + 1, i)\n\t\tpyplot.title(im[1])\n\t\tpyplot.imshow(im[0], cmap='gray') \t\n\t\ti += 1\n\tpyplot.show()\n\n# Upload image convert image to RGB then to gray scale\n# and grab dimensions\noriginal = cv2.imread('./James_Coleman.jpg')\n\nrgb_pic = cv2.cvtColor(original, cv2.COLOR_BGR2RGB)\ngray_im = cv2.cvtColor(rgb_pic, cv2.COLOR_RGB2GRAY)\n## show([(rgb_pic, 'Color original')])\n\nheight, width = gray_im.shape\t\n\n# Filters\n# Averaging \navg1_im = numpy.zeros((height, width))\navg2_im = numpy.zeros((height, width))\navg3_im = numpy.zeros((height, width))\n\na_filter1 = numpy.zeros((3, 3))\na_filter1 += 1/9\na_filter2 = numpy.zeros((5, 5))\na_filter2 += 1/25\na_filter3 = numpy.zeros((11, 11))\na_filter3 += 1/121\n\navg1_im = cv2.filter2D(gray_im, -1, a_filter1)\navg2_im = cv2.filter2D(gray_im, -1, a_filter2)\navg3_im = cv2.filter2D(gray_im, -1, a_filter3)\n\nshow([(avg1_im, '3 x 3'),(avg2_im, '5 x 5'),(avg3_im, '11 x 11')])\n\n# Sobel\nvertical_filter = numpy.array([\n\t[1, 0, -1],\n\t[2, 0, -2],\n\t[1, 0, -1]\n])\nhorizontal_filter = numpy.array([\n\t[1, 2, 1],\n\t[0, 0, 0],\n\t[-1, -2, -1]\n])\nvertical_im = cv2.filter2D(gray_im, -1, vertical_filter)\nhorizontal_im = cv2.filter2D(gray_im, -1, horizontal_filter)\ngradient_im = numpy.maximum(vertical_im, horizontal_im)\n\nshow([(vertical_im, 'Vertical Lines'), \\\n\t (horizontal_im, 'Horizontal Lines'), \\\n\t (gradient_im, 'Gradient Lines')])\n\n# Laplacian\nfour_neighbor_laplacian = numpy.array([\n\t[0,1,0],\n\t[1,-4,1],\n\t[0,1,0]\n])\neight_neighbor_laplacian = numpy.array([\n\t[1,1,1],\n\t[1,-8,1],\n\t[1,1,1]\n])\noutline_im1 = cv2.filter2D(gray_im, -1, four_neighbor_laplacian)\noutline_im2 = cv2.filter2D(gray_im, -1, eight_neighbor_laplacian)\n\nshow([(outline_im1, 'Four Neighbor Laplacian'), \\\n\t (outline_im2, 'Eight Neighbor Lapalcian')])\n\n# Median\nmedian_im = numpy.zeros((height, width))\nfor i in range(2, height - 2):\n\tfor j in range(2, width - 2):\n\t\tpixel = sorted(numpy.ndarray.flatten(gray_im[i-2:i+2,j-2:j+2]))\n\t\tmedian_im[i][j] = pixel[12] \nshow([(median_im, 'Median Filter')])\n# Gaussian\nsmall_gaussian = numpy.array(\n\t[[1/16,1/8,1/16],\n\t[1/8,1/4,1/8],\n\t[1/16,1/8,1/16]]\n)\nbig_gaussian = numpy.array([\n\t[2, 7, 12, 7, 2],\n\t[7, 31, 52, 31, 7],\n\t[12, 52, 127, 52, 12],\n\t[7, 31, 52, 31, 7],\n\t[2, 7, 12, 7, 2]\n])\nbiggest_gaussian = numpy.array([\n\t[1,1,2,2,2,1,1],\n\t[1,3,4,5,4,3,1],\n\t[2,4,7,8,7,4,2],\n\t[2,5,8,10,8,5,2],\n\t[2,4,7,8,7,4,2],\n\t[1,3,4,5,4,3,1],\n\t[1,1,2,2,2,1,1]\t\n])\nbig_gaussian = big_gaussian / numpy.sum(big_gaussian)\nbiggest_gaussian = biggest_gaussian / numpy.sum(biggest_gaussian)\ngaussian_im1 = cv2.filter2D(gray_im, -1, small_gaussian)\ngaussian_im2 = cv2.filter2D(gray_im, -1, big_gaussian)\ngaussian_im3 = cv2.filter2D(gray_im, -1, biggest_gaussian)\n\nshow([(gaussian_im1, 'Small Gaussian Filter'), \\\n\t (gaussian_im2, 'Big Gaussian Filter'),\n\t (gaussian_im3, 'Biggest Gaussian Filter')\n])\n\n# Apply two other filter\n# Prewitt\nvertical_prewitt = numpy.array([\n\t[1, 0, -1],\n\t[2, 0, -2],\n\t[1, 0, -1]\n])\nhorizontal_prewitt = numpy.array([\n\t[1, 2, 1],\n\t[0, 0, 0],\n\t[-1, -2, -1]\n])\nvertical_prewitt_im = cv2.filter2D(gray_im, -1, vertical_prewitt)\nhorizontal_prewitt_im = cv2.filter2D(gray_im, -1, horizontal_prewitt)\ngradient_prewitt_im = numpy.maximum(vertical_prewitt_im, horizontal_prewitt_im)\n\nshow([(vertical_im, 'Vertical Sobel Lines'), \\\n\t (vertical_prewitt_im, 'Vertical Prewitt Filter')]) \nshow([(horizontal_im, 'Horizontal Sobel Lines'), \\\n \t (horizontal_prewitt_im, 'Horizontal Prewitt Filter')])\nshow([(gradient_im, 'Gradient Lines'), \\\n\t (gradient_prewitt_im, 'Gradient Prewitt Filters')])\n\n# Random pixel filter\nrandom_im = numpy.zeros((height, width))\nfor i in range(height):\n\tfor j in range(width):\n\t\tx = randrange(-5, 6)\n\t\ty = randrange(-5, 6)\n\t\tif (i + x >= height or i + x < 0 or j + y >= width or j + y < 0):\n\t\t\trandom_im[i][j] = 255\n\t\telse:\n\t\t\trandom_im[i][j] = gray_im[i + x][j + y]\nshow([(random_im, 'Random pixel filter')])\n","sub_path":"Homework2/Image_filtering.py","file_name":"Image_filtering.py","file_ext":"py","file_size_in_byte":4827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"369514492","text":"from typing import Optional\n\nfrom src.model.Term import Term\nfrom src.model.Sort import Sort\n\n\nclass L4TypeError(Exception):\n def __init__(self, msg:str, term:Optional[Term] = None) -> None:\n self.term = term\n self.msg = msg\n def __str__(self) -> str:\n rv = self.msg\n if self.term and self.term.coord:\n if self.term.coord.col:\n rv += f\"\\nSee (near) line {self.term.coord.line} col {self.term.coord.col}\"\n else:\n rv += f\"\\nSee (near) line {self.term.coord.line}.\"\n return rv\n\nclass L4TypeCheckError(L4TypeError):\n def __init__(self, term:Term, check_sort:Sort) -> None:\n super().__init__(f\"Term {term} failed to check against {check_sort}.\", term)\n self.check_sort = check_sort\n\nclass L4TypeInferError(L4TypeError):\n def __init__(self, term:Term, msg:str=\"\") -> None:\n super().__init__((msg + \"\\n\" if msg else \"\") + f\"Failed to infer sort of term {term}.\", term)\n\nclass L4TypeInferCheckError(L4TypeError):\n def __init__(self, term:Term, inferred_sort:Sort, check_sort:Sort) -> None:\n msg = f\"Term {term}'s inferred sort {inferred_sort} is not a subtype of the sort {check_sort} checked against.\"\n super().__init__(msg, term)\n\n # self.inferred_sort = inferred_sort\n # self.check_sort = check_sort\n # print(msg)\n def __str__(self) -> str:\n rv = self.msg\n\n if self.term and self.term.coord:\n if self.term.coord.col:\n rv += f\"\\nSee (near) line {self.term.coord.line} col {self.term.coord.col}\"\n else:\n rv += f\"\\nSee (near) line {self.term.coord.line}.\"\n return rv","sub_path":"linear_state_machine_language/pyL4/src/typechecking/L4TypeErrors.py","file_name":"L4TypeErrors.py","file_ext":"py","file_size_in_byte":1692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"288343137","text":"# coding: utf-8\n\nfrom flask import Blueprint\nfrom flask import render_template\nfrom ..models import Node, Topic, fill_topics\n\n\nbp = Blueprint('front', __name__)\n\n\n@bp.route('/')\ndef home():\n topics = Topic.query.order_by(Topic.id.desc()).limit(16)\n topics = fill_topics(topics)\n\n nodes = Node.query.order_by(Node.id.desc()).limit(10)\n return render_template('index.html', topics=topics, nodes=nodes)\n","sub_path":"june/views/front.py","file_name":"front.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"520508275","text":"import panel as pn\nimport xarray as xr\nfrom .sigslot import SigSlot\nfrom .utils import _is_coord\n\n\nclass Display(SigSlot):\n \"\"\"\n This widget takes input as a xarray instance. For each Dataset,\n its variables are displayed. In case a DataArray has been\n provided only a single variable of that particular array is shown.\n Variables which are coordinates are annotated with '📈'.\n\n Parameters\n ----------\n data: `xarray` instance: `DataSet` or `DataArray`\n data is used to initialize the DataSelector\n\n Attributes\n ----------\n panel: Displays the generated Multiselect object\n\n \"\"\"\n\n def __init__(self, data):\n super().__init__()\n self.data = data\n self.select = pn.widgets.MultiSelect(size=8, max_width=300,\n height=210,\n width_policy='max',\n name='Variables')\n # self.set_selection(self.data)\n self.set_variables()\n\n self._register(self.select, \"variable_selected\")\n\n self.panel = pn.Row(self.select)\n\n def set_variables(self,):\n self.select.options = {_is_coord(self.data, name): name for name in list(self.data.variables)}\n\n def select_variable(self, variable):\n \"\"\"\n To select variable\n \"\"\"\n if isinstance(variable, str):\n if variable in self.select.options.values():\n self.select.value = [variable]\n else:\n print(f\"Variable {variable} not present in displayer.\")\n\n def setup_initial_values(self, init_params={}):\n if 'Variables' in init_params:\n self.select_variable(init_params['Variables'])\n\n @property\n def kwargs(self):\n \"\"\"\n Select only the first value from the selected variables.\n \"\"\"\n out = {p.name: p.value[0] for p in self.panel}\n return out\n\n def set_coords(self, data):\n self.data = data\n self.set_variables()\n","sub_path":"xrviz/display.py","file_name":"display.py","file_ext":"py","file_size_in_byte":2033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"332974477","text":"# Simple env test.\nimport json\nimport select\nimport time\nimport logging\nfrom logging import getLogger\nimport os\n\nimport gym\nimport minerl\n\nimport numpy as np\n\nimport chainer\n\nimport chainerrl\nfrom chainerrl.wrappers import ContinuingTimeLimit\nfrom chainerrl.wrappers.atari_wrappers import ScaledFloatFrame\n\nimport sys\nsys.path.append(os.path.abspath(os.path.join(__file__, os.pardir)))\nfrom utility import utils\nfrom utility.q_functions import NatureDQNHead, A3CFF\nfrom utility.env_wrappers import (\n SerialDiscreteActionWrapper, CombineActionWrapper, SerialDiscreteCombineActionWrapper,\n ContinuingTimeLimitMonitor,\n MoveAxisWrapper, FrameSkip, FrameStack, ObtainPoVWrapper, FullObservationSpaceWrapper)\n\nfrom utility.env_wrappers import ScaledFloatFrame as SFF\n\n# All the evaluations will be evaluated on MineRLObtainDiamond-v0 environment\nMINERL_GYM_ENV = os.getenv('MINERL_GYM_ENV', 'MineRLTreechop-v0')\nMINERL_MAX_EVALUATION_EPISODES = int(os.getenv('MINERL_MAX_EVALUATION_EPISODES', 5))\n\ndef wrap_env(env, test):\n # wrap env: time limit...\n if isinstance(env, gym.wrappers.TimeLimit):\n env = env.env\n max_episode_steps = env.spec.max_episode_steps\n env = ContinuingTimeLimit(env, max_episode_steps=max_episode_steps)\n # wrap env: observation...\n # NOTE: wrapping order matters!\n env = FrameSkip(env, skip=4)\n env = ObtainPoVWrapper(env)\n # convert hwc -> chw as Chainer requires.\n env = MoveAxisWrapper(env, source=-1, destination=0)\n # env = ScaledFloatFrame(env)\n env = SFF(env)\n env = FrameStack(env, 4, channel_order='chw')\n # wrap env: action...\n env = SerialDiscreteActionWrapper(\n env,\n always_keys=['attack'], reverse_keys=['forward'], exclude_keys=['back', 'left', 'right', 'sneak', 'sprint'], exclude_noop=False)\n\n return env\n\ndef scaleFrames(frames):\n for frame in frames:\n frame = np.array(frame).astype(np.float32) / 255.0\n\n return frames\n\ndef main():\n \"\"\"\n This function will be called for training phase.\n \"\"\"\n # Sample code for illustration, add your code below to run in test phase.\n # Load trained model from train/ directory\n core_env = gym.make(MINERL_GYM_ENV)\n wrapped_env = wrap_env(core_env, test=False)\n # for i in range(wrapped_env.action_space.n):\n # print(\"Action {0}: {1}\".format(i, wrapped_env.action(i)))\n\n head = NatureDQNHead(n_input_channels=12, n_output_channels=512)\n model = A3CFF(n_actions=5, head=head)\n\n opt = chainer.optimizers.Adam(alpha=2.5e-4, eps=1e-8)\n opt.setup(model)\n opt.add_hook(chainer.optimizer.GradientClipping(40))\n\n def phi(x):\n # observation -> NN input\n return np.asarray(x)\n\n CLIP_EPS = 0.1\n agent = chainerrl.agents.ppo.PPO(\n model, opt, gpu=-1, gamma=0.99, phi=phi, update_interval=1024,\n minibatch_size=32, epochs=3, clip_eps=CLIP_EPS, standardize_advantages=False)\n agent.load(\"models/ppo\")\n\n for _ in range(MINERL_MAX_EVALUATION_EPISODES):\n obs = wrapped_env.reset()\n done = False\n netr = 0\n items_crafted = False\n while not done:\n action = agent.act(obs)\n obs, reward, done, info = wrapped_env.step(action)\n \n netr += reward\n print(\"Net reward: \", netr)\n\n\n wrapped_env.close()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"test_ppo.py","file_name":"test_ppo.py","file_ext":"py","file_size_in_byte":3447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"524513148","text":"\"\"\"\nhttps://help.aliyun.com/document_detail/32026.html?spm=a2c4g.11186623.2.22.b4c25fff20gPe2\nupdate: 2020/8/1 9:58:08\nauthor: 一只快死的猿\n\"\"\"\nimport re\nimport time\nimport warnings\nfrom multiprocessing import Process, Queue\nfrom bucket.bsetting import ip_pool\nfrom sqlpool.pool import ConnMysql\nfrom bucket.bybucket import Bucket_Obj_Upload\nfrom toolpackage.retry import request\nfrom toolpackage.hash import md5hash, sha1hash\n\n\nwarnings.filterwarnings('ignore')\n\n\nclass Upload_Img():\n def __init__(self):\n self.q = Queue()\n self.limit_cont = 10000000\n self.limit_start = 0\n\n def get_img_2_mysql(self):\n conn = ConnMysql()\n sql = \"select * from albums order by id limit {0},{1};\".format(self.limit_start, self.limit_cont)\n result = conn.sql_select_many(sql)\n for i in result:\n self.q.put(i)\n\n def upload_object(self):\n end_count = 0\n bou = Bucket_Obj_Upload()\n while True:\n if end_count > 10:\n break\n if self.q.empty():\n time.sleep(10)\n end_count += 1\n else:\n end_count = 0\n info = self.q.get()\n img_url_list = re.sub(r\"\\[|\\]|\\'\", \"\", info[\"img_url\"]).split(\",\")\n headers = {\n \"Referer\": info[\"albums_href\"],\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36\"\n }\n if len(img_url_list) > 0:\n temp_list = []\n for img_url in img_url_list:\n response = request(img_url, headers=headers, proxies_list=ip_pool, verify=False)\n if response is None:\n print(info)\n print(\"response is None:\" + img_url)\n continue\n fsize = response.headers.get(\"Content-Length\")\n if fsize is None:\n print(info)\n print(\"fsize is None\" + img_url)\n continue\n fmd5 = md5hash(response.content)\n fsha1 = sha1hash(response.content)\n code_dict = self.handle_finger(fmd5, fsha1, fsize)\n path = code_dict[\"path\"] + \"/\" + str(code_dict[\"id\"])\n if code_dict[\"code\"] == 0:\n try:\n bou.put_object(path, response.content)\n except:\n time.sleep(3)\n bou.put_object(path, response.content)\n temp_list.append(path)\n self.update_albums(str(temp_list), info)\n else:\n print(info)\n\n def handle_finger(self, fmd5, fsha1, fsize, path=\"xqe/images\"):\n conn = ConnMysql()\n ssql = \"\"\"select count(*) from finger where fingermd5=\"%s\" and fingersha1=\"%s\";\"\"\" % (fmd5, fsha1)\n isql = \"\"\"insert into finger (path,fingermd5,fingersha1,filesize) values (\"%s\",\"%s\",\"%s\",%s)\"\"\" % (path, fmd5, fsha1, fsize)\n esql = \"\"\"select id,path from finger where fingermd5=\"%s\" and fingersha1=\"%s\";\"\"\" % (fmd5, fsha1)\n flag = conn.sql_select_one(ssql)\n if flag[\"count(*)\"] == 0:\n conn.sql_change_msg(isql)\n res = conn.sql_select_one(esql)\n return {\"code\": 0, \"id\": res[\"id\"], \"path\": res[\"path\"]}\n else:\n res = conn.sql_select_one(esql)\n return {\"code\": 1, \"id\": res[\"id\"], \"path\": res[\"path\"]}\n\n def update_albums(self, img_url, info):\n conn = ConnMysql()\n sql = \"\"\"insert into user_albums (albums_name,store_id,albums_href,img_url,other_msg) values (\"%s\",\"%s\",\"%s\",\"%s\",\"%s\");\"\"\" % (info[\"albums_name\"], info[\"store_id\"], info[\"albums_href\"], img_url, info[\"other_msg\"])\n conn.sql_change_msg(sql)\n\n def __del__(self):\n conn = ConnMysql()\n conn.release()\n\n def run(self):\n self.get_img_2_mysql()\n process_list = []\n for p in range(10):\n process_list.append(Process(target=self.upload_object))\n for process in process_list:\n process.start()\n for process in process_list:\n process.join()\n print(\"-\"*50 + \"全部数据上传完毕\" + \"-\"*50)\n\n\nif __name__ == '__main__':\n ui = Upload_Img()\n ui.run()\n","sub_path":"存储优化/workspace.py","file_name":"workspace.py","file_ext":"py","file_size_in_byte":4563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"468783907","text":"import cv2\ncap=cv2.VideoCapture(0); #this is a class for capturing the video\nprint(cap.isOpened())\nwhile(cap.isOpened()):\n ret,frame=cap.read()\n print(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) #we can use differents functions such as this.#watch video flags documentation for detail\n print(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n\n gray=cv2.cvtColor(frame, cv2.COLOR_BAYER_BG2GRAY)\n cv2.imshow('frame',gray)\n\n\n if cv2.waitKey(1) & 0xFF==ord('q'):\n break\ncapp.release()\ncv2.destroyAllWindows()\n\n# #\n# 640.0 width and height by default\n# 480.0","sub_path":"capturing video.py","file_name":"capturing video.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"55235133","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Date : 2018-05-24 15:13:31\n# @Author : Your Name (you@example.org)\n# @Link : http://example.org\n# @Version : $Id$\n\nimport os,sys\nimport json\nfrom magetool import timetool\n# import DATATool\nimport makedata \nfrom copy import deepcopy\n\nSTATEDOT = {}\n\ndef initDataStates():\n\n global STATEDOT\n STATECOUNTS = [1,2,3]\n # STATECOUNTS = [4,8,12]\n MAXPRICES = 20\n startDOT = 1\n\n for ps in range(MAXPRICES):\n tmp = STATECOUNTS[-1] + STATECOUNTS[-2]\n STATECOUNTS.append(tmp)\n STATECOUNTS_ = []\n for ps in STATECOUNTS:\n STATECOUNTS_.append(-ps)\n STATECOUNTS_.sort()\n STATECOUNTS = STATECOUNTS_ + STATECOUNTS\n print(STATECOUNTS)\n\n dics = {}\n\n for i in range(STATECOUNTS[0],STATECOUNTS[-1]):\n for n in range(len(STATECOUNTS)):\n d = STATECOUNTS[n]\n if i < -1 and i <= d:\n dics[i] = d\n break\n elif i >= 1 and i <= d:\n dics[i] = STATECOUNTS[n-1]\n break\n elif i >= -1 and i <= 1:\n dics[i] = 0\n break\n STATEDOT = dics\n\ninitDataStates()\n\ndef stateConvent(dotdat):\n return STATEDOT[dotdat]\n\ndef getOneState2(d0,d1):#6.黄金法2\n # [时间戳,开盘价,最高价,最低价,收盘价,成交量,合约类型,字符串时间]\n #(l1-o1),o1,(c1-o1),(h1-o1),(l2-o2),(o2-c1),(c2-o2),(h2-o2),(v2-v1)\n # l1_ o1_ c1_ h1_ l2_ o2_ c2_ h2_ dv_ \n\n o1 = d0[1]\n o2 = d1[1]\n\n l1_ = d0[3] - o1\n o1_ = 0.0\n c1_ = d0[4] - o1\n h1_ = d0[2] - o1\n\n o2_ = o2 - d0[4]\n\n l2_ = d1[3] - o2\n \n c2_ = d1[4] - o2\n h2_ = d1[2] - o2\n\n dv_ = d1[5] - d0[5]\n\n dt_ = d1[0] - d0[0]\n\n \n out = [d0[0],d0[-1],dt_,int(l1_),int(o1_),int(c1_),int(h1_),int(l2_),int(o2_),int(c2_),int(h2_),dv_]\n tmpl1_ = stateConvent(int(l1_))\n tmpo1_ = int(o1_)\n tmpc1_ = stateConvent(int(c1_))\n tmph1_ = stateConvent(int(h1_))\n tmpl2_ = stateConvent(int(l2_))\n tmpo2_ = stateConvent(int(o2_))\n tmpc2_ = stateConvent(int(c2_))\n tmph2_ = stateConvent(int(h2_))\n out = [d0[0],d0[-1],dt_,tmpl1_,tmpo1_,tmpc1_,tmph1_,tmpl2_,tmpo2_,tmpc2_,tmph2_,dv_]\n return out\n\n\ndef getOneState(d0,d1,dataType): #0.全数据,1.整数,2.偶数,3.奇数,4.差价3,5.黄金法1,6.黄金法2\n # [时间戳,开盘价,最高价,最低价,收盘价,成交量,合约类型,字符串时间]\n #(l1-o1),o1,(c1-o1),(h1-o1),(l2-o1),(o2-o1),(c2-o1),(h2-o1),(v2-v1)\n # l1_ o1_ c1_ h1_ l2_ o2_ c2_ h2_ dv_ \n\n o1 = d0[1]\n\n l1_ = d0[3] - o1\n o1_ = 0.0\n c1_ = d0[4] - o1\n h1_ = d0[2] - o1\n\n l2_ = d1[3] - o1\n o2_ = d1[1] - o1\n c2_ = d1[4] - o1\n h2_ = d1[2] - o1\n\n dv_ = d1[5] - d0[5]\n\n dt_ = d1[0] - d0[0]\n\n \n\n if dataType == 0:\n out = [d0[0],d0[-1],dt_,l1_,o1_,c1_,h1_,l2_,o2_,c2_,h2_,dv_] \n #全数据型态\n return out\n elif dataType == 1:\n #整数型态\n out = [d0[0],d0[-1],dt_,int(l1_),int(o1_),int(c1_),int(h1_),int(l2_),int(o2_),int(c2_),int(h2_),dv_]\n return out\n #偶数型态\n elif dataType == 2:\n out = [d0[0],d0[-1],dt_,int(l1_),int(o1_),int(c1_),int(h1_),int(l2_),int(o2_),int(c2_),int(h2_),dv_]\n outother = []\n for n in range(len(out)):\n if n > 2 and n < len(out) -1:\n tmpi = abs(int(out[n]))\n if tmpi % 2 == 0:\n outother.append(out[n])\n elif out[n] > 0:\n outother.append(out[n] - 1)\n elif out[n] < 0:\n outother.append(out[n] + 1)\n else:\n outother.append(out[n])\n else:\n outother.append(out[n])\n return outother\n elif dataType == 3: #奇数型\n out = [d0[0],d0[-1],dt_,int(l1_),int(o1_),int(c1_),int(h1_),int(l2_),int(o2_),int(c2_),int(h2_),dv_]\n outother = []\n for n in range(len(out)):\n if n > 2 and n < len(out) -1:\n tmpi = abs(int(out[n]))\n if tmpi % 2 == 0:\n if out[n] == 0:\n outother.append(out[n])\n elif out[n] > 0:\n outother.append(out[n] - 1)\n else:\n outother.append(out[n] + 1)\n else:\n outother.append(out[n])\n else:\n outother.append(out[n])\n return outother\n elif dataType == 4: #差价3\n out = [d0[0],d0[-1],dt_,int(l1_),int(o1_),int(c1_),int(h1_),int(l2_),int(o2_),int(c2_),int(h2_),dv_]\n outother = []\n for n in range(len(out)):\n if n > 2 and n < len(out) -1:\n tmpi = int(out[n])\n if abs(tmpi) % 3 == 0:\n outother.append(out[n])\n elif abs(tmpi) % 3 == 1:\n if out[n] > 0:\n outother.append(out[n] - 1)\n elif out[n] < 0:\n outother.append(out[n] + 1)\n else:\n outother.append(out[n])\n elif abs(tmpi) % 3 == 2:\n if out[n] > 0:\n outother.append(out[n] - 2)\n elif out[n] < 0:\n outother.append(out[n] + 2)\n else:\n outother.append(out[n])\n else:\n outother.append(out[n])\n return outother\n elif dataType == 5: #黄金分割间距法\n out = [d0[0],d0[-1],dt_,int(l1_),int(o1_),int(c1_),int(h1_),int(l2_),int(o2_),int(c2_),int(h2_),dv_]\n tmpl1_ = stateConvent(int(l1_))\n tmpo1_ = int(o1_)\n tmpc1_ = stateConvent(int(c1_))\n tmph1_ = stateConvent(int(h1_))\n tmpl2_ = stateConvent(int(l2_))\n tmpo2_ = stateConvent(int(o2_))\n tmpc2_ = stateConvent(int(c2_))\n tmph2_ = stateConvent(int(h2_))\n out = [d0[0],d0[-1],dt_,tmpl1_,tmpo1_,tmpc1_,tmph1_,tmpl2_,tmpo2_,tmpc2_,tmph2_,dv_]\n return out\n elif dataType == 6: #黄金分割间距法\n return getOneState2(d0, d1)\n\n\n# def getAllDataMTCLStateList(dataType):\n# dtool = DATATool.createDataTool()\n# ds = dtool.getALLData()\n# print(len(ds))\n# # ds = ds[:100]\n# outstates = []\n# d0 = None\n# for d in ds:\n# if not d0:\n# d0 = d\n# else:\n# tmp = getOneState(d0, d,dataType)\n# outstates.append(tmp)\n# d0 = d\n# return outstates,ds\n\ndef getAllDataMTCLStateList(dataType,minType = 1):\n maketool = makedata.DataMakeTool()\n ds = maketool.conventInitData(minType)\n print(len(ds))\n # ds = ds[:100]\n outstates = []\n d0 = None\n for d in ds:\n if not d0:\n d0 = d\n else:\n tmp = getOneState(d0, d,dataType)\n outstates.append(tmp)\n d0 = d\n return outstates,ds\n\nimport TreeObj\nimport socket\n\nconfigP = {}\nconfigP['dataType'] = 6 #数据分层类型,0.全数据,1.整数,2.偶数,3.奇数,4.差价3,5.黄金法1,6.黄金法2\nconfigP['priceYuZhi'] = 0.5 #价格方向触发阈值\nconfigP['countYuZhi'] = 1 #统计触发交易的统计数量阈值\nconfigP['closeYuZhi'] = 70 #趋势反转时的反向几率百分比差值,平仓阈值\nconfigP['openPencent'] = 66.5 #单方向的开仓触发几率百分比\nconfigP['beishuMin'] = 4 #在某个方向达到最小触发几率,并且当前几率是另一个方向的触发开仓倍数\nconfigP['openPencentMin'] = 60 #趋势方向达到相反方向的指定倍数时,触发开仓几率百分比\nconfigP['openPencent0'] = 70.5 #另一方向趋势为0时,本方向开仓触发几率百分比\n\n\nconfigP['closeCount'] = 6 #平仓统计数量要求\n\n\nclass MTCLTree(object):\n \"\"\"docstring for MTCLTree\"\"\"\n def __init__(self,maketool,initmintype = 1):\n super(MTCLTree, self).__init__()\n \n self.maketool = maketool\n\n self.dataType = configP['dataType']\n self.yuzhi = configP['priceYuZhi'] \n self.countYuZhi = configP['countYuZhi']\n self.closeYuZhi = configP['closeYuZhi']\n self.openPencent = configP['openPencent']\n self.openPencentMin = configP['openPencentMin']\n self.beishuMin = configP['beishuMin']\n self.openPencent0 = configP['openPencent0']\n self.closeCountP = configP['closeCount']\n\n self.ds = None\n self.stateDates = []\n \n self.mintype = initmintype\n\n self.addDats = []\n\n self.initAllDataMTCLStateList()\n\n self.intStateDic = {} #数据状态ID字典\n self.stateDic = {}\n self.intStateDatas = []\n\n self.index = 0\n self.lastList = None\n\n self.lasttime = None\n\n self.initStateDic()\n\n self.stateCount = 0\n\n\n self.MTCLTree = TreeObj.TreeObj('root', 0,0)\n\n self.initMTCLTree()\n\n # self.mtclTreeMindict = {}\n # for i in range(self.mintype):\n # self.mtclTreeMindict[i] = deepcopy(self.MTCLTree)\n\n self.tradeClient = None\n self.host = None\n self.port = None\n self.tradeStates = {}\n self.lastOp = 'cs'\n self.lastTradeList = {}\n self.isListChanges = {}\n \n def initAllDataMTCLStateList(self):\n ds = self.maketool.conventInitData(self.mintype)\n print(len(ds))\n # ds = ds[:100]\n outstates = []\n d0 = None\n for d in ds:\n if not d0:\n d0 = d\n else:\n tmp = getOneState(d0, d,self.dataType)\n outstates.append(tmp)\n d0 = d\n\n self.ds = ds\n self.stateDates = outstates\n\n def initTradeSocketClient(self,host,port = 9102):\n try:\n self.host = host\n self.port = port\n print('connecting:',host,port)\n self.tradeClient = socket.socket() # instantiate\n self.tradeClient.connect((self.host, self.port)) # connect to the server\n print('connected!')\n return True\n except Exception as e:\n print('connect erro...')\n return False\n \n def sendTrade2(self):\n #下单接口\n #{'type':'os','amount':0,'postOnly':1}\n #{'type':'test','test':1}\n #{'type':'set','amount':100}\n if self.tradeStates and len(self.addDats) == 0:\n states = list(self.tradeStates.keys())\n states.sort()\n\n counts = []\n uppercents = []\n downpercents = []\n unchanges = []\n s = []\n # self.lastTime = ''\n tradedict = {}\n\n for k in states:\n #{'count':count,'up':uppercent,'down':downpercent,'unchange':unchangePercent,'lastTime':d0[-1]}\n tradedict[k] = self.tradeStates[k]\n if self.tradeStates[k]['count'] > 0:\n counts.append(int(self.tradeStates[k]['count']))\n uppercents.append(float(self.tradeStates[k]['up']))\n downpercents.append(float(self.tradeStates[k]['down']))\n unchanges.append(float(self.tradeStates[k]['unchange']))\n s.append(k)\n # self.lastTime = self.tradeStates[k]['lastTime']\n \n for n in range(len(counts)):\n up = uppercents[n]\n down = downpercents[n]\n unchange = unchanges[n]\n count = counts[n]\n st = s[n]\n\n outdict = {} \n outdict['amount'] = 0\n outdict['postOnly'] = 1\n outdict['data'] = tradedict\n outdict['type'] = 'save'\n outdict['con'] = 'none'\n\n needcount = 3\n lcount = needcount - 1\n if any(self.isListChanges.values()) and len(counts) >= needcount:\n \n # self.yuzhi = configP['priceYuZhi'] \n # self.countYuZhi = configP['countYuZhi']\n # self.closeYuZhi = configP['closeYuZhi']\n # self.openPencent = configP['openPencent']\n # self.openPencentMin = configP['openPencentMin']\n # self.openPencent0 = configP['openPencent0']\n if self.lastOp == 'cs' or self.lastOp == 'cl':\n if counts[lcount] > self.countYuZhi and uppercents[lcount] > self.openPencent:\n outdict['type'] = 'ol'\n outdict['con'] = 'ol1'\n self.lastOp = 'ol'\n elif counts[lcount] > self.countYuZhi and uppercents[lcount] > self.openPencentMin and downpercents[lcount] > 0 and uppercents[lcount]/downpercents[lcount] >= self.beishuMin:\n outdict['type'] = 'ol'\n outdict['con'] = 'ol2'\n self.lastOp = 'ol'\n elif counts[lcount] > self.countYuZhi and uppercents[lcount] > self.openPencent0 and downpercents[lcount] == 0:\n outdict['type'] = 'ol'\n outdict['con'] = 'ol3'\n self.lastOp = 'ol'\n elif counts[lcount] > self.countYuZhi and downpercents[lcount] > self.openPencent:\n outdict['type'] = 'os'\n outdict['con'] = 'os1'\n self.lastOp = 'os'\n elif counts[lcount] > self.countYuZhi and downpercents[lcount] > self.openPencentMin and uppercents[lcount] > 0 and downpercents[lcount]/uppercents[lcount] >= self.beishuMin:\n outdict['type'] = 'os'\n outdict['con'] = 'os2'\n self.lastOp = 'os'\n elif counts[lcount] > self.countYuZhi and downpercents[lcount] > self.openPencent0 and uppercents[lcount] == 0:\n outdict['type'] = 'os'\n outdict['con'] = 'os3'\n self.lastOp = 'os'\n elif self.lastOp == 'ol':\n # if downpercents[0] - uppercents[0] > 2 and downpercents[1] - uppercents[1] > 4:\n if True:\n if counts[lcount] > self.countYuZhi and downpercents[lcount] > self.openPencent:#201806300912新加\n #if counts[lcount] > self.countYuZhi and downpercents[lcount] > self.openPencent and (downpercents[0] > uppercents[0] or downpercents[1] > uppercents[1]):#201806300912新加\n outdict['type'] = 'clos'\n outdict['con'] = 'clos1'\n self.lastOp = 'os'\n elif counts[lcount] > self.countYuZhi and downpercents[0] > uppercents[0] and downpercents[lcount] > self.openPencentMin and uppercents[lcount] > 0 and downpercents[lcount]/uppercents[lcount] >= self.beishuMin:#201806300112注释掉的\n # elif counts[lcount] > self.countYuZhi and (downpercents[0] > uppercents[0] or downpercents[1] > uppercents[1]) and downpercents[lcount] > self.openPencentMin and uppercents[lcount] > 0 and downpercents[lcount]/uppercents[lcount] >= self.beishuMin:#201806300112新加\n #elif counts[lcount] > self.countYuZhi and (downpercents[0] > uppercents[0] and downpercents[1] > uppercents[1]) and downpercents[lcount] > self.openPencentMin and uppercents[lcount] > 0 and downpercents[lcount]/uppercents[lcount] >= self.beishuMin:#201806300912新加\n outdict['type'] = 'clos'\n outdict['con'] = 'clos2'\n self.lastOp = 'os'\n elif counts[lcount] > self.countYuZhi and downpercents[lcount] > self.openPencent0 and uppercents[lcount] == 0 and downpercents[0] >= downpercents[1] :#201806300112注释掉的\n # elif counts[lcount] > self.countYuZhi and downpercents[lcount] > self.openPencent0 and uppercents[lcount] == 0 and (downpercents[0] >= uppercents[0] or downpercents[1] >= uppercents[1]):#201806300112新加\n outdict['type'] = 'clos'\n outdict['con'] = 'clos3'\n self.lastOp = 'os'\n elif counts[1] > self.countYuZhi and downpercents[1] >= downpercents[0] and downpercents[1] > self.openPencent0 and counts[0] > 60 and downpercents[0] > self.openPencent0:\n outdict['type'] = 'clos'\n outdict['con'] = 'clos4'\n self.lastOp = 'os'\n elif counts[lcount] > self.countYuZhi and downpercents[0] > 30 and uppercents[0] == 0 and downpercents[1] > 30 and uppercents[1] == 0 and downpercents[lcount] > 30 and uppercents[lcount] == 0:\n outdict['type'] = 'clos'\n outdict['con'] = 'clos5'\n self.lastOp = 'os'\n elif counts[lcount] > self.closeCountP and downpercents[lcount] - uppercents[lcount] > self.closeYuZhi:\n outdict['type'] = 'cl'\n outdict['con'] = 'cl1'\n self.lastOp = 'cl'\n elif self.lastOp == 'os':\n # if uppercents[0] - downpercents[0] > 2 and uppercents[1] - downpercents[1] > 4:\n if True:\n if counts[lcount] > self.countYuZhi and uppercents[lcount] > self.openPencent:#201806300912新加\n #if counts[lcount] > self.countYuZhi and uppercents[lcount] > self.openPencent and (uppercents[0] > downpercents[0] or uppercents[1] > downpercents[1]):#201806300912新加\n outdict['type'] = 'csol'\n outdict['con'] = 'csol1'\n self.lastOp = 'ol'\n elif counts[lcount] > self.countYuZhi and uppercents[0] > downpercents[0] and uppercents[lcount] > self.openPencentMin and downpercents[lcount] > 0 and uppercents[lcount]/downpercents[lcount] >= self.beishuMin:#201806300112注释掉的\n # elif counts[lcount] > self.countYuZhi and (uppercents[0] > downpercents[0] or uppercents[1] > downpercents[1]) and uppercents[lcount] > self.openPencentMin and downpercents[lcount] > 0 and uppercents[lcount]/downpercents[lcount] >= self.beishuMin:#201806300112新加\n #elif counts[lcount] > self.countYuZhi and (uppercents[0] > downpercents[0] and uppercents[1] > downpercents[1]) and uppercents[lcount] > self.openPencentMin and downpercents[lcount] > 0 and uppercents[lcount]/downpercents[lcount] >= self.beishuMin:#201806300912新加\n outdict['type'] = 'csol'\n outdict['con'] = 'csol2'\n self.lastOp = 'ol'\n elif counts[lcount] > self.countYuZhi and uppercents[lcount] > self.openPencent0 and downpercents[lcount] == 0 and uppercents[0] >= uppercents[1]: #201806300112注释掉的\n #elif counts[lcount] > self.countYuZhi and uppercents[lcount] > self.openPencent0 and downpercents[lcount] == 0 and (uppercents[0] >= downpercents[0] or uppercents[1] >= downpercents[1]): #201806300112新加\n outdict['type'] = 'csol'\n outdict['con'] = 'csol3'\n self.lastOp = 'ol'\n elif counts[1] > self.countYuZhi and uppercents[1] >= uppercents[0] and uppercents[1] > self.openPencent0 and counts[0] > 60 and uppercents[0] > self.openPencent0:\n outdict['type'] = 'csol'\n outdict['con'] = 'csol4'\n self.lastOp = 'ol'\n elif counts[lcount] > self.countYuZhi and uppercents[0] > 30 and downpercents[0] == 0 and uppercents[1] > 30 and downpercents[1] == 0 and uppercents[lcount] > 30 and downpercents[lcount] == 0:\n outdict['type'] = 'csol'\n outdict['con'] = 'csol5'\n self.lastOp = 'ol'\n elif counts[lcount] > self.closeCountP and uppercents[lcount] - downpercents[lcount] > self.closeYuZhi:\n outdict['type'] = 'cs'\n outdict['con'] = 'cs1'\n self.lastOp = 'cs'\n \n else: \n print('出现未知状态...')\n if outdict['type'] == 'save':\n print('未达到下单阈值,不进行操作,只保存状态')\n print(s[lcount],counts[lcount],uppercents[lcount],downpercents[lcount],needcount)\n else:\n print('进行下单操作:')\n print(outdict['type'])\n\n elif any(self.isListChanges.values()) and len(counts) == 2:\n if self.lastOp == 'ol':\n if counts[1] > self.countYuZhi and downpercents[1] >= downpercents[0] and downpercents[1] > 90.5 and counts[0] > 45 and downpercents[0] > 48 and downpercents[0]/(uppercents[0]+0.001) > 2.0:\n outdict['type'] = 'clos'\n outdict['con'] = 'clos21'\n self.lastOp = 'os'\n elif counts[1] > self.countYuZhi and downpercents[1] >= downpercents[0] and downpercents[1] > 90.5 and downpercents[0] > 90.5:\n outdict['type'] = 'clos'\n outdict['con'] = 'clos22'\n self.lastOp = 'os'\n elif counts[1] > self.countYuZhi and counts[0] > 2 and downpercents[0] > 65 and downpercents[1] >30 and uppercents[1] < 1:\n outdict['type'] = 'clos'\n outdict['con'] = 'clos23'\n self.lastOp = 'os'\n elif self.lastOp == 'os':\n if counts[1] > self.countYuZhi and uppercents[1] >= uppercents[0] and uppercents[1] > 90.5 and counts[0] > 45 and uppercents[0] > 48 and uppercents[0]/(downpercents[0]+0.001) > 2.0:\n outdict['type'] = 'csol'\n outdict['con'] = 'csol21'\n self.lastOp = 'ol'\n elif counts[1] > self.countYuZhi and uppercents[1] >= uppercents[0] and uppercents[1] > 90.5 and uppercents[0] > 90.5:\n outdict['type'] = 'csol'\n outdict['con'] = 'csol22'\n self.lastOp = 'ol'\n elif counts[1] > self.countYuZhi and counts[0] > 2 and uppercents[0] > 65 and uppercents[1] >30 and downpercents[1] < 1:\n outdict['type'] = 'csol'\n outdict['con'] = 'csol23'\n self.lastOp = 'ol'\n # elif any(self.isListChanges.values()) and len(counts) == 1:\n # if self.lastOp == 'ol':\n # if counts[0] > 11 and downpercents[0] > 90.5:\n # outdict['type'] = 'clos'\n # self.lastOp = 'os'\n # elif self.lastOp == 'os':\n # if counts[0] > 11 and uppercents[0] > 90.5:\n # outdict['type'] = 'csol'\n # self.lastOp = 'ol'\n else:\n print('横盘,价格趋势未改变,只保存数据,不下单')\n outdict['price'] = self.ds[-1][4]\n jstr = json.dumps(outdict)\n if self.tradeClient:\n self.tradeClient.send(jstr)\n else:\n print('下单工具网络链接错误,尝试重新连接后发送数据')\n if self.initTradeSocketClient(self.host,self.port):\n self.tradeClient.send(jstr)\n\n def addNewData(self,ind):\n self.addDats.append(ind)\n if len(self.addDats) < self.mintype:\n print('add data count:%d'%(len(self.addDats)))\n elif len(self.addDats) == self.mintype:\n dstmp = makedata.summinData(self.addDats)\n self.ds.append(dstmp)\n self.addDats = []\n d = self.ds[-1]\n print(d)\n print(self.ds[-2])\n tmp = getOneState(self.ds[-2], d,self.dataType)\n datstate = self.getDataState(tmp)\n # sid = 0\n # if datstate != '0':\n if datstate in self.intStateDic:\n sid = self.intStateDic[datstate]\n else:\n self.index += 1\n sid = self.index\n self.intStateDic[datstate] = sid\n self.stateDic[sid] = d\n\n self.MTCLTree.addChildState(sid)\n self.lastList = self.MTCLTree.stateList\n self.lasttime = d[-1]\n else:\n print('addNewData erro...')\n\n def addNewKlinesDatas(self,datas):\n for d in datas:\n self.addNewData(d)\n self.tradeStates = {}\n print('add end ds list:--------------------')\n if self.ds and len(self.ds) > 5:\n for d in self.ds[-5:]:\n print(d)\n print('add end ds list --------------------')\n\n def getDataState(self,data):\n if data == 'root':\n return data\n # [d0[0],d0[-1],dt_,l1_,o1_,c1_,h1_,l2_,o2_,c2_,h2_,dv_] \n tmplist = [data[4],data[5],data[8],data[9]] #只取两个开盘价和收盘价\n # tmplist = [data[3],data[4],data[5],data[6],data[7],data[8],data[9],data[10]] #取两个的最高价,最低价,开盘价,收盘价\n outstr = ''\n for d in tmplist:\n outstr += str(d)\n return outstr\n\n def initStateDic(self):\n index = 0\n self.intStateDic['root'] = 0\n for d in self.stateDates:\n tmp = self.getDataState(d)\n if tmp in self.intStateDic:\n continue\n else:\n index += 1\n self.intStateDic[tmp] = index\n self.stateDic[index] = d\n self.index = index\n for d in self.stateDates:\n tmp = self.getDataState(d)\n self.intStateDatas.append(self.intStateDic[tmp])\n\n\n def initMTCLTree(self):\n #计划,取1140分钟(24小时)蒙特卡罗树深度测试\n count = 0\n for d in self.intStateDatas:\n count += 1\n self.MTCLTree.addChildState(d)\n if count%10000 == 0:\n print(count)\n self.lastList = self.MTCLTree.stateList\n\n def getStates(self):\n stypes = {}\n for s in self.stateDates:\n jstr = self.getDataState(s)\n if jstr in stypes:\n stypes[jstr] += 1\n else:\n stypes[jstr] = 1\n return stypes\n def getStateWithSID(self,sid):\n return self.stateDic[sid]\n def getDataCount(self):\n return len(self.stateDates)\n\n def getDeepCount(self,deep = 7):\n out = self.MTCLTree.getChildLeafForDeep(deep)\n # for c5 in out:\n olist = []\n for o in out:\n olist.append([o.stateCount,o.childLayer,o.baseState,o])\n # print(o[0].stateCount,o[0].childLayer,o[0].baseState)\n return olist\n\n def getChildTreeWithDataList(self,pDatList):\n mtclchildTree = self.MTCLTree.getStateListChildTree(pDatList)\n return mtclchildTree\n\n # def getLastListState(self):\n # return self.lastList\n\n #获取下一次1分钟k线趋势状态机率\n def getStateDeepWithCountLimit(self,countlimit = 0):\n deep5s = self.getDeepCount()\n deep5s = sorted(deep5s, key=lambda x:x[0],reverse = True)\n countdeep = []\n for n in range(len(deep5s)):\n count = deep5s[n][0]\n if count > countlimit:\n dat = self.getStateWithSID(deep5s[n][2])\n sid = deep5s[n][2]\n sidlist = deep5s[n][3].oid.split('_')[1:]\n countdeep.append([count,sid,dat,sidlist])\n return countdeep\n\n def isAinB(self,A,B):\n # a = any([A==B[i:i+len(A)] for i in range(0,len(B)-len(A)+1)])\n X = [A==B[i:i+len(A)] for i in range(0,len(B)-len(A)+1)]\n return any(X)\n\n def getNextObj(self,A,B):\n X = [A==B[i:i+len(A)] for i in range(0,len(B)-len(A)+1)]\n count = 0\n for d in X:\n if d:\n break\n else:\n count += 1\n pnext = count + len(A)\n if pnext < len(B):\n return B[pnext]\n else:\n return -1\n\n\n def getNextStates(self,states):\n tmplist = self.lastList[-states:]\n tmpliststr = []\n for t in tmplist:\n tmpliststr.append(str(t))\n tmplist = tmpliststr\n countdeep = self.getStateDeepWithCountLimit()\n # tmpliststr = '_'.join(tmplist)\n outs = []\n print(tmplist)\n if states in self.lastTradeList and self.lastTradeList[states] == tmplist:\n self.isListChanges[states] = False\n else:\n self.lastTradeList[states] = tmplist\n self.isListChanges[states] = True\n \n print(len(countdeep))\n for c in countdeep:\n tps = c[3]\n if self.isAinB(tmplist,tps):\n nextobj = self.getNextObj(tmplist,tps)\n if nextobj != -1:\n tmp = c + [nextobj]\n outs.append(tmp)\n return outs\n #获取下一个k线趋势机率\n def getNextPercent(self,datas):\n datadic = {}\n count = 0\n for d in datas:\n if d[-1] in datadic:\n datadic[d[-1]] += d[0]\n else:\n datadic[d[-1]] = d[0]\n count += d[0]\n\n outdic = {}\n for k in datadic.keys():\n tmp = (datadic[k]*100)/float(count)\n outdic[k] = tmp\n return outdic,count\n\n def cleanYuCeStates(self):\n self.tradeStates = {}\n def yuceState(self,states):\n if not self.ds or len(self.ds) < self.mintype * 8:\n print('数据量不够,还要再等数据')\n return ''\n outstr = ''\n d0 = self.ds[-1]\n datatype = self.dataType\n print('*'*10,'statecount=',states,'*'*10)\n outstr += '*'*10 + 'statecount= ' + str(states) + '*'*10 + '\\n'\n\n nextstate = self.getNextStates(states) #预测深度\n print('nextState count:',len(nextstate))\n outstr += 'nextState count:' + str(len(nextstate)) + '\\n'\n\n outdic,count = self.getNextPercent(nextstate)\n uppercent = 0.0\n downpercent = 0.0\n unchangePercent = 0.0\n for k in outdic.keys():\n dat = self.getStateWithSID(int(k))\n if dat[9] - dat[4] > self.yuzhi:\n uppercent += outdic[k]\n elif dat[9] - dat[4] < -self.yuzhi:\n downpercent += outdic[k]\n else:\n unchangePercent += outdic[k]\n print(k,outdic[k],dat[2:])\n outstr += str(k) + ' ' + str(outdic[k]) + ' ' + str(dat[2:]) + '\\n'\n print('-'*10)\n for s in self.lastList:\n dat = self.getStateWithSID(int(s))\n print(s,dat)\n outstr += str(s) + ',' + str(dat) + '\\n'\n print('-'*10)\n outstr += '-'*10 + '\\n'\n d0x = 0\n outtmp = []\n tmpdsx = []\n if len(self.ds) < 201:\n tmpdsx = self.ds\n else:\n tmpdsx = self.ds[-200:]\n for d in tmpdsx:\n if d0x == 0:\n d0x = d\n else:\n tmp = getOneState(d0x, d, datatype)\n # if not (tmp[4] == 0 and tmp[5] == 0 and tmp[8] == 0 and tmp[9] == 0): \n # outtmp.append([d,tmp])\n outtmp.append([d,tmp])\n d0x = d\n outtmp = outtmp[::-1]\n c = 0\n for d in outtmp:\n c += 1\n outstr += str(d[0]) + '-'*6 + str(d[1]) + '\\n'\n print(d[0])\n print(d[1])\n if c > states:\n break\n outstr += str(states) + str(count) + ',up=%.2f,down=%.2f,unchange=%.2f,lastTime:%s\\n'%(uppercent,downpercent,unchangePercent,d0[-1]) \n print('*'*50)\n print(states,count,'up=%.2f'%(uppercent),'down=%.2f'%(downpercent),'unchange=%.2f'%(unchangePercent),d0[-1])\n print('*'*50)\n print('last time:',d0[-1])\n self.tradeStates[states] = {'count':count,'up':'%.3f'%(uppercent),'down':'%.3f'%(downpercent),'unchange':'%.3f'%(unchangePercent),'lastTime':d0[-1]}\n return outstr\n\ndef main():\n maketool = makedata.DataMakeTool()\n mtcltool = MTCLTree(maketool)\n\n mtcltool.yuceState(5)\n mtcltool.yuceState(4)\n mtcltool.yuceState(3)\n\n\n\n#测试\nif __name__ == '__main__':\n main()\n \n","sub_path":"pyscripte/MTCLTool.py","file_name":"MTCLTool.py","file_ext":"py","file_size_in_byte":33002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"560327434","text":"def fibonacci(num):\n num1 = 0\n num2 = 1\n series = 0\n for i in range(num):\n print(series);\n num1 = num2;\n num2 = series;\n series = num1 + num2;\n \n \n# running function after taking user input\nnum = int(input('Enter how many numbers needed in Fibonacci series : '))\nfibonacci(num)","sub_path":"python_fibonacci.py","file_name":"python_fibonacci.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"302426258","text":"#coding:utf-8\n#mnist_test.py\nimport time \nimport tensorflow as tf\nfrom tensorflow.tutorials.mnist import input_data\n\nimport mnist_forward\nimport mnist_backward\n\nTEST_INTERVAL_SECS=5 #定义程序循环时间是5秒\n\ndef test(mnist):\n\twith tf.Graph().as_default() as g: #复现计算图\n\t\tx=tf.placeholder(tf.float32,[None,mnist_forward.INPUT_NODE]) #给输入x,y_占位\n\t\ty_=tf.placeholder(tf.float32,[None,mnist_forward.OUTPUT_NODE])\n\t\ty=mnist_forward.forward(x,None) #前向传播过程计算y的值\n\n\t\t#实例化带滑动平均的saver对象\n\t\tema=tf.train.ExponentialMovingAverage(mnist_backward.MOVING_AVERAGE_DECAY)\n\t\tema_restore=ema.variables_to_restore()\n\t\tsaver=tf.train.Saver(ema_restore) #此时所有的对象在会话中被加载��会赋值为各自的滑动平均值\n\n\t\tcorrect_prediction=tf.equal(tf.argmax(y,1)) #判断是否相等返回True/False\n\t\taccuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) #计算准确率\n\n\t\twhile True:\n\t\t\twith tf.Session() as sess:\n\t\t\t\tckpt=tf.train.get_checkpoint_state(mnist_backward.MODEL_SAVE_PATH)#把滑动平均值赋值给各个参数\n\t\t\t\t#先判断是否已经有模型\n\t\t\t\tif ckpt and ckpt.model_checkpoint_path:\n\t\t\t\t\tsaver.restore(sess.ckpt.model_checkpoint_path) #如果有就恢复模型到当前会话\n\t\t\t\t\tglobal_step=ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1] #恢复global_step值\n\t\t\t\t\taccuracy_score=sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels}) #执行准确率计算\n\t\t\t\t\tprint('After %d training steps,test accuracy=%g'%(global_step,accuracy_score))\n\t\t\t\telse:\n\t\t\t\t\tprint('No checkpoint file found')\n\t\t\t\t\treturn\n\t\t\t\ttime.sleep(TEST_INTERVAL_SECS)\n\ndef main():\n\tmnist.input_data.read_data_sets('./data',one_hot=True)\n\ttest(mnist)\n\nif __name__ == '__main__':\n\tmain()\n\n\n\n\n\n\n\n\n\n","sub_path":"机器学习/tensorflow教程系列/mnist_test.py","file_name":"mnist_test.py","file_ext":"py","file_size_in_byte":1794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"79055919","text":"import os\nimport shutil\n\nfrom argparse import Namespace, ArgumentParser\nfrom typing import List, Tuple, Dict, Any\nfrom blspy import ExtendedPrivateKey, PrivateKey\nfrom src.util.keychain import Keychain\n\nfrom src.types.BLSSignature import BLSPublicKey\nfrom src.consensus.coinbase import create_puzzlehash_for_pk\nfrom src.util.config import unflatten_properties\nfrom pathlib import Path\n\nfrom src.util.config import (\n config_path_for_filename,\n create_default_chia_config,\n load_config,\n save_config,\n initial_config_file,\n)\nfrom src.util.path import mkdir, make_path_relative, path_from_root\nimport yaml\n\nfrom src.ssl.create_ssl import generate_selfsigned_cert\n\n\ndef make_parser(parser: ArgumentParser):\n parser.set_defaults(function=init)\n\n\ndef dict_add_new_default(\n updated: Dict, default: Dict, do_not_migrate_keys: Dict[str, Any]\n):\n for k, v in default.items():\n if isinstance(v, dict) and k in updated:\n # If there is an intermediate key with empty string value, do not migrate all decendants\n if do_not_migrate_keys.get(k, None) == \"\":\n do_not_migrate_keys[k] = v\n dict_add_new_default(updated[k], default[k], do_not_migrate_keys.get(k, {}))\n elif k not in updated or k in do_not_migrate_keys:\n updated[k] = v\n\n\ndef check_keys(new_root):\n keychain: Keychain = Keychain()\n all_pubkeys = keychain.get_all_public_keys()\n if len(all_pubkeys) == 0:\n print(\n \"No keys are present in the keychain. Generate them with 'chia keys generate'\"\n )\n return\n all_targets = [\n create_puzzlehash_for_pk(\n BLSPublicKey(bytes(epk.public_child(0).get_public_key()))\n ).hex()\n for epk in all_pubkeys\n ]\n\n config: Dict = load_config(new_root, \"config.yaml\")\n # Set the destinations\n if (\n \"xch_target_puzzle_hash\" not in config[\"farmer\"]\n or config[\"farmer\"][\"xch_target_puzzle_hash\"] not in all_targets\n ):\n print(\n f\"Setting the xch destination address for coinbase fees reward to {all_targets[0]}\"\n )\n config[\"farmer\"][\"xch_target_puzzle_hash\"] = all_targets[0]\n\n if \"pool\" in config:\n if (\n \"xch_target_puzzle_hash\" not in config[\"pool\"]\n or config[\"pool\"][\"xch_target_puzzle_hash\"] not in all_targets\n ):\n print(\n f\"Setting the xch destination address for coinbase reward to {all_targets[0]}\"\n )\n config[\"pool\"][\"xch_target_puzzle_hash\"] = all_targets[0]\n\n # Set the pool pks in the farmer\n all_pubkeys_hex = set([bytes(pk.get_public_key()).hex() for pk in all_pubkeys])\n if \"pool_public_keys\" in config[\"farmer\"]:\n for pk_hex in config[\"farmer\"][\"pool_public_keys\"]:\n # Add original ones in config\n all_pubkeys_hex.add(pk_hex)\n\n config[\"farmer\"][\"pool_public_keys\"] = all_pubkeys_hex\n save_config(new_root, \"config.yaml\", config)\n\n\ndef migrate_to_keychain(old_root, new_root):\n # Transfer the keys from the old root config folder into the keychain.\n # Also set the right public keys in the config files for farming.\n\n print(\"\\nMigrating keys.yaml to keychain\")\n keychain: Keychain = Keychain()\n\n # Migrate wallet sk\n try:\n keys_config = load_config(old_root, \"keys.yaml\", exit_on_error=False)\n wallet_key_bytes = bytes.fromhex(keys_config[\"wallet_sk\"])\n wallet_sk = ExtendedPrivateKey.from_bytes(wallet_key_bytes)\n keychain.add_private_key(wallet_sk)\n\n # Migrate pool sks\n pool_sks_bytes = [bytes.fromhex(h) for h in keys_config[\"pool_sks\"]]\n for k_bytes in pool_sks_bytes:\n keychain.add_private_key_not_extended(PrivateKey.from_bytes(k_bytes))\n except ValueError:\n print(\"No keys.yaml to migrate from.\")\n\n check_keys(new_root)\n\n\ndef migrate_from(\n old_root: Path,\n new_root: Path,\n manifest: List[str],\n do_not_migrate_settings: List[str],\n):\n \"\"\"\n Copy all the files in \"manifest\" to the new config directory.\n \"\"\"\n if old_root == new_root:\n print(\"same as new path, exiting\")\n return 1\n if not old_root.is_dir():\n print(f\"{old_root} not found - this is ok if you did not install this version.\")\n return 0\n print(f\"\\n{old_root} found\")\n print(f\"Copying files from {old_root} to {new_root}\\n\")\n not_found = []\n for f in manifest:\n old_path = old_root / f\n new_path = new_root / f\n if old_path.is_file():\n print(f\"{new_path}\")\n mkdir(new_path.parent)\n shutil.copy(old_path, new_path)\n else:\n not_found.append(f)\n print(f\"{old_path} not found, skipping\")\n # update config yaml with new keys\n config: Dict = load_config(new_root, \"config.yaml\")\n config_str: str = initial_config_file(\"config.yaml\")\n default_config: Dict = yaml.safe_load(config_str)\n flattened_keys = unflatten_properties({k: \"\" for k in do_not_migrate_settings})\n dict_add_new_default(config, default_config, flattened_keys)\n\n save_config(new_root, \"config.yaml\", config)\n\n # migrate plots\n # for now, we simply leave them where they are\n # and make what may have been relative paths absolute\n if \"config/trusted.key\" in not_found or \"config/trusted.key\" in not_found:\n initialize_ssl(new_root)\n\n plots_config: Dict = load_config(new_root, \"plots.yaml\")\n\n plot_root = (\n load_config(new_root, \"config.yaml\").get(\"harvester\", {}).get(\"plot_root\", \".\")\n )\n\n old_plots_root: Path = path_from_root(old_root, plot_root)\n new_plots_root: Path = path_from_root(new_root, plot_root)\n\n old_plot_paths = plots_config.get(\"plots\", {})\n if len(old_plot_paths) == 0:\n print(\"no plots found, no plots migrated\")\n return 1\n\n print(\"\\nmigrating plots.yaml\")\n\n new_plot_paths: Dict = {}\n for path, values in old_plot_paths.items():\n old_path_full = path_from_root(old_plots_root, path)\n new_path_relative = make_path_relative(old_path_full, new_plots_root)\n print(f\"rewriting {path}\\n as {new_path_relative}\")\n new_plot_paths[str(new_path_relative)] = values\n plots_config_new: Dict = {\"plots\": new_plot_paths}\n save_config(new_root, \"plots.yaml\", plots_config_new)\n print(\"\\nUpdated plots.yaml to point to where your existing plots are.\")\n print(\n \"\\nYour plots have not been moved so be careful deleting old preferences folders.\"\n )\n\n print(\"\\nIf you want to move your plot files, you should also modify\")\n print(f\"{config_path_for_filename(new_root, 'plots.yaml')}\")\n return 1\n\n\ndef initialize_ssl(root_path: Path):\n cert, key = generate_selfsigned_cert()\n path_crt = config_path_for_filename(root_path, \"trusted.crt\")\n path_key = config_path_for_filename(root_path, \"trusted.key\")\n with open(path_crt, \"w\") as f:\n f.write(cert)\n with open(path_key, \"w\") as f:\n f.write(key)\n\n\ndef init(args: Namespace, parser: ArgumentParser):\n return chia_init(args.root_path)\n\n\ndef chia_init(root_path: Path):\n if os.environ.get(\"CHIA_ROOT\", None) is not None:\n print(\n f\"warning, your CHIA_ROOT is set to {os.environ['CHIA_ROOT']}. \"\n f\"Please unset the environment variable and run chia init again\\n\"\n f\"or manually migrate config.yaml, plots.yaml and keys.yaml.\"\n )\n\n print(f\"migrating to {root_path}\")\n if root_path.is_dir():\n # This is reached if CHIA_ROOT is set, or if user has run chia init twice\n # before a new update.\n migrate_to_keychain(root_path, root_path)\n\n print(f\"{root_path} already exists, no migration action taken\")\n return -1\n\n # These are the config keys that will not be migrated, and instead the default is used\n DO_NOT_MIGRATE_SETTINGS: List[str] = [\n \"full_node.introducer_peer\",\n \"wallet.introducer_peer\",\n \"full_node.database_path\",\n \"full_node.simulator_database_path\",\n ]\n\n # These are the files that will be migrated\n MANIFEST: List[str] = [\n \"config/config.yaml\",\n \"config/plots.yaml\",\n \"config/trusted.crt\",\n \"config/trusted.key\",\n ]\n\n PATH_MANIFEST_LIST: List[Tuple[Path, List[str]]] = [\n (Path(os.path.expanduser(\"~/.chia/beta-%s\" % _)), MANIFEST)\n for _ in [\"1.0b5\", \"1.0b5.dev0\", \"1.0b4\", \"1.0b3\", \"1.0b2\", \"1.0b1\"]\n ]\n\n for old_path, manifest in PATH_MANIFEST_LIST:\n # This is reached if the user has updated the application, and therefore a new configuration\n # folder must be used. First we migrate the config fies, and then we migrate the private keys.\n r = migrate_from(old_path, root_path, manifest, DO_NOT_MIGRATE_SETTINGS)\n if r:\n migrate_to_keychain(old_path, root_path)\n break\n else:\n create_default_chia_config(root_path)\n initialize_ssl(root_path)\n check_keys(root_path)\n print(\"\")\n print(\"To see your keys, run 'chia keys show'\")\n print(\"Please generate your keys with 'chia keys generate.'\")\n\n return 0\n","sub_path":"src/cmds/init.py","file_name":"init.py","file_ext":"py","file_size_in_byte":9160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"350750163","text":"import json\nimport time\n\nimport requests\n\nfrom RLBotServer import start_server\nfrom backend.blueprints.spa_api.service_layers.replay.enums import HeatMapType\nfrom tests.utils.killable_thread import KillableThread\nfrom tests.utils.replay_utils import write_proto_pandas_to_file, get_test_file, download_replay_discord\n\nLOCAL_URL = 'http://localhost:8000'\n\n\nclass Test_Heatmaps:\n\n @classmethod\n def setup_class(cls):\n cls.thread = KillableThread(target=start_server)\n cls.thread.daemon = True\n cls.thread.start()\n print('waiting for a bit')\n time.sleep(5)\n print('done waiting')\n\n def test_heatmaps(self):\n proto, pandas, proto_game = write_proto_pandas_to_file(get_test_file(\"ALL_STAR.replay\",\n is_replay=True))\n\n f = download_replay_discord(\"ALL_STAR.replay\")\n r = requests.post(LOCAL_URL + '/api/upload', files={'replays': ('fake_file.replay', f)})\n r.raise_for_status()\n assert(r.status_code == 202)\n\n time.sleep(35)\n\n r = requests.get(LOCAL_URL + '/api/global/replay_count')\n result = json.loads(r.content)\n assert int(result) > 0, 'This test can not run without a replay in the database'\n\n # test default\n self.assert_heatmap(proto_game, has_ball=True)\n\n # test query params\n self.assert_heatmap(proto_game, query_params={\"type\": HeatMapType.POSITIONING.value}, has_ball=True)\n self.assert_heatmap(proto_game, query_params={\"type\": HeatMapType.BOOST.value})\n self.assert_heatmap(proto_game, query_params={\"type\": HeatMapType.BOOST_COLLECT.value})\n self.assert_heatmap(proto_game, query_params={\"type\": HeatMapType.BOOST_SPEED.value})\n self.assert_heatmap(proto_game, query_params={\"type\": HeatMapType.SLOW_SPEED.value})\n\n def assert_heatmap(self, proto_game, query_params=None, has_ball=False):\n id = proto_game.game_metadata.match_guid\n r = requests.get(LOCAL_URL + '/api/replay/' + id + '/heatmaps',\n params=query_params)\n r.raise_for_status()\n assert r.status_code == 200\n result = json.loads(r.content)\n assert 'data' in result\n assert 'maxs' in result\n\n def assert_keys(value):\n if has_ball:\n assert 'ball' in value\n assert proto_game.players[0].name in value\n assert_keys(result['data'])\n assert_keys(result['maxs'])\n\n @classmethod\n def teardown_class(cls):\n try:\n cls.thread.terminate()\n except:\n pass\n cls.thread.join()\n time.sleep(2)\n","sub_path":"tests/integration_tests/no_react/heatmaps_test.py","file_name":"heatmaps_test.py","file_ext":"py","file_size_in_byte":2683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"614860902","text":"#Uses random module and creates an simple game that makes user guess a number.\nimport random\ndef guess():\n tries=1\n print(\"I'm thinking of a number between one and ten. Can you guess it?\")\n number = random.randint(1, 10)\n guess = int(input(\"Take a guess: \\n\"))\n while guess != number and guess != 0:\n if guess > number:\n print(\"Guess a little lower!\")\n tries = tries + 1\n guess = int(input(\"Try again:\"))\n else:\n print(\"Guess a little higher!\")\n tries = tries + 1\n guess = int(input(\"Try again:\"))\n print(\"It was \"+str(number)+\"! It took you \"+str(tries)+\" tries!\")\n\ngreeting=input(\"This is a simple game that makes the user guess a number between one and ten. \\n Do you want to play? [Y/N]\")\n\nif greeting=='n':\n print(\"Okay, see you next time!\")\nelse:\n print(\"Okay! Let's get started!\")\n guess()\n","sub_path":"guessing-game.py","file_name":"guessing-game.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"119807959","text":"# sys\nimport os\nimport sys\nimport numpy as np\nimport random\nimport pickle\n\n# torch\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 datasets, transforms\n\n# visualization\nimport time\n\n# operation\nfrom .tools import *\n\n\nclass Feeder(torch.utils.data.Dataset):\n \"\"\" Feeder for skeleton-based action recognition\n Arguments:\n data_path: the path to '.npy' data, the shape of data should be (N, C, T, V, M)\n label_path: the path to label\n mode: must be train or test\n random_choose: If true, randomly choose a portion of the input sequence\n random_shift: If true, randomly pad zeros at the begining or end of sequence\n window_size: The length of the output sequence\n temporal_downsample_step: Step for down sampling the output sequence\n mean_subtraction: The value of bias should be subtracted from output data\n normalization: If true, normalize input sequence\n debug: If true, only use the first 100 samples\n \"\"\"\n\n def __init__(self,\n data_path,\n label_path,\n mode,\n random_choose=False,\n random_shift=False,\n window_size=-1,\n temporal_downsample_step=1,\n mean_subtraction=0,\n normalization=False,\n debug=False):\n self.debug = debug\n self.mode = mode\n self.data_path = data_path\n self.label_path = label_path\n self.random_choose = random_choose\n self.random_shift = random_shift\n self.window_size = window_size\n self.mean_subtraction = mean_subtraction\n self.temporal_downsample_step = temporal_downsample_step\n self.normalization = normalization\n\n self.load_data()\n if normalization:\n self.get_mean_map()\n\n def load_data(self):\n # data: N C V T M\n\n # load label\n if '.pkl' in self.label_path:\n try:\n with open(self.label_path) as f:\n self.sample_name, self.label = pickle.load(f)\n except:\n # for pickle file from python2\n with open(self.label_path, 'rb') as f:\n self.sample_name, self.label = pickle.load(\n f, encoding='latin1')\n # old label format\n elif '.npy' in self.label_path:\n self.label = list(np.load(self.label_path))\n self.sample_name = [str(i) for i in range(len(self.label))]\n else:\n raise ValueError()\n\n # load data\n self.data = np.load(self.data_path)\n\n if self.debug:\n self.label = self.label[0:100]\n self.data = self.data[0:100]\n self.sample_name = self.sample_name[0:100]\n\n self.N, self.C, self.T, self.V, self.M = self.data.shape\n\n def get_mean_map(self):\n data = self.data\n N, C, T, V, M = data.shape\n self.mean_map = data.mean(\n axis=2, keepdims=True).mean(\n axis=4, keepdims=True).mean(axis=0)\n self.std_map = data.transpose((0, 2, 4, 1, 3)).reshape(\n (N * T * M, C * V)).std(axis=0).reshape((C, 1, V, 1))\n\n def __len__(self):\n return len(self.label)\n\n def __iter__(self):\n return self\n\n def __getitem__(self, index):\n # get data\n data_numpy = self.data[index]\n label = self.label[index]\n\n # normalization\n if self.normalization:\n data_numpy = (data_numpy - self.mean_map) / self.std_map\n\n # processing\n if self.temporal_downsample_step != 1:\n if self.mode is 'train':\n data_numpy = downsample(data_numpy,\n self.temporal_downsample_step)\n else:\n data_numpy = temporal_slice(data_numpy,\n self.temporal_downsample_step)\n if self.mode is 'train':\n if self.random_shift:\n data_numpy = random_shift(data_numpy)\n if self.random_choose:\n data_numpy = random_choose(data_numpy, self.window_size)\n\n # mean subtraction\n if self.mean_subtraction != 0:\n data_numpy = mean_subtractor(data_numpy, self.mean_subtraction)\n\n return data_numpy, label\n\n def top_k(self, score, top_k):\n rank = score.argsort()\n hit_top_k = [l in rank[i, -top_k:] for i, l in enumerate(self.label)]\n return sum(hit_top_k) * 1.0 / len(hit_top_k)\n\n\ndef test(data_path, label_path, vid=None):\n import matplotlib.pyplot as plt\n loader = torch.utils.data.DataLoader(\n dataset=Feeder(data_path, label_path, mode='val'),\n batch_size=64,\n shuffle=False,\n num_workers=2)\n\n if vid is not None:\n sample_name = loader.dataset.sample_name\n sample_id = [name.split('.')[0] for name in sample_name]\n index = sample_id.index(vid)\n data, label = loader.dataset[index]\n data = data.reshape((1, ) + data.shape)\n\n # for batch_idx, (data, label) in enumerate(loader):\n N, C, T, V, M = data.shape\n\n plt.ion()\n fig = plt.figure()\n ax = fig.add_subplot(111)\n\n pose, = ax.plot(np.zeros(V * M), np.zeros(V * M), 'g^')\n ax.axis([-1, 1, -1, 1])\n\n for n in range(N):\n for t in range(T):\n x = data[n, 0, t, :, 0]\n y = data[n, 1, t, :, 0]\n z = data[n, 2, t, :, 0]\n pose.set_xdata(x)\n pose.set_ydata(y)\n fig.canvas.draw()\n plt.pause(1)\n\n\nif __name__ == '__main__':\n data_path = \"./data/NTU-RGB-D/xview/val_data.npy\"\n label_path = \"./data/NTU-RGB-D/xview/val_label.pkl\"\n\n test(data_path, label_path, vid='S003C001P017R001A044')\n","sub_path":"st_gcn/feeder/feeder.py","file_name":"feeder.py","file_ext":"py","file_size_in_byte":5937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"610531126","text":"import pprint as pp\nimport sys\nsys.path.append('src/scheduler/types')\n\nimport Setup\n\ndef main():\n\n config_file = \"config/scheduler/setup.v0\"\n num_setups = 10\n num_apps = 5\n stream_fps = 15\n\n setup_generator = Setup.SetupGenerator(config_file)\n setups = setup_generator.generate_setups(num_setups, num_apps, stream_fps)\n assert len(setups) == num_setups\n pp.pprint(setups)\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"src/scripts/test_get_setups.py","file_name":"test_get_setups.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"433996834","text":"from django.utils.translation import ugettext_lazy as _\nimport re\nfrom django.views.generic.base import TemplateView\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom .forms import GroupForm\nimport json\nfrom .forms import Statistical\nfrom django.http import JsonResponse\nfrom .models import Visitor1,OldSession,OldIp\nimport os\nfrom django_apscheduler.jobstores import DjangoJobStore, register_events, register_job\nfrom apscheduler.schedulers.background import BackgroundScheduler\nfrom django.contrib.auth import (\n REDIRECT_FIELD_NAME, get_user_model, login as auth_login,\n logout as auth_logout, update_session_auth_hash,\n)\nfrom django.contrib.auth.forms import PasswordChangeForm\nfrom django.views.decorators.csrf import csrf_protect\nfrom django.views.decorators.debug import sensitive_post_parameters\nfrom django.utils.decorators import method_decorator\nfrom django.views.generic.edit import FormView\nfrom django.core.paginator import Paginator\nfrom .models import Informations\nfrom django.contrib.auth.decorators import permission_required\nfrom .models import Author, UserExtension1\nfrom django.urls import reverse_lazy\nfrom django.views.generic.edit import CreateView, UpdateView, DeleteView\nfrom django.forms.utils import ErrorList\nfrom .forms import RenewBookForm, AuthorModelForm, RentOutForm, BookinstanceForm1\nfrom django.contrib.auth.mixins import PermissionRequiredMixin\nfrom django.db.models import Q\nfrom django.views import generic\nfrom django.shortcuts import render\nfrom .models import Book, BookInstance, Author, Genre, Language, History, HistoryByManager\nfrom django.forms.models import model_to_dict\nfrom django.contrib.auth.models import User\nfrom django.shortcuts import get_object_or_404\nfrom django.shortcuts import redirect\nfrom django.contrib.auth.hashers import make_password\nfrom django.http import HttpResponseRedirect\nfrom django.urls import reverse\nimport hashlib\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.core.mail import send_mass_mail\nimport datetime\nfrom django.contrib.auth.decorators import login_required\n# Create your views here.\n\n\ndef sendEmail(request, names):\n \"\"\"\n a send email view function\n \"\"\"\n datas = ()\n i = 1\n for name in [name for name in names.split(',')]:\n # user1 = get_object_or_404(User, username='徐超伟')\n # print(user1.email)\n if name:\n # print(name)\n user = get_object_or_404(User, username__exact=name)\n if not user.email:\n request.session['res'] = '0'\n # print(res)\n return HttpResponseRedirect(reverse('catalog:all-borrowed'))\n\n message = (u'还书提示', u'你已经超出了还书期限,请尽快归还图书。',\n 'LocalLibrarySystem<670736258@qq.com>', [user.email])\n datas += (message,)\n\n res = send_mass_mail(datas, fail_silently=False,)\n # print(res)\n request.session['res'] = res\n return HttpResponseRedirect(reverse('catalog:all-borrowed'))\n\n\n# Group\n@permission_required('auth.add_user')\ndef group(request):\n form = GroupForm()\n if request.method == \"GET\":\n # print(request.user.has_perm('auth.add_user'))\n return render(request, \"group.html\", {'form': form})\n elif request.method == \"POST\":\n form = GroupForm(request.POST)\n nums = int(request.POST.get('nums'))\n firstnum = int(request.POST.get('firstnum'))\n user_list = []\n\n if form.is_valid():\n try:\n for i in range(0, nums):\n user_list.append(User.objects.get(username=str(firstnum)))\n firstnum += 1\n if i == nums - 1:\n break\n except Exception:\n return render(request, \"group.html\", {'form': form,\n 'firstnum': int(request.POST.get('firstnum')), 'num': int(request.POST.get('nums')), 'error': '指定用户账号不存在!'})\n\n groups = form.cleaned_data['group']\n for group in groups:\n group.user_set.set(tuple(user_list))\n # print(group)\n return redirect('/admin/auth/user/?e=2')\n# bulk delete users\n@permission_required('auth.delete_user')\ndef deleteusers(request):\n if request.method == \"GET\":\n # print(request.user.has_perm('auth.add_user'))\n return render(request, \"deleteusers.html\",)\n elif request.method == \"POST\":\n if request.POST.get('user-list') != None:\n for user in request.POST.get('user-list').split(','):\n try:\n User.objects.get(username=user).delete()\n except Exception:\n return HttpResponseRedirect('/admin/auth/user/?d=1')\n return redirect('/admin/auth/user/?e=1')\n else:\n nums = int(request.POST.get('nums'))\n firstnum = int(request.POST.get('firstnum'))\n user_list = []\n user_list1 = []\n\n try:\n for i in range(0, nums):\n user_list.append(User.objects.get(username=str(firstnum)))\n user_list1.append(str(firstnum))\n firstnum += 1\n if i == nums - 1:\n break\n user_list1 = ','.join(user_list1)\n # print(user_list1)\n except Exception:\n return render(request, \"deleteusers.html\", {'firstnum': int(request.POST.get('firstnum')), 'num': int(request.POST.get('nums')), 'error': '指定用户账号不存在!'})\n return render(request, 'confirm_deleteusers.html', {'user_list': user_list, 'user_list1': user_list1})\n # return redirect('/admin/auth/user/?e=2')\n\n\n# bulk create user\n@permission_required('auth.add_user')\ndef addusers(request):\n if request.method == \"GET\":\n if request.session.get('error'):\n del request.session['error']\n return render(request, \"addusers.html\", {'error': 'error'})\n return render(request, \"addusers.html\")\n elif request.method == \"POST\":\n # print(int(request.POST.get('firstnum')))\n nums = int(request.POST.get('nums'))\n # print(nums)\n\n firstnum = int(request.POST.get('firstnum'))\n # print(firstnum)\n # if request.session.get('success'):\n # del request.session['success']\n # print(request.session['nums'])\n # return redirect(reverse('catalog:addusers1'))\n user_list = []\n user_list1 = []\n\n for i in range(0, nums):\n str_user = str(firstnum)\n user_list.append(str_user)\n firstnum += 1\n if i == nums - 1:\n break\n user_list = [User(username=line.encode('utf-8').decode('utf-8'),\n password=make_password(\"123456\")) for line in user_list]\n try:\n user_list1 = User.objects.bulk_create(user_list)\n # print(user_list1)\n userextension_list = []\n for user in user_list1:\n # print(user.id)\n user_pk=User.objects.get(username=user)\n # print(type(user_pk.username))\n userextension_list.append(UserExtension1(user=user_pk))\n # print(User.objects.get(username=user).pk)\n UserExtension1.objects.bulk_create(userextension_list)\n return redirect('/admin/auth/user/?e=3')\n except Exception:\n request.session['error'] = 'error'\n return redirect(reverse('catalog:addusers'))\n \n\n # request.session['success'] = '1'\n\n\n# @permission_required('auth.add_user')\n# def addusers1(request):\n# \"\"\"\n# viw function for add users of admin\n# \"\"\"\n# nums = request.session.get('nums')\n# firstnum = request.session.get('firstnum')\n# firstnum = int(firstnum)\n# # print(firstnum)\n# f = open('users.txt', \"w+\")\n# for i in range(0, nums):\n\n# str_user = str(firstnum) + '****\\n'\n# f.write(str_user)\n# firstnum += 1\n# if i == nums-1:\n# break\n# f.close()\n\n# user_list = []\n# with open(u'./users.txt', 'r', encoding='UTF-8') as f:\n# # for line in f:\n# # print(line.split('****')[0].encode('gbk').decode('utf-8'))\n\n# user_list = [User(username=line.split('****')[0].encode('utf-8').decode('utf-8'),\n# password=make_password(\"123456\")) for line in f]\n# try:\n\n# User.objects.bulk_create(user_list)\n# except Exception:\n# request.session['error'] = 'error'\n# return redirect(reverse('catalog:addusers'))\n# del request.session['nums']\n# del request.session['firstnum']\n# if request.session.get('error'):\n# del request.session['error']\n # request.session['success'] = '1'\n # return redirect('/admin/auth/user/?e=1')\n\n\ndef index(request):\n \"\"\"\n Viw function for home page of site.\n \"\"\"\n # print(request.user.has_perm('catalog.change_bookinstance'))\n # Generate counts of some of the main objects\n num_books = Book.objects.all().count()\n num_instances = BookInstance.objects.all().count()\n # Available books(status = 'a')\n num_instances_available = BookInstance.objects.filter(\n status__exact='a').count()\n num_authors = Author.objects.count() # The all() is 'implied' by default\n information = Informations.objects.order_by('-id')\n informations = information[0:5]\n\n # Number of visits to this view, as counted in the session variable.\n num_visits = request.session.get('num_visits', 0)\n request.session['num_visits'] = num_visits + 1\n\n # Render the HTML template index.html with the data in the context variable\n return render(\n request,\n 'index.html',\n context={'num_books': num_books, 'num_instances': num_instances,\n 'num_instances_available': num_instances_available, 'num_authors': num_authors, 'num_visits': num_visits,\n 'informations': informations}\n )\n\n\n# def test(request,name):\n# return render(\n# request,\n# 'catalog/author_list1.html'\n# )\n\n\nclass BookListView(generic.ListView):\n model = Book\n paginate_by = 5\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n genres = Genre.objects.all()\n context['genres'] = genres\n return context\n\n\nclass BookDetailView(generic.DetailView):\n model = Book\n\n\nclass AuthorListView(generic.ListView):\n model = Author\n paginate_by = 5\n\n\nclass AuthorDetailView(generic.DetailView):\n model = Author\n\n\nclass AuthorListView1(generic.ListView):\n def get_queryset(self):\n if not self.kwargs['name']:\n self.authot_list = Author.objects.all()\n else:\n # print(self.kwargs['name'])\n self.author_list = Author.objects.filter(Q(first_name__icontains=self.kwargs['name']) | Q(\n last_name__icontains=self.kwargs['name']))\n name = self.kwargs['name']\n\n return self.author_list\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n return context\n\n paginate_by = 5\n\n\nclass BookListView1(generic.ListView):\n def get_queryset(self):\n if not self.kwargs['name']:\n self.book_list = Book.objects.all()\n else:\n # print(self.kwargs['name'])\n self.book_list = Book.objects.filter(\n title__icontains=self.kwargs['name'])\n name = self.kwargs['name']\n return self.book_list\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['genres'] = Genre.objects.all()\n return context\n\n\n# Genre search\n\n\ndef genre_books(request, name):\n genres = Genre.objects.all()\n book_list = []\n book_list1 = Book.objects.all()\n for book in book_list1:\n genre_name = book.display_genre1()\n # print(book.display_genre())\n # print(re.search(name,genre_name))\n if re.search(name, genre_name) != None:\n book_list.append(book)\n # print(book_list)\n paginator = Paginator(book_list, 5) # Show 5 contacts per page\n\n page = request.GET.get('page')\n page_obj = paginator.get_page(page)\n return render(\n request,\n 'catalog/book_list_genre.html',\n context={'title': name,\n 'genres': genres, 'page_obj': page_obj}\n )\n\n\ndef genre_books1(request, name, name1):\n book_list = []\n book_list1 = Book.objects.all()\n genres = Genre.objects.all()\n book_list2 = []\n for book in book_list1:\n genre_name = book.display_genre1()\n # print(book.display_genre())\n # print(re.search(name,genre_name))\n if re.search(name, genre_name) != None:\n book_list2.append(book)\n # print(book_list)\n for book in book_list2:\n genre_name = book.title\n # print(book.display_genre())\n # print(re.search(name,genre_name))\n if re.search(name1, genre_name) != None:\n book_list.append(book)\n # print(book_list)\n paginator = Paginator(book_list, 5) # Show 5 contacts per page\n page = request.GET.get('page')\n page_obj = paginator.get_page(page)\n return render(\n request,\n 'catalog/book_list_genre.html',\n context={'title': name, 'page_obj': page_obj,\n 'genres': genres}\n )\n\n\nclass LoanedBooksByUserListView(LoginRequiredMixin, generic.ListView):\n \"\"\"\n Generic class-based view listing books on loan to current user. \n \"\"\"\n model = BookInstance\n template_name = 'catalog/bookinstance_list_borrowed_user.html'\n paginate_by = 5\n\n def get_queryset(self):\n return BookInstance.objects.filter(borrower=self.request.user).filter(status__exact='o').order_by('due_back')\n\n\nclass LoanedBooksByUserListView1(LoginRequiredMixin, generic.ListView):\n \"\"\"\n Generic class-based view listing books on loan to current user. \n \"\"\"\n\n template_name = 'catalog/bookinstance_list_borrowed_user.html'\n paginate_by = 5\n\n def get_queryset(self):\n if not self.kwargs['name']:\n self.bookinstance_list = BookInstance.objects.all()\n else:\n # print(self.kwargs['name'])\n self.bookinstance_list = BookInstance.objects.filter(\n book__title__icontains=self.kwargs['name']).filter(borrower=self.request.user).filter(status__exact='o').order_by('due_back')\n name = self.kwargs['name']\n return self.bookinstance_list\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n return context\n\n\nclass LoanedBooksAllListView(PermissionRequiredMixin, generic.ListView):\n \"\"\"Generic class-based view listing all books on loan. Only visible to users with can_mark_returned permission.\"\"\"\n model = BookInstance\n permission_required = 'catalog.can_mark_returned'\n template_name = 'catalog/bookinstance_list_borrowed_all.html'\n paginate_by = 5\n\n def get_queryset(self):\n return BookInstance.objects.filter(status__exact='o').order_by('due_back')\n\n\nclass LoanedBooksAllListView1(PermissionRequiredMixin, generic.ListView):\n \"\"\"Generic class-based view listing all books on loan. Only visible to users with can_mark_returned permission.\"\"\"\n model = BookInstance\n permission_required = 'catalog.can_mark_returned'\n template_name = 'catalog/bookinstance_list_borrowed_all.html'\n paginate_by = 5\n\n def get_queryset(self):\n if not self.kwargs['name']:\n self.bookinstance_list = BookInstance.objects.all()\n else:\n # print(self.kwargs['name'])\n self.bookinstance_list = BookInstance.objects.filter(\n book__title__icontains=self.kwargs['name']).filter(status__exact='o').order_by('due_back')\n name = self.kwargs['name']\n return self.bookinstance_list\n\n\n# myself setting form error css\n\n\nclass DivErrorList(ErrorList):\n def __str__(self):\n return self.as_divs()\n\n def as_divs(self):\n if not self:\n return ''\n return '
%s
' % ''.join(['
%s
' % e for e in self])\n\n\n# form design function\n@login_required\n@permission_required('catalog.can_mark_returned')\ndef renew_book_librarian(request, pk):\n book_inst = get_object_or_404(BookInstance, pk=pk)\n\n # If this is a POST request then process the Form data\n if request.method == 'POST':\n\n # Create a form instance and populate it with data from the request (binding):\n form = RenewBookForm(request.POST, error_class=DivErrorList)\n\n # Check if the form is valid:\n if form.is_valid():\n # process the data in form.cleaned_data as required (here we just write it to the model due_back field)\n book_inst.due_back = form.cleaned_data['renewal_date']\n book_inst.save()\n\n # redirect to a new URL:\n return HttpResponseRedirect(reverse('catalog:all-borrowed') +\n '?m=1')\n\n # If this is a GET (or any other method) create the default form.\n else:\n proposed_renewal_date = datetime.date.today() + datetime.timedelta(weeks=3)\n form = RenewBookForm(\n initial={'renewal_date': proposed_renewal_date, }, error_class=DivErrorList)\n\n return render(request, 'catalog/book_renew_librarian.html', {'form': form, 'bookinst': book_inst})\n\n\n# classes created for the general forms views\n\n\nclass AuthorCreate(PermissionRequiredMixin, CreateView):\n model = Author\n fields = '__all__'\n initial = {}\n\n permission_required = 'catalog.can_mark_returned'\n def get_success_url(self):\n url = super().get_success_url()+'?a=2'\n return url\n\n\nclass AuthorUpdate(PermissionRequiredMixin, UpdateView):\n model = Author\n fields = ['first_name', 'last_name', 'date_of_birth', 'date_of_death']\n permission_required = 'catalog.can_mark_returned'\n def get_success_url(self):\n url = super().get_success_url()+'?u=2'\n return url\n\nclass AuthorDelete(PermissionRequiredMixin, DeleteView):\n model = Author\n # success_url = reverse_lazy('catalog:authors')\n permission_required = 'catalog.can_mark_returned'\n\n def get_success_url(self):\n return reverse_lazy('catalog:authors')+'?d=2'\n\n\nclass BookCreate(PermissionRequiredMixin, CreateView):\n model = Book\n fields = '__all__'\n initial = {}\n\n permission_required = 'catalog.can_mark_returned'\n def get_success_url(self):\n url = super().get_success_url()+'?a=1'\n return url\n\nclass BookUpdate(PermissionRequiredMixin, UpdateView):\n model = Book\n fields = ['title', 'author', 'summary', 'isbn', 'genre', 'language', 'pic']\n permission_required = 'catalog.can_mark_returned'\n\n def get_context_data(self, **kwargs):\n context = super(UpdateView, self).get_context_data(**kwargs)\n if '__next__' in self.request.POST:\n context['i__next__'] = self.request.POST['__next__']\n else:\n context['i__next__'] = self.request.META['HTTP_REFERER']\n return context\n\n def get_success_url(self):\n self.url = self.request.POST['__next__']+\"?u=1\"\n return self.url\n\n\nclass BookDelete(PermissionRequiredMixin, DeleteView):\n model = Book\n # success_url = reverse_lazy('catalog:books')\n permission_required = 'catalog.can_mark_returned'\n\n def get_success_url(self):\n return reverse_lazy('catalog:books')+'?d=1'\n\n# setting popup to add author\n\n\ndef p1(request):\n\n if request.method == \"GET\":\n form = AuthorModelForm(error_class=DivErrorList)\n return render(request, \"p1.html\", {'form': form, })\n elif request.method == \"POST\":\n # Create a form instance and populate it with data from the request (binding):\n form = AuthorModelForm(request.POST, error_class=DivErrorList)\n\n # Check if the form is valid:\n if form.is_valid():\n # process the data in form.cleaned_data as required (here we just write it to the model due_back field)\n author = Author.objects.create()\n author.first_name = form.cleaned_data['first_name']\n author.last_name = form.cleaned_data['last_name']\n author.date_of_birth = form.cleaned_data['date_of_birth']\n author.date_of_death = form.cleaned_data['date_of_death']\n author.save()\n\n # redirect to a new URL:\n return render(request, \"popup_response.html\", {\"author\": author, 'id': author.pk})\n else:\n return render(request, \"p1.html\", {'form': form, })\n\n# setting update user password\n\n\nclass PasswordContextMixin:\n extra_context = None\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context.update({\n 'title': self.title,\n **(self.extra_context or {})\n })\n return context\n\n\nclass PasswordChangeView(PasswordContextMixin, FormView):\n form_class = PasswordChangeForm\n success_url = reverse_lazy('catalog:password_change_done')\n template_name = 'catalog/password_change_form.html'\n title = _('Password change')\n\n @method_decorator(sensitive_post_parameters())\n @method_decorator(csrf_protect)\n @method_decorator(login_required)\n def dispatch(self, *args, **kwargs):\n return super().dispatch(*args, **kwargs)\n\n def get_form_kwargs(self):\n kwargs = super().get_form_kwargs()\n kwargs['user'] = self.request.user\n return kwargs\n\n def form_valid(self, form):\n form.save()\n # Updating the password logs out all other sessions for the user\n # except the current one.\n update_session_auth_hash(self.request, form.user)\n return super().form_valid(form)\n\n\nclass PasswordChangeDoneView(PasswordContextMixin, TemplateView):\n template_name = 'registration/password_change_done.html'\n title = _('Password change successful')\n\n @method_decorator(login_required)\n def dispatch(self, *args, **kwargs):\n return super().dispatch(*args, **kwargs)\n# looking for self information\n\n\nclass UserDetailView(LoginRequiredMixin, generic.DetailView):\n model = User\n template_name = 'catalog/user_profile.html'\n\n# update user profile\n\n\nclass UserUpdate(LoginRequiredMixin, UpdateView):\n model = User\n # success_url = reverse_lazy('catalog:index')\n fields = ['first_name', 'last_name', 'email']\n template_name = 'catalog/user_form.html'\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n if self.request.POST.get('telephone'):\n\n context['tel'] = self.request.POST.get('telephone')\n # print( context['tel'])\n return context\n def get_success_url(self):\n # print(self.request.POST)\n userextension = UserExtension1.objects.get(user=self.request.user)\n userextension.telephone = self.request.POST['telephone']\n userextension.save()\n self.url = reverse_lazy('catalog:index')+\"?p=1\"\n return self.url\n\n# setting rent out\n# class RentOutUpdate(LoginRequiredMixin, UpdateView, PermissionRequiredMixin):\n# model = BookInstance\n# fields = ['status', 'borrower','due_back']\n# template_name = 'catalog/bookinstance_form.html'\n# permission_required = 'catalog.can_mark_returned'\n# def get_success_url(self):\n# print(self.kwargs['pk'])\n# return reverse_lazy('catalog:book-detail', args=[self.kwargs['pk']])\n# def get_object(self):\n# if not self.kwargs['id']:\n# raise Http404(u\"Book not instances!\")\n# else:\n# # print(self.kwargs['id'])\n# return get_object_or_404(BookInstance,id=self.kwargs['id'])\n\n\n@login_required\n@permission_required('catalog.can_mark_returned')\ndef rent_out(request, id, pk):\n book_inst = get_object_or_404(BookInstance, id=id)\n\n # If this is a POST request then process the Form data\n if request.method == 'POST':\n\n # Create a form instance and populate it with data from the request (binding):\n form = RentOutForm(request.POST, error_class=DivErrorList)\n\n # Check if the form is valid:\n if form.is_valid():\n # process the data in form.cleaned_data as required (here we just write it to the model due_back field)\n book_inst.status = form.cleaned_data['status']\n book_inst.borrower = form.cleaned_data['borrower']\n book_inst.appointment = form.cleaned_data['appointment']\n book_inst.due_back = form.cleaned_data['due_back']\n book_inst.appointment_time = form.cleaned_data['appointment_time']\n book_inst.save()\n history = History.objects.create(master=book_inst.borrower)\n history1 = HistoryByManager.objects.create(\n master=book_inst.borrower)\n history.rent_time = datetime.date.today()\n history.books = book_inst.book.title\n history1.rent_time = datetime.date.today()\n history1.books = book_inst.book.title\n history.save()\n history1.save()\n\n # record log\n from django.contrib.admin.options import ModelAdmin\n object = book_inst\n message = '成功修改当前图书副本'\n ModelAdmin.log_change(request, request, object, message)\n\n # redirect to a new URL:\n return HttpResponseRedirect(reverse_lazy('catalog:book-detail', args=(pk,))+'?success=4')\n\n # If this is a GET (or any other method) create the default form.\n else:\n proposed_renewal_date = datetime.date.today() + datetime.timedelta(weeks=3)\n form = RentOutForm(\n initial={'status': 'o', 'borrower': book_inst.borrower, 'due_back': proposed_renewal_date, 'appointment': book_inst.appointment, }, error_class=DivErrorList)\n\n return render(request, 'catalog/bookinstance_form.html', {'form': form, 'bookinst': book_inst})\n\n\n@login_required\ndef appointmentBook(request, pk, id, pk1):\n nums = BookInstance.objects.filter(appointment__exact=request.user)\n if (len(nums) >= 5):\n return redirect(reverse_lazy('catalog:book-detail', args=(pk,)) + '?success=5')\n bookinst = get_object_or_404(BookInstance, id=id)\n # print(bookinst.appointment)\n if bookinst.appointment != None:\n return redirect(reverse_lazy('catalog:book-detail', args=(pk,)) + '?success=2')\n else:\n bookinst.appointment = get_object_or_404(User, pk=pk1)\n bookinst.status = 'r'\n bookinst.appointment_time = datetime.date.today()\n bookinst.save()\n return redirect(reverse_lazy('catalog:book-detail', args=(pk,)) + '?success=3')\n return HttpResponseRedirect(reverse_lazy('catalog:book-detail', args=(pk,)))\n\n\n# auto clear over_appointment\n# 开启定时工作\ntry:\n # 实例化调度器\n scheduler = BackgroundScheduler()\n # 调度器使用DjangoJobStore()\n scheduler.add_jobstore(DjangoJobStore(), \"default\")\n # 设置定时任务,选择方式为interval,时间间隔为10s\n # 另一种方式为每天固定时间执行任务,对应代码为:\n # @register_job(scheduler, 'cron', day_of_week='mon-fri', hour='9', minute='30', second='10',id='task_time')\n @register_job(scheduler, \"interval\", seconds=10)\n def my_job():\n bookinsts = BookInstance.objects.filter(status__exact='r')\n if bookinsts:\n for bookinst in bookinsts:\n if bookinst.is_overappointment:\n bookinst.appointment = None\n bookinst.appointment_time = None\n bookinst.status = 'a'\n bookinst.save()\n\n # 定时执行:这里定时为周一到周日每天早上5:30执行一次\n @register_job(scheduler, 'cron', day_of_week='mon-sun', hour='5', minute='30', second='10', id='delete_stale_data')\n def time_task():\n os.system('py manage.py clearsessions')\n OldSession.objects.all().delete()\n OldIp.objects.all().delete()\n\n register_events(scheduler)\n scheduler.start()\nexcept Exception as e:\n print(e)\n # 有错误就停止定时器\n scheduler.shutdown()\n\n# setting appointment views\n\n\nclass AppointmentByUserListView(LoginRequiredMixin, generic.ListView):\n \"\"\"\n Generic class-based view listing books on appointment to current user. \n \"\"\"\n model = BookInstance\n template_name = 'catalog/bookinstance_list_appointment_user.html'\n paginate_by = 5\n\n def get_queryset(self):\n return BookInstance.objects.filter(appointment=self.request.user).filter(status__exact='r').order_by('appointment_time')\n\n\nclass AppointmentByUserListView1(LoginRequiredMixin, generic.ListView):\n \"\"\"\n Generic class-based view listing books on Appointment to current user. \n \"\"\"\n\n template_name = 'catalog/bookinstance_list_appointment_user.html'\n paginate_by = 5\n\n def get_queryset(self):\n if not self.kwargs['name']:\n self.bookinstance_list = BookInstance.objects.all()\n else:\n # print(self.kwargs['name'])\n self.bookinstance_list = BookInstance.objects.filter(\n book__title__icontains=self.kwargs['name']).filter(appointment=self.request.user).filter(status__exact='r').order_by('appointment_time')\n name = self.kwargs['name']\n return self.bookinstance_list\n\n\nclass AppointmentAllListView(PermissionRequiredMixin, generic.ListView):\n \"\"\"\n Generic class-based view listing all books on appointment. Only visible to users with can_mark_returned permission.\n \"\"\"\n model = BookInstance\n permission_required = 'catalog.can_mark_returned'\n template_name = 'catalog/bookinstance_list_appointment_all.html'\n paginate_by = 5\n\n def get_queryset(self):\n return BookInstance.objects.filter(status__exact='r').order_by('appointment_time')\n\n\nclass AppointmentAllListView1(PermissionRequiredMixin, generic.ListView):\n \"\"\"\n Generic class-based view listing all books on loan. Only visible to users with can_mark_returned permission.\n \"\"\"\n model = BookInstance\n permission_required = 'catalog.can_mark_returned'\n template_name = 'catalog/bookinstance_list_appointment_all.html'\n paginate_by = 5\n\n def get_queryset(self):\n if not self.kwargs['name']:\n self.bookinstance_list = BookInstance.objects.all()\n else:\n print(self.kwargs['name'])\n self.bookinstance_list = BookInstance.objects.filter(\n book__title__icontains=self.kwargs['name']).filter(status__exact='r').order_by('appointment_time')\n name = self.kwargs['name']\n return self.bookinstance_list\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['his'] = '1'\n return context\n\n# setting history by user\n\n\nclass HistoryListView(LoginRequiredMixin, generic.ListView):\n model = History\n template_name = 'catalog/history_list.html'\n paginate_by = 5\n\n def get_queryset(self):\n if self.request.user.history_set.all():\n self.history_list = self.request.user.history_set.all()\n else:\n self.history_list = []\n return self.history_list\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['his'] = '1'\n return context\n\n# delete history recoder\n\n\ndef deleteHistory(request):\n history = History.objects.filter(master=request.user)\n if request.method == \"GET\":\n return render(request, 'catalog/history_confirm_delete.html', {'history': history})\n elif request.method == \"POST\":\n request.user.history_set.clear()\n return redirect(reverse_lazy('catalog:my_history'), {'history_list': []})\n\n# bulk create bookinstance\n\n\n@permission_required('catalog.can_mark_returned')\ndef BulkCreateBookinstance(request, pk):\n\n book = get_object_or_404(Book, pk=pk)\n\n # If this is a POST request then process the Form data\n if request.method == 'POST':\n form = BookinstanceForm1(request.POST, error_class=DivErrorList)\n\n nums = int(request.POST.get('nums'))\n book_inst_list = []\n book_inst_list = [BookInstance(book=book, imprint=request.POST.get(\n 'imprint'), status=request.POST.get('status'),) for i in range(0, nums)]\n try:\n BookInstance.objects.bulk_create(book_inst_list)\n return redirect(reverse('catalog:book-detail', args=[pk, ])+\"?a=6\")\n except Exception:\n return redirect(reverse('catalog:book-detail', args=[pk, ])+\"?e=6\")\n\n # Create a form instance and populate it with data from the request (binding):\n\n # redirect to a new URL:\n\n # If this is a GET (or any other method) create the default form.\n else:\n form = BookinstanceForm1(\n initial={'status': 'a', 'book': book, }, error_class=DivErrorList)\n\n return render(request, 'catalog/addbookinstance.html', {'form': form, 'genres': '1'})\n\n\n# one user\n\n\ndef is_thatone(request):\n x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')\n if x_forwarded_for:\n ip = x_forwarded_for.split(',')[0] # 所以这里是真实的ip\n else:\n ip = request.META.get('REMOTE_ADDR') # 这里获得代理ip\n if request.user.is_authenticated:\n key_from_cookie = request.session.session_key\n # print(request.session.get('sessionid'))\n # print(hasattr(request.user, 'visitor1'))\n if hasattr(request.user, 'visitor'):\n # session_ip = request.user.visitor1.ip\n # print(session_key_in_visitor_db)\n # print(session_key_in_visitor_db != key_from_cookie)\n # print(key_from_cookie)\n if request.session.get('oldip') != str(ip):\n # print(222)\n return JsonResponse({'code': 0})\n \n if request.user.visitor.session_key != key_from_cookie:\n # request.user.visitor1.session_key = key_from_cookie\n # request.user.visitor1.save()\n # print(1111)\n return JsonResponse({'code': 2})\n return JsonResponse({'code': 1})\n\n else:\n return JsonResponse({'code': 1})\n\n\n# statistical state统计\n\n\ndef statistical(request):\n books = Book.objects.all()\n genres = Genre.objects.all()\n borrowers = HistoryByManager.objects.all()\n dic = {}\n list1 = []\n\n dic1 = {}\n list2 = []\n # num_genre_book = 0\n books_num = 0\n for genre in genres:\n if not genre.name in list2:\n list2.append(genre.name)\n # print(list2)\n for name in list2:\n num_genre_book = 0\n for book in books:\n genre_name = book.display_genre1()\n if re.search(name, genre_name) != None:\n num_genre_book += 1\n dic1[name] = num_genre_book\n books_num += num_genre_book\n # print(num_genre_book)\n\n title2 = '图书类别份额'\n\n if request.method == 'GET':\n for borrower in borrowers:\n if not borrower.books in list1:\n list1.append(borrower.books)\n for list in list1:\n dic[list] = HistoryByManager.objects.filter(books=list).count()\n\n title1 = '所有时间段'\n\n form = Statistical(initial={'threeChoice': 0, 'end_date': datetime.date.today(\n ), 'start_date': '2019-11-01'}, error_class=DivErrorList)\n return render(request, 'catalog/statistical.html', {'form': form, 'dic': json.dumps(dic), 'dic1': json.dumps(dic1), 'books_num': json.dumps(books_num), 'title1': title1, 'title2': title2},)\n elif request.method == 'POST':\n form = Statistical(request.POST, error_class=DivErrorList)\n\n # Check if the form is valid:\n if form.is_valid():\n # process the data in form.cleaned_data as required (here we just write it to the model due_back field)\n choice = form.cleaned_data['threeChoice']\n start_date = form.cleaned_data['start_date']\n end_date = form.cleaned_data['end_date']\n title1 = start_date.strftime(\n '%Y-%m-%d') + ' 至 ' + end_date.strftime('%Y-%m-%d')\n # print(title1)\n borrowers = HistoryByManager.objects.filter(\n rent_time__range=(start_date, end_date))\n if borrowers == None:\n dic = {}\n else:\n for borrower in borrowers:\n if not borrower.books in list1:\n list1.append(borrower.books)\n for list in list1:\n dic[list] = HistoryByManager.objects.filter(\n books=list).count()\n return render(request, 'catalog/statistical.html', {'form': form, 'dic': json.dumps(dic), 'dic1': json.dumps(dic1), 'books_num': json.dumps(books_num), 'title1': title1, 'title2': title2},)\n else:\n return render(request, 'catalog/statistical.html', {'form': form, 'error_msg': form.errors})\n\n# -------return book\n@login_required\n@permission_required('catalog.can_mark_returned')\ndef returned(request, id, next):\n bookinst = get_object_or_404(BookInstance, id=id)\n # print(bookinst.appointment)\n bookinst.status = 'a'\n bookinst.appointment_time = None\n bookinst.due_back = None\n bookinst.appointment = None\n bookinst.borrower = None\n bookinst.save()\n next += '?s=1'\n return redirect(next)\nfrom captcha.models import CaptchaStore\nfrom captcha.helpers import captcha_image_url\n#captcha image change\ndef loginCaptcha(request):\n if request.is_ajax(): #请求ajax则返回新的image_url和key\n result = dict()\n result['key'] = CaptchaStore.generate_key()\n result['image_url'] = captcha_image_url(result['key'])\n return JsonResponse(result)\n return redirect('/accounts/login')\n\n#jquery user query\ndef userQuery(request):\n if request.is_ajax(): #请求ajax则返回新的image_url和key\n user = request.POST.get('user','')\n path = str(request.POST.get('path'))\n # print(path)\n # print(user=='')\n if user == '':\n user=None\n \n result = dict()\n try:\n user1 = User.objects.get(username=user)\n # print(user1) \n except Exception:\n user1 = None\n if user1:\n result['key'] = 'success'\n result['val'] = str(user1.pk)\n # print(type(result['val']))\n else:\n result['key'] = None\n \n return JsonResponse(result)\n return redirect(reverse_lazy('catalog:all-borrowed'))","sub_path":"locallibrary/catalog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":38913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"164401743","text":"# -*- coding: utf-8 -*-\n# Django local settings for appstore project.\nfrom os.path import join\n\nfrom .base import *\n\nDEBUG = True\n\nALLOWED_HOSTS = [u'127.0.0.1', ]\n\nUSE_DROPBOX_SHARE = True\n\nSECURE_SSL_REDIRECT = False\n\nEMAIL_SUBJECT_PREFIX = '[appstore - local] '\nEMAIL_FILE_PATH = join(REPOSITORY_ROOT, 'emails')\nEMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'\n\n# Django-compress\nCOMPRESS_ENABLED = False\n\n# Databases\nif USE_DROPBOX_SHARE:\n MEDIA_ROOT = '/media/berg/Working/Dropbox/dj-projs-bs/medias/appstore/'\n DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.\n 'NAME': '/media/berg/Working/Dropbox/dj-projs-bs/dbs/appstore.sqlite3',\n 'USER': '', # Not used with sqlite3.\n 'PASSWORD': '', # Not used with sqlite3.\n 'HOST': '', # Set to empty string for localhost. Not used with sqlite3.\n 'PORT': '', # Set to empty string for default. Not used with sqlite3.\n },\n }\nelse:\n DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.\n 'NAME': join(PROJECT_ROOT, 'appstore.sqlite3'),\n 'USER': '', # Not used with sqlite3.\n 'PASSWORD': '', # Not used with sqlite3.\n 'HOST': '', # Set to empty string for localhost. Not used with sqlite3.\n 'PORT': '', # Set to empty string for default. Not used with sqlite3.\n },\n }\n\n# Caching\n# CACHE_BACKEND = 'memcached://127.0.0.1:11211/'\n\nINTERNAL_IPS = ('127.0.0.1',)\nMAINTENANCE_MODE = False # Set True if you want to put site in maitenance (offline) mode\n\nMIDDLEWARE_CLASSES += (\n 'debug_toolbar.middleware.DebugToolbarMiddleware',\n)\n\nINSTALLED_APPS += (\n 'debug_toolbar',\n 'rosetta',\n)\n\n# Rosetta configuration\nROSETTA_MESSAGES_PER_PAGE = 20\nENABLE_TRANSLATION_SUGGESTIONS = True\nROSETTA_ENABLE_TRANSLATION_SUGGESTIONS = True\n# BING_APP_ID = '56037A20A952135140CCE0C82C292D7C299554C8'\n# ROSETTA_MESSAGES_SOURCE_LANGUAGE_CODE = 'en'\n# ROSETTA_MESSAGES_SOURCE_LANGUAGE_NAME = 'English'\nYANDEX_TRANSLATE_KEY = \"trnsl.1.1.20131227T134851Z.3d9887e6554b4b80.1a22e934387cf73c99c1686b29c8504bb320c55e\"\nROSETTA_WSGI_AUTO_RELOAD = True\nROSETTA_UWSGI_AUTO_RELOAD = True\n# ROSETTA_STORAGE_CLASS = 'rosetta.storage.SessionRosettaStorage'\nROSETTA_STORAGE_CLASS = 'rosetta.storage.CacheRosettaStorage'\n'''\n django-debug-toolbar\n'''\nDEBUG_TOOLBAR_PATCH_SETTINGS = False\nDEBUG_TOOLBAR_PANELS = [\n 'debug_toolbar.panels.versions.VersionsPanel',\n 'debug_toolbar.panels.timer.TimerPanel',\n 'debug_toolbar.panels.settings.SettingsPanel',\n 'debug_toolbar.panels.headers.HeadersPanel',\n 'debug_toolbar.panels.request.RequestPanel',\n 'debug_toolbar.panels.sql.SQLPanel',\n 'debug_toolbar.panels.staticfiles.StaticFilesPanel',\n 'debug_toolbar.panels.templates.TemplatesPanel',\n 'debug_toolbar.panels.cache.CachePanel',\n 'debug_toolbar.panels.signals.SignalsPanel',\n 'debug_toolbar.panels.logging.LoggingPanel',\n 'debug_toolbar.panels.redirects.RedirectsPanel',\n]\n\n# This example is unlikely to be appropriate for your project.\nCONFIG_DEFAULTS = {\n # Toolbar options\n 'RESULTS_STORE_SIZE': 3,\n 'SHOW_COLLAPSED': True,\n # Panel options\n 'INTERCEPT_REDIRECTS': True,\n 'SQL_WARNING_THRESHOLD': 100, # milliseconds\n}\n\nDEBUG_TOOLBAR_CONFIG = {\n 'INTERCEPT_REDIRECTS': False,\n}\n\nTEMPLATES[0]['OPTIONS']['debug'] = DEBUG\n","sub_path":"src/project_src/settings/local_template.py","file_name":"local_template.py","file_ext":"py","file_size_in_byte":3581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"245298592","text":"#---------------------------------------------\n# unit test cases + tools of testing the robot\n# JackRobot Studio, 11/10/2019\n#---------------------------------------------\nfrom pybricks import ev3brick as brick\nfrom pybricks.ev3devices import (Motor, TouchSensor, ColorSensor, InfraredSensor, UltrasonicSensor, GyroSensor)\nfrom pybricks.parameters import (Port, Stop, Direction, Button, Color, SoundFile, ImageFile, Align)\nfrom pybricks.tools import wait, StopWatch\nfrom pybricks.robotics import DriveBase\n\nimport unittest\n\nfrom libs.config import ROBOT \nfrom libs import log\n\nclass TestBasic(unittest.TestCase):\n def test_split(self):\n s = 'hello world'\n self.assertEqual(s.split(), ['hello', 'world'])\n\n # check that s.split fails when the separator is not a string\n with self.assertRaises(TypeError):\n s.split(2)\n\nclass TestRobot(unittest.TestCase):\n def setUp(self):\n # log basic envionment information\n log.log_robot_config()\n log.log_robot_info()\n\n # max speed is up to many conditions, floor, load, size of wheels, battery, etc. \n # so maxt speed has to been got through testing, this it is\n def test_max_speed(self):\n log.info('--- test_max_speed ---')\n SPEED_STEP, MIN_TEST_TIME, CHECK_INTERVAL = 50, 16000, 250\n max_speed, speed_left= 0, SPEED_STEP\n motor_right, motor_left = Motor(ROBOT['drive_motor_port_left']), Motor(ROBOT['drive_motor_port_right'])\n motor_left.reset_angle(0)\n motor_right.reset_angle(0)\n\n robot = DriveBase(motor_left, motor_right, ROBOT['wheel_diameter'], ROBOT['wheel_axle_track'])\n\n watch = StopWatch()\n robot.drive(speed_left, 0)\n angle_left, angle_right = 0,0\n\n while True:\n run_time = watch.time()\n old_speed = speed_left\n speed_left = motor_left.speed()\n\n # timeout \n if run_time >= MIN_TEST_TIME:\n log.info('reach max test time, speed_left=%d, max_speed=%d' % (speed_left, max_speed))\n break\n\n # found higher speed reached\n if speed_left > max_speed:\n print('motor angle: left=%d, right=%d' % (motor_left.angle(), motor_right.angle()))\n print('motor speed: left=%d, right=%d' % (motor_left.speed(), motor_right.speed()))\n\n # stop and run more time with higher speed\n robot.stop()\n watch.reset()\n\n motor_left.reset_angle(0)\n motor_right.reset_angle(0)\n angle_left, angle_right = 0,0\n\n max_speed = speed_left\n speed_left += SPEED_STEP \n \n print('drive one more time, speed_left=%d, max_speed=%d' % (speed_left, max_speed ))\n robot.drive(speed_left, 0)\n continue\n\n # continue\n a_l = motor_left.angle()\n a_r = motor_right.angle()\n angle_left += a_l \n angle_right += a_r\n #print('angle/total angle: %d/%d - %d/%d' % (a_l, angle_left, a_r, angle_right))\n steering = (abs(angle_left-angle_right) // 10) * 10 \n if steering > 30:\n steering = 30\n if angle_left > angle_right:\n steering = 0 - steering\n if abs(angle_left - angle_right) > 10:\n print('delta/total/steering: %3d/%3d/%3d' % (a_l - a_r,angle_left-angle_right, steering))\n motor_left.reset_angle(0)\n motor_right.reset_angle(0)\n robot.drive((motor_left.speed() + motor_right.speed()) / 2, steering)\n else:\n print('.')\n\n wait(CHECK_INTERVAL) # wait one second to let motor reach higher speed\n\n print('motor speed: left=%d, right=%d' % (motor_left.speed(), motor_right.speed()))\n print('total motor angle: left=%d, right=%d' % (angle_left, angle_right))\n log.info('test_max_speed: battery=%d, max_speed=%d' % (brick.battery.voltage(), max_speed))\n robot.stop()\n\nif __name__ == '__main__':\n unittest.main()\n\n","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":4131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"497137128","text":"#!/usr/bin/python3\n\"\"\"_\"\"\"\nfrom flask import Flask, jsonify\nfrom models import storage\nfrom api.v1.views import app_views\nfrom os import getenv\n\n\napp = Flask(__name__)\napp.register_blueprint(app_views)\n\n\n@app.teardown_appcontext\ndef teardown_appcontext(exception):\n \"\"\"Close the database\"\"\"\n storage.close()\n\n\n@app.errorhandler(404)\ndef page_not_found(error):\n \"\"\"Page not found error\"\"\"\n return (jsonify(error=\"Not found\"), 404)\n\nif __name__ == \"__main__\":\n host = getenv(\"HBNB_API_HOST\", default=\"0.0.0.0\")\n port = getenv(\"HBNB_API_PORT\", default=\"5000\")\n app.run(host=host, port=port, threaded=True)\n","sub_path":"api/v1/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"542909904","text":"def GCD(x,y):\n if x>y:\n sm=y\n else:\n sm=x\n for i in range(1,sm+1):\n if((x%i==0) and (y%i==0)):\n gcd=i\n return gcd\ny1,y2=map(int,input().split())\nprint(GCD(y1,y2))\n","sub_path":"gcd1.py","file_name":"gcd1.py","file_ext":"py","file_size_in_byte":207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"514092928","text":"\n\nfrom xai.brain.wordbase.nouns._geranium import _GERANIUM\n\n#calss header\nclass _GERANIUMS(_GERANIUM, ):\n\tdef __init__(self,): \n\t\t_GERANIUM.__init__(self)\n\t\tself.name = \"GERANIUMS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"geranium\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_geraniums.py","file_name":"_geraniums.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"609686615","text":"#Slope of a line - Version 4\n\n#Version 4 adds code to check for valid user input with a function unlike version 3.\n#This does not use the built in isdigit() function. That will be done in version 5.\n\n#Written by: Jeff Brusoe\n#Last Updated: August 10, 2019\n\ndef get_valid_input(InputString):\n #InputSring is the message displayed by the input statement.\n while True:\n \n try:\n UserInput = float(input(InputString))\n except:\n print(\"Please enter a number.\")\n else:\n return UserInput\n\n#First Point\nx1 = get_valid_input(\"Enter the first x coordinate: \")\ny1 = get_valid_input(\"Enter the first y coordinate: \")\n\n\n#Second Point\nx2 = get_valid_input(\"Enter the second x coordinate: \")\ny2 = get_valid_input(\"Enter the second y coordinate: \") \n\ntry:\n slope = (y2-y1)/(x2-x1)\nexcept ZeroDivisionError:\n print(\"The x values are equal. The slope is undefined.\")\nexcept:\n print(\"An error occurred.\")\nelse:\n print(\"The slope of the line is \" + str(slope) + \".\")\n","sub_path":"3MiscPrograms/SlopeOfALine-Ver4/SlopeOfALine-Ver4.py","file_name":"SlopeOfALine-Ver4.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"69652910","text":"# coding: utf-8\n\n\"\"\"\n OANDA v20 REST API\n\n The full OANDA v20 REST API Specification. This specification defines how to interact with v20 Accounts, Trades, Orders, Pricing and more. To authenticate use the string 'Bearer ' followed by the token which can be obtained at https://www.oanda.com/demo-account/tpa/personal_token # noqa: E501\n\n OpenAPI spec version: 3.0.23\n Contact: api@oanda.com\n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\n\nclass PositionBookBucket(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'price': 'str',\n 'long_count_percent': 'str',\n 'short_count_percent': 'str'\n }\n\n attribute_map = {\n 'price': 'price',\n 'long_count_percent': 'longCountPercent',\n 'short_count_percent': 'shortCountPercent'\n }\n\n def __init__(self, price=None, long_count_percent=None, short_count_percent=None): # noqa: E501\n \"\"\"PositionBookBucket - a model defined in Swagger\"\"\" # noqa: E501\n\n self._price = None\n self._long_count_percent = None\n self._short_count_percent = None\n self.discriminator = None\n\n if price is not None:\n self.price = price\n if long_count_percent is not None:\n self.long_count_percent = long_count_percent\n if short_count_percent is not None:\n self.short_count_percent = short_count_percent\n\n @property\n def price(self):\n \"\"\"Gets the price of this PositionBookBucket. # noqa: E501\n\n The lowest price (inclusive) covered by the bucket. The bucket covers the price range from the price to price + the position book's bucketWidth. # noqa: E501\n\n :return: The price of this PositionBookBucket. # noqa: E501\n :rtype: str\n \"\"\"\n return self._price\n\n @price.setter\n def price(self, price):\n \"\"\"Sets the price of this PositionBookBucket.\n\n The lowest price (inclusive) covered by the bucket. The bucket covers the price range from the price to price + the position book's bucketWidth. # noqa: E501\n\n :param price: The price of this PositionBookBucket. # noqa: E501\n :type: str\n \"\"\"\n\n self._price = price\n\n @property\n def long_count_percent(self):\n \"\"\"Gets the long_count_percent of this PositionBookBucket. # noqa: E501\n\n The percentage of the total number of positions represented by the long positions found in this bucket. # noqa: E501\n\n :return: The long_count_percent of this PositionBookBucket. # noqa: E501\n :rtype: str\n \"\"\"\n return self._long_count_percent\n\n @long_count_percent.setter\n def long_count_percent(self, long_count_percent):\n \"\"\"Sets the long_count_percent of this PositionBookBucket.\n\n The percentage of the total number of positions represented by the long positions found in this bucket. # noqa: E501\n\n :param long_count_percent: The long_count_percent of this PositionBookBucket. # noqa: E501\n :type: str\n \"\"\"\n\n self._long_count_percent = long_count_percent\n\n @property\n def short_count_percent(self):\n \"\"\"Gets the short_count_percent of this PositionBookBucket. # noqa: E501\n\n The percentage of the total number of positions represented by the short positions found in this bucket. # noqa: E501\n\n :return: The short_count_percent of this PositionBookBucket. # noqa: E501\n :rtype: str\n \"\"\"\n return self._short_count_percent\n\n @short_count_percent.setter\n def short_count_percent(self, short_count_percent):\n \"\"\"Sets the short_count_percent of this PositionBookBucket.\n\n The percentage of the total number of positions represented by the short positions found in this bucket. # noqa: E501\n\n :param short_count_percent: The short_count_percent of this PositionBookBucket. # noqa: E501\n :type: str\n \"\"\"\n\n self._short_count_percent = short_count_percent\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, PositionBookBucket):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n","sub_path":"python/oanda/models/position_book_bucket.py","file_name":"position_book_bucket.py","file_ext":"py","file_size_in_byte":5787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"344293656","text":"import numpy as np\nimport cv2\n\ncap = cv2.VideoCapture(0)\nmode = 0\nwhile True:\n # Capture frame-by-frame\n ret, frame = cap.read()\n\n # wait for key and switch to mode\n ch = cv2.waitKey(1) & 0xFF\n if ch == ord('1'):\n mode = 1\n # ...\n\n if ch == ord('q'):\n break\n\n if mode == 1:\n # just example code\n # your code should implement\n frame = cv2.GaussianBlur(frame, (5, 5), 0)\n\n # Display the resulting frame\n cv2.imshow('frame', frame)\n\n\n\n\n\n\n# When everything done, release the capture\ncap.release()\ncv2.destroyAllWindows()","sub_path":"1/support/opencv_experiments.py","file_name":"opencv_experiments.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"161332989","text":"from matplotlib import pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport math\nimport seaborn as sns\nimport pandas as pd\nimport numpy as np\nfrom itertools import product\n\n\nclass plot_funcs:\n def test_express_func(x_list, a=100, b=500, c=300):\n x = x_list[0]\n y = x_list[1]\n z = x_list[2]\n ans = 30*math.exp(-(((x - 800)/a)**2\n + ((y - 500)/b)**2\n + ((z - 200)/c)**2))\n return(ans)\n\n def scatter_3d(point_mat, azim=0, elev=0, color=\"r\", size=10):\n fig = plt.figure()\n ax = Axes3D(fig)\n ax.set_xlabel(\"X-axis\")\n ax.set_ylabel(\"Y-axis\")\n ax.set_zlabel(\"Z-axis\")\n ax.view_init(azim=azim, elev=elev)\n ax.scatter3D(point_mat[:, 0], point_mat[:, 1],\n point_mat[:, 2], alpha=1, s=size, c=color, cmap='bwr')\n #plt.show()\n return(ax)\n\n def slice_plot(reconst_mat, low, high, x='x', y='y', spec='z'):\n reconst_df = pd.DataFrame(\n reconst_mat, columns=['x', 'y', 'z', 'mean'])\n cond_str = '&'.join([spec + '>' + str(low), spec + '<' + str(high)])\n reconst_df_lim = reconst_df.query(cond_str)\n upper0 = np.maximum(reconst_df_lim['mean'], 0)\n plt.scatter(reconst_df_lim[x], reconst_df_lim[y],\n c=upper0, cmap='bwr')\n plt.colorbar()\n\n def comp_seq_plot(seq, plot1, plot2):\n for i, val in enumerate(seq):\n plt.subplot(2, len(seq), i + 1)\n plot1(val)\n for i, val in enumerate(seq):\n plt.subplot(2, len(seq), len(seq) + i + 1)\n plot2(val)\n\n def seq_plot(seq, plot):\n for i, val in enumerate(seq):\n plt.subplot(1, len(seq), i + 1)\n plot(val)\n\n def axes_plot(axes, stge, hpf, gene,\n sim=False, true_val=False, colorbar=False,\n clim=None, dt_est=False, sc_est=False,\n ax=plt, file_path=\"\", cmap='viridis'):\n pmat = stge.dm.get_pmat(hpf)\n if not sim:\n new_Mu = stge.reconstruct_specified_step(\n hpf, dt_est=dt_est, sc_est=sc_est)\n gene_idx = list(stge.gene_name_list).index(gene.upper())\n else:\n gene_idx = gene\n if not true_val:\n new_Mu = stge.reconstruct_specified_step(hpf, dt_est, sc_est=sc_est)\n else:\n new_Mu = stge.dm.true_exp_dict[hpf]\n if axes == \"lrva\":\n x, y = pmat[:, 2], pmat[:, 1]\n elif axes == \"vdva\":\n x, y = -pmat[:, 0], pmat[:, 1]\n elif axes == \"avvd\":\n y, x = -pmat[:, 0], -pmat[:, 1]\n elif axes == \"vdlr\":\n x, y = -pmat[:, 0], pmat[:, 2]\n ax.scatter(x, y,\n c=new_Mu[:, gene_idx], cmap=cmap)\n if clim != None:\n plt.clim(clim)\n if colorbar:\n plt.colorbar()\n if file_path != \"\":\n plt.savefig(file_path)\n\n\n def lrva_plot(stge, hpf, gene, min_val=-10,\n sim=False, true_val=False, colorbar=False):\n pmat = stge.dm.get_pmat(hpf)\n if not sim:\n new_Mu = stge.reconstruct_specified_step(hpf)\n new_Mu[new_Mu < min_val] = min_val\n gene_idx = list(stge.gene_name_list).index(gene)\n else:\n gene_idx = gene\n if not true_val:\n new_Mu = stge.reconstruct_specified_step(hpf)\n else:\n new_Mu = stge.dm.true_exp_dict[hpf]\n plt.scatter(pmat[:, 2], pmat[:, 1],\n c=new_Mu[:, gene_idx], cmap='bwr')\n if colorbar:\n plt.colorbar()\n\n def vdva_plot(stge, hpf, gene, min_val=-10,\n sim=False, true_val=False, colorbar=False):\n pmat = stge.dm.get_pmat(hpf)\n if not sim:\n new_Mu = stge.reconstruct_specified_step(hpf)\n new_Mu[new_Mu < min_val] = min_val\n gene_idx = list(stge.gene_name_list).index(gene)\n else:\n gene_idx = gene\n if not true_val:\n new_Mu = stge.reconstruct_specified_step(hpf)\n else:\n new_Mu = stge.dm.true_exp_dict[hpf]\n plt.scatter(-pmat[:, 0], pmat[:, 1],\n c=new_Mu[:, gene_idx], cmap='bwr')\n if colorbar:\n plt.colorbar()\n\n def vdlr_plot(stge, hpf, gene, min_val=-1, sim=False):\n pmat = stge.dm.get_pmat(hpf)\n if not sim:\n new_Mu = stge.reconstruct_specified_step(hpf)\n new_Mu[new_Mu < min_val] = min_val\n else:\n new_Mu = stge.dm.true_exp_dict[hpf]\n gene_idx = list(stge.gene_name_list).index(gene)\n plt.scatter(-pmat[:, 0], pmat[:, 2],\n c=new_Mu[:, gene_idx], cmap='bwr')\n plt.colorbar()\n\n def slice_plot_no_val(reconst_mat, low, high, x='x', y='y', spec='z'):\n reconst_df = pd.DataFrame(\n reconst_mat, columns=['x', 'y', 'z'])\n cond_str = '&'.join([spec + '>' + str(low), spec + '<' + str(high)])\n reconst_df_lim = reconst_df.query(cond_str)\n plt.scatter(reconst_df_lim[x], reconst_df_lim[y], c=\"r\")\n\n def ts_plot(gene_id, ts, **plotargs):\n expression = ts.get_expression(gene_id)\n idx = range(len(expression))\n plt.plot(idx, expression, **plotargs)\n\n def comp_hist(vec_list, label_list, cumulative=False):\n plt.figure()\n plt.hist(vec_list,\n histtype='bar',\n color=['crimson', 'burlywood'],\n label=label_list,\n cumulative=cumulative)\n plt.legend()\n\n def mean_pos_dist_hist(stge, t, cumulative=True):\n tidx = np.arange(stge.dm.t_vec.shape[0])[stge.dm.t_vec == t][0]\n mean_pmat = stge.Pi_list[tidx] @ stge.dm.get_pmat(t)\n true_pmat = stge.dm.get_pmat(t)[stge.dm.sc_idx_dict[t], :]\n random_pmat = stge.dm.get_pmat(t)[np.random.choice(np.arange(\n stge.dm.get_pmat(t).shape[0]), true_pmat.shape[0]), :]\n norm_vec = np.sqrt(np.sum((mean_pmat - true_pmat)**2, axis=1))\n random_norm_vec = np.sqrt(np.sum((mean_pmat - random_pmat)**2, axis=1))\n plt.hist([norm_vec, random_norm_vec],\n color=[\"red\", \"blue\"],\n label=[\"true\", \"random\"],\n cumulative=cumulative,\n density=True, bins=10)\n plt.legend()\n\n def map_pos_dist_hist(stge, t):\n tidx = np.arange(stge.dm.t_vec.shape[0])[stge.dm.t_vec == t][0]\n mean_pmat = stge.dm.get_pmat(t)[\n np.argmax(stge.Pi_list[tidx], axis=1), :]\n true_pmat = stge.dm.get_pmat(t)[stge.dm.sc_idx_dict[t], :]\n random_pmat = stge.dm.get_pmat(t)[np.random.choice(np.arange(\n true_pmat.shape[0]), true_pmat.shape[0]), :]\n norm_vec = np.sqrt(np.sum((mean_pmat - true_pmat)**2, axis=1))\n random_norm_vec = np.sqrt(np.sum((mean_pmat - random_pmat)**2, axis=1))\n plt.hist([norm_vec, random_norm_vec],\n color=[\"red\", \"blue\"], label=[\"true\", \"random\"])\n plt.legend()\n\n def accuracy_plot(file_name, xkey, linekey):\n accuracy_df = pd.read_csv(file_name)\n fig, ax = plt.subplots(1, 2, figsize=(10, 4))\n sns.lineplot(x=xkey, y=\"corr\",\n hue=linekey, data=accuracy_df,\n ax=ax[0], legend=\"full\")\n sns.lineplot(x=xkey, y=\"posdist\",\n hue=linekey, data=accuracy_df,\n ax=ax[1], legend=\"full\")\n\n def time_course_comp_plot(stge, gene_idx, dt_est=False):\n if dt_est:\n true_dict = stge.dm.true_exp_dt_dict\n else:\n true_dict = stge.dm.true_exp_dict\n true_time_course = np.stack(\n [np.mean(true_dict[t], axis=0)\n for t in stge.dm.sim_t_vec], axis=0)\n est_time_course = np.stack(\n [np.mean(stge.reconstruct_specified_step(t, dt_est), axis=0)\n for t in stge.dm.sim_t_vec], axis=0)\n t_vec = stge.dm.t_vec\n fig, ax = plt.subplots(1, 2, figsize=(10, 4))\n print(true_time_course[:, gene_idx])\n ax[0].plot(t_vec, true_time_course[:, gene_idx], \"ro\")\n ax[1].plot(t_vec, est_time_course[:, gene_idx], \"ro\")\n\n def eval_plot(stge, file_name,\n gene_list=np.array([\n \"cdx4\", \"eng2a\", \"rx3\", \"admp\", \"sox2\"]), sc_est=True):\n plt.figure(figsize=(15, 10))\n for i, (gene, hpf) in enumerate(product(gene_list, stge.dm.t_vec)):\n plt.subplot(5, 7, i+1)\n pmat = stge.dm.get_pmat(hpf)\n x, y = -pmat[:, 0], pmat[:, 1]\n new_Mu = stge.reconstruct_specified_step(\n hpf, dt_est=False, sc_est=sc_est)\n gene_idx = list(stge.gene_name_list).index(gene.upper())\n plt.title(gene + \", hpf: \" + str(hpf))\n plt.scatter(x, y, c=new_Mu[:, gene_idx], cmap='bwr', s=10)\n plt.axis('off')\n plt.savefig(file_name)\n plt.close()\n","sub_path":"stge/plot_funcs.py","file_name":"plot_funcs.py","file_ext":"py","file_size_in_byte":9003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"96515540","text":"\"\"\"\n\n 找出符合資料規律的直線,就叫線性迴歸 ( Regression )\n https://brohrer.mcknote.com/zh-Hant/how_machine_learning_works/how_linear_regression_works.html\n\nIn a regression problem, we aim to predict the output of a continuous value, like a price or a probability.\nContrast this with a classification problem, where we aim to select a class from a list of classes\n(for example, where a picture contains an apple or an orange, recognizing which fruit is in the picture).\n\nThis notebook uses the classic Auto MPG Dataset and builds a model to predict the fuel efficiency of late-1970s\nand early 1980s automobiles.\n\nTo do this, we'll provide the model with a description of many automobiles from that time period.\nThis description includes attributes like: cylinders, displacement, horsepower, and weight.\n\nThis example uses the tf.keras API, see this guide for details.\n\n\n\"\"\"\n# Use seaborn for pairplot\n#!pip install -q seaborn\n\nfrom __future__ import absolute_import, division, print_function\n\nimport pathlib\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport seaborn as sns\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\n\nprint(tf.__version__)\n\n\"\"\"\n The Auto MPG dataset\n The dataset is available from the UCI Machine Learning Repository.\n https://archive.ics.uci.edu/ml/index.php\n \n \n Get the data\n First download the dataset.\n\"\"\"\n\n# First download the dataset.\ndataset_path = keras.utils.get_file(\"auto-mpg.data\", \"https://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data\")\nprint(dataset_path)\n\n\ncolumn_names = ['MPG','Cylinders','Displacement','Horsepower','Weight',\n 'Acceleration', 'Model Year', 'Origin']\n# Import it using pandas\nraw_dataset = pd.read_csv(dataset_path, names=column_names,\n na_values = \"?\", comment='\\t',\n sep=\" \", skipinitialspace=True)\n\ndataset = raw_dataset.copy()\nprint(dataset.tail())\n\nprint(dataset.isna().sum())\n\n\"\"\"\n To keep this initial tutorial simple drop those rows.\n\"\"\"\ndataset = dataset.dropna()\n\n\"\"\"\n The \"Origin\" column is really categorical, not numeric. So convert that to a one-hot:\n\"\"\"\norigin = dataset.pop('Origin')\n\ndataset['USA'] = (origin == 1)*1.0\ndataset['Europe'] = (origin == 2)*1.0\ndataset['Japan'] = (origin == 3)*1.0\nprint(dataset.tail())\n\n\"\"\"\n Split the data into train and test\n \n Now split the dataset into a training set and a test set.\n\n We will use the test set in the final evaluation of our model.\n\"\"\"\ntrain_dataset = dataset.sample(frac=0.8,random_state=0)\ntest_dataset = dataset.drop(train_dataset.index)\n\n\n\"\"\"\n Inspect the data\n \n Have a quick look at the joint distribution of a few pairs of columns from the training set.\n\"\"\"\nsns.pairplot(train_dataset[[\"MPG\", \"Cylinders\", \"Displacement\", \"Weight\"]], diag_kind=\"kde\")\n\n\"\"\" \n Also look at the overall statistics:\n\"\"\"\ntrain_stats = train_dataset.describe()\ntrain_stats.pop(\"MPG\")\ntrain_stats = train_stats.transpose()\n\nprint(train_stats)\n\n\"\"\"\n Split features from labels\n \n Separate the target value, or \"label\", from the features. This label is the value that you will train the model to predict.\n\"\"\"\ntrain_labels = train_dataset.pop('MPG')\ntest_labels = test_dataset.pop('MPG')\n\n\n\"\"\"\n Normalize the data\n \n Look again at the train_stats block above and note how different the ranges of each feature are.\n \n It is good practice to normalize features that use different scales and ranges. \n Although the model might converge without feature normalization, it makes training more difficult, \n and it makes the resulting model dependent on the choice of units used in the input.\n \n Note: Although we intentionally generate these statistics from only the training dataset, \n these statistics will also be used to normalize the test dataset. \n We need to do that to project the test dataset into the same distribution that the model has been trained on.\n\"\"\"\ndef norm(x):\n return (x - train_stats['mean']) / train_stats['std']\nnormed_train_data = norm(train_dataset)\nnormed_test_data = norm(test_dataset)\n\n\"\"\"\n This normalized data is what we will use to train the model.\n Caution: \n The statistics used to normalize the inputs here (mean and standard deviation) need to be applied to any other data \n that is fed to the model, along with the one-hot encoding that we did earlier. \n That includes the test set as well as live data when the model is used in production.\n\"\"\"\n\"\"\"\nThe model\n\nBuild the model\n\nLet's build our model. Here, we'll use a Sequential model with two densely connected hidden layers, \nand an output layer that returns a single, continuous value. \nThe model building steps are wrapped in a function, build_model, since we'll create a second model, later on.\n\"\"\"\n\ndef build_model():\n model = keras.Sequential([\n layers.Dense(64, activation=tf.nn.relu, input_shape=[len(train_dataset.keys())]),\n layers.Dense(64, activation=tf.nn.relu),\n layers.Dense(1)\n ])\n\n optimizer = tf.keras.optimizers.RMSprop(0.001)\n\n model.compile(loss='mean_squared_error',\n optimizer=optimizer,\n metrics=['mean_absolute_error', 'mean_squared_error'])\n return model\n\nmodel = build_model()\n\n\"\"\"\nInspect the model\n\nUse the .summary method to print a simple description of the model\n\"\"\"\nmodel.summary()\n\n\"\"\"\nNow try out the model. Take a batch of 10 examples from the training data and call model.predict on it.\n\"\"\"\n\nexample_batch = normed_train_data[:10]\nexample_result = model.predict(example_batch)\nprint(example_result)\n\n\n\"\"\"\nTrain the model\n\nTrain the model for 1000 epochs, and record the training and validation accuracy in the history object.\n\"\"\"\n# Display training progress by printing a single dot for each completed epoch\nclass PrintDot(keras.callbacks.Callback):\n def on_epoch_end(self, epoch, logs):\n if epoch % 100 == 0: print('')\n print('.', end='')\n\nEPOCHS = 1000\n\nhistory = model.fit(\n normed_train_data, train_labels,\n epochs=EPOCHS, validation_split = 0.2, verbose=0,\n callbacks=[PrintDot()])\n\"\"\"\n Visualize the model's training progress using the stats stored in the history object.\n\"\"\"\nhist = pd.DataFrame(history.history)\nhist['epoch'] = history.epoch\nprint(hist.tail())\n\ndef plot_history(history):\n hist = pd.DataFrame(history.history)\n hist['epoch'] = history.epoch\n\n plt.figure()\n plt.xlabel('Epoch')\n plt.ylabel('Mean Abs Error [MPG]')\n plt.plot(hist['epoch'], hist['mean_absolute_error'],\n label='Train Error')\n plt.plot(hist['epoch'], hist['val_mean_absolute_error'],\n label='Val Error')\n plt.ylim([0, 5])\n plt.legend()\n\n plt.figure()\n plt.xlabel('Epoch')\n plt.ylabel('Mean Square Error [$MPG^2$]')\n plt.plot(hist['epoch'], hist['mean_squared_error'],\n label='Train Error')\n plt.plot(hist['epoch'], hist['val_mean_squared_error'],\n label='Val Error')\n plt.ylim([0, 20])\n plt.legend()\n plt.show()\n\n\n#plot_history(history)\n\n\"\"\"\n This graph shows little improvement, or even degradation in the validation error after about 100 epochs. \n Let's update the model.fit call to automatically stop training when the validation score doesn't improve. \n We'll use an EarlyStopping callback that tests a training condition for every epoch. \n If a set amount of epochs elapses without showing improvement, then automatically stop the training.\n\"\"\"\n\nmodel = build_model()\n\n\"\"\"\n Stop training when a monitored quantity has stopped improving.\n https://www.tensorflow.org/api_docs/python/tf/keras/callbacks/EarlyStopping\n\"\"\"\n# The patience parameter is the amount of epochs to check for improvement\nearly_stop = keras.callbacks.EarlyStopping(monitor='val_loss', patience=10)\n\nhistory = model.fit(normed_train_data, train_labels, epochs=EPOCHS,\n validation_split = 0.2, verbose=0, callbacks=[early_stop, PrintDot()])\n\nplot_history(history)\n\n\"\"\"\n The graph shows that on the validation set, the average error is usually around +/- 2 MPG. \n Is this good? We'll leave that decision up to you.\n \n Let's see how well the model generalizes by using the test set, \n which we did not use when training the model. \n This tells us how well we can expect the model to predict when we use it in the real world.\n\n\"\"\"\n# Testing set Mean Abs Error: 1.95 MPG\nloss, mae, mse = model.evaluate(normed_test_data, test_labels, verbose=0)\nprint(\"Testing set Mean Abs Error: {:5.2f} MPG\".format(mae))\n\n\"\"\"\n Make predictions\n\n Finally, predict MPG values using data in the testing set:\n\"\"\"\ntest_predictions = model.predict(normed_test_data).flatten()\n\nplt.scatter(test_labels, test_predictions)\nplt.xlabel('True Values [MPG]')\nplt.ylabel('Predictions [MPG]')\nplt.axis('equal')\nplt.axis('square')\nplt.xlim([0,plt.xlim()[1]])\nplt.ylim([0,plt.ylim()[1]])\n_ = plt.plot([-100, 100], [-100, 100])\nplt.show()\n\n# It looks like our model predicts reasonably well. Let's take a look at the error distribution.\n\nerror = test_predictions - test_labels\nplt.hist(error, bins = 25)\nplt.xlabel(\"Prediction Error [MPG]\")\n_ = plt.ylabel(\"Count\")\nplt.show()\n# It's not quite gaussian, but we might expect that because the number of samples is very small.\n\n\"\"\"\n Conclusion\n \n 1. This notebook introduced a few techniques to handle a regression problem.\n Mean Squared Error (MSE) is a common loss function used for regression problems \n (different loss functions are used for classification problems).\n \n 2. Similarly, evaluation metrics used for regression differ from classification. \n A common regression metric is Mean Absolute Error (MAE).\n \n 3.When numeric input data features have values with different ranges, each feature should be scaled independently to the same range.\n \n 4.If there is not much training data, one technique is to prefer a small network with few hidden layers to avoid overfitting.\n \n 5.Early stopping is a useful technique to prevent overfitting.\n\n\"\"\"\n","sub_path":"Regression_predictFuelEfficiency/regression.py","file_name":"regression.py","file_ext":"py","file_size_in_byte":10078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"417231109","text":"def areaCadrado():\n lado = int(input(\"Ingrese el valor del Lado : \"))\n return print(\"el area del Cuadrado es\", 4 * lado)\n\ndef areaRectangulo():\n base= int(input(\"ingrese el valor de la base : \"))\n altura= int(input(\"Ingrese el valor de altura :\"))\n return print(\"el perimetro del Rectangulo es \", (2 * base), (2 * altura))\n\ndef areaCirculo():\n radio= int(input(\"Ingrese el valor del Radio :\"))\n __pi= 3.1416\n return print(\"el area del circulo es \",2 * __pi * radio)\n\nif __name__==(\"__main__\"):\n print(\"estoy en la funcion principal\")\n areaCirculo()\n areaCadrado()\n areaRectangulo()\nelse:\n print(\"en este momento me comporto como un modulo\")\n","sub_path":"Clase # - copia (8)/directorio/area.py","file_name":"area.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"561369499","text":"import json\n\nGLOBAL_TMP_AVERAGES = [\n { # Balise\n 'coord_tmp_average': [0, 0],\n 'relative_position_average': 0,\n 'elements': 0,\n },\n { # Distant Signal\n 'coord_tmp_average': [0, 0],\n 'relative_position_average': 0,\n 'elements': 0,\n },\n { # Main Signal\n 'coord_tmp_average': [0, 0],\n 'relative_position_average': 0,\n 'elements': 0,\n }\n]\n\nOBJECT_CLASSES = ['balise', 'distant signal', 'main signal']\n\nTRACK_SEGMENT_PDFS = {\n 'LQ': '49600_LQ_Landquart_situation_plan.pdf',\n 'MALA': '49202_MALA_Malans_situation_plan.pdf',\n 'SAGE': '49203_SAGE_Malans_Alte_Saege_situation_plan.pdf',\n 'GRUS': '49208_GRUS_Gruesch_situation_plan.pdf',\n 'SCRS': '49211_SCRS_Schiers_situation_plan.pdf',\n 'FUWI': '49214_FUWI_Fuchswinkel_situation_plan.pdf',\n 'JAZ': '49217_JAZ_Jenaz_situation_plan.pdf',\n 'FID': '49218_FID_Fideris_situation_plan.pdf',\n 'KUEB': '49221_KUEB_Kueblis_situation_plan.pdf',\n 'CAPA': '49223_CAPA_Capaels_situation_plan.pdf',\n 'SAAS': '49225_SAAS_Saas_situation_plan.pdf',\n 'SERN': '49228_SERN_Serneus_situation_plan.pdf',\n 'KLOD': '49231_KLOD_Klosters_Dorf_situation_plan.pdf',\n 'KLO': '49232_KLO_Klosters_situation_plan.pdf',\n}\n\nresult = []\n\nwith open('objects.json') as devices_json:\n\n devices = json.load(devices_json)\n\n def get_id_and_location(relative_position, device_type):\n best_dif = 100\n best_idx = -1\n for idx, device in enumerate(devices):\n device_position = float(device['relativ position'].split()[0])\n if abs(relative_position - device_position) < best_dif \\\n and device_type == device['type']:\n best_dif = relative_position - device_position\n best_idx = idx\n best_id = devices[best_idx]['id']\n return best_id, devices[best_idx]['location abreviation']\n\n with open('image_relative_position.json') as images_json:\n images = json.load(images_json)\n for image in images: # Should also check for the last item\n coordinates = image['coordinates']\n for idx, is_object_present in enumerate(image['objects']):\n if idx != 3:\n coord_avg = GLOBAL_TMP_AVERAGES[idx]['coord_tmp_average']\n rel_avg = \\\n GLOBAL_TMP_AVERAGES[idx]['relative_position_average']\n if idx != 3 and is_object_present:\n GLOBAL_TMP_AVERAGES[idx]['elements'] += 1\n GLOBAL_TMP_AVERAGES[idx]['coord_tmp_average'] = \\\n [coord_avg[0] + coordinates[0], coord_avg[1] +\n coordinates[1]]\n GLOBAL_TMP_AVERAGES[idx]['relative_position_average'] \\\n = rel_avg + image['relative_position']\n elif idx != 3 and (is_object_present == 0 or idx ==\n len(image['objects']) - 1) and \\\n coord_avg[0] != 0:\n latitude = coord_avg[0] / \\\n GLOBAL_TMP_AVERAGES[idx]['elements']\n longitude = coord_avg[1] / \\\n GLOBAL_TMP_AVERAGES[idx]['elements']\n relative_position = rel_avg / \\\n GLOBAL_TMP_AVERAGES[idx]['elements']\n GLOBAL_TMP_AVERAGES[idx] = {\n 'coord_tmp_average': [0, 0],\n 'elements': 0,\n 'relative_position_average': 0\n }\n object_id, location_abreviation = get_id_and_location(\n relative_position, OBJECT_CLASSES[idx])\n result.append({\n 'id': object_id,\n 'latitude': latitude,\n 'longitude': longitude,\n 'type': OBJECT_CLASSES[idx],\n 'relative_position': relative_position,\n 'pdf_file':\n TRACK_SEGMENT_PDFS[location_abreviation],\n 'image': image['image'].split('Res/')[1]\n })\n with open('feed_results.json', 'w+') as ff:\n json.dump(result, ff)\n\n","sub_path":"data_scripts/produce_objects_coordinates.py","file_name":"produce_objects_coordinates.py","file_ext":"py","file_size_in_byte":4456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"29417183","text":"#!/usr/bin/env python2\n\nimport argparse\nimport ast\nimport json\nimport logging\nfrom base64 import b64encode\nfrom textwrap import dedent\n\ntry:\n from urllib.request import urlopen, Request\nexcept ImportError:\n from urllib2 import urlopen, Request\n\n\ndef api_request(instance, route, data, token):\n api_endpoint = \"https://{instance}/{route}\".format(\n instance=instance, route=route.lstrip(\"/\")\n )\n headers = {\n \"Authorization\": \"Bearer {token}\".format(token=token),\n \"Content-Type\": \"application/json\",\n }\n req = Request(api_endpoint, data=data.encode(), headers=headers)\n resp = urlopen(req)\n logging.info(\"status: {} info: {}\".format(resp.getcode(), resp.info()))\n return resp\n\n\ndef generate_runner(module_name, instance, token):\n \"\"\"Generate a runner for the current module to be run in Databricks.\"\"\"\n\n runner_data = \"\"\"\n # This runner has been auto-generated from mozilla/python_mozetl/bin/mozetl-databricks.py.\n # Any changes made to the runner file will be over-written on subsequent runs.\n from {module} import cli\n\n try:\n cli.entry_point(auto_envvar_prefix=\"MOZETL\")\n except SystemExit:\n # avoid calling sys.exit() in databricks\n # http://click.palletsprojects.com/en/7.x/api/?highlight=auto_envvar_prefix#click.BaseCommand.main\n pass\n \"\"\".format(\n module=module_name\n )\n logging.debug(dedent(runner_data))\n\n request = {\n \"contents\": b64encode(dedent(runner_data).encode()).decode(),\n \"overwrite\": True,\n \"path\": \"/FileStore/airflow/{module}_runner.py\".format(module=module_name),\n }\n logging.debug(json.dumps(request, indent=2))\n resp = api_request(instance, \"/api/2.0/dbfs/put\", json.dumps(request), token)\n logging.info(resp.read())\n\n\ndef run_submit(args):\n config = {\n \"run_name\": \"mozetl local submission\",\n \"new_cluster\": {\n \"spark_version\": \"4.3.x-scala2.11\",\n \"node_type_id\": args.node_type_id,\n \"num_workers\": args.num_workers,\n \"aws_attributes\": {\n \"first_on_demand\": 1,\n \"availability\": args.aws_availability,\n \"instance_profile_arn\": \"arn:aws:iam::144996185633:instance-profile/databricks-ec2\",\n \"spot_bid_price_percent\": 100,\n },\n },\n \"spark_python_task\": {\n \"python_file\": \"dbfs:/FileStore/airflow/{module}_runner.py\".format(\n module=args.module_name\n ),\n \"parameters\": args.command,\n },\n \"libraries\": [\n {\n \"pypi\": {\n \"package\": \"git+{path}@{branch}\".format(\n path=args.git_path, branch=args.git_branch\n )\n }\n }\n ],\n }\n\n if args.python == 3:\n config[\"new_cluster\"][\"spark_env_vars\"] = {\n \"PYSPARK_PYTHON\": \"/databricks/python3/bin/python3\"\n }\n\n if len(args.pypi_libs) > 0:\n config[\"libraries\"].extend(\n [{\"pypi\": {\"package\": lib}} for lib in args.pypi_libs]\n )\n\n if args.autoscale:\n # Autoscale from 1 worker up to num_workers\n num_workers = config[\"new_cluster\"][\"num_workers\"]\n config[\"new_cluster\"][\"autoscale\"] = {\n \"min_workers\": 1,\n \"max_workers\": num_workers,\n }\n\n # Delete the num_workers option as it's mutually exclusive\n # with autoscaling\n del config[\"new_cluster\"][\"num_workers\"]\n\n if args.spot_price_percent != 100:\n config[\"new_cluster\"][\"aws_attributes\"][\n \"spot_bid_price_percent\"\n ] = args.spot_price_percent\n\n logging.info(json.dumps(config, indent=2))\n\n # https://docs.databricks.com/api/latest/jobs.html#runs-submit\n resp = api_request(\n args.instance, \"/api/2.0/jobs/runs/submit\", json.dumps(config), args.token\n )\n logging.info(resp.read())\n\n\ndef parse_arguments():\n parser = argparse.ArgumentParser(description=\"run mozetl\")\n\n def coerce_pypi_names(additional_arg):\n \"\"\"\n This safely parses pypi package imports using the ast module\n \"\"\"\n\n class customAction(argparse.Action):\n def __call__(self, parser, args, values, option_string=None):\n\n coerced_values = []\n try:\n coerced_values = ast.literal_eval(values)\n for package in coerced_values:\n # Do some basic checks that this looks like a\n # pypi package\n if (\n not isinstance(package, str)\n or len(package.split(\"==\")) != 2\n ):\n raise ValueError(\n \"Invalid package list spec: {}\".format(values)\n )\n except Exception:\n raise\n setattr(args, self.dest, coerced_values)\n\n return customAction\n\n parser.add_argument(\n \"--git-path\",\n type=str,\n default=\"https://github.com/mozilla/python_mozetl.git\",\n help=\"The URL to the git repository e.g. https://github.com/mozilla/python_mozetl.git\",\n )\n parser.add_argument(\n \"--git-branch\", type=str, default=\"main\", help=\"The branch to run e.g. main\"\n )\n parser.add_argument(\n \"--node-type-id\", type=str, default=\"c3.4xlarge\", help=\"EC2 Node type\"\n )\n parser.add_argument(\n \"--aws-availability\",\n type=str,\n default=\"ON_DEMAND\",\n choices=[\"ON_DEMAND\", \"SPOT\", \"SPOT_WITH_FALLBACK\"],\n help=\"Set the AWS availability type for the cluster\",\n )\n parser.add_argument(\n \"--spot-price-percent\",\n type=int,\n default=100,\n help=\"Set the bid price for AWS spot instances\",\n )\n\n parser.add_argument(\n \"--num-workers\",\n type=int,\n default=2,\n help=\"Number of worker instances to spawn in the cluster\",\n )\n parser.add_argument(\"--autoscale\", action=\"store_true\", help=\"Enable autoscale\")\n parser.add_argument(\n \"--python\",\n type=int,\n choices=[2, 3],\n default=2,\n help=\"Version of Python to run on the cluster\",\n )\n parser.add_argument(\n \"--token\",\n type=str,\n required=True,\n help=\"A Databricks authorization token, generated from the user settings page\",\n )\n parser.add_argument(\n \"--pypi-libs\",\n type=str,\n default=\"\",\n help=\"\"\"PyPI libraries to install. ex: \\\"['pylib1==0.1', 'pylib2==3.1']\\\"\"\"\",\n action=coerce_pypi_names(\"pypi_libs\"),\n )\n parser.add_argument(\n \"--instance\",\n type=str,\n default=\"dbc-caf9527b-e073.cloud.databricks.com\",\n help=\"The Databricks instance.\",\n )\n parser.add_argument(\n \"--module-name\", type=str, default=\"mozetl\", help=\"Top-level module name to run\"\n )\n parser.add_argument(\n \"command\", nargs=argparse.REMAINDER, help=\"Arguments to pass to mozetl\"\n )\n args = parser.parse_args()\n return args\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.DEBUG)\n\n args = parse_arguments()\n generate_runner(args.module_name, args.instance, args.token)\n run_submit(args)\n","sub_path":"bin/mozetl-databricks.py","file_name":"mozetl-databricks.py","file_ext":"py","file_size_in_byte":7351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"407903086","text":"'''\n@author = \"Jury Francia, Simone Olivieri, Vic Zagranowski\"\n@version = \"2.1\"\n@email = \"j.francia@reply.it, s.olivieri@reply.it, v.zagranowski@reply.it\"\n'''\n\nimport os\nimport utility\nimport JaSONx\nimport openpyxl \n\n'''Configuration path, open file configuration.json'''\npaths = utility.readFileJSON(os.path.join(os.path.realpath (''), \"configuration\\\\pathConfiguration.json\"))\ntemplatesPath = paths[\"templatesPath\"]\njsonPath = paths[\"jsonPath\"]\nhierarchyPath = paths[\"hierarchyPath\"]\ntemplatesExcelPath = paths[\"templatesExcelPath\"]\nexcelPath = paths[\"excelPath\"]\n\n'''Constant data variables'''\nsite_name = \"\"\nenvironment_prefix = \"\"\n\n\n'''Setting constant data, triggered by MainInterface'''\ndef setConstantData(site, folder): \n global site_name\n site_name = site \n start(folder)\n \n \n'''Create dict meters'''\ndef search_json(path, diz_xml):\n global environment_prefix\n file_list = utility.createListFile(path, \".json\")\n diz_meters={}\n environment_prefix = \"\" \n count = 0 \n for file in file_list:\n file_json = utility.readFileJSON(os.path.join(path,file))\n \n if(count == 0):\n environment_prefix = file_json[\"parameters\"][\"environment_prefix\"]\n count+=1\n meter_name = file_json[\"parameters\"][\"meter_name\"]\n for key in file_json[\"parameters\"][\"filter_tag\"]: \n if(key[\"tag\"]!=\"CommunicationCode\"):\n if(meter_name not in diz_meters):\n diz_meters[meter_name] = []\n diz_meters[meter_name] += [{key[\"tag\"] [key[\"tag\"].find(\".\")+1:] : {\"id\":key[\"id\"], \"period\":key[\"period\"], \"name\":diz_xml[key[\"tag\"]]}}] \n return([diz_meters, environment_prefix])\n\n'''Create dict meters from xml'''\ndef create_dict_xml(name_hierarchy):\n diz_xml = {}\n hierarchy = utility.readFileXML(os.path.join(hierarchyPath, name_hierarchy+\".xml\"))\n for val in hierarchy.getElementsByTagName(\"Meter\"):\n diz_xml[val.toxml()[val.toxml().find(\"\")+9 : val.toxml().find(\"\")]] = val.toxml()[val.toxml().find(\"\")+6 : val.toxml().find(\"\")] \n return(diz_xml) \n\n'''Create excel file''' \ndef createExcelSheet(list_meters_json):\n diz_json = list_meters_json[0]\n environment_prefix = list_meters_json[1] \n excel_document = openpyxl.load_workbook(os.path.join(templatesExcelPath,\"Meter Upload Template LEONARDO.xlsx\"))\n sheet = excel_document.active\n number_cell = 7 \n for meter in diz_json.values(): \n for lst in meter: \n for diz, val in lst.items():\n sheet['A'+str(number_cell)] = site_name\n sheet['B'+str(number_cell)] = val[\"name\"]\n sheet['C'+str(number_cell)] = environment_prefix+\"_veig1_thing§_\"+str(val[\"id\"])\n sheet['E'+str(number_cell)] = val[\"period\"]/60 \n number_cell+=1 \n excel_document.save(os.path.join(excelPath,JaSONx.name_file_hierarchy+\".xlsx\"))\n \ndef start(folder_json): \n createExcelSheet(search_json(os.path.join(jsonPath,folder_json), create_dict_xml(JaSONx.name_file_hierarchy)))\n \n \ndef getListFolderJSON():\n return(utility.createListDirectory(jsonPath))\n","sub_path":"Versione-2.1.0.0/xCELL.py","file_name":"xCELL.py","file_ext":"py","file_size_in_byte":3236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"47398657","text":"# !/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# FileName: 21. Merge Two Sorted Lists.py\n# Author: binss\n# Create: 2016-03-08 19:45:43\n# Description: No Description\n#\n\n# Merge two sorted linked lists and return it as a new list.\n\n# The new list should be made by splicing together the nodes of the first two lists.\n\n\n# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution(object):\n # 60 ms\n def mergeTwoLists(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n current = head = ListNode(None)\n\n while True:\n if l1 is None:\n current.next = l2\n break\n if l2 is None:\n current.next = l1\n break\n\n if l1.val <= l2.val:\n current.next = l1\n current = l1\n l1 = l1.next\n else:\n current.next = l2\n current = l2\n l2 = l2.next\n\n return head.next\n","sub_path":"Python/21. Merge Two Sorted Lists.py","file_name":"21. Merge Two Sorted Lists.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"372641764","text":"from __future__ import print_function\n\nimport torch, torchvision\nimport torch.nn as nn\nimport torch.backends.cudnn as cudnn\nfrom torchvision import models, transforms, datasets\nimport numpy as np\n\nimport os, sys, time, requests, copy\nfrom torchsummary import summary\nfrom bashplotlib.histogram import plot_hist\nimport matplotlib.pyplot as plt\n\nfrom utils import progress_bar\n\n\n# ----- Set GPU and random seed -----\nseed = 0\ntorch.manual_seed(seed)\n\nuse_gpu = 0\nif use_gpu != -1:\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1,2,3\"\n torch.cuda.set_device(use_gpu)\n use_gpu = torch.cuda.is_available()\nelse:\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\"\n use_gpu = False\n \ndevice = 'cuda' if use_gpu else 'cpu'\n\nif use_gpu:\n torch.cuda.manual_seed_all(seed)\n \n# ------------------------------------\n\n\ndef is_interactive():\n import __main__ as main\n return not hasattr(main, '__file__')\n\n\ndef count_parameters(m):\n return np.sum(p.numel() for p in m.parameters() if p.requires_grad)\n\n\n\ndef replace_layers(model, i, indices, layers):\n if i in indices:\n return layers[indices.index(i)]\n return model[i]\n\n\ndef initiate_pruned_layer(conv, length, type):\n return nn.Conv2d(in_channels = conv.in_channels - (type == 'next')*length, \\\n out_channels = conv.out_channels - (type == 'curr')*length,\n kernel_size = conv.kernel_size, \\\n stride = conv.stride,\n padding = conv.padding,\n dilation = conv.dilation,\n groups = conv.groups,\n bias = (conv.bias is not None)).cuda()\n\n\ndef prune_excecute(old_data, filter_dim, multi_prune = 1):\n \"\"\"\n :param: (tuple) filter_dim [0] (list, tuple, or int) which filters to remove\n [1] (int) along which axes to remove\n \"\"\"\n fd, fa = filter_dim\n if isinstance(fd, int):\n fd = [fd]\n\n fd_ = [range(d * multi_prune, (d + 1) * multi_prune) for d in fd]\n filter = np.s_[[i for j in fd_ for i in j]]\n\n new_data = np.delete(old_data.cpu().numpy(), filter, fa)\n return torch.from_numpy(new_data).cuda()\n\n\ndef prune_vgg_helper(model_in, layer_index, filter_indices):\n\n model = copy.deepcopy(model_in)\n \n # verify classifier\n if not isinstance(model.classifier,nn.Sequential):\n seq_cls = nn.Sequential(model.classifier)\n del model.classifier\n model.classifier = seq_cls\n\n \"\"\"\n Excecute pruning on the layer# by removing filter#\n and set previous and following layers to appropraite shapes\n\n :Param: (torchvision.models) model\n :Param: (int) layer_index\n :Param: (int or list) filter_indices\n \"\"\"\n\n _, conv = list(model.features._modules.items())[layer_index]\n next_conv = None # next conv layer\n batch_norm = None # next batch normalization\n offset = 1\n \n # initiate with layer index to prune\n replace_index_list = [layer_index] \n \n # dont know the new weights and bias yet, leave blank\n replace_content_list = []\n\n # feature modules list \n feature_items = list(model.features._modules.items())\n \n while layer_index + offset < len(feature_items):\n \n res = feature_items[layer_index + offset][1]\n \n if batch_norm is None and isinstance(res, nn.BatchNorm2d):\n batch_norm = res\n \n # add batch norm layer index to the list if exists\n replace_index_list.append(layer_index + offset)\n \n if isinstance(res, nn.modules.conv.Conv2d):\n next_conv = res\n \n # add next conv layer index to the list if exists\n replace_index_list.append(layer_index + offset)\n break\n \n offset += 1\n \n new_conv = initiate_pruned_layer(conv, len(filter_indices), 'curr')\n new_conv.weight.data = prune_excecute(conv.weight.data, (filter_indices, 0))\n new_conv.bias.data = prune_excecute(conv.bias.data, (filter_indices, 0))\n \n # add new conv layer content to the list\n replace_content_list.append(new_conv)\n \n if batch_norm:\n new_bn = nn.BatchNorm2d(batch_norm.num_features-len(filter_indices)).cuda()\n new_bn.weight.data = prune_excecute(batch_norm.weight.data, (filter_indices, 0))\n new_bn.bias.data = prune_excecute(batch_norm.bias.data, (filter_indices, 0))\n \n # add the following batch norm content to the list\n replace_content_list.append(new_bn)\n\n if next_conv:\n next_new_conv = initiate_pruned_layer(next_conv, len(filter_indices), 'next')\n next_new_conv.weight.data = prune_excecute(next_conv.weight.data, (filter_indices, 1))\n next_new_conv.bias.data = next_conv.bias.data \n \n # add new conv layer content to the list\n replace_content_list.append(next_new_conv)\n \n else:\n #Prunning the last conv layer. This affects the first linear layer of the classifier.\n classif_items = list(model.classifier._modules.items())\n \n layer_index = 0\n old_linear_layer = None\n for _, module in classif_items:\n if isinstance(module, nn.Linear):\n old_linear_layer = module\n break\n layer_index += 1\n\n if old_linear_layer is None:\n raise BaseException(\"No linear layer found in classifier\")\n\n params_per_input_channel = int(old_linear_layer.in_features / conv.out_channels)\n\n new_linear_layer = \\\n nn.Linear(old_linear_layer.in_features - params_per_input_channel,\n old_linear_layer.out_features)\n\n new_linear_layer.weight.data = prune_excecute(\n old_data = old_linear_layer.weight.data, # old weights\n filter_dim = (filter_indices, 1),\n multi_prune = params_per_input_channel\n )\n new_linear_layer.bias.data = old_linear_layer.bias.data\n\n classifier = nn.Sequential(\n *(replace_layers(model.classifier, i, [layer_index], \\\n [new_linear_layer]) for i, _ in enumerate(model.classifier)))\n\n del model.classifier\n model.classifier = classifier\n\n # replace the layers in the model \n features = nn.Sequential(\n *(replace_layers(model.features, i, replace_index_list, \\\n replace_content_list) for i, _ in enumerate(model.features)))\n del model.features\n model.features = features\n\n return model.cuda()\n\n\n\ndef get_prunning_plan(w_tensor, c_p_tuple, measure=\"abs_mean\"):\n\n weights = w_tensor.data.cpu().numpy() # gpu method\n\n if measure==\"random\":\n to_prune = np.random.choice(*c_p_tuple, replace=False)\n\n elif measure==\"abs_mean\":\n channel_mean = np.mean(np.abs(weights), axis=(1,2,3))\n assert len(channel_mean)==c_p_tuple[0]\n to_prune = channel_mean.argsort()[:c_p_tuple[1]]\n\n elif measure==\"mean\":\n channel_mean = np.mean(weights, axis=(1,2,3))\n assert len(channel_mean)==c_p_tuple[0]\n to_prune = channel_mean.argsort()[:c_p_tuple[1]]\n \n elif measure==\"bn\":\n assert len(weights)==c_p_tuple[0]\n to_prune = weights.argsort()[:c_p_tuple[1]]\n \n else:\n raise NotImplementedError(\"Sparsity measurement not implemented!\")\n\n return to_prune\n\n\n\ndef prune_conv_layer(model_in, sparsity, criterion):\n\n # find all conv layers and number of channels\n conv_layer_indices, num_channels = find_type_layers(model_in.features,\"conv2d\")\n if criterion=='bn':\n bn_layer_indices, num_channels_bn = find_type_layers(model_in.features,\"batchnorm\")\n assert [i+1 for i in conv_layer_indices]==bn_layer_indices and num_channels==num_channels_bn\n\n # find number of channels to prune for each layers\n num_prune = [np.ceil(c * sparsity).astype(int) for c in num_channels]\n\n # construct a look-up table for pruning\n prune_dict = dict(zip(conv_layer_indices, list(zip(num_channels,num_prune))))\n\n # parameters\n weights = list(model_in.features._modules.items())\n\n # prune from backwards\n for l in sorted(conv_layer_indices, reverse=True):\n chnl_to_prune = get_prunning_plan(weights[l+int(criterion=='bn')][1].weight, prune_dict[l], criterion)\n model_in = prune_vgg_helper(model_in, l, chnl_to_prune)\n\n return model_in.cuda()\n\n\n\ndef prune_conv_layer_legacy(model_in, sparsity):\n\n # find all conv layers and number of channels\n conv_layer_indices, num_channels = find_type_layers(model_in.features,\"conv2d\")\n\n # find number of channels to prune for each layers\n num_prune = [np.ceil(c * sparsity).astype(int) for c in num_channels]\n\n # construct a look-up table for pruning\n prune_dict = dict(zip(conv_layer_indices, list(zip(num_channels,num_prune))))\n\n # parameters\n weights = list(model_in.features._modules.items())\n\n # prune from backwards\n for l in sorted(conv_layer_indices, reverse=True):\n chnl_to_prune = get_prunning_plan(weights[l][1].weight, prune_dict[l], \"abs_mean\")\n model_in = prune_vgg_helper(model_in, l, chnl_to_prune)\n\n return model_in.cuda()\n\n\n\ndef find_type_layers(module, type=\"conv2d\"):\n \"\"\"\n :Return: [0] The indices of layers in the given module of the specified type\n [1] Number of channels available to prune for each layer\n \"\"\"\n\n find_dict = {\n \"conv2d\": nn.modules.conv.Conv2d,\n \"batchnorm\":nn.BatchNorm2d,\n \"linear\": nn.Linear\n }\n assert type in find_dict.keys(), \"Type error!\"\n\n index_list,nchannel_list = [],[]\n\n for i,mod in enumerate(module._modules.items()):\n if isinstance(mod[1], find_dict[type]):\n index_list.append(i)\n try:\n nchannel_list.append(mod[1].out_channels)\n except:\n nchannel_list.append(mod[1].num_features)\n \n\n return index_list, nchannel_list\n\n\n\nglobal_weight = []\ndef get_conv_weights_global(l):\n if isinstance(l, nn.modules.conv.Conv2d):\n# print(type(l))\n global_weight.append(l.weight.data)\n elif '_modules' in dir(l):\n for _, next_l in l._modules.items():\n get_conv_weights_global(next_l)\n \ndef vis_weights_hist(model_in, axis = None):\n global global_weight\n del global_weight[:]\n get_conv_weights_global(model_in)\n params = global_weight\n \n# params = [p.weight.data for n, p in model_in.features._modules.items() if isinstance(p, nn.modules.conv.Conv2d)]\n\n samples = np.concatenate([w.data.cpu().numpy().flatten() for w in params])\n# print(samples.shape)\n\n # visualization\n if is_interactive():\n plot_hist_notebook(samples, axis)\n else:\n plot_hist(samples, height=30, bincount=100, xlab=True, showSummary=True)\n \n \ndef plot_hist_notebook(samples, axis):\n \n if axis is not None:\n xlabel = axis.set_xlabel\n ylabel = axis.set_ylabel\n title = axis.set_title\n grid = axis.grid\n xlim = axis.set_xlim\n ylim = axis.set_ylim\n hist = axis.hist\n else:\n xlabel = plt.xlabel\n ylabel = plt.ylabel\n title = plt.title\n grid = plt.grid\n xlim = plt.xlim\n ylim = plt.ylim\n hist = plt.hist\n \n weights = np.ones_like(samples)/len(samples)\n n, bins, patches = hist(samples, 150, density=0, facecolor='green', alpha=0.75, weights=weights)\n# n, bins, patches = hist(samples, 150, density=0, facecolor='green', alpha=0.75)\n\n xlabel('Weight values')\n ylabel('Probability')\n title('Weights Histogram')\n# xlim(np.min(samples),np.max(samples))\n xlim(-.1,.1)\n ylim(np.min(n),1)#np.max(n))\n grid(True)\n\n if axis is None:\n plt.show()\n \n \n \n \n \n \n \ndef prune_by_sparsity(model_origin, sparsity = 0, num_ep = 50, ft_lrate = 1e-2, \n res_df = None, plot=True, ctri = 'bn', ret = False): \n \n ft = finetuner(loss=\"xent\", optimizer=\"sgd\", lrate=ft_lrate, sparsity=sparsity)\n \n # original model accuracy\n sys.__stdout__.write(\"\\n* original model accuracy *\\n\")\n ft.test(model_origin)\n ft.best_acc = 0 # original acc does not count\n \n model_pruned = prune_conv_layer(model_origin, sparsity, criterion=ctri)\n\n if plot:\n _, ax = plt.subplots(nrows=1, ncols=3, figsize=(15,5), dpi=130)\n \n vis_weights_hist(model_origin, ax[0])\n vis_weights_hist(model_pruned, ax[1])\n \n # resume model if can \n model_path = 'checkpoint/%s/ckpt_ft_%f.t7'%(model_pruned.name, sparsity)\n if os.path.exists(model_path):\n checkpoint_ft = torch.load(model_path)\n model_pruned.load_state_dict(checkpoint_ft['net'])\n ft.best_acc = checkpoint_ft['acc']\n start_epoch = checkpoint_ft['epoch']\n else:\n start_epoch = 0\n \n # right-after-pruning accuracy\n sys.__stdout__.write(\"\\n* right-after-pruning / resumed accuracy *\\n\")\n ft.test(model_pruned)\n \n \n inference_time = np.zeros(num_ep)\n for ep in range(start_epoch, num_ep):\n model_pruned = ft.train(model_pruned, ep)\n # fine-tuning accuracy\n acc, inference_time[ep] = ft.test(model_pruned, ep, save=model_path)\n if res_df is not None:\n res_df.at[sparsity, ep] = acc\n \n if res_df is not None:\n res_df.at[sparsity, 'maxAcc'] = ft.best_acc\n res_df.at[sparsity, 'modSize'] = os.path.getsize(model_path)\n res_df.at[sparsity, 'infTime'] = np.mean(inference_time)\n \n \n sys.__stdout__.write(\"\\n********************************\\n\")\n\n if plot: \n vis_weights_hist(model_pruned, ax[2])\n plt.show()\n \n return model_pruned, res_df\n\n\n# ----------------------------------\n# Fine-tune after pruning to restore accuracy\n\nfrom tensorboardX import SummaryWriter\n\nclass finetuner(object):\n \n best_acc = 0\n \n trainloader = None\n testloader = None\n criterion = None\n optimizer = None\n \n def __init__(self, loss=\"xent\", optimizer=\"sgd\", lrate=1e-2, sparsity=0):\n \n print(\"==> Finetuning ..\")\n self.sparsity = sparsity\n \n self.writer = SummaryWriter()\n\n # -----------------------\n # Data preparation\n \n transform_train = transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n ])\n\n transform_test = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n ])\n\n trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform_train)\n self.trainloader = torch.utils.data.DataLoader(trainset, batch_size=1024, shuffle=True, num_workers=8)\n\n testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform_test)\n self.testloader = torch.utils.data.DataLoader(testset, batch_size=1000, shuffle=False, num_workers=8)\n\n self.classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')\n\n \n # -----------------------\n # loss and optimizer\n \n if loss.lower()==\"xent\":\n self.criterion = nn.CrossEntropyLoss()\n else:\n raise NotImplentedError\n \n if optimizer.lower()==\"sgd\":\n self.optmize = lambda x: torch.optim.SGD(x, lr=lrate, momentum=0.9, weight_decay=5e-4)\n else:\n raise NotImplentedError\n\n def train(self, model, epoch = 0):\n sys.__stdout__.write('\\nEpoch: %d\\n' % epoch)\n \n if device=='cuda' and 'module' not in model._modules.keys():\n model = torch.nn.DataParallel(model)\n cudnn.benchmark = True\n \n model.train()\n train_loss = 0\n correct = 0\n total = 0\n for batch_idx, (inputs, targets) in enumerate(self.trainloader):\n inputs, targets = inputs.to(device), targets.to(device)\n optimizer = self.optmize(model.parameters())\n optimizer.zero_grad()\n outputs = model(inputs)\n loss = self.criterion(outputs, targets)\n loss.backward()\n optimizer.step()\n\n train_loss += loss.item()\n _, predicted = outputs.max(1)\n total += targets.size(0)\n correct += predicted.eq(targets).sum().item()\n\n # -----------------------\n # progress bar\n old_stdout = sys.stdout\n sys.stdout = open('/dev/stdout', 'w')\n\n progress_bar(batch_idx, len(self.trainloader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'\n % (train_loss/(batch_idx+1), 100.*correct/total, correct, total))\n\n sys.stdout = old_stdout\n # -----------------------\n \n return model\n\n\n def test(self, model, epoch = 0, save = None):\n model.eval()\n test_loss = 0\n correct = 0\n total = 0\n \n time_all = 0\n with torch.no_grad():\n for batch_idx, (inputs, targets) in enumerate(self.testloader):\n inputs, targets = inputs.to(device), targets.to(device)\n \n t0 = time.time()\n outputs = model(inputs)\n t1 = time.time()\n time_all += t1-t0\n \n loss = self.criterion(outputs, targets)\n\n test_loss += loss.item()\n _, predicted = outputs.max(1)\n total += targets.size(0)\n correct += predicted.eq(targets).sum().item()\n\n # -----------------------\n # progress bar\n old_stdout = sys.stdout\n sys.stdout = open('/dev/stdout', 'w')\n\n progress_bar(batch_idx, len(self.testloader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'\n % (test_loss/(batch_idx+1), 100.*correct/total, correct, total))\n \n sys.stdout = old_stdout\n # -----------------------\n \n # Save checkpoint.\n acc = 100.*correct/total\n if acc > self.best_acc:\n self.best_acc = acc\n if save:# or epoch==0:\n sys.__stdout__.write('Saving..\\n')\n if 'module' in model._modules.keys():\n model = model.module\n \n state = {\n 'net': model.state_dict(),\n 'acc': acc,\n 'epoch': epoch,\n 'cfg': model.cfg,\n }\n# save_path = 'checkpoint/%s/ckpt_ft_%f.t7'%(model.name,self.sparsity)\n torch.save(state, save)\n \n return acc, time_all\n \n\n\n\n \n \n \n \n \nif __name__ == \"__main__\":\n \n \n import torch.backends.cudnn as cudnn\n import os,sys\n sys.path.append(os.getcwd())\n from models import * \n \n import argparse\n parser = argparse.ArgumentParser(description='PyTorch CIFAR10 Training')\n parser.add_argument('--model', '-m', default='vgg19', type=str, help='model architecture')\n args = parser.parse_args()\n \n timestamp = int(time.time())\n os.environ['CUDA_VISIBLE_DEVICES'] = '1,2,3'\n net = VGG(args.model)\n \n device = 'cuda' if torch.cuda.is_available() else 'cpu'\n net = net.to(device)\n\n ckpt_dir = './checkpoint/%s'%net.name\n if not os.path.exists(ckpt_dir): \n os.makedirs(ckpt_dir)\n checkpoint_path = '%s/ckpt.t7'%ckpt_dir\n\n # if not already exists, train one\n if not os.path.exists(checkpoint_path):\n os.system(\"python main.py --resume --lr=0.01 --model %s\"%net.name)\n \n net.load_state_dict(torch.load(checkpoint_path)['net'])\n\n print(net)\n \n \n import pandas as pd\n\n sparsity = np.linspace(0,1,21)[1:-1]#[0.36]#->0.64 #\n\n \n ft_ep = 100\n ft_leaningrate = 5e-2\n\n df_res = pd.DataFrame(np.zeros((len(sparsity), ft_ep+3)), index=sparsity)\n df_res.columns = list(df_res.columns)[:-3] + ['maxAcc', 'modSize', 'infTime']\n\n \n res_dir = './checkpoint/%s/results'%net.name\n if not os.path.exists(res_dir):\n os.mkdir(res_dir)\n \n for s in sorted(sparsity, reverse=True):\n print(\"sparsity = %g\"%s, end=\"\\t\")\n _, df_res = prune_by_sparsity(net, s, ft_ep, ft_leaningrate, df_res, plot=False)\n print(\"best accuracy = %g\"%df_res.at[s, 'maxAcc'])\n df_res.to_pickle(\"%s/resDf_%d.pkl\"%(res_dir,timestamp))\n\n print(df_res)\n \n \n \n \n \n \n \n \n \n \n \n","sub_path":"prune.py","file_name":"prune.py","file_ext":"py","file_size_in_byte":20885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"600059709","text":"import torch\nfrom torch.optim.optimizer import Optimizer, required\n\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nfrom torch import nn\nfrom torch import Tensor\nfrom torch.nn import Parameter\n\ndef l2normalize(v, eps=1e-12):\n return v / (v.norm() + eps)\n\nclass LayerNorm(nn.Module):\n\n def __init__(self, num_features, eps=1e-5, affine=True):\n super(LayerNorm, self).__init__()\n self.num_features = num_features\n self.affine = affine\n self.eps = eps\n\n if self.affine:\n self.gamma = nn.Parameter(torch.Tensor(num_features).uniform_())\n self.beta = nn.Parameter(torch.zeros(num_features))\n\n def forward(self, x):\n # This implementation is too slow!!!\n\n shape = [-1] + [1] * (x.dim() - 1)\n mean = x.view(x.size(0), -1).mean(1).view(*shape)\n std = x.view(x.size(0), -1).std(1).view(*shape)\n y = (x - mean) / (std + self.eps)\n if self.affine:\n shape = [1, -1] + [1] * (x.dim() - 2)\n y = self.gamma.view(*shape) * y + self.beta.view(*shape)\n return y\n\n\nclass SpectralNorm2d(nn.Module):\n def __init__(self, module, name='weight', power_iterations=1):\n super().__init__()\n self.module = module\n self.name = name\n self.power_iterations = power_iterations\n if not self._made_params():\n self._make_params()\n\n def _update_u_v(self):\n u = getattr(self.module, self.name + \"_u\")\n v = getattr(self.module, self.name + \"_v\")\n w = getattr(self.module, self.name + \"_bar\")\n\n height = w.data.shape[0]\n for _ in range(self.power_iterations):\n v.data = l2normalize(torch.mv(torch.t(w.view(height,-1).data), u.data))\n u.data = l2normalize(torch.mv(w.view(height,-1).data, v.data))\n\n # sigma = torch.dot(u.data, torch.mv(w.view(height,-1).data, v.data))\n sigma = u.dot(w.view(height, -1).mv(v))\n setattr(self.module, self.name, w / sigma.expand_as(w))\n\n def _made_params(self):\n try:\n u = getattr(self.module, self.name + \"_u\")\n v = getattr(self.module, self.name + \"_v\")\n w = getattr(self.module, self.name + \"_bar\")\n return True\n except AttributeError:\n return False\n\n\n def _make_params(self):\n w = getattr(self.module, self.name)\n\n height = w.data.shape[0]\n width = w.view(height, -1).data.shape[1]\n\n u = Parameter(w.data.new(height).normal_(0, 1), requires_grad=False)\n v = Parameter(w.data.new(width).normal_(0, 1), requires_grad=False)\n u.data = l2normalize(u.data)\n v.data = l2normalize(v.data)\n w_bar = Parameter(w.data)\n\n del self.module._parameters[self.name]\n\n self.module.register_parameter(self.name + \"_u\", u)\n self.module.register_parameter(self.name + \"_v\", v)\n self.module.register_parameter(self.name + \"_bar\", w_bar)\n\n\n def forward(self, *args):\n self._update_u_v()\n return self.module.forward(*args)\n","sub_path":"Models/layer.py","file_name":"layer.py","file_ext":"py","file_size_in_byte":3059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"119415923","text":"from bs4 import BeautifulSoup\n\nimport requests\n\nurl = input(\"\")\n\nr = requests.get(\"http://\" +url)\n\ndata = r.text\n\nsoup = BeautifulSoup(data, features='lxml')\n\nfor link in soup.find_all('a'):\n print(link.get('href'))\n","sub_path":"pychromecast/examples/get_media_simple.py","file_name":"get_media_simple.py","file_ext":"py","file_size_in_byte":220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"339035331","text":"#!/usr/bin/python\n'''The MIT License (MIT)\nCopyright (c) 2017 Yu Xiong Wei(try.dash.now@gmail.com)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.'''\n__author__ = 'sean yu (Yu, Xiongwei)'\n__doc__ = '''\nit's GUI of DasH aka Do as Human\ncreated 2017-08-12 by Sean Yu\n'''\n\n\nimport wx.grid as gridlib\nimport wx\nfrom gui.MainFrame import MainFrame\nimport os\nfrom lib.common import load_bench, caller_stack_info, get_next_in_ring_list, get_folder_item, info,debug, warn, error\nimport re\nimport time\nimport threading\nfrom lib.dut import dut\nimport ConfigParser\nimport sys\nimport inspect\nimport Queue\nimport webbrowser\nfrom datetime import datetime\nimport traceback\nclass SessionTab(wx.Panel, dut):\n stdout=None\n stderr=None\n parent = None\n type = type\n output_window = None\n cmd_window = None\n #session = None\n alive =False\n output_lock = None\n font_point = None\n cmd_window_font_size = 19\n history_cmd = None\n history_cmd_index = 0\n sequence_queue =None\n log_path =None\n name = None\n error_pattern =None\n last_json_file_saving_time=None\n def __del__(self):\n\n self.on_close()\n def on_close(self):\n self.alive = False\n self.close_session()\n self.sleep(0.001)\n info('tab {} closed!!!'.format(self.name))\n\n def __freeze_output_window(self):\n if self.output_window.IsFrozen():\n pass\n else:\n self.output_window_last_position =self.output_window.GetScrollRange(wx.VERTICAL)\n self.output_window.Freeze()\n def __thaw_output_window(self):\n self.output_window.SetScrollPos(wx.VERTICAL, self.output_window.GetScrollRange(wx.VERTICAL))\n if self.output_window.IsFrozen():\n self.output_window.Thaw()\n else:\n pass\n\n def update_output(self):\n last = self.output_window.GetLastPosition()\n status =True\n ansi_escape = re.compile(r'\\x1b[^m]*m*|'+r'\\x1b(' \\\n r'(\\[\\??\\d+[hl])|' \\\n r'([=<>a-kzNM78])|' \\\n r'([\\(\\)][a-b0-2])|' \\\n r'(\\[\\d{0,2}[ma-dgkjqi])|' \\\n r'(\\[\\d+;\\d+[hfy]?)|' \\\n r'(\\[;?[hf])|' \\\n r'(#[3-68])|' \\\n r'([01356]n)|' \\\n r'(O[mlnp-z]?)|' \\\n r'(/Z)|' \\\n r'(\\d+)|' \\\n r'(\\[\\?\\d;\\d0c)|' \\\n r'(\\d;\\dR))'\n , flags=re.IGNORECASE)\n BACKSPACE_pat =re.compile('(\\s*\\b+\\n*\\s*)+')\n alive = self.alive\n while( alive):\n try:\n self.alive\n except Exception as e:\n alive = False\n break\n try:\n status = self.alive #and self.session\n\n time.sleep(0.001)\n response=''\n #print('scroll pos', self.output_window.GetScrollPos(wx.VERTICAL), self.output_window.GetScrollRange(wx.VERTICAL))\n if self.alive:\n #self.output_lock.acquire()\n response = self.read_display_buffer()\n if True:\n response = ansi_escape.sub('', response)\n response = BACKSPACE_pat.sub('\\n', response)\n #response = re.sub().replace('\\b', '')\n BACKSPACE = chr(8)\n #response = re.sub(chr(32)+BACKSPACE,'',response)\n\n #BACKSPACE_pat = '.'+BACKSPACE#+'\\[\\d+[;]{0,1}\\d*m'#+chr(27)+'\\[0'\n #print(self.name, 'alive!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')\n if len(response)!=0:\n\n current_pos = self.output_window.GetScrollPos(wx.VERTICAL)\n v_scroll_range = self.output_window.GetScrollRange(wx.VERTICAL)\n char_height = self.output_window.GetCharHeight()\n w_client,h_client = self.output_window.GetClientSize()\n max_gap=h_client*2/char_height/3\n c_col, c_line = self.output_window.PositionToXY(current_pos)\n t_col, t_line = self.output_window.PositionToXY(v_scroll_range)\n\n if t_line- c_line>max_gap:#1000\n self.__freeze_output_window()\n else:\n self.__thaw_output_window()\n err_pattern = self.error_pattern#re.compile('error|\\s+err\\s+|fail|wrong')\n wx.CallAfter(self.output_window.SetDefaultStyle,wx.TextAttr(wx.GREEN, wx.BLACK,font =wx.Font(self.font_point, family = wx.DEFAULT, style = wx.NORMAL, weight = wx.NORMAL, faceName = 'Consolas')))\n\n #if re.search('error|\\s+err\\s+|fail|wrong',response.lower()):\n last_start = 0\n\n for m in err_pattern.finditer(response.lower()):\n #print(m.start(), m.end(), m.group())\n\n wx.CallAfter(self.output_window.SetDefaultStyle,wx.TextAttr(wx.GREEN, wx.BLACK,font =wx.Font(self.font_point, family = wx.DEFAULT, style = wx.NORMAL, weight = wx.NORMAL, faceName = 'Consolas')))\n wx.CallAfter(self.output_window.AppendText, response[last_start:m.start()])\n wx.CallAfter(self.output_window.SetDefaultStyle,wx.TextAttr(wx.YELLOW, wx.RED, font =wx.Font(self.font_point+2, family = wx.DEFAULT, style = wx.NORMAL, weight = wx.NORMAL, faceName = 'Consolas')))\n wx.CallAfter(self.output_window.AppendText, response[m.start():m.end()])\n last_start= m.end()\n\n wx.CallAfter(self.output_window.SetDefaultStyle,wx.TextAttr(wx.GREEN, wx.BLACK,font =wx.Font(self.font_point, family = wx.DEFAULT, style = wx.NORMAL, weight = wx.NORMAL, faceName = 'Consolas')))\n wx.CallAfter(self.output_window.AppendText, response[last_start:])\n\n\n # else:\n # #self.output_window.SetDefaultStyle( wx.TextAttr(wx.GREEN, wx.BLACK,font =wx.Font(self.font_point, family = wx.DEFAULT, style = wx.NORMAL, weight = wx.NORMAL, faceName = 'Consolas')))\n # wx.CallAfter(self.output_window.SetDefaultStyle,wx.TextAttr(wx.GREEN, wx.BLACK,font =wx.Font(self.font_point, family = wx.DEFAULT, style = wx.NORMAL, weight = wx.NORMAL, faceName = 'Consolas')))\n # wx.CallAfter(self.output_window.AppendText, response)\n if False:\n whole_text = self.output_window.GetValue()\n m = re.search('[^\\b]\\b',whole_text)\n while m:\n self.output_window.Remove(m.start(), m.end())\n whole_text = self.output_window.GetValue()\n m = re.search('[^\\b]\\b',whole_text)\n if t_line -c_line>max_gap:\n pass\n else:\n wx.CallAfter(self.output_window.SetScrollPos,wx.VERTICAL, self.output_window.GetScrollRange(wx.VERTICAL))#SetInsertionPoint(self.output_window.GetLastPosition())\n self.__thaw_output_window()\n\n except Exception as e :\n time.sleep(0.05)\n error(traceback.format_exc())\n break\n try:\n pass\n #if self.output_lock.locked():\n #self.output_lock.release()\n except Exception as e:\n error('{}'.format(e))\n time.sleep(0.5)\n\n\n def __init__(self, parent, name,attributes, seq_queue=None, log_path = '../log'):\n #init a session, and stdout, stderr, redirected to\n wx.Panel.__init__(self, parent)\n attributes['log_path']= log_path\n attributes['not_call_open']=True\n\n self.name = name\n self.history_cmd=[]\n self.history_cmd_index = 0\n self.parent = parent\n #self.type = attributes['type']\n self.sequence_queue= seq_queue\n self.output_lock = threading.Lock()\n #wx.stc.StyledTextCtrl #wx.richtext.RichTextCtrl\n dut.__init__(self, name, **attributes)\n self.output_window = wx.TextCtrl( self, -1, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, wx.TE_AUTO_URL|wx.VSCROLL|wx.TE_RICH|wx.TE_READONLY |wx.TE_MULTILINE&(~wx.TE_PROCESS_ENTER))#0|wx.VSCROLL|wx.HSCROLL|wx.NO_BORDER|wx.TE_READONLY )\n self.cmd_window= wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, wx.TE_PROCESS_ENTER|wx.TE_MULTILINE|wx.VSCROLL )\n\n self.font_point = self.output_window.GetFont().PointSize+2\n self.error_pattern = re.compile('error|\\s+err\\s+|fail|wrong|errno')\n sizer = wx.BoxSizer(wx.VERTICAL)\n sizer.Add(self.output_window, 9, wx.EXPAND)\n sizer.Add(self.cmd_window, 0, wx.EXPAND)\n self.SetSizer(sizer)\n #from lib.common import create_session\n info (os.curdir)\n #self.Bind(wx.EVT_CLOSE, self.on_close)\n #parent.Bind(wx.aui.EVT_AUINOTEBOOK_PAGE_CLOSED, self.on_close, parent)\n #self.cmd_window.Bind(wx.EVT_TEXT_ENTER, self.on_enter_a_command)\n #self.output_window.Bind(wx.EVT_SCROLLWIN , self.on_scroll_changed)\n self.cmd_window.Bind(wx.EVT_KEY_UP, self.on_key_up)\n self.cmd_window.Bind(wx.EVT_KEY_DOWN, self.on_key_down)\n self.cmd_window.Bind(wx.EVT_MOUSEWHEEL, self.OnMouseWheel_cmd_window)\n self.cmd_window.Bind(wx.EVT_CHAR, self.on_press_enter)\n self.output_window.SetBackgroundColour('Black')\n self.output_window.SetDefaultStyle(wx.TextAttr(wx.GREEN, wx.BLACK, font =wx.Font(9, family = wx.DEFAULT, style = wx.NORMAL, weight = wx.NORMAL, faceName = 'Consolas')))\n self.cmd_window.SetDefaultStyle(wx.TextAttr(font =wx.Font(19, family = wx.DEFAULT, style = wx.NORMAL, weight = wx.NORMAL, faceName = 'Consolas')))\n self.cmd_window.SetFocus()\n self.output_window.Bind(wx.EVT_TEXT_URL,self.on_leftD_click_url_in_output)\n self.Bind(wx.EVT_IDLE, self.on_idle)\n f =self.cmd_window.GetFont()\n f.PointSize= self.cmd_window_font_size\n self.cmd_window.SetFont(f)\n #self.session = self\n self.alive =True\n self.last_json_file_saving_time=datetime.now()\n th =threading.Thread(target=self.update_output)\n th.start()\n #self.sleep(0.1)\n\n\n th1 = threading.Thread(target=self.open, args= [self.retry_login,60])#, kwargs=attributes)\n th1.start()\n\n\n\n def on_key_up(self, event):\n keycode = event.KeyCode\n\n increase =False\n if keycode ==wx.WXK_UP:\n #self.history_cmd_index= self.history_cmd_index-1 if self.history_cmd_index>0 else len(self.history_cmd)-1\n #get_next_in_ring_list(self.history_cmd_index,self.history_cmd,increase=True)\n pass\n elif keycode ==wx.WXK_DOWN:\n increase =True#\n #self.history_cmd_index= self.history_cmd_index+1 if self.history_cmd_index 0:\n if cmd[-1] in ['?', \"\\t\"]:\n add_newline =False\n lcmd =len(cmd)-1\n cmd ='\\b'*lcmd*4 +cmd + '\\b'*lcmd*4\n th = threading.Thread(target=self.write,args=( cmd,ctrl, add_newline))\n th.start()\n self.sequence_queue.put([\"TC.step(DUT['{}'], '{}')\".format(self.name,cmd.encode(errors= 'ignore')), datetime.now()])#\n else:\n th =threading.Thread(target=self.open, args=[1,60]) #self.alive= self.session#.session_status\n th.start()\n #self.write(cmd,ctrl=ctrl)\n except Exception as e:\n error_msg = traceback.format_exc()\n #self.on_close()\n #self.close_session()\n error ('{} closed unexpected\\n{}'.format(self.name, error_msg))\n #self.alive= False\n #event.Skip()\n self.cmd_window.Clear()\n self.cmd_window.SetValue('')\n self.cmd_window.ShowPosition(100)\n self.cmd_window.SetFocus()\n def add_cmd_to_history(self, cmd):\n if self.history_cmd==[]:\n self.history_cmd.append(cmd)\n elif self.history_cmd[-1]==cmd:\n pass\n else:\n self.history_cmd.append(cmd)\n self.history_cmd_index= len(self.history_cmd)\n def on_key_down(self, event):\n try:\n keycode = event.KeyCode\n if keycode ==wx.WXK_TAB:\n #deliver 2017-10-21 when hitted key_tab or ?, need don't need clear cmd_window--or re-enter the command again\n cmd_string = self.cmd_window.GetValue()\n self.cmd_window.AppendText('\\t')\n self.on_enter_a_command(event)\n self.cmd_window.AppendText(cmd_string)\n elif keycode in [wx.WXK_RETURN]:\n self.cmd_window.SetInsertionPointEnd()\n event.Skip()\n elif keycode == wx.PAPER_ENV_INVITE and wx.GetKeyState(wx.WXK_SHIFT):\n cmd_string = self.cmd_window.GetValue()\n self.cmd_window.AppendText('?')\n self.on_enter_a_command(event)\n self.cmd_window.AppendText(cmd_string)\n elif keycode >= ord('a') and keycode <= ord('Z') and event.controlDown:#keycode == ord('C') and\n data = self.cmd_window.GetStringSelection()\n if len(data)==0:\n self.sequence_queue.put([\"TC.step(DUT['{}'], '{}', ctrl=True)\".format(self.name,chr(keycode).encode(errors= 'ignore')), datetime.now()])#\n self.write(chr(keycode), ctrl=True, add_newline = False)\n\n\n elif keycode == ord('V') and event.controlDown:\n #self.sequence_queue.put([\"TC.step(DUT['{}'], '{}', ctrl=True)\".format(self.name,chr(keycode).encode(errors= 'ignore')), datetime.now()])#\n #self.write(chr(keycode), ctrl=True)\n if not wx.TheClipboard.IsOpened(): # may crash, otherwise\n do = wx.TextDataObject()\n wx.TheClipboard.Open()\n success = wx.TheClipboard.GetData(do)\n wx.TheClipboard.Close()\n if success:\n cmds = do.GetText()\n cmd = cmds.encode(errors= 'ignore')\n if '\\n' not in cmds:\n self.cmd_window.AppendText(cmd)\n else:\n for cmd in cmds.split('\\n'):\n ctrl = False\n add_newline = True\n self.add_cmd_to_history(cmd)\n try:\n if self.session_status:\n th = threading.Thread(target=self.write,args=( cmd,ctrl, add_newline))\n th.start()\n self.sequence_queue.put([\"TC.step(DUT['{}'], '{}')\".format(self.name,cmd.encode(errors= 'ignore')), datetime.now()])#\n th.join()\n else:\n pass #self.alive= self.session#.session_status\n #self.write(cmd,ctrl=ctrl)\n\n except Exception as e:\n error_msg = traceback.format_exc()\n error ('{} closed unexpected\\n{}'.format(self.name, error_msg))\n self.cmd_window.Clear()#append cmd to cmd_window\n self.cmd_window.SetFocus()\n\n else:\n event.Skip()\n\n elif keycode >= ord('A') and keycode <= ord('Z') and event.controlDown:\n info('ctrl+{}'.format(chr(keycode)))\n #done 2017-10-13 2017-10-12 if selected is not empty, ctrl+c should be copy, not send control code to session\n #done 2017-10-13 2017-10-12 if clipboard is not empty, ctrl+v should be paste not send control code to session\n self.sequence_queue.put([\"TC.step(DUT['{}'], '{}', ctrl=True)\".format(self.name,chr(keycode).encode(errors= 'ignore')), datetime.now()])#\n self.write(chr(keycode), ctrl=True)\n event.Skip()\n else:\n event.Skip()\n except Exception as e:\n error(traceback.format_exc())\n event.Skip()\n def OnMouseWheel_cmd_window(self,event):\n min_font_size = 5\n interval_step = 2\n if event.ControlDown():\n pass\n else:\n return\n\n if event.GetWheelRotation() < 0:\n if self.cmd_window_font_size>min_font_size:\n self.cmd_window_font_size-=interval_step\n else:\n self.cmd_window_font_size+=1\n\n f =self.cmd_window.GetFont()\n f.PointSize= self.cmd_window_font_size\n self.cmd_window.SetFont(f)\n\n self.Refresh()\n def on_leftD_click_url_in_output(self, event):\n mouseEvent = event.GetMouseEvent()\n if mouseEvent.LeftDClick():\n urlString = self.output_window.GetRange(event.GetURLStart(),event.GetURLEnd())\n webbrowser.open(urlString)\n event.Skip()\n\n def on_press_enter(self, event):\n if event.GetKeyCode() == 13:\n self.on_enter_a_command(event)\n else:\n event.Skip()\n\n\n def on_idle(self, event):\n try:\n #self.last_cmd_time_stamp\n max_idle_time = 60\n now = datetime.now()\n if (now-self.last_json_file_saving_time).total_seconds()> max_idle_time:\n self.save_dry_run_json()\n self.last_json_file_saving_time=now\n except Exception as e:\n error(e)\n event.Skip()\n#todo EVT_TEXT_CUT = wx.PyEventBinder( wxEVT_COMMAND_TEXT_CUT )\n#todo EVT_TEXT_COPY = wx.PyEventBinder( wxEVT_COMMAND_TEXT_COPY )\n#todo EVT_TEXT_PASTE = wx.PyEventBinder( wxEVT_COMMAND_TEXT_PASTE )","sub_path":"gui/SessionTab.py","file_name":"SessionTab.py","file_ext":"py","file_size_in_byte":20147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"341427968","text":"'''\n거스름돈\n타로는 자주 JOI잡화점에서 물건을 산다.\nJOI잡화점에는 잔돈으로 500엔, 100엔, 50엔, 10엔, 5엔, 1엔이 충분히 있고, 언제나 거스름돈 개수가 가장 적게 잔돈을 준다.\n타로가 JOI잡화점에서 물건을 사고 카운터에서 1000엔 지폐를 한장 냈을 때, 받을 잔돈에 포함된 잔돈의 개수를 구하는 프로그램을 작성하시오.\n\n예를 들어 입력된 예1의 경우에는 아래 그림에서 처럼 4개를 출력해야 한다.\n'''\n\nn = int(input())\nchange = 1000 - n\ncount = 0\n\ncoin_types = [500, 100, 50, 10, 5, 1]\n\nfor coin in coin_types:\n count += change // coin\n change = change % coin\n\nprint(count)","sub_path":"backjoon/greedy/5585.py","file_name":"5585.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"132741610","text":"import tkinter\nfrom time import strftime\n\n\n# Criando janela do relógio e sua configurações\n\njanela = tkinter.Tk()\njanela.title('Relógio Digital')\njanela.geometry('350x100+500+300')\n\nrelogio = tkinter.Label(width=20, height=20)\nrelogio.place(x=150, y=150)\nrelogio['font'] = 'Arial 55 bold'\nrelogio['background'] = 'black'\nrelogio['foreground'] = 'white'\nrelogio.pack(anchor = 'center')\n\n\n# Função responsável por atualizar as horas\n\ndef atualiza_horas():\n hora_atual = strftime('%H:%M:%S')\n relogio.config( text = hora_atual)\n relogio.after(1000, atualiza_horas)\n\n\n# Executando relógio\natualiza_horas()\n\njanela.mainloop()","sub_path":"relogio_digital.py","file_name":"relogio_digital.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"417954707","text":"# Задание синтетическое, значит объект request создадим вручную\nrequest = {\"headers\":{\"accept\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3\",\n \"accept-language\":\"ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7\",\n \"content-type\":\"application/x-www-form-urlencoded\"},\n \"referrerPolicy\":\"no-referrer-when-downgrade\",\n \"body\":\"PayData=05.10.2019&GayData=No+Gay&YesData=Yes+Yes+Yes&UserType=9185573494&Country=&DataCoding=utf-154&PersUserData=Mr.Hankey&Region=&FirstName=Steve&DataVaidTill=10.10.2020&Comment=No+Comments\",\n \"method\":\"POST\"}\nout_file = 'result.txt'\n\n\ndef parse_request(req):\n kw_data = list(map(lambda el: tuple(el.split('=')), req['body'].split('&')))\n kw_data = list(filter(lambda el: el[0].find('Data') > -1, kw_data))\n kw_data.sort(key=lambda item: (len(item[0]), item[0]))\n return kw_data\n\n\ndata = parse_request(request)\n\nwith open(out_file, mode='w') as f:\n f.write('{\"result\":{')\n for n in range(len(data)):\n el = data[n]\n if n < len(data) - 1:\n f.write('\"{}\":\"{}\",'.format(el[0], el[1]))\n else:\n f.write('\"{}\":\"{}\"'.format(el[0], el[1]))\n f.write('}}')\n","sub_path":"test1/form_submit_parser.py","file_name":"form_submit_parser.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"452948273","text":"# -------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n# --------------------------------------------------------------------------\n# pylint: disable=invalid-overridden-method\n\nimport asyncio\nimport random\nimport logging\nfrom typing import Any, TYPE_CHECKING\n\nfrom azure.core.pipeline.policies import AsyncBearerTokenCredentialPolicy, AsyncHTTPPolicy\nfrom azure.core.exceptions import AzureError\n\nfrom .authentication import StorageHttpChallenge\nfrom .constants import DEFAULT_OAUTH_SCOPE, STORAGE_OAUTH_SCOPE\nfrom .policies import is_retry, StorageRetryPolicy\n\nif TYPE_CHECKING:\n from azure.core.credentials_async import AsyncTokenCredential\n from azure.core.pipeline import PipelineRequest, PipelineResponse\n\n\n_LOGGER = logging.getLogger(__name__)\n\n\nasync def retry_hook(settings, **kwargs):\n if settings['hook']:\n if asyncio.iscoroutine(settings['hook']):\n await settings['hook'](\n retry_count=settings['count'] - 1,\n location_mode=settings['mode'],\n **kwargs)\n else:\n settings['hook'](\n retry_count=settings['count'] - 1,\n location_mode=settings['mode'],\n **kwargs)\n\n\nclass AsyncStorageResponseHook(AsyncHTTPPolicy):\n\n def __init__(self, **kwargs): # pylint: disable=unused-argument\n self._response_callback = kwargs.get('raw_response_hook')\n super(AsyncStorageResponseHook, self).__init__()\n\n async def send(self, request):\n # type: (PipelineRequest) -> PipelineResponse\n # Values could be 0\n data_stream_total = request.context.get('data_stream_total')\n if data_stream_total is None:\n data_stream_total = request.context.options.pop('data_stream_total', None)\n download_stream_current = request.context.get('download_stream_current')\n if download_stream_current is None:\n download_stream_current = request.context.options.pop('download_stream_current', None)\n upload_stream_current = request.context.get('upload_stream_current')\n if upload_stream_current is None:\n upload_stream_current = request.context.options.pop('upload_stream_current', None)\n\n response_callback = request.context.get('response_callback') or \\\n request.context.options.pop('raw_response_hook', self._response_callback)\n\n response = await self.next.send(request)\n await response.http_response.load_body()\n\n will_retry = is_retry(response, request.context.options.get('mode'))\n # Auth error could come from Bearer challenge, in which case this request will be made again\n is_auth_error = response.http_response.status_code == 401\n should_update_counts = not (will_retry or is_auth_error)\n\n if should_update_counts and download_stream_current is not None:\n download_stream_current += int(response.http_response.headers.get('Content-Length', 0))\n if data_stream_total is None:\n content_range = response.http_response.headers.get('Content-Range')\n if content_range:\n data_stream_total = int(content_range.split(' ', 1)[1].split('/', 1)[1])\n else:\n data_stream_total = download_stream_current\n elif should_update_counts and upload_stream_current is not None:\n upload_stream_current += int(response.http_request.headers.get('Content-Length', 0))\n for pipeline_obj in [request, response]:\n pipeline_obj.context['data_stream_total'] = data_stream_total\n pipeline_obj.context['download_stream_current'] = download_stream_current\n pipeline_obj.context['upload_stream_current'] = upload_stream_current\n if response_callback:\n if asyncio.iscoroutine(response_callback):\n await response_callback(response)\n else:\n response_callback(response)\n request.context['response_callback'] = response_callback\n return response\n\nclass AsyncStorageRetryPolicy(StorageRetryPolicy):\n \"\"\"\n The base class for Exponential and Linear retries containing shared code.\n \"\"\"\n\n async def sleep(self, settings, transport):\n backoff = self.get_backoff_time(settings)\n if not backoff or backoff < 0:\n return\n await transport.sleep(backoff)\n\n async def send(self, request):\n retries_remaining = True\n response = None\n retry_settings = self.configure_retries(request)\n while retries_remaining:\n try:\n response = await self.next.send(request)\n if is_retry(response, retry_settings['mode']):\n retries_remaining = self.increment(\n retry_settings,\n request=request.http_request,\n response=response.http_response)\n if retries_remaining:\n await retry_hook(\n retry_settings,\n request=request.http_request,\n response=response.http_response,\n error=None)\n await self.sleep(retry_settings, request.context.transport)\n continue\n break\n except AzureError as err:\n retries_remaining = self.increment(\n retry_settings, request=request.http_request, error=err)\n if retries_remaining:\n await retry_hook(\n retry_settings,\n request=request.http_request,\n response=None,\n error=err)\n await self.sleep(retry_settings, request.context.transport)\n continue\n raise err\n if retry_settings['history']:\n response.context['history'] = retry_settings['history']\n response.http_response.location_mode = retry_settings['mode']\n return response\n\n\nclass ExponentialRetry(AsyncStorageRetryPolicy):\n \"\"\"Exponential retry.\"\"\"\n\n def __init__(self, initial_backoff=15, increment_base=3, retry_total=3,\n retry_to_secondary=False, random_jitter_range=3, **kwargs):\n '''\n Constructs an Exponential retry object. The initial_backoff is used for\n the first retry. Subsequent retries are retried after initial_backoff +\n increment_power^retry_count seconds. For example, by default the first retry\n occurs after 15 seconds, the second after (15+3^1) = 18 seconds, and the\n third after (15+3^2) = 24 seconds.\n\n :param int initial_backoff:\n The initial backoff interval, in seconds, for the first retry.\n :param int increment_base:\n The base, in seconds, to increment the initial_backoff by after the\n first retry.\n :param int max_attempts:\n The maximum number of retry attempts.\n :param bool retry_to_secondary:\n Whether the request should be retried to secondary, if able. This should\n only be enabled of RA-GRS accounts are used and potentially stale data\n can be handled.\n :param int random_jitter_range:\n A number in seconds which indicates a range to jitter/randomize for the back-off interval.\n For example, a random_jitter_range of 3 results in the back-off interval x to vary between x+3 and x-3.\n '''\n self.initial_backoff = initial_backoff\n self.increment_base = increment_base\n self.random_jitter_range = random_jitter_range\n super(ExponentialRetry, self).__init__(\n retry_total=retry_total, retry_to_secondary=retry_to_secondary, **kwargs)\n\n def get_backoff_time(self, settings):\n \"\"\"\n Calculates how long to sleep before retrying.\n\n :param Optional[Dict[str, Any]] settings: The configurable values pertaining to the backoff time.\n :return:\n An integer indicating how long to wait before retrying the request,\n or None to indicate no retry should be performed.\n :rtype: int or None\n \"\"\"\n random_generator = random.Random()\n backoff = self.initial_backoff + (0 if settings['count'] == 0 else pow(self.increment_base, settings['count']))\n random_range_start = backoff - self.random_jitter_range if backoff > self.random_jitter_range else 0\n random_range_end = backoff + self.random_jitter_range\n return random_generator.uniform(random_range_start, random_range_end)\n\n\nclass LinearRetry(AsyncStorageRetryPolicy):\n \"\"\"Linear retry.\"\"\"\n\n def __init__(self, backoff=15, retry_total=3, retry_to_secondary=False, random_jitter_range=3, **kwargs):\n \"\"\"\n Constructs a Linear retry object.\n\n :param int backoff:\n The backoff interval, in seconds, between retries.\n :param int max_attempts:\n The maximum number of retry attempts.\n :param bool retry_to_secondary:\n Whether the request should be retried to secondary, if able. This should\n only be enabled of RA-GRS accounts are used and potentially stale data\n can be handled.\n :param int random_jitter_range:\n A number in seconds which indicates a range to jitter/randomize for the back-off interval.\n For example, a random_jitter_range of 3 results in the back-off interval x to vary between x+3 and x-3.\n \"\"\"\n self.backoff = backoff\n self.random_jitter_range = random_jitter_range\n super(LinearRetry, self).__init__(\n retry_total=retry_total, retry_to_secondary=retry_to_secondary, **kwargs)\n\n def get_backoff_time(self, settings):\n \"\"\"\n Calculates how long to sleep before retrying.\n\n :param Optional[Dict[str, Any]] settings: The configurable values pertaining to the backoff time.\n :return:\n An integer indicating how long to wait before retrying the request,\n or None to indicate no retry should be performed.\n :rtype: int or None\n \"\"\"\n random_generator = random.Random()\n # the backoff interval normally does not change, however there is the possibility\n # that it was modified by accessing the property directly after initializing the object\n random_range_start = self.backoff - self.random_jitter_range \\\n if self.backoff > self.random_jitter_range else 0\n random_range_end = self.backoff + self.random_jitter_range\n return random_generator.uniform(random_range_start, random_range_end)\n\n\nclass AsyncStorageBearerTokenCredentialPolicy(AsyncBearerTokenCredentialPolicy):\n \"\"\" Custom Bearer token credential policy for following Storage Bearer challenges \"\"\"\n\n def __init__(self, credential, **kwargs):\n # type: (AsyncTokenCredential, **Any) -> None\n super(AsyncStorageBearerTokenCredentialPolicy, self).__init__(credential, STORAGE_OAUTH_SCOPE, **kwargs)\n\n async def on_challenge(self, request, response):\n # type: (PipelineRequest, PipelineResponse) -> bool\n try:\n auth_header = response.http_response.headers.get(\"WWW-Authenticate\")\n challenge = StorageHttpChallenge(auth_header)\n except ValueError:\n return False\n\n scope = challenge.resource_id + DEFAULT_OAUTH_SCOPE\n await self.authorize_request(request, scope, tenant_id=challenge.tenant_id)\n\n return True\n","sub_path":"sdk/storage/azure-storage-file-datalake/azure/storage/filedatalake/_shared/policies_async.py","file_name":"policies_async.py","file_ext":"py","file_size_in_byte":11742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"96230419","text":"from django.conf.urls import patterns, url, include\n# from django.views.generic import TemplateView\nfrom apps.main.views import (\n AboutView, ShowAllEntries, PhraseDetailsView,\n AllPostsView, AddPostView, PostDetailView, PostUpdateView,\n AllSuggestionsView, PostDeleteView, SuggestionDeleteView,\n)\nfrom tastypie.api import Api\nfrom apps.main.api import UserSuggestionResource, UserResource\npost_user_api = Api(api_name='post_user_api')\npost_user_api.register(UserSuggestionResource())\npost_user_api.register(UserResource())\n# from .views import home\n\nurlpatterns = patterns('apps.main.views',\n url(r'^$', 'home', name='home'),\n url(r'^show_all/', 'show_all', name='show_all'),\n url(r'^show_all2/', ShowAllEntries.as_view(), name='show_all2'),\n url(r'^show_all_posts/', AllPostsView.as_view(), name='show_all_posts'),\n url(r'^add_post/', AddPostView.as_view(success_url='/show_all_posts'), name='add_post'),\n url(r'^post_detail/(?P[0-9a-zA-Z-]+)', PostDetailView.as_view(), name='post_detail'),\n # url(r'^post_detail/(?P\\d+)', PostDetailView.as_view(), name='post_detail'),\n url(r'^post_update/(?P\\d+)', PostUpdateView.as_view(), name='post_update'),\n url(r'^post_delete/(?P\\d+)', PostDeleteView.as_view(), name='post_delete'),\n url(r'^show_exact/(?P\\d+)', PhraseDetailsView.as_view(\n context_object_name=\"obj\"), name='show_exact'),\n # url(r'^cbv/', 'cbv', name='cbv'),\n url(r'^about/$', AboutView.as_view()),\n url(r'^all_suggestions/$', AllSuggestionsView.as_view(), name='all_suggestions'),\n url(r'^send_suggestion/$', 'send_suggestion', name='send_suggestion'),\n url(r'^suggestion_delete/(?P\\d+)$', SuggestionDeleteView.as_view(), name='suggestion_delete'),\n # url(r'^add/', 'add', name='add'),\n)\n\nurlpatterns += patterns('apps.main.views',\n url(r'^api/', include(post_user_api.urls)),\n)\n","sub_path":"apps/main/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"598110417","text":"#encoding:utf-8\nimport logging\nimport os\nimport linecache\nimport datetime\n\nos.popen('>1652814-hw1-q3.log')\nlogging.basicConfig(filename='1652814-hw1-q3.log',\n format='%(message)s')\n\nfilename_2='./1652814-hw1-q2.log'\n\n#行数\nend=len(open(filename_2,'r').readlines())\nlogging.warning(end)\n#print end\n\n#时间差\ntime_1=linecache.getline(filename_2,1)\ntime_end=linecache.getline(filename_2,end)\ntime_1=datetime.datetime.strptime(time_1[1:9],'%H:%M:%S')\ntime_end=datetime.datetime.strptime(time_end[1:9],'%H:%M:%S')\ninter=(time_end-time_1).seconds\nlogging.warning(inter)\n\n#平均质\nsum=0\nfor line in file(filename_2):\n str=line[51:55]\n count=float(str)\n sum=sum+count\naverge=sum/end\nlogging.warning(averge)\n\n#字符总数\ndef prime(a):\n for i in range(2,a):\n if a%i == 0:\n return False\n if i == a-1:\n return True\n\nprimelist = filter(prime,range(2,1000))\nprimelist.insert(0,2)\n\nsum=0\nfor i in primelist:\n sum+=len(linecache.getline(filename_2,i))\nlogging.warning(sum)","sub_path":"homework/1652814-hw1-q3.py","file_name":"1652814-hw1-q3.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"6825593","text":"from django import forms\nfrom django.forms import Textarea, SelectMultiple, TextInput\n\nfrom . import models\n\n\nclass ArticleForm(forms.ModelForm):\n class Meta:\n model = models.Article\n fields = ['title', 'content', 'tags']\n\n widgets = {\n 'title': TextInput(attrs={'class': 'form-control'}),\n 'content': Textarea(attrs={'class': 'form-control'}),\n 'tags': SelectMultiple(attrs={'class': 'form-control'}),\n }\n labels = {\n \"title\": \"Title\",\n \"content\": \"Content\",\n \"tags\": \"Tags\"\n }\n\n\nclass CommentForm(forms.ModelForm):\n article = forms.IntegerField(widget=forms.HiddenInput(), initial=0)\n\n class Meta:\n model = models.Comment\n fields = ['content']\n widgets = {\n 'content': Textarea(attrs={'rows': 5, 'class': 'form-control'})\n }\n labels = {\n 'content': 'Write your comment.'\n }\n","sub_path":"blog/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"376895351","text":"import os\nimport pathlib\nimport subprocess\nclass noscli:\n \n def run(file):\n path = pathlib.Path(__file__).parent.resolve()\n project = os.path.abspath(os.getcwd())\n \n print(\"PATH\", path)\n print(\"PROJECT\", project)\n nosFile = project+\"\\\\\"+file\n code = open(nosFile, \"r\")\n print(\"Executando\", nosFile)\n #subprocess.Popen( \"start \\\"\"+nosFile+\"\\\"\", shell=True, stdout=subprocess.PIPE ).wait()\n print(\"Finalizamos..............................................................\")\n print(code.read())\n \n while True:\n cm = input(\"nos-> \")\n cm = cm.strip().split(\"->\")\n if cm[0].strip() ==\"run\":\n run(cm[1].strip())\n else:\n print(\"Nenhum comando!\")\n\n ","sub_path":"nos-ide/bin/nos.py","file_name":"nos.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"26938831","text":"# Any copyright is dedicated to the Public Domain.\n# http://creativecommons.org/publicdomain/zero/1.0/\n\nfrom nagini_contracts.contracts import *\n\nclass Cell:\n def __init__(self, n: object) -> None:\n self.cnts = n\n Fold(self.val())\n Ensures(self.val() and self.get_contents() is n)\n\n @Predicate\n def val(self) -> bool:\n return Acc(self.cnts)\n\n @Pure\n def get_contents(self) -> object:\n Requires(self.val())\n return Unfolding(self.val(), self.cnts)\n\n def set(self, n: object) -> None:\n Requires(self.val())\n Ensures(self.val() and self.get_contents() is n)\n Unfold(self.val())\n self.cnts = n\n Fold(self.val())\n\n\nclass ReCell(Cell):\n def __init__(self, n: object) -> None:\n self.bak = None # type: object\n super(ReCell, self).__init__(n)\n Fold(self.val())\n Ensures(self.val() and self.get_contents() is n)\n\n @Predicate\n def val(self) -> bool:\n return Acc(self.bak)\n\n @Pure\n def get_last(self) -> object:\n Requires(self.val())\n return Unfolding(self.val(), self.bak)\n\n def set(self, n: object) -> None:\n Requires(self.val())\n Ensures(self.val() and self.get_contents() is n and\n self.get_last() is Old(self.get_contents()))\n Unfold(self.val())\n self.bak = self.cnts\n self.cnts = n\n Fold(self.val())\n\n def undo(self) -> None:\n Requires(self.val())\n Ensures(self.val() and self.get_contents() is Old(self.get_last()))\n Unfold(self.val())\n self.cnts = self.bak\n Fold(self.val())\n\ndef cell_client_1() -> None:\n c = Cell(4) \n assert(c.get_contents() == 4)\n c.set(True)\n assert c.get_contents()\n\ndef cell_client_2() -> None:\n c = Cell(5)\n c.set(4)\n #:: ExpectedOutput(assert.failed:assertion.false)\n assert(c.get_contents() == 5)\n\ndef recell_client_1() -> None:\n c = ReCell(25) \n assert(c.get_contents() == 25)\n c.set(35)\n y = c.get_contents()\n assert(y == 35)\n c.undo()\n assert(c.get_contents() == 25)\n\ndef recell_client_2() -> None:\n c = ReCell(25) \n assert(c.get_contents() == 25)\n c.set(35)\n y = c.get_contents()\n assert(y == 35)\n c.undo()\n #:: ExpectedOutput(assert.failed:assertion.false)\n assert(c.get_contents() == 35)\n\ndef loop_client(n: int) -> None:\n Requires(n > 0) \n c = Cell(35)\n for i in range(0,n):\n c.set(i)\n if i == 2:\n #:: ExpectedOutput(assert.failed:assertion.false)\n assert(c.get_contents() == i+1)\n else:\n assert(c.get_contents() == i) \n\n\n\n","sub_path":"examples/nagini/parkinson_recell.py","file_name":"parkinson_recell.py","file_ext":"py","file_size_in_byte":2663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"508987559","text":"from django.forms import forms\nfrom south.modelsinspector import add_introspection_rules\nfrom validatedfile.fields import ValidatedFileField\nimport pyclamav\n\n\nclass RWValidatedFileField(ValidatedFileField):\n \"\"\"\n Same as FileField, but you can specify:\n * content_types - list containing allowed content_types. \n Example: ['application/pdf', 'image/jpeg']\n \"\"\"\n def __init__(self, content_types=None, **kwargs):\n if content_types:\n self.content_types = content_types\n\n super(RWValidatedFileField, self).__init__(**kwargs)\n\n def clean(self, *args, **kwargs): \n # ValidatedFileField.clean will check the MIME type from the \n # http headers and by peeking in the file\n data = super(RWValidatedFileField, self).clean(*args, **kwargs)\n\n file = data.file\n\n # next scan with pyclamav\n tmpfile = file.file.name\n has_virus, virus_name = pyclamav.scanfile(tmpfile)\n if has_virus:\n fn = file.name\n raise forms.ValidationError(\n 'The file %s you uploaded appears to contain a virus or be'\n 'malware (%s).' % (fn, virus_name)\n )\n \n return data\n\n\nadd_introspection_rules([], [\"^roundware\\.rw\\.fields\\.RWValidatedFileField\"]) \n","sub_path":"roundware/rw/fields.py","file_name":"fields.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"148677145","text":"import random\n\ndef shuffle(deck):\n\t# move through the deck, swapping each index with some random index\n\tn = len(deck)\n\tfor i in range(n-1):\n\t\tswapindex = i + random.randrange(n-i)\n\t\ttemp = deck[i]\n\t\tdeck[i] = deck[swapindex]\n\t\tdeck[swapindex] = temp\n\ndef random_permutation(n):\n\t# create a list of {0,2,...,n-1}\n\tdeck = range(n)\n\tshuffle(deck)\n\treturn deck\n\ndef rotatelist(mylist,k):\n\tn = len(mylist)\n\tnewlist = []\n\tfor i in range(n):\n\t\tnewlist.append(mylist[(k+i)%n])\n\treturn newlist\n\ndef walk(through,i,memory):\n\t# walk through one cycle\n\tif through[i] in memory:\n\t\t# we want a canonical representation, so put the smallest number first\n\t\tminpos = memory.index(min(memory))\n\t\treturn rotatelist(memory,minpos)\n\t\treturn memory\n\telse:\n\t\treturn walk(through,through[i],memory+[through[i]])\n\n\ndef selfcompose(perm):\n\t# [1 2 3 4 5]\n\t# [2 4 3 5 1]\n\t# [4 5 3 1 2]\n\tnewperm = perm[:]\n\tfor count,i in enumerate(perm):\n\t\tnewperm[count] = perm[perm[count]]\n\treturn newperm\n\nclass Perm:\n\tdef __init__(self,perm):\n\t\tself.perm = perm\n\t\tself.cycles = self.cycle_decomp()\n\t\tself.n = len(self.perm)\n\t\t# maybe define acting on what ... group actions\n\tdef cycle_decomp(self):\n\t\tperm = self.perm\n\t\ttoconsider = range(len(perm))\n\t\tcycles = []\n\t\twhile toconsider:\n\t\t\tstart = toconsider[0] # get some element we haven't seen before\n\t\t\tcycle = walk(perm,start,[])\n\t\t\tfor i in cycle: toconsider.remove(i)\n\t\t\tcycles.append(cycle)\n\t\tcycles.sort(lambda x,y:cmp(x[0],y[0]))\n\t\treturn cycles\n\tdef __repr__(self):\n\t\treturn 'P%s'%self.perm\n\tdef __getitem__(self,i):\n\t\treturn self.perm[i]\n\tdef __rmul__(self,p2):\n\t\tnewperm = [0]*self.n\n\t\tfor i in range(self.n):\n\t\t\tnewperm[i] = p2[self[i]]\n\t\treturn Perm(newperm)\n\tdef inverse(self):\n\t\tnewperm = [0]*self.n\n\t\tfor i in range(self.n):\n\t\t\t# note, we are i -> self.perm[i]\n\t\t\t# so the inverse is\n\t\t\t# self.perm[i] -> i, i.e.\n\t\t\tnewperm[self.perm[i]] = i\n\t\treturn Perm(newperm)\n\tdef __pow__(self,exp):\n\t\tif exp == 0:\n\t\t\treturn self.identity()\n\t\telif exp == 1:\n\t\t\treturn self\n\t\telif exp < 0:\n\t\t\treturn pow(self.inverse(),-exp)\n\t\telse:\n\t\t\treturn self * pow(self,exp-1)\n\tdef __eq__(self,p2):\n\t\treturn self.perm == p2.perm\n\tdef identity(self):\n\t\treturn Perm(range(self.n))\n\tdef order(self):\n\t\tk = 0\n\t\tsofarperm = self.identity()\n\t\twhile 1:\n\t\t\tsofarperm = self * sofarperm\n\t\t\tk += 1\n\t\t\tif sofarperm == self.identity():\n\t\t\t\treturn k\n\tdef cycle(self):\n\t\tsofarperm = self.identity()\n\t\tcycle = []\n\t\twhile 1:\n\t\t\tcycle.append(sofarperm)\n\t\t\tsofarperm = self * sofarperm\n\t\t\tif sofarperm == self.identity():\n\t\t\t\treturn cycle\n\tdef act(self,set):\n\t\t#if set doesnt have element just dont do anything\n\t\tdef swapindex(list,i,j):\n\t\t\ttmp = list[i]\n\t\t\tlist[i]=list[j]\n\t\t\tlist[j]=tmp\n\t\tfor cycle in self.cycles:\n\t\t\tfor n in range(len(cycle)-1):\n\t\t\t\tswapindex(set,cycle[n],cycle[(n+1)%len(cycle)])\n\t\t\t\n\t\t\t\n\t\t\n\nclass P(Perm):\n\tpass\n\nclass Group:\n\tdef __init__(self,generators):\n\t\tpass\n\tdef order(self):\n\t\treturn self.order\n\nclass CyclicGroup(Group):\n\tdef __init__(self,order):\n\t\tself.elements = Perm(rotatelist(range(order),-1)).cycle()\n\t\tself.order = order\n\tdef __repr__(self):\n\t\treturn 'Group:Z/%iZ'%self.order\n\tdef identity(self):\n\t\treturn self.elements[0]\n\tdef directproduct(self):\n\t\tpass\n\n\nsize = 10\nr = range(10)\n#p = P([1,2])\np = P([1,0])\na = P(random_permutation(size))\nb = P(random_permutation(size))\nc = P(random_permutation(size))\n\n","sub_path":"oldprogs/complexmap/group_action.py","file_name":"group_action.py","file_ext":"py","file_size_in_byte":3329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"95244254","text":"from pygame.sprite import Sprite\nfrom pygame.transform import flip\n\n\nclass Goomba(Sprite):\n def __init__(self, settings, screen, sprites, x, y):\n super(Goomba, self).__init__()\n self.settings = settings\n self.screen = screen\n\n self.sprites = sprites\n self.rect = sprites[0].get_rect()\n self.rect.x = x * self.settings.scale[\"tile_width\"]\n self.rect.y = y * self.settings.scale[\"tile_height\"] + self.settings.scale[\"tile_height\"] * 1.5\n\n self.frame = 0\n self.x_velocity = self.settings.scale[\"pixel_width\"]/3\n self.y_velocity = 0\n self.direction = False # False = left, True = right\n self.fall = False\n self.alive = True\n self.squish = False # If mario jumps on goomba, squishes\n self.expire = 0 # Timer for destruction if squished\n\n def update(self):\n if not self.direction and not self.squish and self.alive:\n self.rect.x -= self.x_velocity\n elif not self.squish:\n self.rect.x += self.x_velocity\n if (self.fall or not self.alive) and not self.squish:\n self.rect.y += self.y_velocity\n if self.rect.y > self.settings.screen_height:\n self.kill()\n elif self.squish:\n self.expire += 1\n if self.expire == 60:\n self.kill()\n\n def update_frame(self):\n if self.alive:\n if self.frame == 0:\n self.frame += 1\n else:\n self.frame -= 1\n\n def draw(self, x_offset):\n if self.alive or self.squish:\n self.screen.blit(self.sprites[self.frame], self.rect.move(x_offset, 0))\n else:\n self.screen.blit(flip(self.sprites[self.frame], False, True), self.rect.move(x_offset, 0))\n\n\nclass GreenKoopa(Sprite):\n def __init__(self, settings, screen, sprites, x, y):\n super(GreenKoopa, self).__init__()\n self.settings = settings\n self.screen = screen\n\n self.sprites = sprites\n self.rect = self.sprites[0].get_rect()\n self.rect.x = x * self.settings.scale[\"tile_width\"]\n self.rect.y = y * self.settings.scale[\"tile_height\"] + self.settings.scale[\"tile_height\"]\n\n self.frame = 0\n self.x_velocity = self.settings.scale[\"pixel_width\"]/3\n self.x_velocity_kick = self.settings.scale[\"pixel_width\"]*4\n self.y_velocity = 0\n self.direction = False\n self.fall = False\n self.tuck = False # If mario jumps on koopa, tucks in shell\n self.tuck_timer = 0\n self.alive = True\n self.kicked = False\n\n def update(self):\n if not self.direction and self.alive and not self.tuck:\n if not self.tuck:\n self.rect.x -= self.x_velocity\n elif self.kicked:\n self.rect.x -= self.x_velocity_kick\n elif not self.tuck:\n self.rect.x += self.x_velocity\n elif self.kicked:\n self.rect.x += self.x_velocity_kick\n elif self.tuck and not self.kicked:\n self.tuck_timer += 1\n if self.tuck_timer == 600:\n self.tuck = False\n self.tuck_timer = 0\n self.frame = 0\n self.direction = False\n if self.fall or not self.alive:\n self.rect.y += self.y_velocity\n if self.rect.y > self.settings.screen_height:\n self.kill()\n\n def update_frame(self):\n if not self.tuck and self.alive:\n if self.frame == 0:\n self.frame = 1\n else:\n self.frame = 0\n elif self.tuck and self.tuck_timer > 480:\n if self.frame == 2:\n self.frame = 3\n elif self.frame == 3:\n self.frame = 2\n\n def draw(self, x_offset):\n if (not self.direction or self.tuck) and self.alive:\n self.screen.blit(self.sprites[self.frame], self.rect.move(x_offset, 0))\n elif self.direction and self.alive:\n self.screen.blit(flip(self.sprites[self.frame], True, False), self.rect.move(x_offset, 0))\n else:\n self.screen.blit(flip(self.sprites[self.frame], False, True), self.rect.move(x_offset, 0))\n","sub_path":"enemies.py","file_name":"enemies.py","file_ext":"py","file_size_in_byte":4225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"645154362","text":"# The football.csv file contains the results from the English Premier League. \n# The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of \n# goals scored for and against each team in that season (so Arsenal scored 79 goals \n# against opponents, and had 36 goals scored against them). Write a program to read the file, \n# then print the name of the team with the smallest difference in ‘for’ and ‘against’ goals.\n\nimport csv\n\ndef read_data(filename):\n \n with open(filename, 'r') as file:\n reader = csv.reader(file)\n premier_list = [record for record in reader]\n \n return premier_list\n\ndef get_index_score_diff(goals):\n \n i = 1\n old_diff = 100000000\n for records in goals[1:]:\n diff = abs(int(records[5]) - int(records[6]))\n if diff < old_diff:\n index = i\n old_diff = diff\n i += 1\n \n return index\n\ndef get_team(index_value, parsed_data):\n \n return parsed_data[index_value][0]\n\nfootballTable = read_data('football.csv')\nminRow = get_index_score_diff(footballTable)\nprint(str(get_team(minRow, footballTable)))","sub_path":"python/q8_parsing.py","file_name":"q8_parsing.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"344915478","text":"# -*- coding: utf-8 -*-\nimport matplotlib.pyplot as plt # Importation de Matplotlib <3\n\n###################### Importation du tableau ##############################\ntableau = [] # Crée une liste\nwith open(\"netflix.csv\", \"r\", encoding=\"UTF-8\") as fichier : #Ouvre le fichier contenant les données\n cles = fichier.readline()[:-1].split(\";\") # lit la ligne\n for ligne in fichier : # Conversion d'une ligne en dictionnaire\n valeurs = ligne[:-1].split(\";\")\n dico = dict()\n for cle, valeur in zip(cles, valeurs) :\n dico[cle] = valeur\n tableau.append(dico)\n# show_id;type;title;director;cast;country;date_added;release_year;rating;duration;listed_in;description Descripteur\n##############################################################################\n\n\n\n\n################################## Type ####################################\n\n\"\"\"entry = [l[\"type\"] for l in tableau]\nx = list(set(entry))\nx.pop(index(\"\")) # bye bye Memphis belle\ny = [0 for i in range(len(x))]\nfor i in tableau:\n for j in range(len(x)):\n if (i[\"type\"] == x[j]) :\n y[j] += 1\"\"\"\n\n######## Code plus optimisé mais pas \"adaptatif\" :\n\"\"\"\n Le principe *général* :\n | .\n | . . .\ny | . .\n |___________\n x\n\"\"\"\nx = [\"TV Show\", \"Movie\"]\ny = [0, 0]\nfor i in tableau: # Ajoute +1 si c'est un film ou un show télé'\n if (i[\"type\"] == \"TV Show\"):\n y[0] += 1\n else :\n y[1] += 1\n\nplt.bar(range(2), y, zorder=5.0) # Diagramme à barres / Graphique en barres (zorder c'est pour le placer devant la grille (d'où le Z pour l'axe))\nplt.grid(zorder=0) # Grille\nplt.xticks(range(2), [\"Show télévisé\", \"Film\"]) # Ajoute les étiquettes sur l'axe des X\nplt.title(\"Type de programme\") # Titre du graphique\nplt.show() # Montre le graphique\nplt.close() # Ferme Matplotlib\n\n##############################################################################\n\n\n\n\n########################### Tableau des temps #############################\n### Enlever l'élément buggé The Memphis Belle: A Story of a ...\nid_ = 0\nfor i in range (len(tableau)) :\n\tif (tableau[i][\"show_id\"] == \"80119194\") :\n\t\tid_ = i\ntableau.pop(id_)\n\ntime = [] # Créer une liste vide Temps\nfor l in tableau : # Regarde pour chacun des éléments si ...\n if (l[\"type\"] == \"Movie\"): # ... le \"type\" est bien celui d'un film\n n = l[\"duration\"] # Prend sa durée\n n = n[0:len(n)-4] # Enlève \" min\" de la chaîne de caractères\n time.append(int(n)) # Ajoute la durée convertie à la liste\n###############################################################################\n\n\n\n\n############################# Total de films ################################\ni=0\nfor l in tableau: # Ajoute +1 pour chaque élément étant un film\n if (l[\"type\"]==\"Movie\"):\n i+=1\nprint(\"Il y a\", i, \"films sur Netflix\")\n###############################################################################\n\n\n\n\n######################### CONVERTION DUREE ##################################\nfor l in tableau : # Pareil que pour la liste Temps (time) mais là on convertit la liste d'origine\n if (l[\"type\"] == \"Movie\"): # Si c'est un film\n l[\"duration\"] = int(l[\"duration\"][0:len(l[\"duration\"])-4]) # Change la durée stockée (chaîne de caractère avec \" min\") en nombre entier utilisable\n###############################################################################\n\n\n\n\n######################### DUREE ############################################\nmaxi = 0 # Durée max\nid_maxi = \"\" # le film ayant cette durée\nmini = 300 # Durée minimum\nid_mini = \"\" # le film ayant cette durée\nfor l in tableau: # Regarde pour chaque éléments si ...\n if (l[\"type\"] == \"Movie\"): # ... c'est un film et si ...\n if (l[\"duration\"] > maxi): # ... il bat le record Max ...\n maxi = l[\"duration\"] # change le record\n id_maxi = l\n if (l[\"duration\"] < mini): # ... ou le record Minimum\n mini = l[\"duration\"] # change le record\n id_mini = l\n\n# Afdiche les résultats\nprint(\"Plus court film :\", id_mini[\"title\"], \"avec seulement\", mini, \" minutes\")\nprint(\"Plus long film :\", id_maxi[\"title\"], \"avec\", maxi, \" minutes\")\n###############################################################################\n\n\n\n\n######################## FUNCTION SEARCH ####################################\ndef search(list_, element, retour): # PAS UTILISÉE :)\n \"\"\"\n FONCTION PRMETTANT DE RECHERCHER UN ELEMENT PRECIS\n DANS UNE LISTE DONNE. ELLE RETOURNE UNE LISTE DES\n ELEMENTS TROUVES CORRESPONDANTS\n \"\"\"\n result = [ligne for ligne in list_ if(eval(element))]\n if (retour != \"\"):\n return eval(retour)\n else :\n return result\n###############################################################################\n\n\n\n\n####################### TABLEAU DUREE FILMS #################################\nx = list(set(time)) # Liste des différents durées possibles\ny = [0 for i in x] # Liste remplie de 0 et de longueur identique à x\nfor l in time : # Ajoute +1 pour chaque durées trouvées dans le tableau de données des temps\n y[x.index(l)] += 1\n\n### Fonction pour graphique simple\ndef simplePlot(_x, _y, _title, _ylabel, _xlabel, _rotation, _grid) :\n\tplt.plot(_x, _y) # Graphique\n\tplt.title(_title) # Titre\n\tplt.ylabel(_ylabel) # Titre axe des Y\n\tplt.xlabel(_xlabel) # Titre axe des X\n\tif (_grid == True): # Grille\n\t\tplt.grid()\n\tplt.xticks(rotation=_rotation) # Rotation\n\tplt.show() # Affiche\n\tplt.close() # Ferme Matplotlib\n\nsimplePlot(x, y, \"Nombre de films par durée\", \"Nombre de films\", \"Durées\", 0, False)\n###############################################################################\n\n\n\n\n######################### Temps : Max et Min Date ############################\nyearMax = 0 # Max Année\nmonthMax= 0 # Max Mois\ndayMax = 0 # Max Jour\n\nyearMin = 3000 # Minimum Année\nmonthMin= 3000 # Minimum Mois\ndayMin = 3000 # Minimum Jour\n\n# Aide à la division d'une date en indice d'array :\n# 2 2 / 0 9 / 2 0 1 7\n# 0 1 2 3 4 5 6 7 8 9\n\nfor l in tableau : # pour chaque éléments du tableau :\n if (l[\"date_added\"] != \"\" and l[\"date_added\"] != \"00/00/0000\"): # Si la date est valide :\n #print(l[\"date_added\"][6:10], l[\"date_added\"][3:5], l[\"date_added\"][0:2]) # DEBUG\n y = int(l[\"date_added\"][6:10]) # Créer la variable temporaire de l'année\n m = int(l[\"date_added\"][3:5]) # Créer la variable temporaire du mois\n d = int(l[\"date_added\"][0:2]) # Créer la variable temporaire du jour\n\n recordMax = False # Variable si le record est battue\n if (y > yearMax) : recordMax = True # record battue ?\n if (m > monthMax and y >= yearMax) : recordMax = True # record battue ?\n if (d > dayMax and m >= monthMax and y > yearMax) : recordMax = True # record battue ?\n\n if (recordMax == True) : # Si le record a été battue alors il faut actualiser les records\n yearMax = y\n monthMax= m\n dayMax = d\n\n recordMin = False # Variable si le record est battue\n if (y < yearMin) : recordMin = True # record battue ?\n if (m < monthMin and y <= yearMin) : recordMin = True # record battue ?\n if (d < dayMin and m <= monthMin and y < yearMin) : recordMin = True # record battue ?\n\n if (recordMin == True) : # Si le record a été battue alors il faut actualiser les records\n yearMin = y\n monthMin= m\n dayMin = d\n\n# Affiche les résultats\nprint(\"Premier film ajouté :\", dayMax, \"/\", monthMax, \"/\", yearMax)\nprint(\"Dernier film ajouté :\", dayMin, \"/\", monthMin, \"/\", yearMin)\n###############################################################################\n\n\n\n\n################################### Genres ##################################\nlistType = [l[\"listed_in\"].split(\",\") for l in tableau if (l[\"listed_in\"] != \"\")] # Liste de toutes les listes genres\nallList = [] # Crée une liste vide\ny = [] # Crée une liste vide\nfor l in listType : # Pour tout les liste de genres récupérés ...\n for i in l : # Regarder pour tout les genres dans ces listes de genres ...\n i = i.strip() # Enlève les espaces\n if (i in allList) : # Si le genre examiné est dans la liste ...\n y[allList.index(i)] += 1 # Ajoute +1 à au nombre de ce genre trouvé\n else: # Sinon\n allList.append(i) # Ajoute le genre à la liste\n y.append(1) # not 0 because it has to be found to be added to the list\nprint(\"There are\",len(allList),\"different show categories\")\n\n### -> Partie rangement\ndef sortList(list1=list, list2=list):\n\tsortTest = [[list1[i], list2[i]] for i in range (len(list2))] # Joint les éléments dans de petites listes (pour qu'ils restent ensembles lors du trie)\n\tfrom operator import itemgetter # Importe \"itemgetter\", qui permet d'obtenir le trie selon 1 objet dans une liste (sortTest en a 2)\n\tsortTest = sorted(sortTest, key=itemgetter(1)) # Trie selon la list2\n\tallSorted_ = [l[0] for l in sortTest] # Re-Distribue les valeurs en 2 listes\n\tySorted_ = [l[1] for l in sortTest] # Re-Distribue les valeurs en 2 listes\n\treturn allSorted_, ySorted_ # Retourne ces listes\n\nallListSorted, ySorted = sortList(allList, y)\n###\nprint(\"Le genre le plus présent est\", allListSorted[-1], \"avec\", ySorted[-1], \"films/séries de ce genre\")\n\n### -> Graph :) j'adore lire les documentations\nplt.figure(figsize=(17, 8)) # Taille de la fenêtre qui contient les 2 graphs\nplt.subplot(1, 2, 1) # Graph n°1\nplt.subplots_adjust(left=0.04, bottom=0.35, right=1, top=0.802, wspace=-0.24, hspace=0.2) # Adjuste les valeurs de placement du graph\nplt.title(\"Nombres films par genre\") # Titre\nplt.ylabel(\"Nombre de films\") # Titre axe des y\nplt.xlabel(\"Genres\") # Titre axe des x\nplt.xticks(rotation=90) # Valeur graduée à la vertical\nplt.plot(allListSorted, ySorted) # Ajoute les valeurs\nplt.grid() # Ajoute la grille\nfor i in range(16): # Enlève les éléments mineurs pour un graph plus clair\n ySorted.pop(0)\n allListSorted.pop(0)\nplt.subplot(1, 3, 3) # Graph n°2\nplt.pie(ySorted, labels=allListSorted, rotatelabels=True) # Graphique camembert :)\nplt.show() # Affiche le tout\nplt.close() # Ferme Matplotlib\n##############################################################################\n\n\n\n\n\n########################## CONVERSION DES DATES ############################\n\nfor l in tableau : # Pour tout les éléments du tableau ...\n if (l[\"date_added\"] != \"\" and l[\"date_added\"] != \"00/00/0000\"): # Regarde si la date est \"valide\"\n y = int(l[\"date_added\"][6:10]) # Récupère l'année\n m = int(l[\"date_added\"][3:5]) # Récupère le mois\n d = int(l[\"date_added\"][0:2]) # Récupère le jour\n l[\"date_added\"] = [y , m , d] # Crée une liste contenant l'année, mois et jour\n else : l[\"date_added\"] = [2021, 12, 31] # Si la date n'est pas \"valide\" alors remplace la date par le 31 décembre 2021\n\n##############################################################################\n\n\n\n\n################### DATE PLUS JEUNE ET VIEUX FILM SUR NETFLIX ###############\n# Variables des records (et k = l'index de ce qui est mauvais)\nsortiePremier = 3000\nsortieDernier = 0\nk = 0\n\nfor l in tableau : # Pour chaque éléments du tableau\n if (l[\"release_year\"] != \"\"): # Si l'année de sortie est valide :\n if (int(l[\"release_year\"]) > sortieDernier): \t# Si l'année analysée est au dessus du record\n sortieDernier = int(l[\"release_year\"]) \t# Actualise le record\n if (int(l[\"release_year\"]) < sortiePremier): \t# Si l'année analysée est en dessous du record\n sortiePremier = int(l[\"release_year\"]) \t# Actualise le record\n else : # Si la l'année n'est pas valide :\n tableau.pop(k) # Enlève l'élément\n k-=1 # Enlève 1 à k car on a supprimé un élément\n k+=1 #Ajoute 1 à k pour changer l'index\n\n# Affiche les résultats\nprint(\"Plus 'jeune' film sur Netflix est sortie en\", sortieDernier)\nprint(\"Plus vieux film sur Netflix est sortie en\", sortiePremier)\n###############################################################################\n\n\n\n\n########################### HORNY ###########################################\nhorny = 0 # Crée une variable\nfor l in tableau : # Pour chaque éléments du tableau ...\n if (\"sex\" in l[\"description\"]): # Si le mot \"sex\" est contenue dans la description ...\n horny+=1 # ... Ajoute +1 à la variable 'libidineuse'\nprint(\"Eh beh ! il y a\", horny, \"films libidineux\") # Affiche le résultat\n##############################################################################\n\n\n\n\n####################### GRAPH FILMS AJOUTÉS CHAQUE ANNÉES ###################\nyear = [l[\"date_added\"][0] for l in tableau] # Crée une liste de toutes les dates d'ajout à Netflix\nx = list(set(year)) # Crée une liste des années sans doublons\nx.sort() # Range cette liste\ny = [0 for i in x] # Crée une liste remplie de 0 et de longueur identque à la liste x\nfor l in year : # Pour chaque éléments du tableau de toutes les années\n y[x.index(l)] += 1 # Ajoute 1 au nombre de films ajoutés cette année sur Netflix\nfor i in range(len(x)): # Convertit les années de nombre entier à chaîne de caractère pour un meilleur graph\n x[i] = str(x[i])\n\nplt.figure(figsize=(9,6)) # Crée le graph et change sa taille\nsimplePlot(x, y, \"Nombre de films ajoutés à Netflix chaque années\", \"Nombre de films\", \"Années\", 90, True)\n##############################################################################\n\n\n\n\n############################ Date de sortie ################################\nyear = [l[\"release_year\"] for l in tableau] # Crée une liste de toutes les dates de sortie\nx = list(set(year)) # Cr��e une liste des années sans doublons\nx.sort() # Range cette liste\ny = [0 for i in x] # Crée une liste remplie de 0 et de longueur identique à la liste x\nfor l in year : # Pour chaque éléments du tableau de toutes les années\n y[x.index(l)] += 1 # Ajoute 1 au nombre de films sortie cette année\nfor i in range(len(x)): # Convertit les années de nombre entier à chaîne de caractère pour un meilleur graph\n x[i] = str(x[i])\n\nplt.figure(figsize=(14,6)) # Crée le graph et change sa taille\nsimplePlot(x, y, \"Nombre de films selon leur date de sortie\", \"Nombre de films\", \"Années\", 90, True)\n##############################################################################\n\n\n\n\n############################# LONGEST TITLE ################################\nrecord = 0 # Crée une variable pour le record\ntitleL = \"\" # Crée une variable pour le nom du record\nfor l in tableau : # Pour chaque éléments du tableau\n if (len(l[\"title\"]) > record): # Si la longueur du titre est plus longue que celle du record\n record = len(l[\"title\"]) # Actualise le record\n titleL = l[\"title\"] # Actualise le nom du record\nprint(\"Le plus long titre de film/série sur Netflix est '\", titleL, \"' avec\", record, \"charactères\") # Affiche le record\n##############################################################################\n\n\n\n\n################################# Âge ######################################\nrating = [l[\"rating\"] for l in tableau] # Crée une liste avec toutes les restrictions d'âges\nallRating = list(set(rating)) # Crée une liste de ces restrictions sans doublons\ny = [0 for i in range(len(allRating))] # Crée une liste remplie de 0 et de longueur identique à la liste allRating\nfor l in tableau : # Pour chaque éléments du tableau :\n y[allRating.index(l[\"rating\"])] += 1 # Ajoute 1 à la catégorie correspondante\n\nallRating[allRating.index(\"\")] = \"vide\" # Remplace la catégorie vide par le nom \"vide\"\nallRatingSorted, ySorted = sortList(allRating, y) # Range ces listes dans l'ordre croissant du nombre de films\nsimplePlot(allRatingSorted, ySorted, \"Nombres de films par categories d'âges\", \"Nombre de films\", \"Categorie d'âge\", 90, True) # Graph\n##############################################################################\n\n\n\n\n########################## Âge && Netflix != chill #############################\nrating = [l[\"rating\"] for l in tableau] # Crée une liste avec toutes les restrictions d'âges\nallRating = list(set(rating)) # Crée une liste de ces restrictions sans doublons\nfor i in [\"UR\", \"\", \"NR\"] : # Enlève les catégorie non-définit\n allRating.remove(i)\n\n### Liste toutes les catégories d'âges\nprint(\"voici la liste des catégorie retenues :\")\nfor i in allRating :\n print(\" - \", i)\n\n### 'Tableau' fait-main pour les explications sur les catégories d'âges\nprint(\"Table des âges : \\n\",\n\t\"TV-MA : 2027 =17 réservé aux adultes et inapproprié pour la jeune audience de moins de 17 ans \\n\",\n\t\"PG : 184 ~~~ Parental Guidance Suggested \\n\",\n\t\"G : 37 ok+ All ages admitted \\n\",\n\t\"TV-Y : 143 ok+ approprié aux enfants \\n\",\n\t\"TV-Y7-FV : 95 ~~~ approprié aux enfants MAIS avec violence fantasy (Mickey qui frappe Dingo apr exemple) \\n\",\n\t\"TV-PG : 700 ~~~ éléments que les parents peuvent considérer inappropriés pour les enfants \\n\",\n\t\"NC-17 : 2 >17 Adults Only – No one 17 and under admitted. \\n\",\n\t\"TV-14 : 1698 =14 les parents peuvent considérer inappropriés pour les enfants âgés de moins de 14 ans \\n\",\n\t\"R : 508 ~~~ Under 17 requires accompanying parent or adult guardian. \\n\",\n\t\"TV-G : 149 ~~~ plupart des parents peuvent considérer ce programme comme approprié pour les enfants \\n\",\n\t\"TV-Y7 : 169 ok+ désigné pour les enfants âgés de 7 ans \\n\",\n\t\"PG-13 : 286 ~13 Parents Strongly Cautioned – Some material may be inappropriate for children under 13. \\n\")\n\nx = [str(i) for i in range(7, 19)] # Crée une liste des âges de 7 à 18 (compris) au format chaîne de caractères\nx[-1] = x[-1]+\"+\" # ajoute \"+\" au 18 pour faire -> 18+\ny = [0 for i in range(7,19)] # Crée une liste de 0\nfor l in tableau : # Pour chaque éléments du tableau :\n e = l[\"rating\"] # Variable e = la catégorie analysée\n if e in [\"PG-13\", \"TV-Y7\", \"TV-Y\", \"G\", \"PG\", \"TV-Y7-FV\",\"TV-PG\", \"TV-G\"] : # Si e est dans ces catégories :\n for i in range(0, 12): \t# Pour les âges de 7 à 18+ :\n y[i] += 1 \t\t# Ajoute 1 à leur nombre de films/séries visibles à leur âge\n if e in [\"R\",\"TV-14\"] : # Si e est dans ces catégories :\n for i in range(7, 12): \t# Pour les âges de 14 à 18+ :\n y[i] += 1 \t\t# Ajoute 1 à leur nombre de films/séries visibles à leur âge\n if e == \"NC-17\" : # Pour la catégorie Adulte :\n y[11] += 1 \t# Ajoute 1 au nombre de films/séries visibles par les 18+\n\nsimplePlot(x, y, \"Nombres de films visibles par âges\", \"Nombre de films\", \"Âge\", 0, True) # Graph\n\nx = [\"Appropriés aux enfants\", \"Adulte requis\"] # Titre pour axe X\ny = [0, 0] # Crée une liste pour stocker les nombres de films par catégorie\nfor l in tableau : # Pour chaque éléments du tableau :\n if l[\"rating\"] in [\"G\", \"TV-Y\", \"TV-Y7-FV\", \"TV-Y7\"] : # Si l'élément analysé est dans ces catégories :\n y[0] += 1 # Ajoute 1 au nombre de cette catégorie\n if l[\"rating\"] in [\"PG-13\", \"PG\", \"TV-PG\", \"TV-G\"] : # Si l'élément analysé est dans ces catégories :\n y[1] += 1 # Ajoute 1 au nombre de cette catégorie\n\nplt.bar(range(2), y, zorder=5.0) # Histogramme\nplt.grid(zorder=0) # Grille\nplt.xticks(range(2), x) # Nomme les éléments sur l'axe des abscisses\nplt.title(\"Contenue et présence adulte\") # Titre\nplt.show() # Affiche l'histogramme\nplt.close() # Ferme Matplotlib\nprint(\"Il faut faire attention à ce que les enfants regarde !\") # Message de prévention\n##################################################################################\n\n\n\n\n############################## Interactivité ###################################\n### Tableau neuf (sans la conversion des temps)\ntableau_bis = []\nwith open(\"netflix.csv\", \"r\", encoding=\"UTF-8\") as fichier :\n cles = fichier.readline()[:-1].split(\";\")\n for ligne in fichier :\n valeurs = ligne[:-1].split(\";\")\n dico = dict()\n for cle, valeur in zip(cles, valeurs) :\n dico[cle] = valeur\n tableau_bis.append(dico)\n\n##### - Application avec Tkinter\nimport tkinter as tk # Importe Tkinter \n# Original : programme Hello World de la documentation officiel de Python sur Tkinter et aussi un peu de la documentation TkDocs\n\n\"\"\" D'abord. Très important. Prière.\nOOP makes me go yes (Louis -> OOP : Object Oriented Programming)\nBodging is my way to sucess\n\"\"\"\n\ndef tagChanger(tag, id): # Fonction qui prend un \"tag\" donné et l'applique au label donné\n id.config(text=tag)\n\nclass Application(tk.Frame): # Crée la fenetre de l'application\n def __init__(self, master=None): # Initialisation\n super().__init__(master) # Initialisation automatique\n self.master = master\n self.master.title(\"Explorateur de donnée\") # titre de la fenêtre\n self.pack() # Package (anglicisme) de la fenêtre\n self.create_widgets() # Execution du contenue\n\n def searchExe(self): # Fonction de recherche :\n self.element = self.entrySearch.get() # Récupère ce qu'il faut rechercher\n self.tag = self.labelTag.cget(\"text\") # Récupère le tag dans lequel fouiller depuis le text des tags (astucieux, non ?)\n self.found = [] # Crée une liste vide pour les élements trouvés\n self.output = \"\" # Crée une chaîne de caractères vide pour le résultat\n\n for l in tableau_bis : # Pour toutes les lignes dans le tableau neuf (sans conversion de temps) ...\n if (self.element) in l[self.tag] : # ... Regarde si l'élément est présent dans la partie du tag donné\n self.found.append([l[\"title\"], l[\"type\"], l[\"release_year\"], l[\"duration\"]]) # Ajoute une liste d'éléments du film / de la série trouvé(e)\n \n if len(self.found) == 0 : # Si rien n'a été trouvé ...\n self.output = \"Désoler, \" + self.element + \" n'apparait pas\" # ... Assigne un message d'erreur au résultat\n else : # sinon\n self.output = self.element + \" appears in \" + self.tag + \" for :\\n\" # Annonce le résultat\n for i in self.found : # Pour chaque éléments trouvés ...\n self.output += \" - \" + i[0] + \" a \" + i[1] + \" released in \" + i[2] + \" (\" + i[3] + \")\" +\"\\n\" # Ajoute une présentation clair de la trouvaille au résultat\n \n self.labelResult.config(text=self.output) # Retourne dans une case de texte le résultat\n\n\n def create_widgets(self):\n self.labelInput = tk.Label(root, text=\"Entrez votre recherche et choisissez votre catégorie :\", pady=20) # Crée un \"titre\"\n self.entrySearch = tk.Entry(root, width=20) # Crée une boîte de texte\n self.executeBT = tk.Button(root, text=\"CHERCHER\", fg=\"green\", command=self.searchExe, pady=7) # Crée un bouton pour executer la recherche\n self.typeBtTitle = tk.Button(root, text=\"Titre\", command=lambda: tagChanger(\"title\", self.labelTag)) # Crée un bouton pour le tag : Titre\n self.typeBtDirec = tk.Button(root, text=\"Réalisateur\", command=lambda: tagChanger(\"director\", self.labelTag)) # Crée un bouton pour le tag : Réalisateur\n self.typeBtCast = tk.Button(root, text=\"Acteur\", command=lambda: tagChanger(\"cast\", self.labelTag)) # Crée un bouton pour le tag : Acteur/Actrice\n self.typeBtTime = tk.Button(root, text=\"Durée\", command=lambda: tagChanger(\"duration\", self.labelTag)) # Crée un bouton pour le tag : Durée\n self.typeBtDesc = tk.Button(root, text=\"Description\", command=lambda: tagChanger(\"description\", self.labelTag)) # Crée un bouton pour le tag : Description\n\n self.labelResult = tk.Label(root, height=30) # Crée un text pour le résultat\n self.labelTagDes = tk.Label(root, text=\"Catégorie :\", pady=20) # Crée un text pour le annoncer les boutons des tags\n self.labelTag = tk.Label(root, text=\"cast\") # Crée un bouton pour montrer le tag actuellement choisi\n\n self.labelInput. pack(side=\"top\") # Pack le texte (et donc l'affiche)\n self.entrySearch.pack(side=\"top\") # Pack la boîte de texte\n self.executeBT. pack(side=\"top\") # Pack le bouton\n self.labelTagDes.pack(side=\"top\") # Pack le texte\n self.labelTag. pack(side=\"top\") # Pack le texte\n self.typeBtTitle.pack(side=\"top\") # Pack le bouton\n self.typeBtDirec.pack(side=\"top\") # Pack le bouton\n self.typeBtCast. pack(side=\"top\") # Pack le bouton\n self.typeBtTime. pack(side=\"top\") # Pack le bouton\n self.typeBtDesc. pack(side=\"top\") # Pack le bouton\n self.labelResult.pack(side=\"top\") # Pack le texte\n\n self.quit = tk.Button(root, text=\"QUITTER\", fg=\"red\", command=self.master.destroy) # Crée un bouton Quitter\n self.quit.pack(side=\"bottom\") # Pack le bouton Quitter\n\n\nroot = tk.Tk()\nroot.geometry(\"500x800\") # Taille de la fenêtre\napp = Application(master=root) # Lance l'application\napp.mainloop() # Repète en boucle l'application\n\n##################################################################################\n\n\n\n\n####################### Actors (Grosse partie) #############################\nactors = [l[\"cast\"].split(\",\") for l in tableau if (l[\"cast\"] != \"\")] # Liste de tout les castings\nallActors = [] # Crée une liste pour tout les acteurs\nfor l in actors : # Pour chaque casting :\n\tfor i in l : # Pour chaque acteurs dans ce casting :\n\t\ti = i.strip() # Enlève l'espace avant chaque nom\n\t\tallActors.append(i) # Ajoute cette acteur à la liste\nlistActors = list(set(allActors)) # Crée une liste des acteurs qui n'a aucun doublons\ny = [0 for i in range(len(listActors))] # Crée une liste remplie de 0 de longueur identique à la listActors\nfor i in allActors : # Pour chaque apparition d'acteurs sur Netflix :\n\ty[listActors.index(i)] += 1 # Ajoute 1 au nombre de films joué par cette acteur index() est super lent hélas :(\n\n### -> Moyene\nmovieTotal = 0 # Total des films\nfor i in y : # Pour chaque acteurs :\n movieTotal += i # Ajoute le nombre de films/séries joués\nprint(\"In average, actors on Netflix act in\", round(movieTotal/(len(listActors))), \"movies/series\") # Affiche le résultat tout en calculant la moyenne\n\nmaxMovie = 0 # Le plus grand nombre de films joué par une seule personne\nfor l in y : # Pour chaque acteurs :\n if (l>maxMovie): # Si il bat le record\n maxMovie=l # Actualise le record\n\nx_ = [i for i in range(maxMovie+1)] # Crée une liste numéroté de 0 à maxMovie\ny_ = [i for i in range(maxMovie+1)] # Crée une liste numéroté de 0 à maxMovie\nfor i in y : # Pour tout les acteurs\n y_[i] += 1 # Ajoute 1 au nombre de films/séries qu'ils ont joués\nfor i in range(len(x_)) : # Convertit toute la liste x en chaîne de caractères pour un meilleur graph\n x_[i] = str(x_[i])\n\nx_.pop(0) # Enlève l'élément 0 car aucun acteur n'a joué dans 0 films (logique)\ny_.pop(0)\n\nsimplePlot(x_, y_, \"Nombres du total de films joués par un/une acteur/actrice\", \"Nombre d'acteurs/actrices\", \"Total de films\", 90, True) # Graph\n\nfor i in range(len(y)-1, -1, -1) : # Pour tout les acteurs du dernier de la liste au premier\n if (y[i] <= 13) : # Si l'acteur a moins de 14 films :\n y.pop(i) # Supprime l'acteur des données\n allActors.pop(i)\n\nallActorsSorted, ySorted = sortList(listActors, y) # Range les valeurs\nprint(\"L'acteur qui apparait le plus est\", allActorsSorted[-1], \"avec\", ySorted[-1], \"apparitions\") # Affiche des résultats divers\n\n### -> Graph Double\nplt.figure(figsize=(16, 8)) # Taille de la fenêtre qui contient les 2 graphs\nplt.subplot(1, 2, 1) # Graph n°1\nplt.subplots_adjust(left=0.04, bottom=0.35, right=1, top=0.802, wspace=-0.24, hspace=0.2) # Adjuste les valeurs de placement du graph\nplt.title(\"Nombres films joués par acteur/actrice\") # Titre\nplt.ylabel(\"Nombre de films\") # Titre axe des y\nplt.xlabel(\"Acteurs\") # Titre axe des x\nplt.xticks(rotation=90) # Valeur graduée à la vertical\nplt.plot(allActorsSorted, ySorted) # Ajoute les valeurs\nplt.grid() # Ajoute la grille\nplt.subplot(1, 3, 3) # Graph n°2\nplt.pie(ySorted, labels=allActorsSorted, rotatelabels=True) # Graphique camembert :)\nplt.show() # Affiche le tout\nplt.close() # Ferme Matplotlib\n##############################################################################\n\n\n\n\n################## Well-known people (Actors II) ###########################\n### -> Barack Obama & George Clooney\ndef actorFinder(name) :\n print(name, \"appears in :\")\n found = False\n for l in tableau :\n if (name in l[\"cast\"]):\n print(\" - \", l[\"title\"], \"a\", l[\"type\"], \"released in\", l[\"release_year\"])\n found = True\n if (found == False) :\n print(\"Désoler, cette personne n'est pas sur Netflix\")\nactorFinder(\"Barack Obama\")\nactorFinder(\"George Clooney\")\nprint(\"Conclusion : GEORGE CLOONEY IS INSIDE !!!!!\")\n\n##### Interactivity ! version antiquité\nactorFinder(input(\"Donnez moi un nom d'acteur/actrice ou d'une personne connue : \")) # :)\n\nanswer = input(\"Encore ? Y/N\")\nwhile(answer == \"Y\") :\n actorFinder(input(\"Donnez moi un nom d'acteur/actrice ou d'une personne connue : \"))\n answer = input(\"Encore ? Y/N\")\n\n##### Version compliqué :)\nimport tkinter as tk\n\nclass Application(tk.Frame):\n def __init__(self, master=None):\n super().__init__(master)\n self.master = master\n self.master.title(\"Chercheur d'acteurs !\")\n self.pack()\n self.create_widgets()\n\n def searchExe(self):\n self.element = self.entrySearch.get()\n self.found = []\n self.output = \"\"\n for l in tableau : # Search\n if (self.element) in l[\"cast\"] :\n self.found.append([l[\"title\"], l[\"type\"], l[\"release_year\"]])\n if len(self.found) == 0 : # Nothing ?\n self.output = \"Désoler, \" + self.element + \" n'apparait pas\"\n else :\n self.output = self.element + \" appears in :\\n\"\n for i in self.found :\n self.output += \" - \" + i[0] + \" a \" + i[1] + \" released in \" + i[2] + \"\\n\"\n self.labelResult.config(text=self.output)\n\n def create_widgets(self):\n self.labelInput = tk.Label( root, text=\"Entrez le nom et/ou prénom d'un acteur ou d'une actrice :\", pady=20)\n self.executeBT = tk.Button( root, text=\"CHERCHER\", fg=\"green\", command=self.searchExe, pady=7)\n self.labelResult = tk.Label( root, height=20)\n self.entrySearch = tk.Entry( root, width=20)\n\n self.labelInput. pack(side=\"top\")\n self.entrySearch. pack(side=\"top\")\n self.executeBT. pack(side=\"top\")\n self.labelResult. pack(side=\"top\")\n\n self.quit = tk.Button(root, text=\"QUITTER\", fg=\"red\", command=self.master.destroy)\n self.quit.pack(side=\"bottom\")\n\n\nroot = tk.Tk()\nroot.geometry(\"500x500\")\napp = Application(master=root)\napp.mainloop()\n\n##################################################################################\n\nprint(\"Merci beaucoup d'avoir lu jusqu'au bout !\")","sub_path":"project_TOUDOUM.py","file_name":"project_TOUDOUM.py","file_ext":"py","file_size_in_byte":37112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"400708404","text":"# Converts list to comma separated string with 'and' before final item\nspamList = [] # create empty list\nwhile True: # Filling list with user input\n print('Enter the items in the list to be format ' +\n '(Or enter nothing to stop.)')\n spam = input()\n if spam == '':\n break\n spamList = spamList + [spam]\n\n\ndef comma(commaList): # function changes list to formatted str\n for i in range(len(commaList)):\n if i < len(commaList) - 2:\n print(str(commaList[i]) + ', ', end=\"\")\n else:\n print(str(commaList[len(commaList) - 2]) + ' and ', end=\"\")\n print(str(commaList[len(commaList) - 1]))\n break\n\n\ncomma(spamList) # call function\n","sub_path":"commaCode.py","file_name":"commaCode.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"556287794","text":"import random\nfrom functools import reduce\nimport threading\nfrom multiprocessing import cpu_count\nfrom multiprocessing import Process, Value, Manager\nimport multiprocessing\n\ndef thread_thing(trials, uniqueItems, dropTables, cummulativeKC, cummulativeItemKCs, cummulativeItemsFound, lock):\n local_cumulative_items_found = {}\n local_cumulative_item_KCs = {}\n local_cummulative_KC = 0\n for itemName in uniqueItems:\n local_cumulative_item_KCs[itemName] = 0\n local_cumulative_items_found[itemName] = 0\n for i in range(trials):\n itemsFound = {}\n itemKCs = {}\n KC = 0\n while len(itemsFound.keys()) < len(uniqueItems):\n KC = KC + 1\n for table in dropTables:\n rand = random.random()\n cummulativeRate = 0\n for itemName in table.keys():\n itemRate = table[itemName]\n cummulativeRate = cummulativeRate + itemRate\n if rand <= cummulativeRate:\n if itemName in itemsFound:\n itemsFound[itemName] = itemsFound[itemName] + 1\n else:\n itemsFound[itemName] = 1\n itemKCs[itemName] = KC\n break\n for itemName in uniqueItems:\n local_cumulative_item_KCs[itemName] = local_cumulative_item_KCs[itemName] + itemKCs[itemName]\n local_cumulative_items_found[itemName] = local_cumulative_items_found[itemName] + itemsFound[itemName]\n local_cummulative_KC = local_cummulative_KC + KC\n with lock:\n print(local_cummulative_KC)\n cummulativeKC.value = cummulativeKC.value + local_cummulative_KC\n print(cummulativeKC)\n for name, val in local_cumulative_item_KCs.items():\n cummulativeItemKCs[name] = cummulativeItemKCs[name] + val\n cummulativeItemsFound[name] = cummulativeItemsFound[name] + local_cumulative_items_found[name]\n\ndef simulate(dropTables, trials: int):\n uniqueItems = set()\n for table in dropTables:\n for itemName in table.keys():\n uniqueItems.add(itemName)\n\n manager = Manager()\n\n cummulativeItemKCs = manager.dict()\n cummulativeItemsFound = manager.dict()\n\n for itemName in uniqueItems:\n cummulativeItemKCs[itemName] = 0\n cummulativeItemsFound[itemName] = 0\n cummulativeKC = Value(\"i\", 0)\n work_per_thread = int(trials / cpu_count())\n spare_work = trials % cpu_count()\n threads = []\n lock = multiprocessing.Lock()\n for i in range(cpu_count()):\n this_work = work_per_thread\n if i == 0:\n this_work += spare_work\n this_thread = Process(target=thread_thing, args=(this_work, uniqueItems, dropTables, cummulativeKC, cummulativeItemKCs, cummulativeItemsFound, lock))\n threads.append(this_thread)\n threads[-1].start()\n if work_per_thread == 0:\n break\n for thread in threads:\n thread.join()\n averageKC = cummulativeKC.value / trials\n averageItemKCs = {}\n averageItemsFound = {}\n for itemName in uniqueItems:\n averageItemKCs[itemName] = cummulativeItemKCs[itemName] / trials\n averageItemsFound[itemName] = cummulativeItemsFound[itemName] / trials\n\n return averageKC, averageItemKCs, averageItemsFound\n\ndef dry(dropTables, trials):\n noDropChancePerTable = []\n for table in dropTables:\n noDropChancePerTable.append(1 - sum(table.values()))\n chanceOfNoDropAllTables = reduce(lambda x, y: x * y, noDropChancePerTable)\n print(chanceOfNoDropAllTables)\n print(trials)\n chanceOfDropInGivenKC = chanceOfNoDropAllTables ** trials\n return chanceOfDropInGivenKC","sub_path":"dropsim.py","file_name":"dropsim.py","file_ext":"py","file_size_in_byte":3822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"13063096","text":"'''\n(c) 2012 Steven Armstrong steven-cconfig@armstrong.cc\n\nA cconfig [1] implementation for python.\n\n[1] http://nico.schotteli.us/papers/linux/cconfig/\n'''\n\nimport os\nimport glob\nimport collections\nimport logging\nlog = logging.getLogger(__name__)\n\nfrom . import Cconfig\n\n\nclass Schema(object):\n \"\"\"\n schema_decl = (\n # path, type, subschema_decl\n ('changed', bool),\n ('code-remote', str),\n ('source', str),\n ('explorer', dict, (\n ('state', str),\n )),\n ('parameter', dict, (\n ('state', str),\n )),\n ('require', SomeCustomCconfigType),\n ('nested', dict, (\n ('first', str),\n ('second', int),\n ('third', dict, (\n ('alist', list),\n ('adict', dict),\n )),\n )),\n )\n\n \"\"\"\n def __init__(self, schema=None):\n self._schema = schema or ()\n self._schema_map = {}\n self.__type_map = None\n for entry in self._schema:\n assert len(entry) >= 2\n subschema = None\n if len(entry) == 2:\n key, type_ = entry\n elif len(entry) == 3:\n key, type_, subschema = entry\n cconfig_type = self.type_map[type_]\n self._schema_map[key] = cconfig_type(schema=subschema)\n\n def __contains__(self, key):\n return key in self._schema_map\n\n def __getitem__(self, key, default=None):\n try:\n return self._schema_map[key]\n except KeyError:\n if default:\n return default\n else:\n raise\n\n def __iter__(self):\n return iter(self._schema_map.keys())\n\n def keys(self):\n return self._schema_map.keys()\n\n def items(self):\n return self._schema_map.items()\n\n @property\n def type_map(self):\n if not self.__type_map:\n subclasses = CconfigType.__subclasses__()\n for subclass in subclasses:\n subclasses.extend(subclass.__subclasses__())\n self.__type_map = dict((getattr(subclass, '_type', subclass), subclass) for subclass in subclasses)\n return self.__type_map\n\n\nclass CconfigType(object):\n\n def __init__(self, schema=None):\n self.schema = schema\n\n def __str__(self):\n return self.__class__.__name__\n\n def _read(self, path):\n value = None\n # if file does not exist return None\n try:\n with open(path, 'r') as fd:\n value = fd.read().strip('\\n')\n except EnvironmentError as e:\n # error ignored\n pass\n return value\n\n def _write(self, path, value):\n try:\n with open(path, 'w') as fd:\n fd.write(str(value) + '\\n')\n except EnvironmentError as e:\n # error ignored\n pass\n\n\nclass BoolCconfigType(CconfigType):\n _type = bool\n\n def from_path(self, path):\n return os.path.isfile(path)\n\n def to_path(self, path, value):\n # True: file exists, False: file does not exist\n if value:\n open(path, 'w').close()\n elif os.path.isfile(path):\n os.unlink(path)\n\n\nclass StrCconfigType(CconfigType):\n _type = str\n\n def from_path(self, path):\n \"\"\"Return the string stored in path or None if path doies not exist.\n \"\"\"\n return self._read(path)\n\n def to_path(self, path, value):\n if value is not None:\n self._write(path, value)\n\n\nclass IntCconfigType(StrCconfigType):\n _type = int\n\n def from_path(self, path):\n return int(super(IntType, self).from_path(path))\n\n\nclass DateTimeType(StrCconfigType):\n \"\"\"Datetime from unix timestamp in a file.\n TODO: maybe set/get file ctime instead of storing value inside file?\n \"\"\"\n _type = 'datetime'\n\n def from_path(self, path):\n value = super(DateTimeType, self).from_path(path)\n if value:\n return datetime.datetime.fromtimestamp(float(value))\n\n def to_path(self, path, value):\n if value:\n super(DateTimeType, self).to_path(path, value.timestamp())\n\n\nclass ListCconfigType(CconfigType):\n \"\"\"List from lines in a file.\n \"\"\"\n _type = list\n\n def from_path(self, path):\n value = self._read(path)\n if value:\n return value.split('\\n')\n else:\n return []\n\n def to_path(self, path, value):\n if value is not None:\n if not isinstance(value, collections.MutableSequence):\n value = []\n # value is a list, save as newline delimited string\n self._write(path, '\\n'.join(value))\n\n\nclass ListDirCconfigType(CconfigType):\n \"\"\"List from directory contents instead of from lines in a file.\n \"\"\"\n _type = 'listdir'\n\n def from_path(self, path):\n try:\n return os.listdir(path)\n except EnvironmentError:\n return []\n\n def to_path(self, path, value):\n raise NotImplementedError('ListDirCconfigType is implemented read only, to_path not implemented.')\n\n\nclass DictCconfigType(CconfigType):\n \"\"\"Dictionary from a directory, where file names are the keys and their\n content the values.\n \"\"\"\n _type = dict\n\n def from_path(self, path):\n o = Cconfig(schema=Schema(self.schema))\n o.from_dir(path)\n return o\n\n def to_path(self, path, value):\n if value is not None:\n if isinstance(value, Cconfig):\n # value is a cconfig object, delegate serialization to it\n value.to_dir(path)\n elif isinstance(value, collections.MutableMapping):\n # value is a dictionary, create a cconfig object and delegate serialization to it\n o = Cconfig(schema=Schema(self.schema))\n o.update(value)\n o.to_dir(path)\n\n\nclass CollectionType(CconfigType):\n \"\"\"List from directory contents where each item in the list is itself a\n cconfig object.\n \"\"\"\n _type = 'collection'\n\n def from_path(self, path):\n collection = []\n for file_name in glob.glob1(path, '*'):\n file_path = os.path.join(path, file_name)\n o = Cconfig(schema=Schema(self.schema))\n o.from_dir(file_path)\n collection.append(o)\n return collection\n\n def to_path(self, path, collection):\n os.mkdir(path)\n if collection is not None:\n for item in collection:\n if isinstance(item, Cconfig):\n # item is a cconfig object, delegate serialization to it\n # first schema item is primary key\n key = self.schema[0][0]\n file_name = item[key]\n file_path = os.path.join(path, file_name)\n item.to_dir(file_path)\n elif isinstance(item, collections.MutableMapping):\n # value is a dictionary, create a cconfig object and delegate serialization to it\n o = Cconfig(schema=Schema(self.schema))\n o.update(item)\n key = self.schema[0][0]\n file_name = o[key]\n file_path = os.path.join(path, file_name)\n o.to_dir(file_path)\n\n\nclass MappingType(CconfigType):\n \"\"\"A Mapping is a generic container for associating key/value pairs.\n\n Usage Example:\n schema_decl = (\n ('user', 'mapping', (\n ('first_name', str),\n ('last_name', str),\n ),\n )\n schema = cconfig.Schema(schema_decl)\n c = cconfig.Cconfig(schema=schema)\n print(c)\n c['user']['john'] = {'first_name': 'John', 'last_name': 'Doe'}\n import tempfile\n path = tempfile.mkdtemp()\n c.to_dir(path)\n \"\"\"\n _type = 'mapping'\n\n def from_path(self, path):\n mapping = {}\n for file_name in glob.glob1(path, '*'):\n file_path = os.path.join(path, file_name)\n o = Cconfig(schema=Schema(self.schema))\n o.from_dir(file_path)\n mapping[file_name] = o\n return mapping\n\n def to_path(self, path, mapping):\n os.mkdir(path)\n if mapping is not None:\n for key,value in mapping.items():\n if isinstance(value, Cconfig):\n # item is a cconfig object, delegate serialization to it\n # first schema item is primary key\n file_name = key\n file_path = os.path.join(path, file_name)\n value.to_dir(file_path)\n elif isinstance(value, collections.MutableMapping):\n # value is a dictionary, create a cconfig object and delegate serialization to it\n o = Cconfig(schema=Schema(self.schema))\n o.update(value)\n file_name = key\n file_path = os.path.join(path, file_name)\n o.to_dir(file_path)\n","sub_path":"cconfig/schema.py","file_name":"schema.py","file_ext":"py","file_size_in_byte":9033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"619108766","text":"import random\n\n# 声明状态\nstates = [i for i in range(16)]\n\nactions = [\"N\", \"E\", \"S\", \"W\"]\n# 声明行为对状态的改变,move north then the current state -4\nds_actions = {\"N\": -4, \"E\": 1, \"S\": 4, \"W\": -1}\ngramma = 1.00 # 衰减系数\nvalue = [0 for x in range(16)]\ntimes = [0 for x in range(16)]\nresult = [0 for x in range(16)]\n\n# determin the next state according to the current state with the action\ndef nextState(s, a):\n next_state = s\n # 边界情况\n if (s % 4 == 0 and a == \"W\") or (s < 4 and a == \"N\") or ((s + 1) % 4 == 0 and a == \"E\") or \\\n (s > 11 and a == \"S\"):\n pass\n else:\n ds = ds_actions[a]\n next_state = s + ds\n return next_state\n\n\n# get the reward when leaving the state\ndef rewardOf(s):\n return 0 if s in [0, 15] else -1\n\n\n# check whether the terminatestate\ndef isTerminateState(s):\n return s in [0, 15]\n\n\ndef isNotTerminateState(s):\n return s not in [0, 15]\n\n\ndef line(actions):\n start=random.choice(states)\n current = start\n sample = []\n move = []\n act = random.choice(actions)\n sample.append(current)\n move.append(act)\n while isNotTerminateState(current):\n act = random.choice(actions)\n move.append(act)\n current = nextState(current, act)\n sample.append(current)\n return sample, move\n\n\n\n\n\n\ndef printValue(v):\n for i in range(16):\n print('{0:>6.2f}'.format(v[i]), end=\" \")\n if (i + 1) % 4 == 0:\n print(\"\")\n print()\n\n\n\ndef EVMC(sample):\n #occur = [0 for x in range(16)]\n lenth = len(sample)\n for index, s in enumerate(sample):\n if isTerminateState(s):\n continue\n times[s]+=1\n gt=lenth-index-1\n value[s]+=gt\n\n\n\ndef main():\n\n\n for i in range(1000000):\n example, moves = line(actions)\n EVMC(example)\n # print(example)\n print(times)\n print(value)\n\n # printValue(value)\n result = [0 for x in range(16)]\n for i in range(1, 15):\n result[i] = -value[i] / times[i]\n printValue(result)\n\n\nif __name__ == '__main__':\n main()","sub_path":"MC_TD/EVMC.py","file_name":"EVMC.py","file_ext":"py","file_size_in_byte":2081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"69349046","text":"# -*- coding: utf-8 -*-\nimport math\nimport statistics\n#n denotes the number of periods everywhere it is used\nclass FinancialTimeSeries:\n def __init__(self, values):\n self.values = values\n def ema_list(self, n):\n ema_list = []\n for index in range(len(self.values)):\n if (index < n-1):\n ema_list.append(math.nan)\n elif (index == n-1):\n ema_list.append(sum(self.values[index-n+1:index+1])/n)\n else:\n k = 2/(n+1)\n ema_list.append(self.values[index]*k + ema_list[index-1]*(1-k))\n return ema_list; \n def sma_list(self, n):\n sma_list = []\n for index in range(len(self.values)):\n if (index < n-1):\n sma_list.append(math.nan)\n else:\n sma_list.append(sum(self.values[index-n+1:index+1])/n)\n return sma_list;\n def external_sma_list(val, n):\n sma_list = []\n for index in range(len(val)):\n if (index < n-1):\n sma_list.append(math.nan)\n else:\n sma_list.append(sum(val[index-n+1:index+1])/n)\n return sma_list;\n #Here n is the number of days between the two prices.\n def price_ratio_list(self, n):\n price_ratio_list = []\n for index in range(len(self.values)):\n if (index < n):\n price_ratio_list.append(math.nan)\n else:\n price_ratio_list.append(self.values[index]/self.values[index-n])\n return price_ratio_list;\n def macd_list (self, shortwindow=12, longwindow=26):\n macd_list = []\n short_ema = self.ema_list(shortwindow)\n long_ema = self.ema_list(longwindow)\n for index in range(len(self.values)):\n if (math.isnan(short_ema[index]) or math.isnan(long_ema[index])):\n macd_list.append(math.nan)\n else:\n macd_list.append(short_ema[index] - long_ema[index])\n return macd_list;\n #Returns z-score of current value based on mean, sd of previous n values\n def z_score_list (self, n=100):\n z_score_list = []\n for index in range(len(self.values)):\n if (index < n):\n z_score_list.append(math.nan)\n else:\n average_price = sum(self.values[index-n:index])/n\n stdev = statistics.stdev(self.values[index-n:index])\n z_score_list.append((self.values[index] - average_price)/stdev)\n return z_score_list;\n #Fast stochastic when moving_average_window = 1\n #Slow stochastic when moving_average_window > 1\n def stochastic_oscillator_list (self, n=14, moving_average_window=3):\n stochastic_oscillator = []\n K = []\n for index in range(len(self.values)):\n if (index < n-1):\n stochastic_oscillator.append(math.nan)\n K.append(math.nan)\n elif (index < n-1 + moving_average_window-1):\n lowest_low = min(self.values[index-n+1:index+1])\n highest_high = max(self.values[index-n+1:index+1])\n if (highest_high > lowest_low):\n K.append((self.values[index]-lowest_low)/(highest_high - lowest_low))\n else:\n K.append(0.5)\n stochastic_oscillator.append(math.nan)\n else:\n lowest_low = min(self.values[index-n+1:index+1])\n highest_high = max(self.values[index-n+1:index+1])\n if (highest_high > lowest_low):\n K.append((self.values[index]-lowest_low)/(highest_high - lowest_low))\n else:\n K.append(0.5)\n stochastic_oscillator.append(sum(K[index-moving_average_window+1:index+1])/moving_average_window)\n return stochastic_oscillator;\n\n#SPX = FinancialTimeSeries([2,5,3,4,2.5])\n#print(SPX.sma_list(3))\n#print(SPX.ema_list(1))\n#print(SPX.price_ratio_list(3))\n#print(SPX.macd_list())\n#print(SPX.stochastic_oscillator_list(3, 2))\n#print(SPX.z_score_list(2))","sub_path":"FinancialTimeSeries.py","file_name":"FinancialTimeSeries.py","file_ext":"py","file_size_in_byte":4075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"361587996","text":"# -*- coding:utf-8 -*-\n\n# DIALOGUE STATUS\nDIALOGUE_FAILED = 0\nDIALOGUE_SUCCESS = 1\nNOT_COME_YET = -1\nINFORM_WRONG_DISEASE = 2\n\n# REWORD FOR DIFFERENT DIALOGUE STATUS.\nREWARD_FOR_DIALOGUE_FAILED = -100\nREWARD_FOR_DIALOGUE_SUCCESS = 1000\nREWARD_FOR_NOT_COME_YET = 0\nREWARD_FOR_INFORM_WRONG_DISEASE = -100\n\n# Special Actions.\nCLOSE_DIALOGUE = \"closing\"\nTHANKS = \"thanks\"\n\n# Slot value for unknown, placeholder and no value matches.\nVALUE_UNKNOWN = \"UNK\"\nVALUE_PLACEHOLDER = \"placeholder\"\nVALUE_NO_MATCH = \"No value matches.\"\n\n# RESPONSE\nI_DO_NOT_CARE = \"I don't care.\"\nI_DO_NOT_KNOW = \"I don't know.\"\nI_DENY = \"No\"\n\n# Constraint Check\nCONSTRAINT_CHECK_SUCCESS = 1\nCONSTRAINT_CHECK_FAILURE = 0\n\n# Update condition\nSUCCESS_RATE_THRESHOLD = 0.3\nAVERAGE_WRONG_DISEASE = 7","sub_path":"src/dialogue_system/dialogue_configuration.py","file_name":"dialogue_configuration.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"167887616","text":"from .models import Cart, CartItem\nfrom .views import cart_id\n\ndef cart_counter(request):\n\tcartcounts= 0\n\tif 'admin' in request.path:\n\t\treturn{}\n\telse:\n\t\ttry:\n\t\t\tcart = Cart.objects.filter(cart_id=cart_id(request))\n\t\t\tcart_items = CartItem.objects.all().filter(cart_id=cart[:1])\n\t\t\tfor item in cart_items:\n\t\t\t\tcartcounts +=item.quantity\n\t\texcept Cart.DoesNotExist:\n\t\t\tcartcounts = 0\n\treturn dict(cartcounts=cartcounts)\n\n","sub_path":"cart/cart_context.py","file_name":"cart_context.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"495260721","text":"# -*- coding: utf-8 -*-\r\n\r\nimport os\r\nimport sys\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\n\r\ndata_dir = '/scratch/nbe/tbi-meg/veera/processed'\r\noutdir = '/scratch/nbe/tbi-meg/veera/zmap-data'\r\ndecim_freqs = 8\r\nparc = 'aparc_sub'\r\nlabels_dir = f'/scratch/nbe/tbi-meg/veera/labels_{parc}'\r\n\r\n\r\ndef main(cohorts=None, window=True):\r\n subjects = sorted([f.name for f in os.scandir(data_dir) if f.is_dir()])\r\n labels = sorted([l.name.replace('.label', '') for l in os.scandir(labels_dir) if l.is_file()\r\n and not l.name.startswith('unknown')])\r\n\r\n if parc is None:\r\n outfile = os.path.join(outdir, f'zmap_data_f{decim_freqs}.csv')\r\n else:\r\n outfile = os.path.join(outdir, f'zmap_data_{parc}_f{decim_freqs}.csv')\r\n if cohorts is not None:\r\n outfile = outfile.replace('.csv', f'_{cohorts}.csv')\r\n if 'restmeg' in data_dir:\r\n task = 'rest'\r\n outfile = outfile.replace('.csv', '_normative.csv')\r\n else:\r\n task = 'EC'\r\n\r\n os.makedirs(outdir, exist_ok=True)\r\n if os.path.exists(outfile):\r\n print(\"Removing existing file\")\r\n os.remove(outfile)\r\n\r\n for subject in subjects:\r\n zmap_dir = os.path.join(data_dir, subject, 'zmap')\r\n aparc_dir = os.path.join(data_dir, subject, 'parc')\r\n if window:\r\n for i in range(40, 390, 50):\r\n if parc is None:\r\n zmap_file = os.path.join(zmap_dir, f'{subject}-{task}-{i}-psd-zmap-data.csv')\r\n index = None\r\n else:\r\n zmap_file = os.path.join(aparc_dir, f'{subject}-{task}-{i}-psd-zmap-mean-aparc-data.csv')\r\n index = [f'{subject}_{i}-{label}' for label in labels]\r\n if cohorts is not None:\r\n zmap_file = zmap_file.replace(str(i), str(i) + f'-{cohorts}')\r\n print(zmap_file)\r\n try:\r\n df = pd.read_csv(zmap_file, header=None)\r\n except FileNotFoundError:\r\n print('not found')\r\n continue\r\n df = df[df.columns[::decim_freqs]]\r\n df = df.iloc[:448,:]\r\n if index is not None:\r\n df['index'] = index\r\n df = df.set_index('index')\r\n print(df)\r\n df.to_csv(outfile, mode='a', header=False)\r\n else:\r\n if parc is None:\r\n zmap_file = os.path.join(zmap_dir, f'{subject}-{task}-psd-zmap-data.csv')\r\n index = None\r\n else:\r\n zmap_file = os.path.join(aparc_dir, f'{subject}-{task}-psd-zmap-mean-aparc-data.csv')\r\n index = [f'{subject}-{label}' for label in labels]\r\n if cohorts:\r\n zmap_file = zmap_file.replace(task, task + f'-{cohorts}')\r\n print(zmap_file)\r\n try:\r\n df = pd.read_csv(zmap_file, header=None)\r\n except FileNotFoundError:\r\n continue\r\n df = df[df.columns[::decim_freqs]]\r\n df = df.iloc[:448,:]\r\n if index is not None:\r\n df['index'] = index\r\n df = df.set_index('index')\r\n print(df)\r\n df.to_csv(outfile, mode='a', header=False)\r\n\r\n\r\nif __name__ == '__main__':\r\n if len(sys.argv) > 1:\r\n cohorts = sys.argv[1]\r\n else:\r\n cohorts = None\r\n main(cohorts=cohorts, window=True)\r\n\r\n","sub_path":"pipeline-tbi/zmap/create_zmap_dataset.py","file_name":"create_zmap_dataset.py","file_ext":"py","file_size_in_byte":3461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"4474379","text":"import time\nimport os\nimport numpy as np\nimport random\n\nimport torch\nimport torch.nn as nn\nfrom torchtext import data\n\nfrom args import get_args\nfrom model import SmPlusPlus, PairwiseConv\nfrom trec_dataset import TrecDataset\nimport operator\nimport heapq\nfrom torch.nn import functional as F\n\nfrom evaluate import evaluate\n\nargs = get_args()\nconfig = args\ntorch.manual_seed(args.seed)\ntorch.backends.cudnn.deterministic = True\n\ndef set_vectors(field, vector_path):\n if os.path.isfile(vector_path):\n stoi, vectors, dim = torch.load(vector_path)\n field.vocab.vectors = torch.Tensor(len(field.vocab), dim)\n\n for i, token in enumerate(field.vocab.itos):\n wv_index = stoi.get(token, None)\n if wv_index is not None:\n field.vocab.vectors[i] = vectors[wv_index]\n else:\n # initialize with U(-0.25, 0.25) vectors\n field.vocab.vectors[i] = torch.FloatTensor(dim).uniform_(-0.25, 0.25)\n else:\n print(\"Error: Need word embedding pt file\")\n print(\"Error: Need word embedding pt file\")\n exit(1)\n return field\n\n\n# Set random seed for reproducibility\ntorch.manual_seed(args.seed)\nif not args.cuda:\n args.gpu = -1\nif torch.cuda.is_available() and args.cuda:\n print(\"Note: You are using GPU for training\")\n torch.cuda.set_device(args.gpu)\n torch.cuda.manual_seed(args.seed)\nif torch.cuda.is_available() and not args.cuda:\n print(\"You have Cuda but you're using CPU for training.\")\nnp.random.seed(args.seed)\nrandom.seed(args.seed)\n\nQID = data.Field(sequential=False)\nAID = data.Field(sequential=False)\nQUESTION = data.Field(batch_first=True)\nANSWER = data.Field(batch_first=True)\nLABEL = data.Field(sequential=False)\nEXTERNAL = data.Field(sequential=True, tensor_type=torch.FloatTensor, batch_first=True, use_vocab=False,\n postprocessing=data.Pipeline(lambda arr, _, train: [float(y) for y in arr]))\n\ntrain, dev, test = TrecDataset.splits(QID, QUESTION, AID, ANSWER, EXTERNAL, LABEL)\n\nQID.build_vocab(train, dev, test)\nAID.build_vocab(train, dev, test)\nQUESTION.build_vocab(train, dev, test)\nANSWER.build_vocab(train, dev, test)\nLABEL.build_vocab(train, dev, test)\n\nQUESTION = set_vectors(QUESTION, args.vector_cache)\nANSWER = set_vectors(ANSWER, args.vector_cache)\n\ntrain_iter = data.Iterator(train, batch_size=args.batch_size, device=args.gpu, train=True, repeat=False,\n sort=False, shuffle=False)\ndev_iter = data.Iterator(dev, batch_size=args.batch_size, device=args.gpu, train=False, repeat=False,\n sort=False, shuffle=False)\ntest_iter = data.Iterator(test, batch_size=args.batch_size, device=args.gpu, train=False, repeat=False,\n sort=False, shuffle=False)\n\nconfig.target_class = len(LABEL.vocab)\nconfig.questions_num = len(QUESTION.vocab)\nconfig.answers_num = len(ANSWER.vocab)\n\nprint(\"Dataset {} Mode {}\".format(args.dataset, args.mode))\nprint(\"VOCAB num\", len(QUESTION.vocab))\nprint(\"LABEL.target_class:\", len(LABEL.vocab))\nprint(\"LABELS:\", LABEL.vocab.itos)\nprint(\"Train instance\", len(train))\nprint(\"Dev instance\", len(dev))\nprint(\"Test instance\", len(test))\n\nif args.resume_snapshot:\n if args.cuda:\n pw_model = torch.load(args.resume_snapshot, map_location=lambda storage, location: storage.cuda(args.gpu))\n else:\n pw_model = torch.load(args.resume_snapshot, map_location=lambda storage, location: storage)\nelse:\n model = SmPlusPlus(config)\n model.static_question_embed.weight.data.copy_(QUESTION.vocab.vectors)\n model.nonstatic_question_embed.weight.data.copy_(QUESTION.vocab.vectors)\n model.static_answer_embed.weight.data.copy_(ANSWER.vocab.vectors)\n model.nonstatic_answer_embed.weight.data.copy_(ANSWER.vocab.vectors)\n\n if args.cuda:\n model.cuda()\n print(\"Shift model to GPU\")\n\n\n # pw_model = SmPlusPlus(model)\n\nparameter = filter(lambda p: p.requires_grad, model.parameters())\n\n# the SM model originally follows SGD but Adadelta is used here\noptimizer = torch.optim.Adadelta(parameter, lr=args.lr, weight_decay=args.weight_decay, eps=1e-6)\n# A good lr is required to use Adam\n# optimizer = torch.optim.Adam(parameter, lr=args.lr, weight_decay=args.weight_decay, eps=1e-8)\n\ncriterion = nn.CrossEntropyLoss(weight=torch.cuda.FloatTensor([0,0.875,0.125]))\nmarginRankingLoss = nn.MarginRankingLoss(margin = 1, size_average = True)\n\n\n\nearly_stop = False\niterations = 0\niters_not_improved = 0\nepoch = 0\nq2neg = {} # a dict from qid to a list of aid\nquestion2answer = {} # a dict from qid to the information of both pos and neg answers\nbest_dev_map = 0\nbest_dev_mrr = 0\nfalse_samples = {}\n\nstart = time.time()\nheader = ' Time Epoch Iteration Progress (%Epoch) Average_Loss Train_Accuracy Dev/MAP Dev/MRR'\ndev_log_template = ' '.join(\n '{:>6.0f},{:>5.0f},{:>9.0f},{:>5.0f}/{:<5.0f} {:>7.0f}%,{:>11.6f},{:>11.6f},{:12.6f},{:8.4f}'.split(','))\nlog_template = ' '.join('{:>6.0f},{:>5.0f},{:>9.0f},{:>5.0f}/{:<5.0f} {:>7.0f}%,{:>11.6f},{:>11.6f},'.split(','))\nos.makedirs(args.save_path, exist_ok=True)\nos.makedirs(os.path.join(args.save_path, args.dataset), exist_ok=True)\nprint(header)\n\nindex2label = np.array(LABEL.vocab.itos) # ['', '0', '1']\nindex2qid = np.array(QID.vocab.itos) # torchtext index to qid in the TrecQA dataset\nindex2aid = np.array(AID.vocab.itos) # torchtext index to aid in the TrecQA dataset\nindex2question = np.array(QUESTION.vocab.itos) # torchtext index to words appearing in questions in the TrecQA dataset\nindex2answer = np.array(ANSWER.vocab.itos) # torchtext index to words appearing in answers in the TrecQA dataset\n\n\n# get the nearest negative samples to the positive sample by computing the feature difference\ndef get_nearest_neg_id(pos_feature, neg_dict, distance=\"cosine\", k=1):\n dis_list = []\n pos_feature = pos_feature.data.cpu().numpy()\n pos_feature_norm = pos_feature / np.sqrt(sum(pos_feature ** 2))\n neg_list = []\n for key in neg_dict:\n if distance == \"l2\":\n dis = np.sqrt(np.sum((np.array(pos_feature) - neg_dict[key][\"feature\"]) ** 2))\n elif distance == \"cosine\":\n neg_feature = np.array(neg_dict[key][\"feature\"])\n feat_norm = neg_feature / np.sqrt(sum(neg_feature ** 2))\n dis = 1 - feat_norm.dot(pos_feature_norm)\n dis_list.append(dis)\n neg_list.append(key)\n # index2dis[key] = dis\n\n k = min(k, len(neg_dict))\n min_list = heapq.nsmallest(k, enumerate(dis_list), key=operator.itemgetter(1))\n min_id_list = [neg_list[x[0]] for x in min_list]\n return min_id_list\n\n# get the negative samples randomly\ndef get_random_neg_id(q2neg, qid_i, k=5):\n # question 1734 has no neg answer\n if qid_i not in q2neg:\n return []\n k = min(k, len(q2neg[qid_i]))\n ran = random.sample(q2neg[qid_i], k)\n return ran\n\n# pack the lists of question/answer/ext_feat into a torchtext batch\ndef get_batch(question, answer, ext_feat, size):\n new_batch = data.Batch()\n new_batch.batch_size = size\n new_batch.dataset = batch.dataset\n setattr(new_batch, \"answer\", torch.stack(answer))\n setattr(new_batch, \"question\", torch.stack(question))\n setattr(new_batch, \"ext_feat\", torch.stack(ext_feat))\n return new_batch\n\n\ndef get_qid_batch(qid, qid_questions_dict, qid_anwers_dict, qid_ext_feat_dict, qid_label_dict):\n new_batch = data.Batch()\n question = qid_questions_dict[qid]\n answers = qid_anwers_dict[qid]\n labels = qid_label_dict[qid]\n ext_feats = qid_ext_feat_dict[qid]\n\n\n\n size = len(qid_anwers_dict[qid])\n new_batch.batch_size = size\n new_batch.dataset = \"trecqa\"\n\n \n max_len_a = max([ans.size()[0] for ans in answers])\n\n padding_answers = []\n\n for ans in answers:\n padding_answers.append(F.pad(ans,(0, max_len_a - ans.size()[0]), value=1))\n\n setattr(new_batch, \"answer\", torch.stack(padding_answers))\n setattr(new_batch, \"question\", torch.stack(question.repeat(size,1)))\n setattr(new_batch, \"ext_feat\", torch.stack(ext_feats))\n setattr(new_batch, \"label\", torch.stack(labels))\n return new_batch\n\nqid_correct_ans_dict = {}\nqid_questions_dict = {}\nqid_anwers_dict = {}\nqid_ext_feat_dict = {}\nqid_label_dict = {}\n\nwhile True:\n if early_stop:\n print(\"Early Stopping. Epoch: {}, Best Dev MAP: {}\".format(epoch, best_dev_map))\n break\n \n train_iter.init_epoch()\n \n n_correct, n_total = 0, 0\n\n\n '''\n batch size issue: padding is a choice (add or delete them in both train and test)\n associated with the batch size. Currently, it seems to affect the result a lot.\n '''\n acc = 0\n tot = 0\n\n\n if epoch == 0:\n for batch_idx, batch in enumerate(iter(train_iter)):\n for i in range(batch.batch_size):\n label_i = batch.label[i].cpu().data.numpy()[0]\n question_i = batch.question[i]\n # question_i = question_i[question_i!=1] # remove padding 1 \n answer_i = batch.answer[i]\n # answer_i = answer_i[answer_i!=1] # remove padding 1 \n ext_feat_i = batch.ext_feat[i]\n qid_i = batch.qid[i].data.cpu().numpy()[0]\n aid_i = batch.aid[i].data.cpu().numpy()[0]\n\n qid_questions_dict[qid_i] = question_i\n\n if qid_i not in qid_anwers_dict:\n qid_anwers_dict[qid_i] = []\n qid_anwers_dict[qid_i].append(answer_i)\n\n if qid_i not in qid_ext_feat_dict:\n qid_ext_feat_dict[qid_i] = []\n qid_ext_feat_dict[qid_i].append(ext_feat_i)\n\n if qid_i not in qid_label_dict:\n qid_label_dict[qid_i] = []\n qid_label_dict[qid_i].append(batch.label[i])\n\n\n if label_i == 2:\n qid_correct_ans_dict[qid_i] = qid_correct_ans_dict.get(qid_i, 0) + 1\n \n\n elif epoch >=1:\n # for batch_idx, batch in enumerate(iter(train_iter)):\n for qid in qid_questions_dict:\n batch = get_qid_batch(qid, qid_questions_dict, qid_anwers_dict, qid_ext_feat_dict, qid_label_dict)\n iterations += 1\n loss_num = 0\n model.train()\n optimizer.zero_grad()\n scores = model(batch)\n # print(scores)\n # print(torch.max(scores, 1))\n # exit(0)\n\n n_correct += (torch.max(scores, 1)[1].view(batch.label.size()).data == batch.label.data).sum()\n n_total += batch.batch_size\n train_acc = 100. * n_correct / n_total\n\n \n # loss = marginRankingLoss(output[:, 0], output[:, 1], torch.autograd.Variable(torch.ones(1)))\n loss = criterion(scores, batch.label.view(-1))\n # loss_num = loss.data.numpy()[0]\n loss.backward()\n optimizer.step()\n\n # Evaluate performance on validation set\n if iterations % args.dev_every == 1:\n # switch model into evaluation mode\n model.eval()\n dev_iter.init_epoch()\n n_dev_correct = 0\n dev_losses = []\n instance = []\n for dev_batch_idx, dev_batch in enumerate(dev_iter):\n qid_array = index2qid[np.transpose(dev_batch.qid.cpu().data.numpy())]\n true_label_array = index2label[np.transpose(dev_batch.label.cpu().data.numpy())]\n\n scores = model(dev_batch)\n n_dev_correct += (torch.max(scores, 1)[1].view(dev_batch.label.size()).data == dev_batch.label.data).sum()\n dev_loss = criterion(scores, dev_batch.label)\n dev_losses.append(dev_loss.data[0])\n index_label = np.transpose(torch.max(scores, 1)[1].view(dev_batch.label.size()).cpu().data.numpy())\n label_array = index2label[index_label]\n # get the relevance scores\n score_array = scores[:, 2].cpu().data.numpy()\n for i in range(dev_batch.batch_size):\n this_qid, predicted_label, score, gold_label = qid_array[i], label_array[i], score_array[i], true_label_array[i]\n instance.append((this_qid, predicted_label, score, gold_label))\n\n\n dev_map, dev_mrr = evaluate(instance, 'valid','trecqa', config.mode)\n print(dev_log_template.format(time.time() - start,\n epoch, iterations, 1 + batch_idx, len(train_iter),\n 100. * (1 + batch_idx) / len(train_iter), loss.data[0],\n sum(dev_losses) / len(dev_losses), train_acc, dev_map, dev_mrr))\n\n # Update validation results\n if dev_map > best_dev_map:\n iters_not_improved = 0\n best_dev_map = dev_map\n snapshot_path = os.path.join(args.save_path, args.dataset, args.mode+'_best_model.pt')\n torch.save(model, snapshot_path)\n else:\n iters_not_improved += 1\n if iters_not_improved >= args.patience:\n early_stop = True\n break\n epoch += 1\n\n ","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":13338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"570917709","text":"import json\nimport requests\nimport logging\n\nfrom utils import getLogger\n\nlogger = getLogger()\n\nclass RequireSmartThingsAccessToken(Exception):\n pass\n\nclass SmartThingsClient(object):\n def __init__(self, onRequireAuth=None):\n self.config = SmartThingsConfig()\n self.onRequireAuth = onRequireAuth\n\n def get(self, route):\n res = self.req('get', route)\n return res\n\n def post(self, route, payload):\n stringPayload = json.dumps(payload)\n res = self.req('post', route, stringPayload)\n return res\n\n def req(self, method, route, payload=None):\n if not self.config.access_token:\n raise RequireSmartThingsAccessToken() \n\n headers = {'Authorization': 'Bearer ' + self.config.access_token}\n uri = self.config.app_url + self.config.app_id + route\n if method == 'get':\n res = requests.get(uri, headers=headers)\n elif method == 'post':\n res = requests.post(uri, data=payload, headers=headers)\n else:\n raise Exception(\"method %s not implemented\" % method)\n\n if res.status_code == 403:\n logger.debug(\"received 403 method={} uri={} token={} response={}\".format(method, uri, self.config.access_token, res.text))\n self.requireAuthentication()\n raise RequireSmartThingsAccessToken()\n \n return res\n\n def requireAuthentication(self):\n logger.warning(\"requireAuthentication\")\n if self.onRequireAuth:\n self.onRequireAuth()\n \n def sendEvent(self, event):\n return self.sendEvents([event])\n \n def sendEvents(self, events):\n return self.post('/incomingEvents', { 'events': events })\n \n def sendDevices(self, devices):\n return self.post('/devices', { 'devices': devices })\n\nclass SmartThingsConfig(object):\n def __init__(self, config_file='smartthings_config.json'):\n self.config_file = config_file\n self.app_url = None \n self.app_id = None\n self.access_token = None\n self.loadConfig()\n\n def setConfig(self, config):\n self.app_url = config['app_url']\n self.app_id = config['app_id']\n self.access_token = config['access_token']\n self.saveConfig()\n\n def loadConfig(self):\n try:\n with open(self.config_file, 'r') as f:\n data = json.load(f)\n self.app_id = data['app_id']\n self.app_url = data['app_url']\n self.access_token = data['access_token']\n except FileNotFoundError:\n pass\n except Exception:\n pass #logger.error('Error decoding json from %s' % self.config_file)\n \n def saveConfig(self):\n data = {\n 'app_id': self.app_id,\n 'app_url': self.app_url, \n 'access_token': self.access_token\n }\n with open(self.config_file, 'w+') as f:\n json.dump(data, f, indent=4)","sub_path":"connector-server/SmartThingsClient.py","file_name":"SmartThingsClient.py","file_ext":"py","file_size_in_byte":2967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"552151948","text":"# Given an integer array with no duplicates. \n# A maximum tree building on this array is defined as follow:\n# The root is the maximum number in the array.\n# The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.\n# The right subtree is the maximum tree constructed from right part subarray divided by the maximum number.\n# Construct the maximum tree by the given array and output the root node of this tree.\n\n# Input: [3,2,1,6,0,5]\n# Output: return the tree root node representing the following tree:\n\n# 6\n# / \\\n# 3 5\n# \\ / \n# 2 0 \n# \\\n# 1\n\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\nimport sys\nclass Solution(object):\n def constructMaximumBinaryTree(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: TreeNode\n \"\"\"\n stack = []\n for i in range(len(nums)+1):\n \tif i == len(nums):\n \t\tright = TreeNode(sys.maxint)\n \telse:\n \t\tright = TreeNode(nums[i])\n \twhile stack:\n \t\tif right.val > stack[-1].val:\n \t\t\tcurnode = stack.pop()\n \t\t\tif not stack:\n \t\t\t\t# no potential left parent\n \t\t\t\tright.left = curnode\n \t\t\telse:\n \t\t\t\tleft = stack[-1]\n \t\t\t\tif left.val < right.val:\n \t\t\t\t\tleft.right = curnode\n \t\t\t\telse:\n \t\t\t\t\tright.left = curnode\n \t\telse:\n \t\t\tbreak\n \tstack.append(right)\n return stack[-1].left\n\n\n\n ","sub_path":"Advanced_week3/max_binary_tree.py","file_name":"max_binary_tree.py","file_ext":"py","file_size_in_byte":1608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"563365141","text":"import tensorflow as tf\nimport datetime\nimport os\n# import argparse\nimport Portpolio.Object_detection.Yolo_mobilenet.model.config as cfg\nfrom Portpolio.Object_detection.Yolo_mobilenet.model.mobilenet_new import Mobilenet\nfrom Portpolio.Object_detection.Yolo_mobilenet.utils.timer import Timer\nfrom Portpolio.Object_detection.Yolo_mobilenet.utils.pascal import pascal_voc\n\nclass Train_model(object):\n def __init__(self, model, data):\n self.model = model\n self.data = data\n self.weights_file = cfg.WEIGHTS_FILE\n self.max_iter = cfg.MAX_ITER\n self.initial_learning_rate = cfg.LEARNING_RATE\n self.decay_steps = cfg.DECAY_STEPS\n self.decay_rate = cfg.DECAY_RATE\n self.staircase = cfg.STAIRCASE\n self.summary_iter = cfg.SUMMARY_ITER\n self.save_iter = cfg.SAVE_ITER\n self.output_dir = os.path.join(cfg.OUTPUT_DIR, datetime.datetime.now().strftime('%Y_%m_%d_%H_%M'))\n if not os.path.exists(self.output_dir):\n os.makedirs(self.output_dir)\n self.save_cfg()\n\n self.restore = cfg.RESTORE\n # self.restorer = tf.train.Saver(tf.global_variables(), max_to_keep=None)\n self.saver = tf.train.Saver(tf.global_variables(), max_to_keep=None)\n self.ckpt_file = os.path.join(self.output_dir, 'save.ckpt')\n self.summary_op = tf.summary.merge_all()\n self.writer = tf.summary.FileWriter(self.output_dir, flush_secs=60)\n\n self.global_step = tf.get_variable('global_step', [], initializer=tf.constant_initializer(0), trainable=False)\n self.learning_rate = tf.train.exponential_decay(self.initial_learning_rate,\n self.global_step,\n self.decay_steps,\n self.decay_rate,\n self.staircase,\n name='learning_rate')\n self.optimizer = tf.train.AdamOptimizer(self.learning_rate).minimize(self.model.total_loss,\n global_step=self.global_step)\n self.ema = tf.train.ExponentialMovingAverage(decay=0.9999)\n self.averages_op = self.ema.apply(tf.trainable_variables())\n with tf.control_dependencies([self.optimizer]):\n self.train_op = tf.group(self.averages_op)\n\n # gpu_options = tf.GPUOptions(allow_growth=True)\n gpu_options = tf.GPUOptions()\n config = tf.ConfigProto(gpu_options=gpu_options)\n self.sess = tf.Session(config=config)\n self.sess.run(tf.global_variables_initializer())\n\n if self.restore :\n # print('Restoring weigths from : ' + self.weights_file)\n # self.restorer = tf.train.import_meta_graph(self.weights_file + '.meta')\n # # self.restorer.restore(self.sess, self.weights_file)\n # self.restorer.restore(self.sess, tf.train.latest_checkpoint(\n # 'C:\\\\python\\\\source\\\\Portpolio\\\\Object_detection\\\\Yolo_mobilenet\\\\data\\\\train\\\\weights'))\n print('Restoring weigths from : ' + self.weights_file)\n # self.restorer = tf.train.import_meta_graph(self.weights_file + '.meta')\n # self.restorer.restore(self.sess, self.weights_file)\n self.saver.restore(self.sess, tf.train.latest_checkpoint(cfg.WEIGHTS_DIR))\n\n\n self.writer.add_graph(self.sess.graph)\n\n def train(self):\n train_timer = Timer()\n load_timer = Timer()\n\n for step in range(1, self.max_iter + 1):\n load_timer.tic()\n images, labels = self.data.get()\n load_timer.toc()\n feed_dict = {self.model.images : images, self.model.labels : labels}\n\n if step % self.summary_iter == 0:\n if step % (self.summary_iter * 10) == 0:\n train_timer.tic()\n summary_str, loss, _ = self.sess.run([self.summary_op, self.model.total_loss, self.train_op],\n feed_dict=feed_dict)\n train_timer.toc()\n\n log_str = ('{} Epoch: {}, Step: {}, Learning rate: {}, Loss: {:5.3f}\\n\\t'\n 'Speed: {:.3f}s/iter, Load: {:.3f}s/iter, Remain: {}').format(\n datetime.datetime.now().strftime('%m/%d %H:%M:%S'),\n self.data.epoch,\n int(step),\n round(self.learning_rate.eval(session=self.sess), 10),\n loss,\n train_timer.average_time,\n load_timer.average_time,\n train_timer.remain(step, self.max_iter))\n print(log_str)\n\n else:\n train_timer.tic()\n summary_str, _ = self.sess.run([self.summary_op, self.train_op], feed_dict=feed_dict)\n train_timer.toc()\n # print(self.model.logits.eval(session=self.sess))\n # print(self.model.labels.eval(session=self.sess))\n self.writer.add_summary(summary_str, step)\n\n else:\n train_timer.tic()\n self.sess.run(self.train_op, feed_dict=feed_dict)\n train_timer.toc()\n\n if step % self.save_iter == 0:\n print('\\n{} {} Epoch\\'s Saving checkpoint file to: {}\\n'.format(\n datetime.datetime.now().strftime('%m/%d %H:%M:%S'),\n self.data.epoch,\n self.output_dir))\n self.saver.save(self.sess, self.ckpt_file, global_step=self.global_step)\n\n def save_cfg(self):\n\n with open(os.path.join(self.output_dir, 'config.txt'), 'w') as f:\n cfg_dict = cfg.__dict__\n for key in sorted(cfg_dict.keys()):\n if key[0].isupper():\n cfg_str = '{}: {}\\n'.format(key, cfg_dict[key])\n f.write(cfg_str)\n\n# def update_config_paths(data_dir, weights_file):\n# cfg.TRAIN_DATA_PATH = data_dir\n# cfg.PASCAL_PATH = os.path.join(data_dir, 'pascal_voc')\n# cfg.CACHE_PATH = os.path.join(cfg.PASCAL_PATH, 'cache')\n# cfg.OUTPUT_DIR = os.path.join(cfg.PASCAL_PATH, 'output')\n# cfg.WEIGHTS_DIR = os.path.join(cfg.PASCAL_PATH, 'weights')\n# cfg.WEIGHTS_FILE = os.path.join(cfg.WEIGHTS_DIR, weights_file)\n\ndef main():\n # parser = argparse.ArgumentParser()\n # parser.add_argument('--weights', default=\"YOLO_small.ckpt\", type=str)\n # parser.add_argument('--data_dir', default=cfg.TRAIN_DATA_PATH, type=str)\n # parser.add_argument('--threshold', default=0.2, type=float)\n # parser.add_argument('--iou_threshold', default=0.5, type=float)\n # parser.add_argument('--gpu', default='', type=str)\n # args = parser.parse_args()\n\n # if args.gpu is not None:\n # cfg.GPU = args.gpu\n\n # if args.data_dir != cfg.TRAIN_DATA_PATH:\n # update_config_paths(args.data_dir, args.weights)\n\n # os.environ['CUDA_VISIBLE_DEVICES'] = cfg.GPU\n\n model = Mobilenet(is_training=True)\n pascal = pascal_voc('train')\n\n train_model = Train_model(model, pascal)\n\n print('Start training')\n train_model.train()\n print('Training ended')\n\nif __name__ == '__main__':\n main()\n","sub_path":"Portpolio/Object_detection/Yolo_mobilenet/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":7390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"133359728","text":"from pyspark.sql import SparkSession\nfrom pyspark.sql.types import *\nfrom pyspark.sql.functions import *\nfrom ..config import Config\nfrom ..prophecylibs import *\n\n@Visual(id = \"Source0\", label = \"Source0\", x = 170, y = 50, phase = 0)\n@UsesDataset(id = \"17\", version = 0)\ndef Source0(spark: SparkSession) -> Source:\n fabric = Config.fabricName\n out = None\n\n if fabric == \"Delta\":\n out = spark.read.format(\"parquet\").option(\"location\", \"heds\").load(\"heds\")\n elif fabric == \"emr2\":\n schemaArg = StructType([\n StructField(\"customer_id\", IntegerType(), False),\n StructField(\"country_code\", StringType(), False),\n StructField(\"order_id\", LongType(), False),\n StructField(\"amount\", DoubleType(), False)\n ])\n out = spark.read\\\n .format(\"parquet\")\\\n .schema(schemaArg)\\\n .option(\"location\", \"s3://abinitio-spark-redshift-testing/Users/prophecy/eng/CustomerDatasetOutput2.csv/\")\\\n .load(\"s3://abinitio-spark-redshift-testing/Users/prophecy/eng/CustomerDatasetOutput2.csv/\")\n elif fabric == \"narayan\":\n out = spark.read.format(\"parquet\").option(\"location\", \"mmm\").load(\"mmm\")\n elif fabric == \"awsdbold\":\n out = spark.read.format(\"parquet\").option(\"location\", \"testing12.3.com\").load(\"testing12.3.com\")\n elif fabric == \"emr\":\n out = spark.read.format(\"parquet\").option(\"location\", \"qwq\").load(\"qwq\")\n elif fabric == \"azdbdp1\":\n schemaArg = StructType([\n StructField(\"customer_id\", IntegerType(), False),\n StructField(\"country_code\", StringType(), False),\n StructField(\"order_id\", LongType(), False),\n StructField(\"amount\", DoubleType(), False)\n ])\n out = spark.read\\\n .format(\"csv\")\\\n .schema(schemaArg)\\\n .load(\"dbfs:/Users/prophecy/eng/CustomerOrdersDatasetOutput7.csv/\")\n elif fabric == \"awsnewdp1\":\n schemaArg = StructType([\n StructField(\"customer_id\", IntegerType(), False),\n StructField(\"country_code\", StringType(), False),\n StructField(\"order_id\", LongType(), False),\n StructField(\"amount\", DoubleType(), False)\n ])\n out = spark.read\\\n .format(\"csv\")\\\n .schema(schemaArg)\\\n .load(\"dbfs:/Prophecy/rajat@prophecy.io/CustomerOrdersDatasetOutput1.csv/\")\n elif fabric == \"livy\":\n schemaArg = StructType([\n StructField(\"customer_id\", IntegerType(), False),\n StructField(\"country_code\", StringType(), False),\n StructField(\"order_id\", LongType(), False),\n StructField(\"amount\", DoubleType(), False)\n ])\n out = spark.read\\\n .format(\"csv\")\\\n .schema(schemaArg)\\\n .load(\"s3://abinitio-spark-redshift-testing/Users/prophecy/eng/CustomerOrdersDatasetOutput.csv/\")\n elif fabric == \"azdb\":\n schemaArg = StructType([\n StructField(\"customer_id\", IntegerType(), False),\n StructField(\"country_code\", StringType(), False),\n StructField(\"orders\", LongType(), False),\n StructField(\"amount\", DoubleType(), False)\n ])\n out = spark.read\\\n .format(\"parquet\")\\\n .schema(schemaArg)\\\n .option(\"location\", \"dbfs:/Users/prophecy/eng/CustomerOrdersDatasetOutput6.csv\")\\\n .load(\"dbfs:/Users/prophecy/eng/CustomerOrdersDatasetOutput6.csv\")\n else:\n raise ValueError(\"The fabric %s is not supported\" % fabric)\n\n return out\n","sub_path":"workflows/testpy/code/src/main/python/graph/Source0.py","file_name":"Source0.py","file_ext":"py","file_size_in_byte":3671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"287699893","text":"import pdb\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import rcParams\nrcParams['figure.figsize'] = (14, 7)\nrcParams['axes.spines.top'] = False\nrcParams['axes.spines.right'] = False\nfrom sklearn.datasets import load_diabetes\nfrom sklearn.model_selection import train_test_split\n\n\nclass LinearRegression:\n \"\"\"\n A class which implements linear regression model with gradient descent.\n \"\"\"\n\n def __init__(self, lr=0.01, epochs=10000):\n self.lr = lr\n self.epochs = epochs\n self.parameters = {\"W\": None, \"b\": None}\n self.loss = []\n\n @staticmethod\n def _mean_squared_error(y, y_hat):\n \"\"\"\n Private method, used to evaluate loss at each iteration.\n Args:\n y : np.array, labels\n y_hat : np.array, predicted values\n\n Returns:\n error : float\n\n \"\"\"\n m = y_hat.shape[0]\n error = np.mean(np.square(y_hat - y))\n return error\n\n def fit(self, X, y, optimizer=\"gradient descent\", beta1=0.9, beta2=0.999, epsilon=1e-8):\n \"\"\"\n Used to calculate the coefficient of the linear regression model.\n Args:\n X : np.array, features\n y : np.array, labels\n optimizer : string. Gradient Descent or Adam\n beta1 : Adam's coefficient\n beta2 : Adam's coefficient\n epsilon : hedging against division by zero.\n\n Returns:\n None\n \"\"\"\n # 1. Initialize weights and bias to zeros\n m = X.shape[0]\n self.parameters[\"W\"], self.parameters[\"b\"] = np.zeros((X.shape[1], 1)), np.zeros(1)\n grads = {}\n v, s, v_correct, s_correct = {}, {}, {}, {}\n t = 0\n v[\"dW\"], v[\"db\"] = np.zeros(self.parameters[\"W\"].shape), np.zeros(self.parameters[\"b\"].shape)\n s[\"dW\"], s[\"db\"] = np.zeros(self.parameters[\"W\"].shape), np.zeros(self.parameters[\"b\"].shape)\n\n # 2. Perform gradient descent\n for i in range(self.epochs):\n\n # Line equation\n y_hat = np.dot(X, self.parameters[\"W\"]) + self.parameters[\"b\"]\n loss = self._mean_squared_error(y, y_hat)\n self.loss.append(loss)\n\n # Calculate derivatives\n grads[\"dW\"] = 1 / m * 2 * np.dot(X.T, (y_hat - y))\n grads[\"db\"] = 1 / m * 2 * np.sum(y_hat - y)\n\n # Update the coefficients\n if optimizer == \"gradient descent\":\n for key, d_key in zip([\"W\", \"b\"], [\"dW\", \"db\"]):\n self.parameters[key] -= self.lr * grads[d_key]\n if optimizer == \"adam\":\n t += 1\n for key, d_key in zip([\"W\", \"b\"], [\"dW\", \"db\"]):\n v[d_key] = beta1 * v[d_key] + (1 - beta1) * grads[d_key]\n s[d_key] = beta2 * s[d_key] + (1 - beta2) * np.square(grads[d_key])\n v_correct[d_key] = v[d_key] / (1 - np.power(beta1, t))\n s_correct[d_key] = s[d_key] / (1 - np.power(beta2, t))\n self.parameters[key] -= self.lr * v_correct[d_key] / (np.sqrt(s_correct[d_key]) + epsilon)\n\n def predict(self, X):\n \"\"\"\n Makes predictions using the line equation.\n Args:\n X : array, features\n\n Returns:\n array, predictions\n \"\"\"\n W, b = self.parameters[\"W\"], self.parameters[\"b\"]\n return np.dot(X, W) + b\n\n\n# Test decreasing error\ndata = load_diabetes()\nX = data.data\ny = data.target.reshape(-1, 1)\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n\nmodel = LinearRegression(lr=0.05)\nmodel.fit(X_train, y_train, optimizer=\"adam\")\npreds = model.predict(X_test)\n\nxs = np.arange(len(model.loss))\n# ys = model.loss\n#\n# plt.plot(xs, ys, lw=3, c='#087E8B')\n# plt.title('Loss per iteration (MSE)', size=20)\n# plt.xlabel('Iteration', size=14)\n# plt.ylabel('Loss', size=14)\n# plt.show()\n\n\n# Plots for multiple learning rates\nlosses = {}\nfor lr in [0.5, 0.1, 0.01, 0.001]:\n model = LinearRegression(lr=lr)\n model.fit(X_train, y_train, optimizer=\"adam\")\n losses[f'LR={str(lr)}'] = model.loss\n\nxs = np.arange(len(model.loss))\n\nplt.plot(xs, losses['LR=0.5'], lw=3, label=f\"LR = 0.5, Final = {losses['LR=0.5'][-1]:.2f}\")\nplt.plot(xs, losses['LR=0.1'], lw=3, label=f\"LR = 0.1, Final = {losses['LR=0.1'][-1]:.2f}\")\nplt.plot(xs, losses['LR=0.01'], lw=3, label=f\"LR = 0.01, Final = {losses['LR=0.01'][-1]:.2f}\")\nplt.plot(xs, losses['LR=0.001'], lw=3, label=f\"LR = 0.001, Final = {losses['LR=0.001'][-1]:.2f}\")\nplt.title('Loss per iteration (MSE) for different learning rates', size=20)\nplt.xlabel('Iteration', size=14)\nplt.ylabel('Loss', size=14)\nplt.legend()\nplt.show()\n\nif __name__ == \"__main__\":\n model = LinearRegression(lr=0.5)\n model.fit(X_train, y_train, optimizer=\"adam\")\n preds = model.predict(X_test)\n\n print(model._mean_squared_error(y_test, preds))\n\n\n from sklearn.linear_model import LinearRegression\n from sklearn.metrics import mean_squared_error\n\n lr_model = LinearRegression()\n lr_model.fit(X_train, y_train)\n lr_preds = lr_model.predict(X_test)\n\n print(mean_squared_error(y_test, lr_preds))","sub_path":"regressions/linear/boston/Multiple_LR_Adam_01a.py","file_name":"Multiple_LR_Adam_01a.py","file_ext":"py","file_size_in_byte":5168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"594970680","text":"import re\nfrom collections import defaultdict\nfrom gensim.utils import lemmatize as lem\nimport matplotlib.pyplot as plt\nimport plotly as py\n\nclass ParteB:\n # inizializza variabili\n def __init__(self, filename_data=\"dati_salvati.txt\", filename_frequent=\"parole_frequenti.txt\", filename_frequent_modified=\"parole_modificate.txt\", show_graph=True, lemmatize=True): # grafico = sceglie se visualizzare o no il grafico\n # nomi dei file in cui leggere / salvare dati e frequenze\n self.filename_data = filename_data\n self.filename_frequent1 = filename_frequent\n self.filename_frequent2 = filename_frequent_modified\n # dizionari e liste\n self.dictionary = defaultdict(int)\n self.frequents_words = {}\n self.modified_words = list()\n self.stop_words = list()\n # boolean per visualizzare o no il grafico e per lemmatizzar o no le parole frequenti\n self.show_graph = show_graph\n self.lemmatize = lemmatize\n\n # parte B1, legge il file e costruisce un dizionario delle parole trovate\n def readFile(self):\n with open(self.filename_data, \"r\") as f:\n print(\"Leggendo il file {}...\".format(self.filename_data))\n for line in f.readlines():\n for word in line.split():\n if not re.sub('[^a-zA-Z0-9]', '', word) is \"\":\n self.dictionary[re.sub('[^a-zA-Z0-9]', '', word.lower())] += 1\n f.close()\n\n # trova le 500 parole piu frequenti e le scrive su file con la loro frequenza\n def findWords(self):\n self.frequents_words = sorted(self.dictionary.iteritems(), key=lambda x: int(x[1]))\n self.frequents_words.reverse()\n while len(self.frequents_words) > 500:\n self.frequents_words.pop()\n with open(self.filename_frequent1, \"w\") as f:\n print(\"Scrivendo file {}...\".format(self.filename_frequent1))\n for word in self.frequents_words:\n f.write(word[0] + \" \" + str(word[1]) + \"\\n\")\n f.close()\n\n # legge il file stopwords-en e crea un file parole_modificate con le parole eliminate e sostituite\n def deleteStopWords(self, lemmatize):\n with open(\"stopwords-en.txt\", \"r\") as f:\n print(\"Leggendo file 'stopwords-en.txt'...\")\n for line in f.readlines():\n for word in line.split():\n self.stop_words.append(word) # salva le stopWords lette\n f.close()\n with open(self.filename_frequent2, \"w\") as f:\n print(\"Scrivendo file {}...\".format(self.filename_frequent2))\n for word in self.frequents_words:\n if not(word[0] in self.stop_words):\n if not(u''.join(lem(word[0])).encode('utf-8').strip() is \"\"):\n if lemmatize:\n self.modified_words.append((u''.join(lem(word[0])).encode('utf-8').strip(), word[1]))\n f.write(u''.join(lem(word[0])).encode('utf-8').strip() + \" \" + str(word[1]) + \"\\n\") # sostituisce le parole non in stopWords, quelle presenti le ignora\n else:\n self.modified_words.append((u''.join(word[0]).encode('utf-8').strip(), word[1]))\n f.write(u''.join(word[0]).encode('utf-8').strip() + \" \" + str(word[1]) + \"\\n\") # sostituisce le parole non in stopWords, quelle presenti le ignora\n f.close()\n\n def plotGraph(self, values, title):\n y = list()\n x = list()\n i = 1\n for value in values:\n y.append(int(value[1]))\n x.append(i)\n i += 1\n plt.bar(x, y, align='center') # A bar chart\n plt.title(title)\n plt.xlabel(\"Rank\")\n plt.ylabel(\"Frequenza\")\n plt.show()\n fig = plt.gcf()\n #plot_url = py.plotly.plot_mpl(fig, filename='istogramma_parole1')\n\n def exe(self):\n py.tools.set_credentials_file(username='bara96', api_key='yxyk0sCwGD63aOsFaq3A')\n self.readFile()\n self.findWords()\n self.deleteStopWords(self.lemmatize)\n if self.show_graph:\n self.plotGraph(self.frequents_words, \"Istogramma frequenza\")\n self.plotGraph(self.modified_words, \"Istogramma frequenza modificato\")\n\n\n def getDictionary(self):\n return self.dictionary\n\n def setDictionary(self, dictionary):\n self.dictionary = dictionary\n\n def getFrequentsWords(self):\n return self.frequents_words\n\n def getModifiedWords(self):\n return self.modified_words\n\n def getStopWords(self):\n return self.stop_words\n\n def setStopWords(self, stopWords):\n self.stop_words = stopWords\n","sub_path":"parteB.py","file_name":"parteB.py","file_ext":"py","file_size_in_byte":4732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"554091868","text":"class Category:\n\tdef __init__(self,classes,unknown=False):\n\t\tself.gameObjectType = {\n\t\t\t'BACKGROUND':0\n\t\t}\n\n\t\tself.id_to_cat = {\n\t\t\t0:'BACKGROUND'\n\t\t}\n\t\tself.colormap = {\n\t\t\t'BACKGROUND':[0,0,0],\n\t\t\t'BLACKBIRD':[128,0,0],\n\t\t\t'BLUEBIRD':[0,128,0],\n\t\t\t'HILL':[128,128,0],\n\t\t\t'ICE':[0,0,128],\n\t\t\t'PIG':[128,0,128],\n\t\t\t'REDBIRD':[0,128,128],\n\t\t\t'STONE':[128,128,128],\n\t\t\t'WHITEBIRD':[64,0,0],\n\t\t\t'WOOD':[192,0,0],\n\t\t\t'YELLOWBIRD':[64,128,128],\n\t\t\t'SLING':[192,128,128],\n\t\t\t'TNT':[64,128,128],\n\t\t\t'UNKNOWN':[255,255,255]\n\t\t}\n\t\tfor i in range(len(classes)):\n\t\t\tself.gameObjectType[classes[i]] = i+2\n\t\t\tself.id_to_cat[i+2] = classes[i]\n\t\tif unknown:\n\t\t\tself.gameObjectType['UNKNOWN'] = 1\n\t\t\tself.id_to_cat[1] = 'UNKNOWN'\n\n\t@property\n\tdef ids(self):\n\t\treturn self.id_to_cat.keys()\n\t\n\n\tdef convert_class_to_category(self,class_name):\n\t\treturn self.gameObjectType[class_name]\n\n\tdef convert_category_to_class(self,category_id):\n\t\treturn self.id_to_cat[category_id]\n\n\t# def adjust_label(self):\n\t\t\n","sub_path":"classlabel.py","file_name":"classlabel.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"605375047","text":"#!/usr/bin/env python\n# coding=utf-8\nfrom __future__ import print_function\nimport numpy\n\n#import theano\n#theano.config.device = 'gpu'\n#theano.config.floatX = 'float32'\n\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense,Dropout,Activation,Flatten\nfrom keras.layers.convolutional import Convolution2D, MaxPooling2D, Convolution1D, MaxPooling1D, Convolution3D, MaxPooling3D\nfrom keras.optimizers import SGD\n#import imdb\n#from keras.processing import sequence\n#from keras.layers.Activation import tanh, softmax\n\nfrom keras.utils import np_utils\n\nimport scipy.io as sio\nimport random\nimport math\nfrom keras import backend as K\nfrom sklearn.externals import joblib\nfrom sklearn import cross_validation,decomposition,svm\n\nimport time\ndef getMiddleOutPut(model,inputVector,kthlayer):\n getFunc = K.function([model.layers[0].input],[model.layers[kthlayer].output])\n layer_output = getFunc(inputVector)[0]\n return layer_output\n\n################################\n#按照数据预处理的格式,装载数据#\n################################\ndef loadData(dataFile, typeId = -1, bShowData = False):\n data = sio.loadmat(dataFile)\n\n train_data = data['DataTr']\n train_label_temp = data['CIdTr'][0,:]\n# train_label = train_label[0,:]\n# return train_data,train_label\n# train_set = [train_data, train_label]\n\n test_data = data['DataTe']\n test_label_temp = data['CIdTe'][0,:]\n# test_set = [test_data, test_label]\n\n valid_data = data['DataTr']\n valid_label_temp = data['CIdTr'][0,:]\n# valid_set = [valid_data, valid_label]\n\n# def shared_dataset(data_xy, borrow=True):\n# data_x, data_y = data_xy\n# shared_x = theano.shared(numpy.asarray(data_x,dtype=theano.config.floatX))\n# shared_y = theano.shared(numpy.asarray(data_y,dtype='int32'))\n# return shared_x, shared_y\n\n# test_set_x, test_set_y = shared_dataset(test_set)\n# valid_set_x, valid_set_y = shared_dataset(valid_set)\n# train_set_x, train_set_y = shared_dataset(train_set)\n\n# rval = [(train_set_x, train_set_y), (valid_set_x, valid_set_y), (test_set_x, test_set_y)]\n \n\n# train_dataset_data = train_data.tolist()\n# test_dataset_data = test_data.tolist()\n# valid_dataset_data = valid_data.tolist()\n \n train_label = numpy.empty(len(train_label_temp))\n valid_label = numpy.empty(len(valid_label_temp))\n test_label = numpy.empty(len(test_label_temp))\n\n train_dataset_data = []\n nX = []\n count = 0\n for x in train_data:\n nx = []\n for w in x:\n nx.append(w)\n numpy.array(nx,dtype=\"object\",copy=True)\n nX.append(nx)\n train_label[count] = int(train_label_temp[count])\n count = count + 1\n train_dataset_data = nX\n# testTemp = numpy.array(nX[:len(nX)])\n\n valid_dataset_data = []\n nX = []\n count = 0\n for x in valid_data:\n nx = []\n for w in x:\n nx.append(w)\n numpy.array(nx,dtype=\"object\",copy=True)\n nX.append(nx)\n valid_label[count] = int(valid_label_temp[count])\n count = count + 1\n valid_dataset_data = nX\n\n\n test_dataset_data = []\n nX = []\n count = 0\n for x in test_data:\n nx = []\n for w in x:\n nx.append(w)\n numpy.array(nx,dtype=\"object\",copy=True)\n nX.append(nx)\n test_label[count] = int(test_label_temp[count])\n count = count + 1\n test_dataset_data = nX\n\n train_dataset_data = numpy.array(train_dataset_data,dtype=\"object\")\n test_dataset_data = numpy.array(test_dataset_data)\n valid_dataset_data = numpy.array(valid_dataset_data)\n\n return [(train_dataset_data, train_label),(valid_dataset_data,valid_label),(test_dataset_data,test_label)]\n# return rval\n\n#######################################################################################\n#currently, I wrote all the network constructing and training and testing in this file#\n#laterly, I will seperate them apart. #\n#######################################################################################\ndef temp_network(filePath, number_of_con_filters, con_step_length, max_pooling_feature_map_size, number_of_full_layer_nodes, learning_ratio, train_decay):\n #get the train data, train label, validate data, validate label, test data, test label\n train_dataset, valid_dataset, test_dataset = loadData(\"/home/jiabing/HSICNNKSC/\" + filePath + \".mat\")\n\n file = open(filePath + \"CNNSVMdescription.txt\",'w')\n\n# file.write(\"The network have \" + str(channel_length) + \"input nodes in the 1st layer.\\n\")\n# file.write(\"The amount of samples in the dataset is \" + str(sample_counts) +\".\\n\")\n# file.write(\"The number of classification classes is \" + str(destinations) +\".\\n\")\n# file.write(\"The size of the first convolutional layer is \" + str(layer1_input_length)+\".\\n\")\n# file.write('The number of convolutional filters is '+ str(number_of_con_filters)+ \",each kernel sizes \"+ str(con_filter_length) + \"X1.\\n\")\n# file.write(\"There are \"+str(number_of_full_layer_nodes)+\" nodes in the fully connect layer.\\n\")\n\n #the dimension of the input signal's chanel\n channel_length = train_dataset[0].shape[1]\n sample_counts = train_dataset[0].shape[0]\n\n# train_dataset, test_dataset = imdb.load_data() \n #initialize parameters\n layer1_input_length = len(test_dataset[0][0])\n con_filter_length = int((math.ceil( (layer1_input_length / con_step_length) / 9)) * con_step_length)\n\n destinations = numpy.max(test_dataset[1])\n \n #############################\n #Network Information Display#\n #############################\n #file = open(filePath + \"description.txt\",'w')\n\n # file.write(\"The network have \" + str(channel_length) + \"input nodes in the 1st layer.\\n\")\n # file.write(\"The amount of samples in the dataset is \" + str(sample_counts) +\".\\n\")\n # file.write(\"The number of classification classes is \" + str(destinations) +\".\\n\")\n # file.write(\"The size of the first convolutional layer is \" + str(layer1_input_length)+\".\\n\")\n # file.write('The number of convolutional filters is '+ str(number_of_con_filters)+ \",each kernel sizes \"+ str(con_filter_length) + \"X1.\\n\")\n # file.write(\"There are \"+str(number_of_full_layer_nodes)+\" nodes in the fully connect layer.\\n\")\n\n # print(\"The network have \", channel_length, \"input nodes in the 1st layer.\")\n # print(\"The amount of samples in the dataset is \", sample_counts)\n # print(\"The number of classification classes is \", destinations)\n # print(\"The size of the first convolutional layer is \", layer1_input_length)\n # print('The number of convolutional filters is ', number_of_con_filters, \",each kernel sizes \", con_filter_length,\"X1.\")\n # print(\"There are \",number_of_full_layer_nodes,\" nodes in the fully connect layer.\")\n #########################\n #Construct the CNN model# \n #########################\n \n model = Sequential()\n \n #the first convolutional layer\n layer1 = Convolution2D(number_of_con_filters,nb_row = con_filter_length, nb_col = 1,border_mode='valid', subsample=(1,1),dim_ordering='th', bias=True,input_shape=(1,layer1_input_length, 1))\n\n print(\"The input to the first convolutional layer shapes\", (1,layer1_input_length,1))\n file.write(\"The input to the first convolutional layer shapes 1X\" + str(layer1_input_length) + \"X1.\\n\" )\n model.add(layer1)\n\n model.add(Activation('tanh'))\n\n #the max pooling layer after the first convolutional layer\n first_feature_map_size = (layer1_input_length - con_filter_length) / con_step_length + 1\n max_pooling_kernel_size = int(math.ceil(first_feature_map_size / max_pooling_feature_map_size))\n print(\"The max pooling kernel size is \", max_pooling_kernel_size)\n file.write(\"The max pooling kernel size is \" + str(max_pooling_kernel_size) +\".\\n\")\n layer2 = MaxPooling2D(pool_size = (max_pooling_kernel_size,1), strides=(max_pooling_kernel_size,1), border_mode='valid',dim_ordering='th')\n model.add(layer2)\n\n #Flatten the variables outputed from maxpooling layer\n model.add(Flatten())\n \n #the fully connected layer\n layer3 = Dense(number_of_full_layer_nodes, bias = True)\n model.add(layer3)\n model.add(Activation('tanh'))\n\n #the activation layer which will output the final classification result\n layer4 = Dense(destinations + 1,activation = 'tanh', bias=True)\n# layer4 = Activation('tanh')\n model.add(layer4)\n\n layer5 = Activation('softmax')\n model.add(layer5)\n\n #the optimizer\n sgd = SGD(lr = learning_ratio, decay = train_decay, momentum = 0.6, nesterov=True)\n\n model.compile(optimizer=sgd, loss='categorical_crossentropy',metrics=['accuracy'])\n \n train_dataset_data = train_dataset[0].reshape(train_dataset[0].shape[0],1,train_dataset[0].shape[1],1)\n # train_dataset_label = np_utils.to_categorical(train_dataset[1])\n# file.close()\n #根据已有的代码去构建训练好的网络\n model.load_weights(filePath + 'Model.h5')\n test_dataset_data = test_dataset[0].reshape(test_dataset[0].shape[0],1,test_dataset[0].shape[1],1)\n # test_dataset_label = np_utils.to_categorical(test_dataset[1])\n \n #根据已有的代码去构建训练好的网络\n model.load_weights(filePath + 'Model.h5')\n #拿到CNN全连接层提取到的特征\n train_data_for_svm = getMiddleOutPut(model,[train_dataset_data],5)\n# print(\"层号5,shape:\",train_data_for_svm.shape)\n train_label_for_svm = train_dataset[1]\n# print(\"训练数据label的shape:\",train_label_for_svm.shape)\n \n test_data_for_svm = getMiddleOutPut(model,[test_dataset_data],5) \n test_dataset_label = test_dataset[1].astype(numpy.int) \n test_label_for_svm = test_dataset[1]\n\n #下面这部分是把上面的CNN喂到SVM里面\n# pca = decomposition.RandomizedPCA(n_components = 100,whiten=True)\n# pca.fit(X_train)\n\n# X_train_pca = pca.transform(X_train)\n# X_test_pca = pca.transform(X_test)\n\n #原来gamma的值为0.0008\n kernel_1 = 'linear'\n kernel_2 = 'rbf'\n\n#\t用rbf核\n clf1 = svm.SVC(C=1.0, kernel = kernel_2, gamma='auto', probability=True,\n tol = 0.00000000000001, max_iter = -1)\n \n clf2 = svm.SVC(C=1.0, kernel = kernel_2, gamma='auto', probability=True,\n tol = 0.00000000000001, max_iter = -1)\n #用linear\n clf3 = svm.SVC(C=0.8, kernel = kernel_2, gamma='auto', probability=True,\n tol = 0.00001, max_iter = -1) \n clf4 = svm.SVC(C=0.8, kernel = kernel_2, gamma='auto', probability=True,\n tol = 0.00001, max_iter = -1)\n\n print(\"#####################################################\")\n print(\"在CNN-SVM-RBF上的结果:\")\n print(\"数据集\",filePath)\n print(\"kernel为\")\n print(kernel_2)\n print(\"开始训练\")\n \n start_time = time.time()\n clf1.fit(train_data_for_svm, train_label_for_svm)\n end_time = time.time()\n train_time = end_time - start_time\n print(\"训练用时:\",train_time)\n\n start_time = time.time()\n print(\"在测试集上的平均正确率为\",clf1.score(test_data_for_svm, test_label_for_svm))\n end_time = time.time()\n test_time = end_time - start_time\n print(\"测试用时:%f\" % test_time)\n #result = clf.predict(X_train)\n file.write(\"#########################################################################################################\")\n file.write(\"The CNN-SVM joint use kernel \" + kernel_2 + \"\\n\")\n file.write(\"The SVM train time is \" + str(train_time) +\"\\n\")\n file.write(\"The testing time is \" + str(test_time) + \"\\n\")\n file.write(\"The correct ratio of CNN-SVM is \" + str(clf1.score(test_data_for_svm,test_label_for_svm)))\n result = clf1.predict(test_data_for_svm)\n cnnsvmtraintime = str(train_time)\n cnnsvmtesttime = str(test_time)\n cnnsvmacc = str((clf1.score(test_data_for_svm,test_label_for_svm)))\n sio.savemat(filePath + \"CNNSVMResult.mat\",{'predict':result,'actual':test_label_for_svm})\n file.write(\"#########################################################################################################\")\n joblib.dump(clf1,filePath + 'cnnsvmrbf.model')\n\t\t\n #result = clf.predict(X_train)\n #correctRatio = np.mean(np.equal(result,Y_train))\n\n print(\"#####################################################\")\n print(\"正在SVM上进行测试\")\n \n print(\"数据集\",filePath)\n print(\"kernel为\")\n print(kernel_2)\n print(\"开始训练\")\n\n start_time= time.time()\n clf2.fit(train_dataset[0], train_dataset[1])\n end_time = time.time()\n train_time = end_time - start_time\n print(\"训练用时:\",train_time)\n\n start_time = time.time()\n print(\"在测试集上的平均正确率为\",clf2.score(test_dataset[0],test_dataset[1]))\n end_time = time.time()\n test_time = end_time - start_time\n print(\"测试用时:%f\" % test_time)\n #result = clf.predict(X_train)\n file.write(\"#########################################################################################################\")\n file.write(\"The SVM only use kernel \" + kernel_2 + \"\\n\")\n file.write(\"The SVM train time is \" + str(train_time) +\"\\n\")\n file.write(\"The testing time is \" + str(test_time) + \"\\n\")\n file.write(\"The correct ratio of CNN-SVM is \" + str(clf2.score(test_dataset[0],test_dataset[1])))\n result = clf2.predict(test_dataset[0])\n svmtraintime = str(train_time)\n svmtesttime = str(test_time)\n svmacc = str(clf2.score(test_dataset[0],test_dataset[1]))\n sio.savemat(filePath + \"SVMonlyResult.mat\",{'predict':result,'actual':test_dataset[1]})\n file.write(\"#########################################################################################################\")\n joblib.dump(clf2,filePath + 'svmrbf.model')\n\n print(\"#####################################################\")\n print(\"正在CNN上进行测试\\n\")\n\n classes = model.predict_classes(test_dataset_data)\n start_time = time.time()\n test_accuracy = numpy.mean(numpy.equal(test_dataset_label,classes))\n end_time = time.time()\n print(\"同一个测试集,在CNN上的正确率为:\",test_accuracy)\n print(\"测试用时:%f\" % (end_time - start_time))\n file.write(\"#########################################################################################################\")\n file.write(\"The CNN only\\n\")\n file.write(\"The testing time is \" + str(end_time - start_time) + \"\\n\")\n file.write(\"The correct ratio of CNN only is \" + str(test_accuracy))\n sio.savemat(filePath + \"CNNOnlyResult.mat\",{'predict':classes,'actual':test_dataset_label})\n file.write(\"#########################################################################################################\")\n cnntesttime = str(end_time - start_time)\n cnnacc = str(test_accuracy)\n return {'cnnsvmtraintime':cnnsvmtraintime,'cnnsvmtesttime':cnnsvmtesttime,'cnnsvmacc':cnnsvmacc, 'svmtraintime':svmtraintime,'svmtesttime':svmtesttime,'svmacc':svmacc,'cnntesttime':cnntesttime,'cnnacc':cnnacc}\n file.close\n\ndef network(path, con_step_length, max_pooling_feature_map_size):\n result = temp_network(path, number_of_con_filters = 20, con_step_length = con_step_length, max_pooling_feature_map_size = max_pooling_feature_map_size, number_of_full_layer_nodes = 100, learning_ratio = 0.06, train_decay = 0.001)\n return result\n\ndef run_batch(flag):\n result1 = network(\"newKSC\" + str(flag) + \"N\",1,40)\n result2 = network(\"newKSC\" + str(flag) + \"N4\",5,40)\n result3 = network(\"newKSC\" + str(flag) + \"N8\",9,40)\n return result1, result2, result3\n\nif __name__ == '__main__':\n cnnsvmtraintime1 = 0.\n cnnsvmtesttime1 = 0.\n cnnsvmacc1 = 0.\n svmtraintime1 = 0.\n svmtesttime1 = 0.\n svmacc1 = 0.\n cnntesttime1 = 0.\n cnnacc1 = 0.\n\n cnnsvmtraintime4 = 0.\n cnnsvmtesttime4 = 0.\n cnnsvmacc4 = 0.\n svmtraintime4 = 0.\n svmtesttime4 = 0.\n svmacc4 = 0.\n cnntesttime4 = 0.\n cnnacc4 = 0.\n\n cnnsvmtraintime8 = 0.\n cnnsvmtesttime8 = 0.\n cnnsvmacc8 = 0.\n svmtraintime8 = 0.\n svmtesttime8 = 0.\n svmacc8 = 0.\n cnntesttime8 = 0.\n cnnacc8 = 0.\n \n file_all_result = open(\"KSCEXPResultTOTAL.txt\",'w')\n\n for flag in range(1,31):\n if flag == 13:\n continue\n result = run_batch(flag)\n \n cnnsvmtraintime1 = cnnsvmtraintime1 + float(result[0]['cnnsvmtraintime'])\n cnnsvmtesttime1 = cnnsvmtesttime1 + float(result[0]['cnnsvmtesttime'])\n cnnsvmacc1 = cnnsvmacc1 + float(result[0]['cnnsvmacc'])\n svmtraintime1 = svmtraintime1 + float(result[0]['svmtraintime'])\n svmtesttime1 = svmtesttime1 + float(result[0]['svmtesttime'])\n svmacc1 = svmacc1 + float(result[0]['svmacc'])\n cnntesttime1 = cnntesttime1 + float(result[0]['cnntesttime'])\n cnnacc1 = cnnacc1 + float(result[0]['cnnacc'])\n\n cnnsvmtraintime4 = cnnsvmtraintime4 + float(result[1]['cnnsvmtraintime'])\n cnnsvmtesttime4 = cnnsvmtesttime4 + float(result[1]['cnnsvmtesttime'])\n cnnsvmacc4 = cnnsvmacc4 + float(result[1]['cnnsvmacc'])\n svmtraintime4 = svmtraintime4 + float(result[1]['svmtraintime'])\n svmtesttime4 = svmtesttime4 + float(result[1]['svmtesttime'])\n svmacc4 = svmacc4 + float(result[1]['svmacc'])\n cnntesttime4 = cnntesttime4 + float(result[1]['cnntesttime'])\n cnnacc4 = cnnacc4 + float(result[1]['cnnacc'])\n \n cnnsvmtraintime8 = cnnsvmtraintime8 + float(result[2]['cnnsvmtraintime'])\n cnnsvmtesttime8 = cnnsvmtesttime8 + float(result[2]['cnnsvmtesttime'])\n cnnsvmacc8 = cnnsvmacc8 + float(result[2]['cnnsvmacc'])\n svmtraintime8 = svmtraintime8 + float(result[2]['svmtraintime'])\n svmtesttime8 = svmtesttime8 + float(result[2]['svmtesttime'])\n svmacc8 = svmacc8 + float(result[2]['svmacc'])\n cnntesttime8 = cnntesttime8 + float(result[2]['cnntesttime'])\n cnnacc8 = cnnacc8 + float(result[2]['cnnacc'])\n file_all_result.write(\"|\" +str(flag) + \"|\" + \"1pixel\" + \"|\" + result[0]['cnnsvmacc'] + \"|\" + result[0]['svmacc'] + \"|\" + result[0]['cnnacc'] + \"|\\n\")\n\n file_all_result.write(\"|\" +str(flag) + \"|\" + \"4pixles\" + \"|\" + result[1]['cnnsvmacc'] + \"|\" + result[1]['svmacc'] + \"|\" + result[1]['cnnacc'] + \"|\\n\")\n \n file_all_result.write(\"|\" +str(flag) + \"|\" + \"8pixels\" + \"|\" +result[2]['cnnsvmacc'] + \"|\" + result[2]['svmacc'] + \"|\" + result[2]['cnnacc'] + \"|\\n\")\n# file_all_result.write(str(flag) + \"|\" + str(cnnsvmtraintime1) + \"|\" + str(cnnsvmtesttime1) + \"|\" + str(cnnsvmacc1) + \"|\" + str(svmtraintime1) + \"|\" + str(svmtesttime1) + \"|\" + str(svmacc1) + \"|\" + str(cnntesttime1) + \"|\" + str(cnnacc1) + \"|\\n\")\n# file_all_result.write(str(flag) + \"|\" + str(cnnsvmtraintime4) + \"|\" + str(cnnsvmtesttime1) + \"|\" + str(cnnsvmacc1) + \"|\" + str(svmtraintime1) + \"|\" + str(svmtesttime1) + \"|\" + str(svmacc1) + \"|\" + str(cnntesttime1) + \"|\" + str(cnnacc1) + \"|\\n\")\n# file_all_result.write(str(flag) + \"|\" + str(cnnsvmtraintime1) + \"|\" + str(cnnsvmtesttime1) + \"|\" + str(cnnsvmacc1) + \"|\" + str(svmtraintime1) + \"|\" + str(svmtesttime1) + \"|\" + str(svmacc1) + \"|\" + str(cnntesttime1) + \"|\" + str(cnnacc1) + \"|\\n\")\n file = open(\"KSCEXPResultSUM.txt\",'w')\n\n file.write(\"---------------------单像素-----------------------\\n\")\n\n file.write(str(cnnsvmtraintime1) + \"\\n\")\n\n file.write(str(cnnsvmtesttime1) + \"\\n\")\n\n file.write(str(cnnsvmacc1) + \"\\n\")\n\n file.write(str(svmtraintime1) + \"\\n\")\n\n file.write(str(svmtesttime1) + \"\\n\")\n\n file.write(str(svmacc1) + \"\\n\")\n\n file.write(str(cnntesttime1) + \"\\n\")\n\n file.write(str(cnnacc1) + \"\\n\")\n\n\n file.write(\"---------------------4近邻像素-----------------------\\n\")\n \n file.write(str(cnnsvmtraintime4) + \"\\n\")\n\n file.write(str(cnnsvmtesttime4) + \"\\n\")\n\n file.write(str(cnnsvmacc4) + \"\\n\")\n\n file.write(str(svmtraintime4) + \"\\n\")\n\n file.write(str(svmtesttime4) + \"\\n\")\n\n file.write(str(svmacc4) + \"\\n\")\n\n file.write(str(cnntesttime4) + \"\\n\")\n \n file.write(str(cnnacc4) + \"\\n\")\n\n\n file.write(\"---------------------8近邻像素-----------------------\\n\")\n\n file.write(str(cnnsvmtraintime8) + \"\\n\")\n\n file.write(str(cnnsvmtesttime8) + \"\\n\")\n\n file.write(str(cnnsvmacc8) + \"\\n\")\n\n file.write(str(svmtraintime8) + \"\\n\")\n\n file.write(str(svmtesttime8) + \"\\n\")\n\n file.write(str(svmacc8) + \"\\n\")\n\n file.write(str(cnntesttime8) + \"\\n\")\n \n file.write(str(cnnacc8) + \"\\n\")\n\n file.close\n\n# network(\"newKSC1N4\",5,40)\n# network(\"newKSC1N4\",5,40)\n# network(\"newKSC1N8\",9,40)\n# temp_network(\"newPU1NWith2RestN.mat\", number_of_con_filters = 20, con_step_length = 1, max_pooling_feature_map_size = 40, number_of_full_layer_nodes = 100, learning_ratio = 0.01, train_decay = 0.001)\n","sub_path":"SVM/cnnsvm_for_KSC.py","file_name":"cnnsvm_for_KSC.py","file_ext":"py","file_size_in_byte":20789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"310621561","text":"__author__ = 'Ivan'\n__version__ = 'beta'\n\nimport sqlite3\nimport os\nimport py.lib.exceptions as exc\n\n\nclass DataBaseGate():\n def __init__(self):\n \"\"\"\n Initialize gate. Create fields for further usage\n :return:\n \"\"\"\n self.db_name = None\n self.cursor = None\n self.connection = None\n\n def connect(self, db_name):\n \"\"\"\n Connect to database. Throw ConnectError exception if not successful\n :param db_name: (str) name of database including filename extension (located in dbs folder)\n :return:\n \"\"\"\n self.db_name = db_name\n if os.path.exists(os.path.join('dbs', db_name)):\n self.connection = sqlite3.connect(os.path.join('dbs', db_name))\n else:\n raise exc.ConnectError(db_name, 'Not found database')\n self.cursor = self.connection.cursor()\n\n def execute(self, command_lines, need_return):\n \"\"\"\n Execute sql command\n :param command_lines: (str) target command\n :param need_return: (bool) True if u need top get result from command\n :return: (str) if available and needed,\n (None) if not available or not needed\n \"\"\"\n try:\n self.cursor.execute(command_lines)\n except sqlite3.OperationalError as error:\n raise exc.CommandError(error, command_lines)\n if need_return:\n return self.cursor.fetchall()\n\n def commit(self):\n \"\"\"\n Commit changes to database\n :return:\n \"\"\"\n self.connection.commit()\n\n def close(self):\n \"\"\"\n Close connection to database\n :return:\n \"\"\"\n self.connection.close()\n self.cursor = None\n self.connection = None\n self.db_name = None","sub_path":"py/core/db/basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":1790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"110214051","text":"from apps.acl.models import SystemRole, RuleDescriptor\n\ndefault_org_rules = []\ndefault_global_rules = []\n\n# REGISTERED_USER 访问错误代码列表\nr = {\n 'role': SystemRole.REGISTERED_USER,\n 'resource_descriptor': {\n 'class': 'SimpleResourceDescriptor',\n 'desc': 'i18n-properties-list'},\n 'permission': RuleDescriptor.PERMISSION_VIEW,\n 'allow_or_deny': RuleDescriptor.ALLOW,\n 'priority': 10,\n 'is_system': 1,\n}\ndefault_global_rules.append(r)\n","sub_path":"starfish-ws/apps/i18n/acl_rules.py","file_name":"acl_rules.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"282793481","text":"import read_data as d\nimport model\nimport train\nfrom torch import optim\nimport torch.nn as nn\nimport random\nimport time\nimport helper\nimport torch\n\n# parameters\nhidden_size = 256\nprint_every = 1000\nplot_every = 100\nlearning_rate = 0.01\nn_iters = 100000\nMAX_LENGTH = 30\nn_evaluations = 10\nteacher_forcing_rate = 0.5\nbeam_size = 3\n\n# data preparing\nlang, pairs = d.read_data()\npairs = d.filterPairs(pairs, MAX_LENGTH)\nprint(\"after filter, the number of pairs is %s.\" % len(pairs))\ntraining_pairs = [d.tensorsFromPair(\n lang, random.choice(pairs)) for i in range(n_iters)]\n\nencoder_save = torch.load('lstm_encoder.pth',map_location='cpu')\ndecoder_save = torch.load('lstm_decoder.pth',map_location='cpu')\nfor i in range(n_evaluations):\n pair = random.choice(pairs)\n print('>', pair[0])\n print('=1', pair[1])\n output_words_ = train.evaluate(\n encoder_save, decoder_save, lang, pair[0], MAX_LENGTH)\n output_sentence = ' '.join(output_words_)\n print('<', output_sentence)\n output_words_ = train.beamSearchEvaluate(\n encoder_save, decoder_save, lang, pair[0], MAX_LENGTH, beam_size, lang.n_words)\n output_sentence = ' '.join(output_words_)\n print('<', output_sentence)\n print('')\n\nprint('-----------------------')","sub_path":"seq2seq_beamsearch/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"355445014","text":"from cls_webpage_fetcher import ClsWebpageFetcher\nfrom cls_excel_handler import ClsExcelHandler\nimport datetime\nfrom lxml import etree\nfrom typing import List\nfrom typing import Union\nfrom typing import NamedTuple\nimport PySimpleGUI as gui\nfrom functools import wraps\nfrom win10toast import ToastNotifier\n\n\nclass ClsTaiwanStock():\n def __init__(self):\n self._fetcher = ClsWebpageFetcher()\n self._excel = ClsExcelHandler()\n self._current_process_count: int = 0\n self._total_process_count: int = 0\n self.books_path: str = ''\n self.notifier = ToastNotifier()\n\n def main(self):\n try:\n config = self.show_config_form()\n if config.action == 'Submit':\n self.books_path = config.drive_letter + ':\\\\' + config.directory_name\n self._excel.open_books_directory(self.books_path)\n self.get_stock_files(config)\n self.notifier.show_toast('Stock Statments', '建立完成')\n else:\n self.show_popup('取消建立!')\n except ValueError as ex:\n gui.Popup(ex)\n\n def show_current_process(function):\n @wraps(function)\n def wrapper(self, *args, **kwargs):\n func = function(self, *args, **kwargs)\n self._current_process_count += 1\n self.notifier.show_toast('Stock Statments', '完成進度:' + str(round((self._current_process_count / self._total_process_count * 100), 2)) + '%', duration=1)\n return func\n return wrapper\n\n @show_current_process\n def get_basic_info_files(self, stock: NamedTuple('stock', [('id', str), ('name', str)])):\n \"\"\"\n 取得台股上巿股票基本資料檔案\n\n Arguments:\n stock -- 股票代號/名稱\n \"\"\"\n def get_basic_info() -> List[List[str]]:\n \"\"\"\n 取得台股上巿股票基本資料\n\n Returns:\n 基本資料\n \"\"\"\n basic_info = dict()\n\n html = self._fetcher.download_html('http://mops.twse.com.tw/mops/web/t05st03', 'post', 'firstin=1&co_id=' + stock.id)\n\n title = ''\n rows = self._fetcher.find_elements(html, '//table[@class=\"hasBorder\"]//tr')\n for row in rows:\n if (row[0].text.strip() == '本公司'):\n basic_info[row[2].text.strip()] = row[1].text.strip()\n basic_info[row[5].text.strip()] = row[4].text.strip()\n if (row[0].text.strip() == '本公司採'):\n basic_info['會計年度月制(現)'] = row[1].text.strip()\n if (row[0].text.strip() == '本公司於'):\n basic_info['會計年度月制(前)'] = row[3].text.strip()\n basic_info['會計年度月制轉換'] = row[1].text.strip()\n if (row[0].text.strip() == '編製財務報告類型'):\n report_type = row[1].text.strip()\n basic_info[row[0].text.strip()] = report_type[1:3] if report_type[0] == '●' else report_type[4:6]\n else:\n for index, cell in enumerate(row, start=1):\n if (index % 2 == 1):\n if (cell.tag == 'th'):\n title = cell.text.strip()\n basic_info[title] = ''\n else:\n if (cell.tag == 'td'):\n basic_info[title] = cell.text.strip()\n basic_info_list = self._to_list(basic_info)\n\n return basic_info_list\n\n book_path = self.books_path + '\\\\' + stock.id + '(' + stock.name + ')_基本資料' + '.xlsx'\n if not self._excel.is_book_existed(book_path):\n self._fetcher.wait(30, 35)\n self._excel.open_book(book_path)\n basic_info = get_basic_info()\n self._excel.write_to_sheet(basic_info)\n self._excel.save_book(book_path)\n\n def get_stock_list(self, start_stock_id: str, finish_stock_id: str) -> List[NamedTuple('stock', [('id', str), ('name', str)])]:\n \"\"\"\n 取得台股上巿股票代號/名稱列表\n\n Returns:\n 股票代號/名稱列表\n \"\"\"\n stock_list = list()\n\n html = self._fetcher.download_html('http://www.twse.com.tw/zh/stockSearch/stockSearch')\n\n stock_items = self._fetcher.find_elements(html, '//table[@class=\"grid\"]//a/text()')\n for stock_item in stock_items:\n stock = NamedTuple('stock', [('id', str), ('name', str)])\n stock.id = stock_item[0:4]\n stock.name = stock_item[4:]\n if stock.id >= (start_stock_id if start_stock_id != '' else '0000') and stock.id <= (finish_stock_id if finish_stock_id != '' else '9999'):\n stock_list.append(stock)\n return stock_list\n\n def _get_periods(self, start_season: str, finish_season: str) -> List[NamedTuple('period', [('roc_year', str), ('ad_year', str), ('season', str)])]:\n html = self._fetcher.download_html('http://mops.twse.com.tw/server-java/t164sb01')\n\n years = self._fetcher.find_elements(html, '//select[@id=\"SYEAR\"]//option/@value')\n current_year = datetime.datetime.now().year\n\n periods = list()\n\n for year in reversed(years):\n if int(year) <= current_year:\n first_season_date = datetime.datetime(int(year), 5, 15)\n second_season_date = datetime.datetime(int(year), 8, 14)\n third_season_date = datetime.datetime(int(year), 11, 14)\n fourth_season_date = datetime.datetime(int(year) + 1, 3, 31)\n\n for season in reversed(['01', '02', '03', '04']):\n if ((season == '01' and datetime.datetime.now() > first_season_date) or\n (season == '02' and datetime.datetime.now() > second_season_date) or\n (season == '03' and datetime.datetime.now() > third_season_date) or\n (season == '04' and datetime.datetime.now() > fourth_season_date)):\n period = NamedTuple('period', [('roc_year', str), ('ad_year', str), ('season', str)])\n period.ad_year = year\n period.roc_year = str(int(year) - 1911)\n period.season = season\n periods.append(period)\n\n return periods[int((start_season if start_season != '' else '1')) - 1:int(finish_season if finish_season != '' else str(len(periods)))]\n\n @show_current_process\n def get_statment_file(self, table_type: str, stock: NamedTuple('stock', [('id', str), ('name', str)]), period: NamedTuple('period', [('roc_year', str), ('ad_year', str), ('season', str)])):\n \"\"\"\n 取得財務狀況Excel檔案\n\n Arguments:\n table_type -- 表格類型(資產負債表/綜合損益表/權益變動表/現金流量表/財報附註/財務分析/股利分配/會計報告)\n stock -- 股票代碼\n period -- 年度季別\n \"\"\"\n\n def get_statment_table() -> List[str]:\n \"\"\"\n 取得表格內容\n\n Returns:\n 表格內容\n \"\"\"\n if table_type == '資產負債表':\n row_xpath = '//table[@class=\"hasBorder\"]//tr[not(th)]'\n cell_xpath = './td[position() <= 3]'\n url = 'http://mops.twse.com.tw/mops/web/ajax_t164sb03'\n data = 'encodeURIComponent=1&step=1&firstin=1&off=1&keyword4=&code1=&TYPEK2=&checkbtn=&queryName=co_id&inpuType=co_id&TYPEK=all&isnew=false&co_id={0}&year={1}&season={2}'.format(stock.id, period.roc_year, period.season)\n elif table_type == '綜合損益表':\n row_xpath = '//table[@class=\"hasBorder\"]//tr[not(th)]'\n cell_xpath = './td[position() <= 3]'\n url = 'http://mops.twse.com.tw/mops/web/ajax_t164sb04'\n data = 'encodeURIComponent=1&step=1&firstin=1&off=1&keyword4=&code1=&TYPEK2=&checkbtn=&queryName=co_id&inpuType=co_id&TYPEK=all&isnew=false&co_id={0}&year={1}&season={2}'.format(stock.id, period.roc_year, period.season)\n elif table_type == '現金流量表':\n row_xpath = '//table[@class=\"hasBorder\"]//tr[not(th)]'\n cell_xpath = './td[position() <= 2]'\n url = 'http://mops.twse.com.tw/mops/web/ajax_t164sb05'\n data = 'encodeURIComponent=1&step=1&firstin=1&off=1&keyword4=&code1=&TYPEK2=&checkbtn=&queryName=co_id&inpuType=co_id&TYPEK=all&isnew=false&co_id={0}&year={1}&season={2}'.format(stock.id, period.roc_year, period.season)\n elif table_type == '權��變動表':\n row_xpath = '//table[@class=\"hasBorder\" and position() = 2]//tr[position() >=3]'\n cell_xpath = './*'\n url = 'http://mops.twse.com.tw/mops/web/ajax_t164sb06'\n data = 'encodeURIComponent=1&step=1&firstin=1&off=1&keyword4=&code1=&TYPEK2=&checkbtn=&queryName=co_id&inpuType=co_id&TYPEK=all&isnew=false&co_id={0}&year={1}&season={2}'.format(stock.id, period.roc_year, period.season)\n elif table_type == '財報附註':\n row_xpath = '//table[@class=\"main_table hasBorder\" and contains(., \"財報附註\")]//tr[position() >= 2]'\n cell_xpath = './td'\n url = 'http://mops.twse.com.tw/server-java/t164sb01'\n data = 'step=1&CO_ID={0}&SYEAR={1}&SSEASON={2}&REPORT_ID=C'.format(stock.id, period.ad_year, period.season.replace(\"0\", \"\"))\n elif table_type == '財務分析':\n row_xpath = '//table[@style = \"width:90%;\"]//tr[position() >= 2]'\n cell_xpath = './th[@style = \"text-align:left !important;\"] | ./td[position() = 3]'\n url = 'http://mops.twse.com.tw/mops/web/ajax_t05st22'\n data = 'encodeURIComponent=1&run=Y&step=1&TYPEK=sii&year={1}&isnew=false&co_id={0}&firstin=1&off=1&ifrs=Y'.format(stock.id, period.roc_year)\n elif table_type == '股利分配':\n row_xpath = '//table[@class=\"hasBorder\"]//tr'\n cell_xpath = './*'\n url = 'http://mops.twse.com.tw/mops/web/ajax_t05st09'\n data = 'encodeURIComponent=1&step=1&firstin=1&off=1&keyword4=&code1=&TYPEK2=&checkbtn=&queryName=co_id&inpuType=co_id&TYPEK=all&isnew=false&co_id={0}&year={1}'.format(stock.id, period.roc_year)\n elif table_type == '會計報告':\n row_xpath = '//table[@class=\"main_table hasBorder\" and contains(., \"會計師查核報告\")]//tr[position() >= 2]'\n cell_xpath = './td'\n url = 'http://mops.twse.com.tw/server-java/t164sb01'\n data = 'step=1&CO_ID={0}&SYEAR={1}&SSEASON={2}&REPORT_ID=C'.format(stock.id, period.ad_year, period.season.replace(\"0\", \"\"))\n else:\n raise ValueError('table_type值只能是(資產負債表/綜合損益表/權益變動表/現金流量表/財報附註/財務分析/股利分配/會計報告)其中之一')\n\n records = list()\n\n html = self._fetcher.download_html(url, 'post', data)\n rows = self._fetcher.find_elements(html, row_xpath)\n\n for row in rows:\n record = list()\n cells = row.xpath(cell_xpath)\n for cell in cells:\n record.append(''.join(cell.itertext()).strip())\n records.append(record)\n\n return records\n\n book_path = self.books_path + '\\\\' + stock.id + '(' + stock.name + ')_{0}'.format(table_type) + '.xlsx'\n self._excel.open_book(book_path)\n\n sheet_name = period.ad_year + '_' + period.season\n if not self._excel.is_sheet_existed(sheet_name):\n self._fetcher.wait(30, 35)\n self._excel.open_sheet(sheet_name)\n table = get_statment_table()\n self._excel.write_to_sheet(table)\n self._excel.save_book(book_path)\n\n def _to_list(self, source: Union[dict, etree.Element]) -> List[List[str]]:\n result = list()\n\n if type(source) is dict:\n for key, value in source.items():\n result.append([key, value])\n return result\n elif type(source) is etree._Element:\n for row in source:\n record = list()\n for cell in row:\n record.append(cell.text)\n result.append(record)\n return result\n\n return result\n\n def show_config_form(self) -> NamedTuple('result', [('action', str), ('drive_letter', str), ('directory_name', str), ('start_stock_id', str), ('finish_stock_id', str), ('start_season', str), ('finish_season', str)]):\n \"\"\"\n 開啟設定介面\n\n Returns:\n 設定結果(執行動作+磁碟代號+目錄名稱+前n季)\n \"\"\"\n form = gui.FlexForm('設定台股上巿股票Excel存放路徑')\n layout = [\n [gui.Text('請輸入下載Excel存放的磁碟代號及目錄名稱')],\n [gui.Text('磁碟代號', size=(15, 1), key='Drive'), gui.InputText('D')],\n [gui.Text('目錄名稱', size=(15, 1), key='Folder'), gui.InputText('Excel')],\n [gui.Text('請輸入起始股票代碼(未輸入=不限)')], [gui.Text('代碼', size=(15, 1), key='StartStockId'), gui.InputText('')],\n [gui.Text('請輸入結束股票代碼(未輸入=不限)')], [gui.Text('代碼', size=(15, 1), key='FinishStockId'), gui.InputText('')],\n [gui.Text('請輸入起始季數(未輸入=不限)')], [gui.Text('季數', size=(15, 1), key='StartSeason'), gui.InputText('1')],\n [gui.Text('請輸入結束季數(未輸入=不限)')], [gui.Text('季數', size=(15, 1), key='FinishSeason'), gui.InputText('1')],\n [gui.Submit(), gui.Cancel()]\n ]\n window = form.Layout(layout)\n return_values = window.Read()\n\n window.Close()\n\n result = NamedTuple('result', [('action', str), ('drive_letter', str), ('directory_name', str), ('start_stock_id', str), ('finish_stock_id', str), ('start_season', str), ('finish_season', str)])\n result.action = return_values[0]\n result.drive_letter = return_values[1][0]\n result.directory_name = return_values[1][1]\n result.start_stock_id = return_values[1][2]\n result.finish_stock_id = return_values[1][3]\n result.start_season = return_values[1][4]\n result.finish_season = return_values[1][5]\n\n return result\n\n def show_popup(self, message: str):\n \"\"\"\n 顯示跳顯訊息\n\n Arguments:\n message -- 訊息文字\n \"\"\"\n gui.Popup(message)\n pass\n\n def get_stock_files(self, config: NamedTuple('result', [('action', str), ('drive_letter', str), ('directory_name', str), ('start_stock_id', str), ('finish_stock_id', str), ('start_season', str), ('finish_season', str)])):\n stock_list = self.get_stock_list(config.start_stock_id, config.finish_stock_id)\n stock_count = len(stock_list)\n periods = self._get_periods(config.start_season, config.finish_season)\n period_count = len(periods)\n roc_years = self._get_roc_years(periods)\n roc_year_count = len(roc_years)\n self._total_process_count = stock_count + (stock_count * roc_year_count) + (stock_count * period_count * 7)\n\n for stock in stock_list:\n self.get_basic_info_files(stock)\n for roc_year in roc_years:\n self.get_analysis_file(stock, roc_year)\n for period in periods:\n if (roc_year == period.roc_year):\n self.get_statment_files(stock, period)\n\n def get_statment_files(self, stock: NamedTuple('stock', [('id', str), ('name', str)]), period: NamedTuple('period', [('roc_year', str), ('ad_year', str), ('season', str)])):\n self.get_statment_file('資產負債表', stock, period)\n self.get_statment_file('綜合損益表', stock, period)\n self.get_statment_file('現金流量表', stock, period)\n self.get_statment_file('權益變動表', stock, period)\n self.get_statment_file('財報附註', stock, period)\n self.get_statment_file('股利分配', stock, period)\n self.get_statment_file('會計報告', stock, period)\n\n def _get_roc_years(self, periods: List[NamedTuple('period', [('roc_year', str), ('ad_year', str), ('season', str)])]):\n years = list()\n\n for period in periods:\n years.append(period.roc_year)\n\n return years\n\n def get_analysis_file(self, stock: NamedTuple('stock', [('id', str), ('name', str)]), roc_year: str):\n period = NamedTuple('period', [('roc_year', str), ('ad_year', str), ('season', str)])\n period.roc_year = roc_year\n period.ad_year = str(int(roc_year) + 1911)\n period.season = \"00\"\n self.get_statment_file('財務分析', stock, period)\n","sub_path":"cls_taiwan_stock.py","file_name":"cls_taiwan_stock.py","file_ext":"py","file_size_in_byte":17082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"160053849","text":"###### Spectral Embedding & Spectral Clustering ######\r\n###### Artificial Intelligence ######\r\n###### Statistical Learning - Computational Intelligence #######\r\n\r\n\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\nimport time\r\n\r\nfrom sklearn import metrics\r\nimport seaborn as sns\r\nfrom sklearn.preprocessing import MinMaxScaler\r\nfrom sklearn.metrics.cluster import contingency_matrix\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.preprocessing import LabelEncoder\r\n\r\nfrom sklearn.cluster import KMeans\r\nfrom sklearn.manifold import TSNE\r\nfrom sklearn.manifold import LocallyLinearEmbedding\r\nfrom sklearn.manifold import Isomap\r\nfrom sklearn.manifold import MDS\r\nfrom sklearn import linear_model\r\nfrom sklearn.multioutput import MultiOutputRegressor\r\n\r\nsave_pictures_to = 'C:/Users/User/Desktop/tefas/shapes/pictures directory/'\r\n\r\ndef clustering_print_scores(labels,X,n):\r\n cla = KMeans(n_clusters = n,random_state=0).fit(X)\r\n pred_classes = cla.predict(X)\r\n print('--Number of clusters is %.f --\\n' %n)\r\n print('--Homogenity of clusters is %.3f --' %metrics.homogeneity_score(labels,pred_classes),'\\n')\r\n print('--Silhouette measure of clusters is %.3f--' %metrics.silhouette_score(X,pred_classes),'\\n')\r\n print('--Completness of clusters is %.3f --' %metrics.completeness_score(labels,pred_classes),'\\n')\r\n print('--V measure score of clusters is %.3f--' %metrics.v_measure_score(labels,pred_classes),'\\n')\r\n print('--Adjusted Mutual Information score of clusters is %.3f--'\\\r\n %metrics.adjusted_mutual_info_score(labels,pred_classes),'\\n')\r\n print('--Calinski Harabaz Index score is %.3f--' %metrics.calinski_harabaz_score(X,pred_classes),'\\n')\r\n print('--Purity Score is %.3f--' %purity_score(labels,pred_classes))\r\n vm[n-2] = metrics.v_measure_score(labels,pred_classes)\r\n pur[n-2] = purity_score(labels,pred_classes)\r\n sil[n-2] = metrics.silhouette_score(X,pred_classes)\r\n cal[n-2] = metrics.calinski_harabaz_score(X,pred_classes)\r\n c_m = contingency_matrix(labels,pred_classes)\r\n df_cm=pd.DataFrame(c_m).rename(index = {i:'Class : %.f' %i for i in range(4)}\\\r\n ,columns={i:'Cluster : %.f' %i for i in range(n)})\r\n plt.figure(figsize=(5,5))\r\n sns.heatmap(df_cm,annot=True,linewidths=.5)\r\n plt.title('Contigency Matrix C_ij True class i and Predicted j')\r\n plt.show()\r\n\r\ndef plot(X,y,title):\r\n plt.figure(figsize = (8,8))\r\n for color,marker,i in zip(colorlist,markers,n_r):\r\n plt.scatter(X [y == i ,0] ,X [y == i,1],\r\n marker=marker , color=color ,label='shapes'+str(i))\r\n plt.title(title+ 'scatter plot') \r\n plt.xlabel('component 1')\r\n plt.ylabel('component 2')\r\n plt.legend() \r\n plt.show() \r\n\r\n#Using Bayesian Ridge because its suited for datasets with large features\r\ndef regression(X_before,X_After,X_test):\r\n regressor = linear_model.BayesianRidge()\r\n multi_reg = MultiOutputRegressor(regressor).fit(X_before,X_After)\r\n X_new = multi_reg.predict(X_test)\r\n return(X_new)\r\n\r\n\r\ndef plot_metrics(X, title):\r\n plt.figure(figsize=(7, 7))\r\n plt.style.use('bmh')\r\n plt.plot(range(2, 8), X, marker='o')\r\n plt.xlabel('Number of clusters, k')\r\n plt.ylabel(title)\r\n plt.show()\r\n\r\n\r\ndef scores_for_test(labels,pred_classes,X):\r\n print('--Number of clusters is %.f --\\n' %4)\r\n print('--Homogenity of clusters is %.3f --' %metrics.homogeneity_score(labels,pred_classes),'\\n')\r\n print('--Silhouette measure of clusters is %.3f--' %metrics.silhouette_score(X,pred_classes),'\\n')\r\n print('--Completness of clusters is %.3f --' %metrics.completeness_score(labels,pred_classes),'\\n')\r\n print('--V measure score of clusters is %.3f--' %metrics.v_measure_score(labels,pred_classes),'\\n')\r\n print('--Adjusted Mutual Information score of clusters is %.3f--'\\\r\n %metrics.adjusted_mutual_info_score(labels,pred_classes),'\\n')\r\n print('--Calinski Harabaz Index score is %.3f--' %metrics.calinski_harabaz_score(X,pred_classes),'\\n')\r\n print('--Purity Score is %.3f--' %purity_score(labels,pred_classes))\r\n c_m = contingency_matrix(labels,pred_classes)\r\n df_cm=pd.DataFrame(c_m).rename(index = {i:'Class : %.f' %i for i in range(4)}\\\r\n ,columns={i:'Cluster : %.f' %i for i in range(4)})\r\n plt.figure(figsize=(5,5))\r\n sns.heatmap(df_cm,annot=True,linewidths=.5)\r\n plt.title('Contigency Matrix C_ij True class i and Predicted j')\r\n plt.show()\r\n\r\ndef purity_score(y_true, y_pred):\r\n # compute contingency matrix (also called confusion matrix)\r\n contingency_matrix = metrics.cluster.contingency_matrix(y_true, y_pred)\r\n # return purity\r\n return np.sum(np.amax(contingency_matrix, axis=0)) / np.sum(contingency_matrix)\r\n","sub_path":"MSAI/Spectral-Embedding-and-Spectral-Clustering/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"78818808","text":"# 내 풀이.\ndef solution(s):\n\n if len(s) % 2:\n answer = s[len(s) // 2]\n else:\n answer = s[(len(s) // 2) - 1:len(s) // 2 + 1]\n\n print(str[(len(str)-1)//2:len(str)//2+1])\n return answer\n\ns1 = 'abcde'\ns2 = 'qwer'\ns3 = 'qw'\ns4 = 'q'\n# print(solution(s1))\n# print(solution(s2))\n# print(solution(s3))\n# print(solution(s4))\n\n\n# 다른사람 풀이\n\n# 풀이 1.\ndef solution2(s):\n return s[(len(s) - 1) // 2:len(s) // 2 + 1]\n\n\nprint(solution2(s1))\nprint(solution2(s2))\nprint(solution2(s3))\nprint(solution2(s4))","sub_path":"Programmers/level1/가운데 글자 가져오기.py","file_name":"가운데 글자 가져오기.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"36165182","text":"import http.client\nimport json\nfrom constants import (token, SQL_COMPETITION_CODE, SQL_TEAM_IDS,\n SQL_TOTAL_PLAYERS, HTTP_CODES)\nfrom time import sleep\nfrom importer import import_to_db\nfrom database import db\n\n\nclass FootballData():\n\n COMPETITIONS = '/v2/competitions/{}'\n TEAMS = '/v2/competitions/{}/teams'\n TEAM = '/v2/teams/{}'\n\n def __init__(self):\n \"\"\"Constructor, creates connection\"\"\"\n self.connection, self.headers = self.get_connection()\n\n def get_connection(self):\n \"\"\"Establish connection\"\"\"\n connection = http.client.HTTPConnection('api.football-data.org')\n headers = {'X-Auth-Token': token}\n return connection, headers\n\n def request(self, url, method='GET'):\n \"\"\"Request to football API\n\n Arguments:\n url - url to get competitions, teams or squad\n \"\"\"\n self.connection.request(method, url,\n None, self.headers)\n response = json.loads(self.connection.getresponse().read().decode())\n print(response)\n return response\n\n def get_data(self, url):\n response = {'errorCode': 999}\n while 'errorCode' in response.keys():\n print('retry connection')\n response = self.request(url)\n return response\n\n def import_league(self, code):\n \"\"\"Get all data from football API\n\n Arguments:\n code - league code\n \"\"\"\n res = False\n id_teams = []\n print(code)\n imported = self.competition_imported(code)\n if imported:\n return HTTP_CODES.ALREADY_IMPORTED\n league = self.get_competition(code)\n if 'errorCode' in league.keys():\n res = HTTP_CODES.CONNECTION_ERROR\n elif 'error' in league.keys():\n res = HTTP_CODES.NOT_FOUND_ERROR\n else:\n try:\n teams = self.get_teams(league['id'])\n id_teams = [t['id'] for t in teams['teams']]\n league['teams'] = teams['teams']\n inserted_teams = self.already_inserted_teams(id_teams)\n print(type(inserted_teams))\n for i, team in enumerate(league['teams']):\n # only do the request if the team is not in the database\n print('id {} - {}'.format(team['id'], inserted_teams))\n if int(team['id']) not in inserted_teams:\n print('peticion {}'.format(team['id']))\n squad = self.get_team(team['id'])\n league['teams'][i]['squad'] = squad['squad']\n # get 5 only for demonstration purposes,\n # with the free api access, the restriction is 10 request per minute\n if i > 5:\n break\n try:\n import_to_db(league)\n res = HTTP_CODES.OK\n except Exception as e:\n res = HTTP_CODES.NOT_FOUND_ERROR\n except Exception as e:\n res = HTTP_CODES.CONNECTION_ERROR\n return res\n\n def get_competition(self, code):\n \"\"\"Get competition from football API\n\n Arguments:\n code - league code\n \"\"\"\n response = self.request(self.COMPETITIONS.format(code))\n return response\n\n def get_teams(self, id_league):\n \"\"\"Get teams from football API\n\n Arguments:\n id_league - league id\n \"\"\"\n response = self.request(self.TEAMS.format(id_league))\n return response\n\n def get_team(self, id_team):\n \"\"\"Get squad (and other data from the team) from football API\n\n Arguments:\n id_team - team id\n \"\"\"\n response = self.request(self.TEAM.format(id_team))\n return response\n\n def get_total_players(self, code):\n \"\"\"Total players by league code\n\n Arguments:\n code - league code\n \"\"\"\n res = 0\n sql = SQL_TOTAL_PLAYERS.format(code)\n query = db.engine.execute(sql)\n result = query.fetchone()\n if result:\n res = result[1]\n return res\n\n def already_inserted_teams(self, id_teams):\n \"\"\"Returns already inserted teams\n\n Arguments:\n id_teams - array with teams that belongs to a league\n \"\"\"\n sql = SQL_TEAM_IDS.format(str(id_teams)[1:-1])\n query = db.engine.execute(sql)\n return [r[0] for r in query.fetchall()]\n\n def competition_imported(self, code):\n \"\"\"Check if competition exists\n\n Arguments:\n code - league code\n \"\"\"\n res = False\n sql = SQL_COMPETITION_CODE.format(code)\n query = db.engine.execute(sql)\n result = query.fetchone()\n if result:\n res = True\n return res\n","sub_path":"app/football_data.py","file_name":"football_data.py","file_ext":"py","file_size_in_byte":4885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"66407568","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 1 20:10:58 2020\n\n@author: Paul\n\"\"\"\n\nimport pandas as pd\nimport tweepy\nimport yfinance\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output\nimport plotly.graph_objs as go\nimport yaml\nimport text_analysis\nimport read_files\n\nconfig = read_files.read_yaml_file('config.yaml')\n\nconsumer_key = config['TWITTER_ACCOUNT']['CONSUMER_KEY']\nconsumer_secret = config['TWITTER_ACCOUNT']['CONSUMER_SECRET']\naccess_token = config['TWITTER_ACCOUNT']['ACCESS_TOKEN']\naccess_token_secret = config['TWITTER_ACCOUNT']['ACCESS_TOKEN_SECRET']\n\nauthenticate = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauthenticate.set_access_token(access_token, access_token_secret)\n\napi = tweepy.API(authenticate, wait_on_rate_limit=True)\n\ndf_names = read_files.read_stock_names_tickers('stocks_names.txt')\nnames_dict = df_names.to_dict()['name']\n\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\n\napp = dash.Dash(__name__, external_stylesheets = external_stylesheets)\nserver = app.server\n\napp.layout = html.Div(children=[\n html.H1(children='Stock analysis app',\n style={'width': '20%', 'display': 'inline-block'}),\n\n html.Div([\n html.Div(children='Choose stock, wich you are interested in'),\n dcc.Dropdown(\n id='companies_choice',\n options=[{'label': names_dict[company], 'value': company}\n for company in names_dict]\n )\n\n ], style={'width': '20%', 'display': 'inline-block'}),\n\n html.Div([\n dcc.RangeSlider(\n id='time_filter',\n updatemode='drag',\n marks={}\n )\n ], style={'width': '80%', 'display': 'inline-block'} ),\n html.Div([\n dcc.Graph(id='stock_plot'),\n dcc.Graph(id='sentiment_chart')\n ], style={'width': '49%', 'display': 'inline-block'}),\n\n html.Div(id='current_tweets', style={'whiteSpace': 'pre-line', 'display': 'inline-block', 'width': '49%'})\n] )\n\n@app.callback(\n Output('stock_plot', 'figure'),\n [Input('companies_choice', 'value')])\ndef update_stock_plot(selected_company):\n if selected_company != None:\n df_temp = yfinance.Ticker(selected_company)\n df_temp = df_temp.history(period='max')[['Close']]\n # df_temp = df_temp.loc[slider_value]\n fig = go.Figure()\n fig.add_trace(go.Scatter(x=df_temp.index,\n y=df_temp['Close'].values,\n mode='lines'))\n fig.update_layout(title='Stocks history for {} company'.format(selected_company),\n xaxis_title='Date',\n yaxis_title='Stock rate [USD]')\n return fig\n else:\n return go.Figure()\n\n@app.callback(\n Output('current_tweets', 'children'),\n Input('companies_choice', 'value'))\ndef update_tweets(selected_company):\n if selected_company != None:\n tweets = tweepy.Cursor(api.search, q=names_dict[selected_company], \n lang=\"en\").items(100)\n tweets_content = [text_analysis.clean_text(tweet.text) + '\\n' for tweet in tweets]\n return tweets_content[:20]\n\n@app.callback(\n Output('sentiment_chart', 'figure'),\n Input('companies_choice', 'value'))\ndef update_sentiment_chart(selected_company):\n if selected_company != None:\n tweets = tweepy.Cursor(api.search, q=names_dict[selected_company], \n lang=\"en\").items(100)\n df = pd.DataFrame([tweet.text for tweet in tweets], columns=['Tweets'])\n df['Tweets'] = df['Tweets'].apply(text_analysis.clean_text)\n df['Subjectivity'] = df['Tweets'].apply(text_analysis.get_subjectivity)\n df['Polarity'] = df['Tweets'].apply(text_analysis.get_polarity)\n df['Sentiment'] = df['Polarity'].apply(text_analysis.get_sentiment)\n df_sentiment_output = df['Sentiment'].value_counts().sort_index(ascending=False)\n fig = go.Figure()\n sentiment_color = {'Positive': 'green', 'Neutral': 'yellow', 'Negative': 'red'}\n fig.add_trace(go.Bar(x=df_sentiment_output.index,\n y=df_sentiment_output.values,\n orientation='v',\n marker=dict(\n color=[color for sentiment, color in sentiment_color.items() if sentiment in df_sentiment_output.index.to_list()],\n opacity=0.5)))\n return fig\n else:\n return go.Figure()\n\n\nif __name__ == '__main__':\n app.run_server(debug=True)\n","sub_path":"dash_stocks_app.py","file_name":"dash_stocks_app.py","file_ext":"py","file_size_in_byte":4615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"7383354","text":"#uproszczony plik jak z faif\n\nclass Module:\n path = './src/'\n head = [ ]\n test = [ ]\n\npr = Module()\npr.path = ''\nsrc = pr.path\npr.head = [src+'hello.cpp', src+'EvolutionaryAlgorithm.hpp', src+'Space.hpp']\n\n\n#klasy pomocnicze (utils) - teraz wlasciwie tylko po to zeby sprawdzic czy dziala budowanie testow - w przeciwnym razie mozna przenisc Random do glownego i tyle\nutils = Module()\nutils.path = 'utils/'\nsrc = utils.path\nutils.head = [ src+'Random.hpp', src+'GaussEliminator.hpp', src+'Power.hpp', src+'RandomCustomDistr.hpp']\n\nmodules = [pr]\n","sub_path":"EvolutionaryFaif/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"61051972","text":"# 1. Написать ф-цию которая выбрасывает одно из трех исключений: ValueError, TypeError или RuntimeError случайным\n# В месте вызова ф-ции обрабатывать все три исключения\n# 2. Написать ф-цию, которая принимает на вход список, если в списке все объекты - int, сортирует\n# 3. Написать ф-цию которая принимает словарь, преобразует все ключи словаря к строкам и возвращает новый словарь\n# 4. Написать ф-цию, которая принимает список чисел и возвращает их произведение\n\n# 1\nimport random\n\nrandom_num = random.randint(1, 3)\n\ndef random_error(num):\n if num == 1:\n raise ValueError\n elif num == 2:\n raise TypeError\n else:\n raise RuntimeError\n\ntry:\n random_error(random_num)\nexcept ValueError as v_e:\n print(\"Value Error was raised {}\".format(v_e))\nexcept TypeError as t_e:\n print(\"Type Error was raised {}\".format(t_e))\nexcept RuntimeError as r_e:\n print(\"Runtime Error was raised {}\".format(r_e))\n\nprint(\"\\n\\n\")\n\n# 2\nint_list = [3, 4, 7, 10, 2, 1, 9]\nnot_int_list = [\"sd\", 2, 5, True, 10]\n\ndef check_int_and_sort(check_list):\n for i in check_list:\n if type(i) != int:\n check = False\n break\n else:\n check = True\n\n if check == True:\n check_list.sort()\n print(check_list)\n else:\n print(\"Not all elements in the list are integers\")\n\ncheck_int_and_sort(int_list)\n\nprint(\"\\n\\n\")\n\n# 3\ndic_for_def = {4: \"four\", '3': \"three\", 11: \"eleven\", 8: \"eight\", '9': \"nine\", False: \"zero\", True: \"one\"}\n\ndef key_dict_to_str(change_dict):\n for i in change_dict.keys():\n if type(i) != str:\n change_dict[str(i)] = change_dict.pop(i)\n\n print(change_dict)\n\nkey_dict_to_str(dic_for_def)\n\nprint('\\n\\n')\n\n# 4\nnum_list_mult = [2, 4, 3, 7, 9, 6]\n\ndef multiple_list(m_list):\n mult_value = 1\n\n for i in m_list:\n if type(i) != int:\n mult_value = \"One of the value in list not an integer\"\n break\n else:\n mult_value *= i\n\n if mult_value != int:\n print('Multiple list values is {}'.format(mult_value))\n else:\n print(mult_value)\n\nmultiple_list(num_list_mult)","sub_path":"lesson3/exercises/lesson_exercises.py","file_name":"lesson_exercises.py","file_ext":"py","file_size_in_byte":2462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"526232938","text":"import tensorflow.compat.v1 as tf\ntf.disable_v2_behavior()\nimport numpy as np \nimport gym\n\nenv = gym.make('CartPole-v0')\n\nstate_size = env.observation_space.shape[0]\nnum_actions = env.action_space.n\n\ngamma = 0.9\n\ndef discount_and_normalise_rewards(episode_rewards):\n\tdiscounted_rewards = np.zeros_like(episode_rewards)\n\treward_to_go = 0\n\tfor i in reversed(range(len(episode_rewards))):\n\t\treward_to_go = reward_to_go*gamma + episode_rewards[i]\n\t\tdiscounted_rewards[i] = reward_to_go\n\n\tdiscounted_rewards -= np.mean(discounted_rewards)\n\tdiscounted_rewards /= np.std(discounted_rewards)\n\n\treturn discounted_rewards\n\nstate_ph = tf.placeholder(tf.float32, [None, state_size], name = 'state_ph')\naction_ph = tf.placeholder(tf.float32, [None, num_actions], name = 'action_ph')\ndiscounted_rewards_ph = tf.placeholder(tf.float32, [None,], name = 'discounted_rewards_ph')\n\nlayer1 = tf.layers.dense(state_ph, units = 32, activation = tf.nn.relu)\nlayer2 = tf.layers.dense(layer1, units = num_actions)\n\nprob_dist = tf.nn.softmax(layer2)\n\nneg_log_policy = tf.nn.softmax_cross_entropy_with_logits_v2(logits = layer2, labels = action_ph)\nloss = tf.reduce_mean(neg_log_policy * discounted_rewards_ph)\ntrain = tf.train.AdamOptimizer(0.01).minimize(loss)\n\nnum_iterations = 1000\nwith tf.Session() as sess:\n\tsess.run(tf.global_variables_initializer())\n\tfor i in range(num_iterations):\n\t\tepisode_states, episode_rewards, episode_actions = [],[],[]\n\t\tdone = False\n\t\ttotal_reward = 0\n\t\tstate = env.reset()\n\n\t\twhile not done:\n\t\t\tstate = state.reshape([1,4])\n\t\t\tpi = sess.run(prob_dist, feed_dict = {state_ph:state})\n\t\t\ta = np.random.choice(range(pi.shape[1]), p=pi.ravel())\n\t\t\tnext_state, reward, done, info = env.step(a)\n\t\t\tenv.render()\n\t\t\ttotal_reward += reward\n\t\t\taction = np.zeros(num_actions)\n\t\t\taction[a] = 1\n\t\t\tepisode_states.append(state)\n\t\t\tepisode_actions.append(action)\n\t\t\tepisode_rewards.append(reward)\n\n\t\t\tstate = next_state\n\n\t\tdiscounted_rewards = discount_and_normalise_rewards(episode_rewards)\n\t\tfeed_dict = {state_ph: np.vstack(np.array(episode_states)),\n\t\t\t\t\taction_ph: np.vstack(np.array(episode_actions)),\n\t\t\t\t\tdiscounted_rewards_ph: discounted_rewards}\n\n\t\tloss_,_ = sess.run([loss, train], feed_dict = feed_dict)\n\n\t\tif i%10==0:\n\t\t\tprint('Iteration: '+str(i)+'Total Reward: '+str(total_reward))\n","sub_path":"model-free/policy-optimisation/policy_gradient.py","file_name":"policy_gradient.py","file_ext":"py","file_size_in_byte":2290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"456172234","text":"import numpy as np\n\nfrom sklearn.utils import check_random_state\nfrom mne.io import BaseRaw\nfrom joblib import Memory\n\nfrom .core_smica import SMICA\nfrom .mne import ICA, transfer_to_mne\nfrom .utils import fourier_sampling\n\nlocation = './cachedir'\nmemory = Memory(location, verbose=0)\n\n\ndef _transform_set(M, D):\n '''Moves the matrices D using the matrix M\n\n Parameters\n ----------\n M : array-like, shape (N, N)\n Movement\n\n D : array-like, shape (K, N, N)\n Array of current estimated matrices. K is the number of matrices\n\n Returns\n -------\n op : array-like, shape (K, N, N)\n Array of the moved matrices. op[i] = M.D[i].M.T\n '''\n K, _, _ = D.shape\n N, _ = M.shape\n op = np.zeros((K, N, N))\n for i, d in enumerate(D):\n op[i] = M.dot(d.dot(M.T))\n return op\n\n\ndef _move(epsilon, D):\n '''Moves the matrices D by a perturbation epsilon\n\n Parameters\n ----------\n epsilon : array-like, shape (N, N)\n Perturbation\n\n D : array-like, shape (K, N, N)\n Array of current estimated matrices. K is the number of matrices\n\n Returns\n -------\n M : array-like, shape (N, N)\n Displacement matrix\n\n op : array-like, shape (K, N, N)\n Array of the moved matrices. op[i] = M.D[i].M.T\n '''\n _, N, _ = D.shape\n M = np.eye(N) + epsilon\n return M, _transform_set(M, D)\n\n\ndef _loss(B_list):\n op = 0.\n for B in B_list:\n Br = B.ravel()\n Bd = np.diag(B)\n op += Br.dot(Br) - Bd.dot(Bd)\n return op\n\n\ndef _joint_diag(C, max_iter, tol=1e-7, theta=0.5, max_ls_tries=20,\n verbose=False):\n if verbose:\n print(C.shape)\n K, N, _ = C.shape\n D = C.copy()\n W = np.eye(N)\n old_loss = _loss(D)\n step = 1.\n for n in range(max_iter):\n # Isolate the diagonals\n diagonals = np.diagonal(D, axis1=1, axis2=2)\n # Compute the z_ij\n z = np.dot(diagonals.T, diagonals)\n # Compute the y_ij\n y = np.sum(D * diagonals[:, None, :], axis=0)\n # Compute the new W\n z_diag = np.diagonal(z)\n det = (z_diag[:, None] * z_diag[None, :] - z ** 2) + np.eye(N)\n\n eps = (z * y.T - z_diag[:, None] * y) / det\n # np.fill_diagonal(W, 0.)\n # Stopping criterion\n norm = np.sqrt(np.mean(eps ** 2))\n if verbose:\n print(n, norm)\n if norm < tol:\n break\n # Scale\n if norm > theta:\n eps *= theta / norm\n # Move\n\n for ls in range(max_ls_tries):\n M, D_new = _move(step * eps, D)\n new_loss = _loss(D_new)\n if new_loss < old_loss:\n step = min(1, 2 * step)\n break\n else:\n step = max(step / 2, 1e-5)\n old_loss = new_loss\n D = D_new\n W = M @ W\n return W\n\n\n@memory.cache(ignore=['verbose'])\ndef sobi(X, lags, n_components=None,\n tol=1e-7, max_iter=1000, verbose=False):\n \"\"\"\n Use sobi for source estimation\n X : data matrix\n p : number of time lags to use\n \"\"\"\n n_sensors, n_samples = X.shape\n p = len(lags)\n if n_components is None:\n n_components = n_sensors\n u, d, _ = np.linalg.svd(X, full_matrices=False)\n del _\n whitener = (u / d).T[:n_components]\n del u, d\n Y = whitener.dot(X)\n C = np.zeros((p, n_components, n_components))\n for i, lag in enumerate(lags):\n t = n_samples - lag\n C[i] = np.dot(Y[:, -t:], Y[:, lag:].T) / t\n W = _joint_diag(C, max_iter=max_iter, tol=tol, verbose=verbose)\n return W.dot(whitener)\n\n\nclass SOBI(SMICA):\n def __init__(self, p, n_components,\n freqs, sfreq, avg_noise=False, rng=None):\n '''\n n_components : number of sources\n freqs : the frequency intervals\n sfreq : sampling frequency\n '''\n self.p = p\n self.lags = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9,\n 10, 12, 14, 16, 18, 20,\n 25, 30, 35, 40, 45, 50,\n 55, 60, 65, 70, 80, 90, 95, 100,\n 120, 140, 160, 180, 200, 220,\n 240, 260, 280, 300]) * sfreq / 1000\n self.lags = self.lags.astype(int)\n self.n_components = n_components\n self.freqs = freqs\n self.sfreq = sfreq\n self.avg_noise = avg_noise\n self.f_scale = 0.5 * (freqs[1:] + freqs[:-1])\n self.rng = check_random_state(rng)\n self.filtering_method = 'pinv'\n\n def fit(self, X, y=None, **kwargs):\n '''\n Fits sobi to data X (p x n matrix sampled at fs)\n '''\n self.X = X\n C, ft, freq_idx = fourier_sampling(X, self.sfreq, self.freqs)\n n_mat, n_sensors, _ = C.shape\n self.C_ = C\n self.ft_ = ft\n self.freq_idx_ = freq_idx\n W = sobi(X, self.lags, self.n_components, **kwargs)\n self.A_ = np.linalg.pinv(W)\n self.powers_ = np.zeros((n_mat, self.n_components))\n for i in range(n_mat):\n self.powers_[i] = np.diag(W.dot(C[i]).dot(W.T))\n scale = np.mean(self.powers_, axis=0, keepdims=True)\n self.A_ = self.A_ * np.sqrt(scale)\n self.powers_ = self.powers_ / scale\n self.sigmas_ = np.zeros((C.shape[0], X.shape[0]))\n return self\n\n def compute_sources(self, X=None, method='pinv'):\n if method == 'wiener':\n raise ValueError('Only method=pinv is implemented for SOBI')\n return super().compute_sources(X=X, method=method)\n\n\nclass SOBI_mne(ICA):\n def __init__(self, p, n_components, freqs, rng=None):\n self.p = p\n self.n_components = n_components\n self.freqs = freqs\n self.f_scale = 0.5 * (freqs[1:] + freqs[:-1])\n self.rng = check_random_state(rng)\n\n def fit(self, inst, picks=None, avg_noise=False, **kwargs):\n '''\n Fits smica to inst (either raw or epochs)\n '''\n self.inst = inst\n self.info = inst.info\n self.sfreq = inst.info['sfreq']\n self.picks = picks\n self.avg_noise = avg_noise\n if isinstance(inst, BaseRaw):\n self.inst_type = 'raw'\n X = inst.get_data(picks=picks)\n else:\n self.inst_type = 'epoch'\n X = inst.get_data(picks=picks)\n n_epochs, _, _ = X.shape\n X = np.hstack(X)\n self.X = X\n X /= np.std(X)\n smica = SOBI(self.p, self.n_components, self.freqs, self.sfreq,\n self.avg_noise)\n smica.fit(X, **kwargs)\n self.powers = smica.powers_\n self.A = smica.A_\n self.sigmas = smica.sigmas_\n self.smica = smica\n self.ica_mne = transfer_to_mne(self.A, self.inst, self.picks)\n return self\n\n def compute_sources(self, X=None, method='pinv'):\n return self.smica.compute_sources(X, method=method)\n","sub_path":"smica/sobi.py","file_name":"sobi.py","file_ext":"py","file_size_in_byte":6903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"262208570","text":"from django.conf import settings\nfrom django.conf.urls import include\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\nfrom django.urls import path\n\nfrom hardees.views import (\n CreateItemFormView,\n DeleteItemView,\n ItemListView,\n ItemDetailView,\n likeItem,\n UpdateItemFormView,\n)\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('items/', ItemListView.as_view(), name='items'),\n path('items//', ItemDetailView.as_view(), name='item-detail'),\n path('create/item/', CreateItemFormView.as_view(), name='item-create'),\n path('update/item//', UpdateItemFormView.as_view(), name='item-update'),\n path('delete/item//', DeleteItemView.as_view(), name='item-delete'),\n path('like_item/', likeItem, name='like-item'),\n path('api/items/', include(('hardees.api.urls', 'items'), namespace='items-api')),\n]\n\nurlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","sub_path":"Hardees_Restaurant/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"616121389","text":"import cv2\nimport json\nimport numpy as np\n\n####################################################\n#Input : intrinsics, extrinsics, depth, color #\n#Output: The color map which align to depth space #\n#Desc : The goal is to generate align's color map #\n# which is align to depth space. #\n####################################################\n\n\ndef imageRegistration( intr, extr, depth, color, is_holefilling_on = True ):\n r = extr['depth2color_extrinsics.rotation']\n t = extr['depth2color_extrinsics.translation']\n\n #depth\n cx2 = float(intr['depth_intrinsics.ppx'])\n cy2 = float(intr['depth_intrinsics.ppy'])\n fx2 = float(intr['depth_intrinsics.fx'])\n fy2 = float(intr['depth_intrinsics.fy'])\n #rgb\n cx1 = float(intr['color_intrinsics.ppx'])\n cy1 = float(intr['color_intrinsics.ppy'])\n fx1 = float(intr['color_intrinsics.fx'])\n fy1 = float(intr['color_intrinsics.fy'])\n #rotation\n R = [[float(r[0]), float(r[1]), float(r[2])],\n [float(r[3]), float(r[4]), float(r[5])],\n [float(r[6]), float(r[7]), float(r[8])]]\n #translation\n T = [float(t[0]),\n float(t[1]),\n float(t[2])]\n \n invfx2 = 1.0 / fx2\n invfy2 = 1.0 / fy2\n\n ( d_height, d_width ) = depth.shape[:2]\n ( c_height, c_width ) = color.shape[:2]\n \n Z2 = depth.copy()\n depth_scale = 0.001 #Realsense depth unit\n\n #do depth hole filling\n kernel = np.asarray( [[0, 1, 0], [1, 1, 1], [0, 1, 0]] ).astype(np.uint8)\n num_all_pixels = d_width * d_height\n while is_holefilling_on == True:\n mask = (Z2 == 0)\n Z2[mask] = cv2.dilate( Z2, kernel )[mask]\n num_invalid_pixels = num_all_pixels - cv2.countNonZero(Z2)\n if num_invalid_pixels == 0:\n break\n \n #get x and y map in depth space\n indexX = np.asarray( [list( range(d_width) ) for y in range(d_height)] ).astype( np.float32 )\n indexY = np.asarray( [[y] * d_width for y in range(d_height)] ).astype( np.float32 )\n\n Z2 = Z2.astype(np.float32) * depth_scale\n X2 = ( indexX - cx2 ) * Z2 * invfx2 \n Y2 = ( indexY - cy2 ) * Z2 * invfy2 \n\n R = np.asarray(R)\n R = R.ravel() #ravel to 1d array\n \n X1 = R[0] * X2 + R[3] * Y2 + R[6] * Z2 + T[0]\n Y1 = R[1] * X2 + R[4] * Y2 + R[7] * Z2 + T[1]\n Z1 = R[2] * X2 + R[5] * Y2 + R[8] * Z2 + T[2]\n \n matMap1 = cx1 + fx1 * X1 / Z1\n matMap2 = cy1 + fy1 * Y1 / Z1\n\n out_image = cv2.remap( color, matMap1, matMap2, cv2.INTER_LINEAR )\n\n return out_image\n\n\n\n\n\n#with open('test/camera_extrinsics.json') as reader:\n# extrinsics = json.loads( reader.read() )\n# \n#\n#with open('test/camera_intrinsics.json', 'r') as camera_intrinsics:\n# intrinsics = json.loads( camera_intrinsics.read() )\n#\n#\n# depth = cv2.imread( 'test/nocutoff_depth_000002.pgm', -1 )\n# color = cv2.imread( 'test/rgb_000002.png', -1 )\n#\n#\n# out_image = imageRegistration( intrinsics, extrinsics, depth, color )\n","sub_path":"rgb2depth.py","file_name":"rgb2depth.py","file_ext":"py","file_size_in_byte":2939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"27505976","text":"#!/usr/bin/env python\r\n\r\nclass Item:\r\n key = \"\"\r\n value = 0\r\n\r\n def __init__(self, key, value):\r\n self.key = key\r\n self.value = value\r\n\r\n def print(self):\r\n print(\" '\" + self.key + \"' / \" + str(self.value))\r\n\r\n\r\nclass HashTable:\r\n \"\"\"Common base class for a hash table\"\"\"\r\n tableSize = 0\r\n entriesCount = 0\r\n alphabetSize = 2 * 26\r\n hashTable = []\r\n\r\n def __init__(self, size):\r\n self.tableSize = size\r\n # Making list of list for hash table chain\r\n self.hashTable = [[] for i in range(size)]\r\n\r\n @staticmethod\r\n def char2int(char):\r\n if 'A' <= char <= 'Z':\r\n return ord(char) - 65\r\n elif 'a' <= char <= 'z':\r\n return ord(char) - 65 - 7\r\n else:\r\n raise NameError('Invalid character in key! Alphabet is [a-z][A-Z]')\r\n\r\n # note the hash function hash+=(52^len(key)-i-1)*char2int(c)\r\n\r\n def hashing(self, key):\r\n hash = 0\r\n for i, c in enumerate(key):\r\n hash += pow(self.alphabetSize, len(key) - i - 1) * self.char2int(c)\r\n # print(self.alphabetSize, len(key) - i - 1, self.char2int(c))\r\n # print(hash)\r\n return hash % self.tableSize\r\n\r\n def insert(self, item):\r\n hash = self.hashing(item.key)\r\n # print(hash)\r\n for i, it in enumerate(self.hashTable[hash]):\r\n if it.key == item.key:\r\n del self.hashTable[hash][i]\r\n self.entriesCount -= 1\r\n self.hashTable[hash].append(item)\r\n self.entriesCount += 1\r\n\r\n def get(self, key):\r\n print(\"\\nGetting item(s) with key '\" + key + \"'\")\r\n hash = self.hashing(key)\r\n for i, it in enumerate(self.hashTable[hash]):\r\n if it.key == key:\r\n return self.hashTable[hash]\r\n print(\" NOT IN TABLE!\")\r\n return None\r\n\r\n def delete(self, key):\r\n print(\"\\nDeleting item with key '\" + key + \"'\")\r\n hash = self.hashing(key)\r\n for i, it in enumerate(self.hashTable[hash]):\r\n if it.key == key:\r\n del self.hashTable[hash][i]\r\n self.entriesCount -= 1\r\n return\r\n print(\" NOT IN TABLE!\")\r\n\r\n def print(self):\r\n print(\"\\n>>>>> CURRENT TABLE BEGIN >>>>\")\r\n print(str(self.getNumEntries()) + \" entries in table\")\r\n for i in range(self.tableSize):\r\n print(\"[\", str(i), \"]:\", sep='', end='')\r\n for j in range(len(self.hashTable[i])):\r\n self.hashTable[i][j].print()\r\n print('\\n', \"<<<<< CURRENT TABLE END <<<<<\")\r\n\r\n def getNumEntries(self):\r\n return self.entriesCount\r\n\r\n\r\nif __name__ == \"__main__\":\r\n hs = HashTable(11)\r\n\r\n item = Item(\"one\", 1)\r\n hs.insert(item)\r\n # print(hs.hashing(\"a\"))\r\n hs.print()\r\n # reenter 1 in the same location\r\n hs.insert(item)\r\n hs.print()\r\n\r\n item = Item(\"two\", 2)\r\n hs.insert(item)\r\n\r\n item = Item(\"three\", 3)\r\n hs.insert(item)\r\n hs.print()\r\n\r\n # changing the value for key \"one\"\r\n item = Item(\"one\", 4)\r\n hs.insert(item)\r\n\r\n items = hs.get(\"one\")\r\n if items is not None:\r\n for j in range(len(items)):\r\n items[j].print()\r\n\r\n item = Item(\"PheewThisIsALongOne\", 12345)\r\n hs.insert(item)\r\n hs.print()\r\n\r\n items = hs.get(\"PheewThisIsALongOne\")\r\n if items is not None:\r\n for j in range(len(items)):\r\n items[j].print()\r\n\r\n items = hs.get(\"PheewThisIsOne\")\r\n if items is not None:\r\n for j in range(len(items)):\r\n items[j].print()\r\n\r\n hs.delete(\"PheewThisIsALongOne\")\r\n hs.print()\r\n\r\n hs.delete(\"PheewThisIsTheOne\")\r\n hs.print()\r\n\r\n hs.delete(\"one\")\r\n hs.print()\r\n\r\n # This one leads to an exception as '!' is not part of the allowed alphabet\r\n # item = Item(\"!\", 5)\r\n # hs.insert(item)\r\n","sub_path":"HashMap2.py","file_name":"HashMap2.py","file_ext":"py","file_size_in_byte":3875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"580611195","text":"from django.db import models\nfrom django.conf import settings\n\n# Create your models here.\n\nclass CartItemManager(models.Manager):\n\n def add_item(self, cart_key, produto):\n if self.filter(cart_key=cart_key, produto=produto).exists():\n created = False\n cart_item = self.get(cart_key=cart_key, produto=produto)\n cart_item.quantidade = cart_item.quantidade + 1\n cart_item.save()\n else:\n created = True\n cart_item = CartItem.objects.create(cart_key=cart_key, produto=produto, preco=produto.price)\n \n return cart_item, created\n\nclass CartItem(models.Model):\n\n cart_key = models.CharField('Chave do Carrinho', max_length=40, db_index=True)\n quantidade = models.PositiveIntegerField('Quantidade', default=1)\n preco = models.DecimalField('Preço', decimal_places=2, max_digits=8)\n produto = models.ForeignKey(\n 'catalogo.produto',\n on_delete=models.DO_NOTHING,\n verbose_name='catalogo.produto'\n )\n\n objects = CartItemManager()\n\n class Meta:\n verbose_name = 'Item do Carrinho'\n verbose_name_plural = 'Itens dos Carrinhos'\n unique_together = (('cart_key', 'produto'),)\n\n\n def __str__(self):\n return '{} [{}]'.format(self.produto, self.quantidade)\n\n class Meta:\n verbose_name = 'Item do pedido'\n verbose_name_plural = 'Itens dos pedidos'\n\n def __str__(self):\n return '[{}] {}'.format(self.order, self.produto)\n\n\ndef post_save_cart_item(instance, **kwargs):\n if instance.quantidade < 1:\n instance.delete()\n\nmodels.signals.post_save.connect(\n post_save_cart_item, sender=CartItem, dispatch_uid='post_save_cart_item')\n","sub_path":"checkout/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"379624598","text":"import json\n\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\n\nfrom webapp.cms.models.pages.module_page import ModulePage\n\n\ndef handler404(request):\n try:\n page_404 = ModulePage.objects.get(slug='404')\n context = page_404.get_context(request)\n context['status'] = 400\n except ModulePage.DoesNotExist:\n context = {'status': 400, 'api_data': {}, 'pages': []}\n\n response = render_to_response(\n 'cms/module_page.html', context)\n response.status_code = 404\n return response\n\n\ndef handler500(request):\n response = render_to_response(\n 'webapp/500.html', {'status': 500, 'api_data': {}, 'pages': []})\n response.status_code = 500\n return response","sub_path":"src/server/webapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"13137656","text":"import bpy\n\n\nclass Movies(object):\n def __init__(self, camera, render_directory, render_name, *args, render_type = None, render_steps=10, \n object_locations=None, camera_locations = [(0,0,0),(0,0,2)], \n camera_pointings=[(0,0,0),(0,0,3)], zoom_factor = 0.0, \n bezier_locations = [(0,0,0),(0,0,3)], bezier_pointings = [(0,0,0), (0,0,5)], \n bezier_visualize = False, radius_start = 1.0, radius_end = 2.0, theta_start = 40., \n theta_end = 0.1, phi_start=40., phi_end = 180., use_current_start_angles = False, \n use_current_radius = False, rotate_verbose = True, \n scene_name = 'Scene'):\n from render import Render\n import numpy as np\n self.render = Render(render_directory, render_name)\n # see how many are simple objects\n self.simple_objects = []\n for i in range(0,len(args)):\n if (args[i].__class__.__name__ is 'Arrow') or (args[i].__class__.__name__ is 'Sphere') or (args[i].__class__.__name__ is 'Text'):\n self.simple_objects.append(True)\n else:\n self.simple_objects.append(False)\n # first, figure out where objects are gonna go throughout this thing\n if object_locations is None:\n object_locations = [(0,0,0)]\n for i in range(0,len(args)):\n object_locations.append( (0,0,0) )\n # now, figuring out how many render frames we need and how much \n # we need to update the evolution of other objects based on this number of frames\n n = render_steps\n # if bezier then make sure we have enough points\n if render_type is 'Bezier':\n if len(bezier_locations) > n:\n print(\"You gave me too many points for your render steps. Upping the number of render steps\")\n n = len(bezier_locations)\n # also, make sure pointings and locations have same number of points\n if len(bezier_locations) is not len(bezier_pointings):\n print(\"Bezier locations and Bezier pointings need to have the same number of elements!\")\n for i in range(0,len(args)):\n # make sure not a simple object\n if self.simple_objects[i] is False:\n if args[i].filelistlength[0] > n:\n n = args[i].filelistlength[0]\n # now figure out what delta for each object\n # i.e. how many steps till we update the object's file?\n dn = np.zeros(len(args)) \n for i in range(0,len(args)):\n if self.simple_objects[i] is False:\n dn[i] = float(n)/args[i].filelistlength[0]\n self.__dn = dn\n self.__render_steps = n\n self.render_steps = n\n self.camera = camera\n self.object_locations = object_locations\n self.camera_locations = camera_locations\n self.camera_pointings = camera_pointings\n self.objects = args\n self.scene_name = scene_name\n self.loaded = 0\n self.zoom_factor = zoom_factor\n self.render_type = render_type\n self.bviz = 0\n if self.render_type is 'Zoom':\n self.zoom_camera(self.zoom_factor)\n elif self.render_type is 'Bezier':\n self.set_camera_bezier(bezier_locations, bezier_pointings, bezier_visualize, self.scene_name)\n elif self.render_type is 'Rotation':\n self.rotate_translate(radius_start, radius_end, theta_start, \n phi_start, theta_end, phi_end, \n use_current_start_angles, use_current_radius, \n rotate_verbose)\n else:\n print(\"You didn't set the Render type! I'm not doing a damn thing.\")\n\n\n\n\n @property\n def render_steps(self):\n return self.__render_steps\n\n @render_steps.setter\n def render_steps(self, render_steps):\n self.__dn = self.__dn*self.__render_steps/render_steps\n self.__render_steps = render_steps\n\n def zoom_camera(self, zoom_factor=1.0):\n from math import floor, sqrt#, abs\n # floor it \n #f = min(zoom_factor,0.99) # not 1 since then it will be ontop of pointing\n #f = zoom_factor\n if zoom_factor < 1.0:\n f = zoom_factor\n else:\n f = 0.0 - zoom_factor\n render_steps = self.render_steps\n cam_name = self.camera.name\n a = self.camera.pointing[0] \n b = self.camera.pointing[1] \n c = self.camera.pointing[2] \n x0 = self.camera.location[0]\n y0 = self.camera.location[1]\n z0 = self.camera.location[2]\n r = sqrt((x0-a)**2+(y0-b)**2+(z0-c)**2)\n # rotate where cam is looking\n ifileold = 1\n for i in range(0,render_steps):\n xx = x0 - f*(x0-abs(a))*i/(render_steps-1.)\n yy = y0 - f*(y0-abs(b))*i/(render_steps-1.)\n zz = z0 - f*(z0-abs(c))*i/(render_steps-1.)\n self.camera.location = (xx,yy,zz)#(xx+a,yy+b,zz+c)\n #print(xx)\n #print(yy)\n #print(zz)\n #print(\" \")\n # now, loop through each object and set its location\n # and upload a new file if necessary\n #iframe = i*self.__dn[0]\n for j in range(0,len(self.objects)):\n if self.simple_objects[j] is False:\n if i > 0: # have already loaded first file\n if i > ifileold*self.__dn[j]: # are we ready to update the file?\n ifileold = ifileold + 1\n self.objects[j].ifile = self.objects[j].ifile+1 # this deletes and reuploads stuff... hopefully\n #if floor(iframe) > iframeold:\n # iframeold = iframe\n self.render.render()\n\n\n\n # move the camera based on a bunch of bezier curves\n # locs and pts of form [[x,y,z],[x,y,z],[x,y,z]...]\n def set_camera_bezier(self, locs, pts, visualize=False, scene_name='Scene'):\n import mathutils\n import bmesh\n from scienceutils import deselect_all, makeMaterial, setMaterial, delete_object\n from math import floor\n # initialize cam pointing and whatnot\n self.camera.location = locs[0]\n self.camera.pointing = pts[0]\n nf = self.render_steps\n cam_name = self.camera.name\n camloc = []\n campts = []\n n_points_bezier = floor((nf*1.000)/len(locs))\n # first, delete if we have previously visualized\n for obj in bpy.data.objects:\n if ((obj.name.find('bezier') != -1)):\n delete_object(obj.name)\n for i in range(0,len(locs)-1):\n if i is (len(locs)-2):\n nfin = nf - i*n_points_bezier # if non-even #\n else:\n nfin = n_points_bezier\n # locations\n l1 = mathutils.Vector(locs[i])\n l2 = mathutils.Vector(locs[i+1])\n # pointings\n p1 = mathutils.Vector(pts[i])\n p2 = mathutils.Vector(pts[i+1])\n # pointing vectors for bezier tangents\n h1 = mathutils.Vector([l1[0]-p1[0],l1[1]-p1[1],l1[2]-p1[2]])\n h2 = mathutils.Vector([l2[0]-p2[0],l2[1]-p2[1],l2[2]-p2[2]])\n # create curve for cam loc\n curloc = mathutils.geometry.interpolate_bezier(l1,h1,h2,l2,nfin)\n # and one for pointing\n curpts = mathutils.geometry.interpolate_bezier(p1,h1,h2,p2,nfin)\n # add pts to curves for cam loc and cam pointing\n for j in range(0,nfin):\n camloc.append(curloc[j].to_tuple(10))\n campts.append(curpts[j].to_tuple(10))\n # rotate where cam is looking & render\n if not visualize:\n #iframeold = -1\n ifileold = 1\n for i in range(0,self.render_steps):\n self.camera.location = camloc[i]\n self.camera.pointing = campts[i]\n # now, loop through each object and set its location\n # and upload a new file if necessary\n #iframe = i*self.__dn[0]\n for j in range(0,len(self.objects)):\n if self.simple_objects[j] is False:\n if i > 0: # have already loaded first file\n if i > ifileold*self.__dn[j]: # are we ready to update the file?\n ifileold = ifileold + 1\n self.objects[j].ifile = self.objects[j].ifile+1 # this deletes and reuploads stuff... hopefully\n #if floor(iframe) > iframeold:\n # iframeold = iframe\n self.render.render()\n else: # otherwise, draw points on path\n #plot pts if you want to visualize stuff\n print('locs = ')\n print(camloc)\n print('pts = ')\n print(campts)\n #global bviz ## CHANGE!!!\n deselect_all()\n num = \"%04d\" % (self.bviz)\n # first, for location curves\n me = bpy.data.meshes.new('bezierCurveLoc'+num)\n ob = bpy.data.objects.new('bezierCurveLoc'+num,me)\n ob.location = (0,0,0)\n bpy.context.scene.objects.link(ob) # Link object to scene\n coords = [(0,0,0)]\n me.from_pydata(coords,[],[])\n color = (1,0,0) # location pts will be red\n halo_size = 0.1\n mat = makeMaterial('bezierCurveLoc'+num, color, (1,1,1), 1.0, 1.0, \n mat_type='HALO', halo_size=halo_size)\n setMaterial(ob,mat) # sets everything to material 0 by default\n ob = bpy.data.objects['bezierCurveLoc'+num] # select right object\n ob.select = True\n bpy.context.scene.objects.active=ob\n bpy.ops.object.mode_set(mode='OBJECT') # toggle to edit mode \n bpy.ops.object.mode_set(mode='EDIT') # toggle to edit mode\n bm = bmesh.from_edit_mesh(ob.data)\n bm.verts[0].co = camloc[0]\n #print(camloc[i])\n for i in range(1,len(camloc)):\n bm.verts.new(camloc[i])\n #print(camloc[i])\n bmesh.update_edit_mesh(ob.data)\n bpy.ops.object.mode_set(mode='OBJECT') # toggle to edit mode\n # now, for pointings\n deselect_all()\n me = bpy.data.meshes.new('bezierCurvePts'+num)\n ob = bpy.data.objects.new('bezierCurvePts'+num,me)\n ob.location = (0,0,0)\n bpy.context.scene.objects.link(ob) # Link object to scene\n coords = [(0,0,0)]\n me.from_pydata(coords,[],[])\n color = (0,0,1) # location pts will be blue\n halo_size = 0.1\n mat = makeMaterial('bezierCurvePts'+num, color, (1,1,1), 1.0, 1.0, \n mat_type='HALO', halo_size=halo_size)\n setMaterial(ob,mat) # sets everything to material 0 by default\n ob = bpy.data.objects['bezierCurvePts'+num] # select right object\n ob.select = True\n bpy.context.scene.objects.active=ob\n bpy.ops.object.mode_set(mode='OBJECT') # toggle to edit mode \n bpy.ops.object.mode_set(mode='EDIT') # toggle to edit mode\n bm = bmesh.from_edit_mesh(ob.data)\n bm.verts[0].co = campts[0] \n for i in range(1,len(campts)):\n bm.verts.new(campts[i])\n bmesh.update_edit_mesh(ob.data)\n bpy.ops.object.mode_set(mode='OBJECT') # toggle to edit mode\n self.bviz = self.bviz+1 # update curve counter\n\n\n\n # rotates and changes the radius of rotation, allows for the object to be placed in a fixed location (for now)\n # and for the object to be made to point some where. Also, object can be scaled - all files scaled by same amount\n def rotate_translate(self, radius1, radius2, th1, ph1, th2, ph2, use_current_angles=False, \n use_current_radius = False, verbose=True):\n from math import degrees, atan2, acos, sqrt, cos, sin, pi, floor\n scene_name = self.scene_name\n camloc = self.camera.location\n campt = self.camera.pointing\n ang_frames = self.render_steps\n cam_name = self.camera.name\n if use_current_radius: # rotate around this radius\n radius1 = sqrt((camloc[0]-campt[0])**2. + (camloc[1]-campt[1])**2. + (camloc[2]-campt[2])**2.)\n #radius2 = radius1\n if use_current_angles: # use the current angle as the start angle\n cx = camloc[0] - campt[0]\n cy = camloc[1] - campt[1]\n cz = camloc[2] - campt[2]\n th1 = degrees(atan2(cy,cx))\n ph1 = degrees(acos(cz/sqrt(cx*cx+cy*cy+cz*cz)))\n scene = bpy.data.scenes[scene_name]\n # get the angle and radius steps\n dth = (th2 - th1)/(ang_frames-1.)\n dph = (ph2 - ph1)/(ang_frames-1.)\n drad = (radius2 - radius1)/(ang_frames-1.0)\n #iframeold = -1\n ifileold = 1\n for i in range(0,self.render_steps):\n radius = radius1+drad*i\n cx = radius*cos((th1+dth*i)*(pi/180.))*sin((ph1+dph*i)*(pi/180.0)) + campt[0]\n cy = radius*sin((th1+dth*i)*(pi/180.))*sin((ph1+dph*i)*(pi/180.0)) + campt[1]\n cz = radius*cos((ph1+dph*i)*(pi/180.0)) + campt[2]\n self.camera.location = (cx,cy,cz)\n # now, loop through each object and set its location\n # and upload a new file if necessary\n #iframe = i*self.__dn[0]\n for j in range(0,len(self.objects)):\n if self.simple_objects[j] is False:\n if i > 0: # have already loaded first file\n if i > ifileold*self.__dn[j]: # are we ready to update the file?\n ifileold = ifileold + 1\n self.objects[j].ifile = self.objects[j].ifile+1 # this deletes and reuploads stuff... hopefully\n #if floor(iframe) > iframeold:\n # iframeold = iframe\n self.render.render()\n# COME BACK TO AND USE\n# # move lamp\n# if lamp_motion is 'TRACKING': \n# rotate_lamp(radius, th1, ph1, th1+dth*r, ph1+dph*r)\n\n\n \n\n","sub_path":"science/movie.py","file_name":"movie.py","file_ext":"py","file_size_in_byte":14336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"632084994","text":"import pytest\n\nfrom helpers.cluster import ClickHouseCluster\nfrom multiprocessing.dummy import Pool\nfrom helpers.network import PartitionManager\nimport time\n\ncluster = ClickHouseCluster(__file__)\n\nnode1 = cluster.add_instance('node1', with_zookeeper=True)\n\n\n@pytest.fixture(scope=\"module\")\ndef started_cluster():\n try:\n cluster.start()\n\n node1.query('''\n CREATE TABLE replicated_mt(date Date, id UInt32, value Int32)\n ENGINE = ReplicatedMergeTree('/clickhouse/tables/replicated_mt', '{replica}') ORDER BY id;\n '''.format(replica=node1.name))\n\n yield cluster\n\n finally:\n cluster.shutdown()\n\ndef corrupt_data_part_on_disk(node, table, part_name):\n part_path = node.query(\n \"SELECT path FROM system.parts WHERE table = '{}' and name = '{}'\".format(table, part_name)).strip()\n node.exec_in_container(['bash', '-c',\n 'cd {p} && ls *.bin | head -n 1 | xargs -I{{}} sh -c \\'echo \"1\" >> $1\\' -- {{}}'.format(\n p=part_path)], privileged=True)\n\n\ndef test_merge_and_part_corruption(started_cluster):\n node1.query(\"SYSTEM STOP REPLICATION QUEUES replicated_mt\")\n for i in range(4):\n node1.query(\"INSERT INTO replicated_mt SELECT toDate('2019-10-01'), number, number * number FROM numbers ({f}, 100000)\".format(f=i*100000))\n\n assert node1.query(\"SELECT COUNT() FROM system.parts WHERE table='replicated_mt' AND active=1\") == \"4\\n\"\n\n # Need to corrupt \"border part\" (left or right). If we will corrupt something in the middle\n # clickhouse will not consider merge as broken, because we have parts with the same min and max\n # block numbers.\n corrupt_data_part_on_disk(node1, 'replicated_mt', 'all_3_3_0')\n\n with Pool(1) as p:\n def optimize_with_delay(x):\n node1.query(\"OPTIMIZE TABLE replicated_mt FINAL\", timeout=30)\n\n # corrupt part after merge already assigned, but not started\n res_opt = p.apply_async(optimize_with_delay, (1,))\n node1.query(\"CHECK TABLE replicated_mt\", settings={\"check_query_single_value_result\": 0})\n # start merge\n node1.query(\"SYSTEM START REPLICATION QUEUES replicated_mt\")\n res_opt.get()\n\n # will hung if checked bug not fixed\n node1.query(\"ALTER TABLE replicated_mt UPDATE value = 7 WHERE 1\", settings={\"mutations_sync\": 2}, timeout=30)\n assert node1.query(\"SELECT sum(value) FROM replicated_mt\") == \"2100000\\n\"\n","sub_path":"tests/integration/test_broken_part_during_merge/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"166425171","text":"import os\nfrom argparse import ArgumentParser\nimport threading\nimport warnings\n\nimport numpy as np\nimport vtk\n\ndef random_rotation(x, rgs, channel_axis=0,\n fill_mode='nearest', cval=0., order=0):\n\n rgs = scipy.ndimage._ni_support._normalize_sequence(rgs, 3)\n theta = [np.random.uniform(-rg, rg) * np.pi / 180. for rg in rgs]\n\n rotation_matrix_x = np.array([[1, 0, 0, 0],\n [0, np.cos(theta[0]), -np.sin(theta[0]), 0],\n [0, np.sin(theta[0]), np.cos(theta[0]), 0],\n [0, 0, 0, 1]])\n\n rotation_matrix_y = np.array([[np.cos(theta[1]), 0, np.sin(theta[1]), 0],\n [0, 1, 0, 0],\n [-np.sin(theta[1]), 0, np.cos(theta[1]), 0],\n [0, 0, 0, 1]])\n\n rotation_matrix_z = np.array([[np.cos(theta[2]), -np.sin(theta[2]), 0, 0],\n [np.sin(theta[2]), np.cos(theta[2]), 0, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 1]])\n\n transform_matrix = np.dot(rotation_matrix_x, np.dot(rotation_matrix_y, rotation_matrix_z))\n axes = [i for i in range(len(x.shape)) if i != channel_axis]\n sides = [x.shape[i] for i in axes]\n transform_matrix = transform_matrix_offset_center(transform_matrix, sides)\n x = apply_transform(x, transform_matrix, channel_axis, fill_mode, cval, order)\n return x\n\n\ndef random_shift(x, rgs, channel_axis=0,\n fill_mode='nearest', cval=0.):\n\n rgs = scipy.ndimage._ni_support._normalize_sequence(rgs, 3)\n axes = [i for i in range(4) if i != channel_axis]\n sides = [x.shape[i] for i in axes]\n translations = [np.random.uniform(-rg, rg) * side for rg, side in zip(rgs, sides)]\n translation_matrix = np.array([[1, 0, 0, translations[0]],\n [0, 1, 0, translations[1]],\n [0, 0, 1, translations[2]],\n [0, 0, 0, 1]])\n\n x = apply_transform(x, translation_matrix, channel_axis, fill_mode, cval)\n return x\n\n\ndef random_shear(x, intensity, channel_axis=0,\n fill_mode='nearest', cval=0.):\n\n rgs = scipy.ndimage._ni_support._normalize_sequence(intensity, 3)\n shear = [np.random.uniform(-rg, rg) * np.pi / 180 for rg in rgs]\n shear_matrix = np.array([[1, -np.sin(shear[0]), np.cos(shear[1]), 0],\n [np.cos(shear[0]), 1, -np.sin(shear[2]), 0],\n [-np.sin(shear[1]), np.cos(shear[2]), 1, 0],\n [0, 0, 0, 1]])\n\n axes = [i for i in range(4) if i != channel_axis]\n sides = [x.shape[i] for i in axes]\n transform_matrix = transform_matrix_offset_center(shear_matrix, sides)\n x = apply_transform(x, transform_matrix, channel_axis, fill_mode, cval)\n return x\n\n\ndef random_zoom(x, zoom_lower, zoom_upper, independent, channel_axis=0,\n fill_mode='nearest', cval=0.):\n\n axes = [i for i in range(4) if i != channel_axis]\n zoom_lower = scipy.ndimage._ni_support._normalize_sequence(zoom_lower, len(axes))\n zoom_upper = scipy.ndimage._ni_support._normalize_sequence(zoom_upper, len(axes))\n\n if independent:\n zoom_fctr = [np.random.uniform(l, u) for l, u in zip(zoom_lower, zoom_upper)]\n else:\n fctr = np.random.uniform(0, 1)\n zoom_fctr = [fctr * l + (1 - fctr) * u for l, u in zip(zoom_lower, zoom_upper)]\n\n zoom_fctr = [1. / zf for zf in zoom_fctr]\n zoom_matrix = np.array([[zoom_fctr[0], 0, 0, 0],\n [0, zoom_fctr[1], 0, 0],\n [0, 0, zoom_fctr[2], 0],\n [0, 0, 0, 1]])\n\n sides = [x.shape[i] for i in axes]\n transform_matrix = transform_matrix_offset_center(zoom_matrix, sides)\n x = apply_transform(x, transform_matrix, channel_axis, fill_mode, cval)\n return x\n\n\ndef random_channel_shift(x, intensity, channel_axis=0):\n x = np.rollaxis(x, channel_axis, 0)\n min_x, max_x = np.min(x), np.max(x)\n channel_images = [np.clip(x_channel + np.random.uniform(-intensity, intensity), min_x, max_x)\n for x_channel in x]\n x = np.stack(channel_images, axis=0)\n x = np.rollaxis(x, 0, channel_axis + 1)\n return x\n\n\ndef transform_matrix_offset_center(matrix, sides):\n sides = [float(side) / 2 - 0.5 for side in sides]\n offset_matrix = np.array([[1, 0, 0, sides[0]], [0, 1, 0, sides[1]], [0, 0, 1, sides[2]], [0, 0, 0, 1]])\n reset_matrix = np.array([[1, 0, 0, -sides[0]], [0, 1, 0, -sides[1]], [0, 0, 1, -sides[2]], [0, 0, 0, 1]])\n transform_matrix = np.dot(np.dot(offset_matrix, matrix), reset_matrix)\n return transform_matrix\n\n\ndef apply_transform(x, transform_matrix,\n channel_axis=0,\n fill_mode='nearest',\n cval=0., order=0):\n\n x = np.rollaxis(x, channel_axis, 0)\n final_affine_matrix = transform_matrix[:3, :3]\n final_offset = transform_matrix[:3, 3]\n channel_images = [scipy.ndimage.interpolation.affine_transform(\n x_channel,\n final_affine_matrix,\n final_offset,\n order=order,\n mode=fill_mode,\n cval=cval) for x_channel in x]\n x = np.stack(channel_images, axis=0)\n x = np.rollaxis(x, 0, channel_axis + 1)\n return x\n\n\ndef flip_axis(x, axis):\n x = np.asarray(x).swapaxes(axis, 0)\n x = x[::-1, ...]\n x = x.swapaxes(0, axis)\n return x\n\ndef parse_args():\n parser = ArgumentParser(description=\"Randomly translate and rotate image\")\n parser.add_argument('--input-path'\n ,help=\"Path to the input file\")\n\n parser.add_argument('--output-path-format'\n ,help=\"Template path for the output file. ex (/tmp/foo.{:04d}.ply)\")\n\n parser.add_argument('--min_rotation_w'\n ,default=-180\n ,type=float\n ,help=\"\")\n parser.add_argument('--max_rotation_w'\n ,default=180\n ,type=float\n ,help=\"\")\n parser.add_argument('--min_rotation_xyz'\n ,default=-1\n ,type=float\n ,help=\"\")\n parser.add_argument('--max_rotation_xyz'\n ,default=1\n ,type=float\n ,help=\"\")\n parser.add_argument('--min_translation_distance'\n ,default=-.4\n ,type=float\n ,help=\"\")\n parser.add_argument('--max_translation_distance'\n ,default=.4\n ,type=float\n ,help=\"\")\n parser.add_argument('--num-iterations','-n'\n ,default=20\n ,type=int\n ,help=\"\")\n parser.add_argument('-v','--verbose',action='store_true')\n\n return parser.parse_args()","sub_path":"augmentation.py","file_name":"augmentation.py","file_ext":"py","file_size_in_byte":7009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"171867075","text":"# Usage\r\n# python main.py --image imagefile\r\n# import the necessary packages\r\nimport numpy as np\r\nimport cv2 as cv\r\nimport argparse\r\n\r\n\r\ndef adjust_gamma(image, gamma=1.0):\r\n # build a look up table mapping the pixel values [0, 255] to their adjusted gamma values\r\n invGamma = 1.0/gamma\r\n table = np.array([((i / 255.0) ** invGamma) * 255 for i in np.arange(0, 256)]).astype(\"uint8\")\r\n\r\n # apply Gamma correction using the lookup table\r\n return cv.LUT(image, table)\r\n\r\n\r\n# construct an argparse to parse the arguments\r\nap = argparse.ArgumentParser()\r\nap.add_argument(\"-i\", \"--image\", help=\"path to input file\", required=True, type=str)\r\nargs = vars(ap.parse_args())\r\n\r\n# load the original image\r\noriginal = cv.imread(args[\"image\"])\r\n\r\n# loop over various values of gamma\r\nfor gamma in np.arange(0.0, 3.5, 0.5):\r\n # When when gamma is 1 (because there will be no change)\r\n if gamma == 1:\r\n continue\r\n\r\n # apply gamma correction and show the image\r\n gamma = gamma if gamma > 0 else 0.1\r\n adjusted = adjust_gamma(original, gamma)\r\n cv.putText(adjusted, f\"g={gamma}\", (10, 30), cv.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 3)\r\n cv.imshow(\"images\", np.hstack([original, adjusted]))\r\n cv.waitKey(0)\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"227596413","text":"import pygame\n\n\ncboard=[]\nradius=[]\n\nw,h = (1400,950)\n\nbg_color = (255,255,255)\n\ndef makein(a,x,y):\n \n im = pygame.image.load(a)\n im = pygame.transform.scale(im,(x,y))\n return im \n \nbim = makein('res/board.jpeg',800,800)\nsel = makein('res/selected.png',100,100)\nmark = makein('res/mark.png',100,100)\nkill = makein('res/kill.png',100,100)\n\nwpawn = makein('res/wpawn.png',100,100)\nwknight = makein('res/wknight.png',100,100)\nwbishop = makein('res/wbishop.png',100,100)\nwrook = makein('res/wrook.png',100,100)\nwqueen = makein('res/wqueen.png',100,100)\nwking = makein('res/wking.png',100,100)\nbpawn = makein('res/bpawn.png',100,100)\nbknight = makein('res/bknight.png',100,100)\nbbishop = makein('res/bbishop.png',100,100)\nbrook = makein('res/brook.png',100,100)\nbqueen = makein('res/bqueen.png',100,100)\nbking = makein('res/bking.png',100,100)\n\npiece=\"\"\np_x,p_y = 0,0\n\nturn = 0\n\n\ndef init():\n\n global cboard\n\n for i in range(8):\n\n cb=[]\n \n for j in range(8):\n\n if(i==1):\n cb.append(\"wpawn\")\n\n elif(i==6):\n cb.append(\"bpawn\")\n\n elif(i==0):\n cb = [\"wrook\",\"wknight\",\"wbishop\",\"wqueen\",\"wking\",\"wbishop\",\"wknight\",\"wrook\"]\n\n elif(i==7):\n cb = [\"brook\",\"bknight\",\"bbishop\",\"bqueen\",\"bking\",\"bbishop\",\"bknight\",\"brook\"]\n\n else:\n \n cb=[\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",]\n\n cboard.append(cb)\n\n\n\ndef setpeice():\n\n defx=300\n defy=100\n\n for i in range(8):\n for j in range(8):\n\n if(cboard[i][j]==\"bpawn\"):\n screen.blit(bpawn,(defx+j*100,defy+i*100))\n elif(cboard[i][j]==\"wpawn\"):\n screen.blit(wpawn,(defx+j*100,defy+i*100))\n elif(cboard[i][j]==\"wknight\"):\n screen.blit(wknight,(defx+j*100,defy+i*100))\n elif(cboard[i][j]==\"wbishop\"):\n screen.blit(wbishop,(defx+j*100,defy+i*100)) \n elif(cboard[i][j]==\"bbishop\"):\n screen.blit(bbishop,(defx+j*100,defy+i*100))\n elif(cboard[i][j]==\"wqueen\"):\n screen.blit(wqueen,(defx+j*100,defy+i*100))\n elif(cboard[i][j]==\"wking\"):\n screen.blit(wking,(defx+j*100,defy+i*100))\n elif(cboard[i][j]==\"bking\"):\n screen.blit(bking,(defx+j*100,defy+i*100))\n elif(cboard[i][j]==\"bqueen\"):\n screen.blit(bqueen,(defx+j*100,defy+i*100))\n elif(cboard[i][j]==\"bknight\"):\n screen.blit(bknight,(defx+j*100,defy+i*100))\n elif(cboard[i][j]==\"wrook\"):\n screen.blit(wrook,(defx+j*100,defy+i*100))\n elif(cboard[i][j]==\"brook\"):\n screen.blit(brook,(defx+j*100,defy+i*100)) \n\n\n\ndef board(a):\n \n screen.fill(bg_color)\n screen.blit(bim,(300,100))\n\n if(a==1):\n init()\n\n setpeice()\n\n\n \ndef set_text(string,_font,_size,x,y,color,textRect,fill):\n\n global w,h,bg_color\n\t\n font = pygame.font.Font(_font, _size)\n text = font.render(string, True, color, (256,256,256))\n textRect = text.get_rect()\n textRect.center = (x,y)\n if(fill==1):\n screen.fill(bg_color)\n screen.blit(text,textRect)\n\n\ndef killable(x,y):\n \n if(cboard[y][x] != \"1\"):\n if(cboard[y][x][:1] != piece[:1]):\n return [x,y,kill]\n else:\n return [\"x\"]\n else:\n return [\"x\"]\n\n\ndef path(x,y):\n\n if(cboard[y][x] == \"1\"):\n return [x,y,mark]\n else:\n return [\"x\"]\n\n\n\n \n\n\ndef clicked(x,y):\n\n global piece,cboard,p_x,p_y\n\n board(0) \n screen.blit(sel,(x*100+300,y*100+100))\n \n\n piece = cboard[y][x]\n if(piece != \"1\"):\n cboard[y][x]=\"1\"\n #capacity(piece,x,y)\n\n pygame.display.update()\n p_x,p_y = x,y\n\n\n\ndef moved(x,y):\n\n global cboard,turn,hover\n\n if(piece != \"1\"):\n if(piece[:1] != cboard[y][x][:1]):\n cboard[y][x] = piece\n turn+=1\n \n else:\n hover=0\n cboard[p_y][p_x]=piece\n\n\n board(0) \n pygame.display.update()\n\n\nscreen = pygame.display.set_mode((w,h))\npygame.display.set_caption('CHESS')\n\nboard(1)\npygame.display.update()\n\nalive=1\n\nhover = 1\n\n\n\nwhile(alive):\n\n for event in pygame.event.get():\n \n\n if event.type == pygame.KEYDOWN:\n pass\n\n \n\n elif event.type == pygame.QUIT:\n pygame.quit()\n quit()\n \n elif event.type == pygame.MOUSEBUTTONDOWN:\n \n (x,y) = pygame.mouse.get_pos()\n x=x//100 - 3\n y=y//100 - 1\n\n if(hover == 1): \n \n if(x > 7 or x<0 or y>7 or y<0):\n hover=1 \n else:\n clicked(x,y)\n hover=0 \n \n else:\n \n if(x > 7 or x<0 or y>7 or y<0):\n hover=0\n else:\n if([x,y] ):\n moved(x,y)\n hover=1 \n radius=[] \n else:\n moved(p_x,p_y)\n hover=1\n\n \n\n\n\n\n\n","sub_path":"chess/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":5277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"321521020","text":"from tkinter import *\nimport subprocess\nimport threading\nimport os\nimport platform\nimport re\n\n\n#------------------------------------\n\ndef addBox():\n print (\"ADD\")\n\n frame = Frame(root)\n frame.pack()\n\n Label(frame, text='User').grid(row=0, column=0)\n\n usr1 = Entry(frame)\n usr1.grid(row=1, column=0)\n\n Label(frame, text='Password').grid(row=0, column=1)\n\n paswd1 = Entry(frame)\n paswd1.grid(row=1, column=1)\n\n subprocess.call(r'net user ' + usr1 + \" \" + paswd1 + ' /add', shell = True)\n\n all_entries.append( (usr1, paswd1) )\n\n#------------------------------------\n\ndef showEntries():\n\n for number, (usr1, paswd1) in enumerate(all_entries):\n print (number, usr1.get(), paswd1.get())\n\n#------------------------------------\n\nall_entries = []\n\nroot = Tk()\n\nshowButton = Button(root, text='Show all text', command=showEntries)\nshowButton.pack()\n\naddboxButton = Button(root, text='Add Users', fg=\"Blue\", command=addBox)\naddboxButton.pack()\n\nroot.mainloop()\n\n#------------------------------------\n","sub_path":"guiexample.py","file_name":"guiexample.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"305121014","text":"'''\nAuthor: Gtylcara.\nDate: 2021-03-04 20:50:10\nLastEditors: Gtylcara.\nLastEditTime: 2021-03-12 19:54:03\n'''\n\"\"\"Guard 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 . import views\nfrom django.contrib import admin\nfrom django.urls import path\n\nurlpatterns = [\n # path('admin/', admin.site.urls),\n path('index/', views.index),\n path('battery/', views.battery),\n path('log/', views.log),\n path('login/', views.login),\n path('register/', views.register),\n path('api/login', views.api_login),\n path('api/register', views.api_register),\n path('api/data', views.api_data),\n path('api/control', views.api_control),\n]\n","sub_path":"Guard/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"93190815","text":"import numpy as np\nimport time\nfrom cafeteria import BotCafeteria\nfrom random import shuffle\nfrom random import randrange\n\n\n\nclass Drink_cafeteria(BotCafeteria):\n def __init__(self):\n super().__init__()\n\n\n\n\n def run(self):\n while True:\n print(\"waiting...\")\n time.sleep(30)\n if randrange(10)<=3:\n self.find_cafe_and_go()\n if randrange(10)<=5:\n self.give_drink_to_some_habbo()\n continue\n elif self.find_chair_and_sit():\n continue\n else:\n self.find_floor_and_go()\n\n\n\n\nprint(\"Charging bot\")\nbot = Drink_cafeteria()\n# bot.find_floor_and_go()\n# bot.find_chair_and_sit()\n# bot.find_cafe_and_go()\nbot.run()\n# bot.find_habbos_talking()\n# bot.give_drink_to_some_habbo()","sub_path":"ver1/drink_cafeteria.py","file_name":"drink_cafeteria.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"618036518","text":"import functools\nimport os\n# librerias adicionales\nfrom os import getenv\n\nimport click\nfrom dotenv import load_dotenv\nfrom flask import *\nfrom flask_compress import Compress\nfrom flask_htmlmin import HTMLMIN\nfrom flask_menu import Menu\n\n# modulos del sistema\nfrom core.auth import auth\nfrom core.core import ProdEnvironment, DevEnvironment, verify_all_system_folders\nfrom core.logger import getDefaultLogger\n# cargar configuracion .env\nfrom database import CacheDatabase\n\n# modulso del core\n# from database import CacheDatabase\n# from modulos.cajas import cajas\n# from modulos.empresa import empresa\n# from modulos.set import rucs\n\nload_dotenv(verbose=True)\n\napplication = dict(version=getenv(\"VERSION\"), name=getenv(\"NAME\"))\n\n# Detectar plataforma del servidor\nisserver = os.getenv(\"isserver\", \"0\") == \"1\"\nisdebug = os.getenv(\"debug\", \"1\") == \"1\"\n# Mostrar el modo activado\nprint(\"Iniciando a modo {}\".format('Servidor' if isserver == 1 else 'Desarrollo'))\n\n# Instancia y auto configuracion\napp = Flask(__name__)\napp.config.from_object(ProdEnvironment if isserver else DevEnvironment)\nmenu = Menu(app=app)\ncompress = Compress(app=app)\nhtmlmin = HTMLMIN(app=app)\n\n# importando modulos\napp.register_blueprint(auth)\n# app.register_blueprint(empresa)\n# app.register_blueprint(cajas)\n# app.register_blueprint(rucs)\n\n# creando directorios requeridos\nverify_all_system_folders(os.path.dirname(__file__))\n\n\n# create_folder(app.config.get('UPLOAD_FOLDER'))\n# create_folder(app.config.get('BACKUP_FOLDER'))\n# create_folder(app.config.get('TEMP_FOLDER'))\n# create_folder(app.config.get('DATA_FOLDER'))\n# create_folder(app.config.get('LOGS_FOLDER'))\n\n\n@app.route('/')\ndef home():\n if 1:\n return redirect(url_for('lobby'))\n\n # if 'auth' in app.blueprints:\n # app.logger.info('auth.login')\n # return redirect(url_for('auth.login'))\n # else:\n # app.logger.info('welcame screen')\n # return render_template('init.html')\n\n\n@app.route('/lobby')\ndef lobby():\n return render_template('lobby.html')\n\n\ndef login_required(view):\n @functools.wraps(view)\n def wrapped_view(**kwargs):\n if g.user is None:\n return redirect(url_for('auth.login'))\n\n return view(**kwargs)\n\n return wrapped_view\n\n\n@app.context_processor\ndef context_processor():\n return dict(application=application, log=app.logger)\n\n\n@app.before_first_request\ndef before_request():\n if request is not None:\n if 'static' not in request.endpoint:\n g.cache = CacheDatabase()\n print(\"asigned g.cache\")\n\n\n# @app.after_request\n# def after_request(response):\n# return response\n\n\n@app.cli.command()\ndef export():\n click.echo(\"Generando requirements\")\n os.system('pip freeze > requirements')\n click.echo('Listo')\n\n\n@app.cli.command()\ndef instalar():\n click.echo(\"Instalando requerimientos\")\n os.system('pip install -r requirements')\n click.echo(\"Listo\")\n\n\n@app.cli.command()\ndef update_rucs():\n click.echo(\"Iniciando actualizacion de rucs...\")\n click.echo(\"Finalizado.\")\n\n\nif __name__ == '__main__':\n app.logger.addHandler(getDefaultLogger(app))\n app.logger.info('Starting application')\n app.run(host='0.0.0.0', port=18000, debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"551742665","text":"#63 SequÊncia de Fibonacci\r\nn=int(input('Quantos termos você quer mostrar? '))\r\ncont=2\r\nt1=0\r\nt2=1\r\nprint(' 0 - 1', end=' - ')\r\n\r\nwhile cont < n:\r\n cont+=1\r\n t=t1+t2\r\n print(t, end= ' - ')\r\n t1=t2\r\n t2=t\r\nprint('FIM')\r\n \r\n \r\n \r\n","sub_path":"Exercícios/ex063.py","file_name":"ex063.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"395381859","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n#######################################################################\n#\n# This module support creation of guideways\n#\n#######################################################################\n\n\nimport copy\nfrom border import get_bicycle_border, cut_line_by_relative_distance, cut_border_by_point, \\\n get_border_length\nfrom matplotlib.patches import Polygon\nfrom right_turn import get_right_turn_border, get_link, get_link_destination_lane, \\\n is_right_turn_allowed, \\\n get_destination_lanes_for_right_turn\nfrom left_turn import is_left_turn_allowed, get_destination_lanes_for_left_turn\nfrom through import is_through_allowed, get_destination_lane\nfrom u_turn import is_u_turn_allowed, get_destination_lanes_for_u_turn, get_u_turn_border\nfrom turn import get_turn_border\nfrom log import get_logger, dictionary_to_log\nfrom footway import crosswalk_intersects_median, get_crosswalk_to_crosswalk_distance\n\nlogger = get_logger()\n\n\ndef get_bicycle_left_turn_guideways(all_lanes, nodes_dict):\n \"\"\"\n Compile a list of bicycle guideways for all legal left turns\n :param all_lanes: list of dictionaries\n :param nodes_dict: dictionary\n :return: list of dictionaries\n \"\"\"\n logger.info('Starting bicycle left turn guideways')\n guideways = []\n through_guideways = get_through_guideways(all_lanes)\n\n for origin_lane in all_lanes:\n logger.debug(\"Allowed %r: %s %s %s\" % (is_left_turn_allowed(origin_lane),\n origin_lane[\"lane_type\"],\n origin_lane[\"direction\"],\n origin_lane[\"name\"]\n )\n )\n\n # ll = [(l[\"name\"], l[\"direction\"]) for l in get_destination_lanes_for_left_turn(origin_lane, all_lanes, nodes_dict) ]\n # logger.debug(\"%r\" % ll)\n\n if is_left_turn_allowed(origin_lane):\n for destination_lane in get_destination_lanes_for_left_turn(origin_lane, all_lanes,\n nodes_dict):\n origin_candidates = [g for g in through_guideways if\n g['origin_lane']['id'] == origin_lane['id']]\n destination_candidates = [g for g in through_guideways\n if g['destination_lane']['id'] == destination_lane['id']\n ]\n logger.debug('Number of candidates: origin %d, destination %d' % (\n len(origin_candidates), len(destination_candidates)))\n if origin_candidates and destination_candidates:\n logger.debug('Origin Lane ' + dictionary_to_log(origin_candidates[0]))\n logger.debug('Destin Lane ' + dictionary_to_log(destination_candidates[0]))\n try:\n guideway_data = get_bicycle_left_guideway(origin_lane,\n destination_lane,\n origin_candidates[0],\n destination_candidates[0]\n )\n set_guideway_id(guideway_data)\n except Exception as e:\n logger.exception(e)\n guideway_data = None\n\n else:\n guideway_data = None\n\n if guideway_data is not None \\\n and guideway_data['left_border'] is not None \\\n and guideway_data['median'] is not None \\\n and guideway_data['right_border'] is not None:\n logger.debug('Guideway ' + dictionary_to_log(guideway_data))\n guideways.append(guideway_data)\n\n logger.info('Created %d guideways' % len(guideways))\n return guideways\n\n\ndef get_bicycle_left_guideway(origin_lane, destination_lane, origin_through, destination_through):\n \"\"\"\n Get a bicycle guideway for the left turn assuming that the bicyclist making the left turn as pedestrian, \n i.e. as an instant 90 degree turn. Creating the bicycle guideway from an origin and destination lanes \n and previously calculated through guideways. \n :param origin_lane: dictionary\n :param destination_lane: dictionary\n :param origin_through: dictionary\n :param destination_through: dictionary\n :return: dictionary\n \"\"\"\n return {\n 'direction': 'left',\n 'origin_lane': origin_lane,\n 'destination_lane': destination_lane,\n 'left_border': get_bicycle_border(origin_through['left_border'],\n destination_through['left_border']),\n 'median': get_bicycle_border(origin_through['median'], destination_through['median']),\n 'right_border': get_bicycle_border(origin_through['right_border'],\n destination_through['right_border'])\n }\n\n\ndef get_left_turn_guideways(all_lanes, nodes_dict):\n \"\"\"\n Compile a list of guideways for all legal left turns\n :param all_lanes: list of dictionaries\n :param nodes_dict: dictionary\n :return: list of dictionaries\n \"\"\"\n logger.info('Starting left turn guideways')\n guideways = []\n for origin_lane in all_lanes:\n if is_left_turn_allowed(origin_lane):\n logger.debug('Origin Lane ' + dictionary_to_log(origin_lane))\n for destination_lane in get_destination_lanes_for_left_turn(origin_lane, all_lanes,\n nodes_dict):\n logger.debug('Destin Lane ' + dictionary_to_log(destination_lane))\n try:\n guideway_data = get_direct_turn_guideway(origin_lane, destination_lane,\n all_lanes, turn_type='left')\n set_guideway_id(guideway_data)\n except Exception as e:\n logger.exception(e)\n guideway_data = None\n\n if guideway_data is not None:\n logger.debug('Guideway ' + dictionary_to_log(guideway_data))\n guideways.append(guideway_data)\n\n logger.info('Created %d guideways' % len(guideways))\n return guideways\n\n\ndef create_right_turn_guideway(origin_lane, all_lanes):\n \"\"\"\n Calculate the right border and create a guideway\n :param origin_lane: dictionary\n :param all_lanes: list of dictionary\n :return: dictionary\n \"\"\"\n logger.info('Starting right turn guideway')\n guideway = {\n 'direction': 'right',\n 'origin_lane': origin_lane,\n }\n\n link_lane = get_link(origin_lane, all_lanes)\n if link_lane is None:\n destination_lanes = get_destination_lanes_for_right_turn(origin_lane, all_lanes)\n if len(destination_lanes) > 0:\n return get_direct_turn_guideway(origin_lane, destination_lanes[0], all_lanes,\n turn_type='right')\n else:\n return None\n\n guideway['link_lane'] = link_lane\n\n destination_lane = get_link_destination_lane(link_lane, all_lanes)\n if destination_lane is None:\n logger.debug('Link destination not found. Origin id %d' % origin_lane['id'])\n return None\n\n if origin_lane['left_shaped_border'] is None:\n left_border_type = 'left_border'\n else:\n left_border_type = 'left_shaped_border'\n if origin_lane['right_shaped_border'] is None:\n right_border_type = 'right_border'\n else:\n right_border_type = 'right_shaped_border'\n\n guideway['destination_lane'] = destination_lane\n guideway['left_border'] = get_right_turn_border(origin_lane[left_border_type],\n link_lane['left_border'],\n destination_lane['left_border']\n )\n guideway['median'] = get_right_turn_border(origin_lane['median'],\n link_lane['median'],\n destination_lane['median']\n )\n guideway['right_border'] = get_right_turn_border(origin_lane[right_border_type],\n link_lane['right_border'],\n destination_lane['right_border']\n )\n if guideway['left_border'] is None:\n logger.debug(\n 'Left border for the linked right turn is None. Origin id %d' % origin_lane['id'])\n return None\n if guideway['right_border'] is None:\n logger.debug(\n 'Right border for the linked right turn is None. Origin id %d' % origin_lane['id'])\n return None\n\n return guideway\n\n\ndef get_through_guideway(origin_lane, destination_lane):\n \"\"\"\n Create a through guideway from an origin and destination lanes\n :param origin_lane: dictionary\n :param destination_lane: dictionary\n :return: dictionary\n \"\"\"\n logger.info('Starting through guideway')\n if origin_lane['nodes'][-1] == destination_lane['nodes'][0]:\n return {\n 'direction': 'through',\n 'origin_lane': origin_lane,\n 'destination_lane': destination_lane,\n 'left_border': origin_lane['left_border'] + destination_lane['left_border'][1:],\n 'median': origin_lane['median'] + destination_lane['median'][1:],\n 'right_border': origin_lane['right_border'] + destination_lane['right_border'][1:]\n }\n else:\n return {\n 'direction': 'through',\n 'origin_lane': origin_lane,\n 'destination_lane': destination_lane,\n 'left_border': origin_lane['left_border'][:-1] + destination_lane['left_border'][1:],\n 'median': origin_lane['median'][:-1] + destination_lane['median'][1:],\n 'right_border': origin_lane['right_border'][:-1] + destination_lane['right_border'][1:]\n }\n\n\ndef get_u_turn_guideways(all_lanes, x_data):\n \"\"\"\n Compile a list of bicycle guideways for all legal u-turns\n :param all_lanes: list of dictionaries\n :param x_data: intersection dictionary\n :return: list of dictionaries\n \"\"\"\n\n logger.info('Starting U-turn guideways')\n guideways = []\n\n for origin_lane in all_lanes:\n if is_u_turn_allowed(origin_lane, x_data):\n logger.debug('Origin Lane ' + dictionary_to_log(origin_lane))\n for destination_lane in get_destination_lanes_for_u_turn(origin_lane, all_lanes):\n logger.debug('Destin Lane ' + dictionary_to_log(destination_lane))\n try:\n guideway_data = get_u_turn_guideway(origin_lane, destination_lane, all_lanes)\n set_guideway_id(guideway_data)\n except Exception as e:\n logger.exception(e)\n guideway_data = None\n\n if guideway_data is not None \\\n and guideway_data['left_border'] is not None \\\n and guideway_data['median'] is not None \\\n and guideway_data['right_border'] is not None:\n logger.debug('Guideway ' + dictionary_to_log(guideway_data))\n guideways.append(guideway_data)\n\n logger.info('Created %d guideways' % len(guideways))\n return guideways\n\n\ndef get_u_turn_guideway(origin_lane, destination_lane, all_lanes):\n \"\"\"\n Create a u-turn guideway from an origin and destination lanes\n :param origin_lane: dictionary\n :param destination_lane: dictionary\n :param all_lanes: list of dictionaries\n :return: dictionary\n \"\"\"\n return {\n 'direction': 'u_turn',\n 'origin_lane': origin_lane,\n 'destination_lane': destination_lane,\n 'left_border': get_u_turn_border(origin_lane, destination_lane, all_lanes, 'left'),\n 'median': get_u_turn_border(origin_lane, destination_lane, all_lanes, 'median'),\n 'right_border': get_u_turn_border(origin_lane, destination_lane, all_lanes, 'right')\n }\n\n\ndef get_through_guideways(all_lanes):\n \"\"\"\n Create through guideways from a list of merged lanes\n :param all_lanes: list of dictionaries\n :return: list of dictionaries\n \"\"\"\n\n logger.info('Starting through guideways')\n guideways = []\n for origin_lane in all_lanes:\n if is_through_allowed(origin_lane):\n logger.debug('Origin Lane ' + dictionary_to_log(origin_lane))\n destination_lane = get_destination_lane(origin_lane, all_lanes)\n if destination_lane is not None:\n logger.debug('Destin Lane ' + dictionary_to_log(destination_lane))\n try:\n guideway_data = get_through_guideway(origin_lane, destination_lane)\n set_guideway_id(guideway_data)\n guideways.append(guideway_data)\n logger.debug('Guideway ' + dictionary_to_log(guideway_data))\n except Exception as e:\n logger.exception(e)\n\n logger.info('Created %d guideways' % len(guideways))\n return guideways\n\n\ndef get_crosswalk_to_crosswalk_distance_along_guideway(guideway_data, crosswalks,\n max_distance=50.0):\n \"\"\"\n Calculate max distance between crosswalks along a guideway\n :param guideway_data: guideway dictionary\n :param crosswalks: list of crosswalks dictionaries\n :return: float in meters\n \"\"\"\n nearest_crosswalks = [c for c in crosswalks if\n \"distance_to_center\" not in c or c[\"distance_to_center\"] < max_distance]\n origin_crosswalks = [c for c in nearest_crosswalks\n if (c['simulated'] == 'no' or c['name'] == guideway_data['origin_lane'][\n 'name'])\n and crosswalk_intersects_median(c, guideway_data['origin_lane']['median'])\n ]\n destination_crosswalks = [c for c in nearest_crosswalks\n if (c['simulated'] == 'no' or c['name'] ==\n guideway_data['destination_lane']['name'])\n and crosswalk_intersects_median(c, guideway_data['destination_lane'][\n 'median'])\n ]\n\n if len(origin_crosswalks) == 0:\n logger.warning('Unable to find origin crosswalks for %s guideway %d %s'\n % (guideway_data['direction'], guideway_data['id'],\n guideway_data['origin_lane']['name'])\n )\n return -3\n if len(destination_crosswalks) == 0:\n logger.warning('Unable to find destination crosswalks for %s guideway %d %s'\n % (guideway_data['direction'], guideway_data['id'],\n guideway_data['destination_lane']['name'])\n )\n return -4\n\n return max([get_crosswalk_to_crosswalk_distance(c1, c2, guideway_data['median'])\n for c1 in origin_crosswalks\n for c2 in destination_crosswalks\n ]\n )\n\n\ndef get_direct_turn_guideway(origin_lane, destination_lane, all_lanes, turn_type='right'):\n \"\"\"\n Create a right or left turn guideway if there is no link lane connecting origin and destination\n :param origin_lane: dictionary\n :param destination_lane: dictionary\n :param all_lanes: list of dictionaries\n :param turn_type: string: 'right' for a right turn, left' a for left one\n :return: dictionary\n \"\"\"\n\n logger.debug('Starting direct turn guideway')\n if turn_type == 'right':\n if not is_right_turn_allowed(origin_lane, all_lanes):\n logger.debug('Right turn not allowed. Origin id %d' % origin_lane['id'])\n return None\n turn_direction = 1\n else:\n if not is_left_turn_allowed(origin_lane):\n logger.debug('Left turn not allowed. Origin id %d' % origin_lane['id'])\n return None\n turn_direction = -1\n\n guideway = {\n 'direction': turn_type,\n 'origin_lane': origin_lane,\n 'destination_lane': destination_lane,\n }\n\n left_border = get_turn_border(origin_lane,\n destination_lane,\n all_lanes,\n border_type='left',\n turn_direction=turn_direction\n )\n if left_border is None:\n logger.debug('Left border failed. Origin id %d, Dest id %d' % (\n origin_lane['id'], destination_lane['id']))\n return None\n\n right_border = get_turn_border(origin_lane,\n destination_lane,\n all_lanes,\n border_type='right',\n turn_direction=turn_direction\n )\n if right_border is None:\n logger.debug('Right border failed. Origin id %d, Dest id %d' % (\n origin_lane['id'], destination_lane['id']))\n return None\n\n median = get_turn_border(origin_lane,\n destination_lane,\n all_lanes,\n border_type='median',\n turn_direction=turn_direction\n )\n if median is None:\n logger.debug(\n 'Median failed. Origin id %d, Dest id %d' % (origin_lane['id'], destination_lane['id']))\n return None\n\n guideway['left_border'] = left_border\n guideway['median'] = median\n guideway['right_border'] = right_border\n return guideway\n\n\ndef get_right_turn_guideways(all_lanes):\n \"\"\"\n Create a list of right turn guideways for lanes having an additional link to the destination\n :param all_lanes: list of dictionaries\n :return: list of dictionaries\n \"\"\"\n\n logger.info('Starting right guideways')\n guideways = []\n for origin_lane in all_lanes:\n if is_right_turn_allowed(origin_lane, all_lanes):\n logger.debug('Origin Lane ' + dictionary_to_log(origin_lane))\n try:\n guideway_data = create_right_turn_guideway(origin_lane, all_lanes)\n set_guideway_id(guideway_data)\n except Exception as e:\n logger.exception(e)\n guideway_data = None\n\n if guideway_data is not None:\n logger.debug('Guideway ' + dictionary_to_log(guideway_data))\n guideways.append(guideway_data)\n\n logger.info('Created %d guideways' % len(guideways))\n return guideways\n\n\ndef set_guideway_ids(guideways):\n \"\"\"\n Set guideway ids as a combination of the origin and destination ids.\n This function also sets guideway length.\n Set guideway types based on the origin lane type\n :param guideways: list of dictionaries\n :return: list of dictionaries\n \"\"\"\n\n for g in guideways:\n set_guideway_length(g)\n set_guideway_id(g)\n\n return guideways\n\n\ndef set_guideway_length(g):\n \"\"\"\n Set guideway length as the length of its median\n :param g: guideway dictionary\n :return: None\n \"\"\"\n if g is None:\n logger.error('Guideway is None')\n else:\n g['length'] = get_border_length(g['median'])\n logger.debug('Guideway id %d length %r' % (g['id'], g['length']))\n\n\ndef set_guideway_id(g):\n \"\"\"\n Set guideway id as a combination of the origin and destination ids.\n Set guideway types based on the origin lane type.\n This function also sets guideway length.\n :param g: guideway dictionary\n :return: None\n \"\"\"\n\n if g is not None:\n g['id'] = 100 * g['origin_lane']['id'] + g['destination_lane']['id']\n if g['origin_lane']['lane_type'] == 'cycleway':\n g['type'] = 'bicycle'\n elif 'rail' in g['origin_lane']['lane_type']:\n g['type'] = 'railway'\n elif g['origin_lane']['lane_type'] == 'crosswalk':\n g['type'] = 'footway'\n else:\n g['type'] = 'drive'\n set_guideway_length(g)\n\n\ndef get_polygon_from_guideway(guideway_data,\n fc='y',\n ec='w',\n alpha=0.8,\n linestyle='dashed',\n joinstyle='round',\n reduced=False\n ):\n \"\"\"\n Get a polygon from a guideway\n \"\"\"\n\n if reduced:\n polygon_sequence = guideway_data['reduced_left_border'] + guideway_data[\n 'reduced_right_border'][::-1]\n else:\n polygon_sequence = guideway_data['left_border'] + guideway_data['right_border'][::-1]\n\n return Polygon(polygon_sequence,\n closed=True,\n fc=fc,\n ec=ec,\n alpha=alpha,\n linestyle=linestyle,\n joinstyle=joinstyle\n )\n\n\ndef plot_guideways(guideways, fig=None, ax=None, cropped_intersection=None,\n fig_height=15,\n fig_width=15,\n axis_off=False,\n edge_linewidth=1,\n margin=0.02,\n bgcolor='#CCFFE5',\n edge_color='#FF9933',\n alpha=1.0,\n fc='y',\n ec='w'\n ):\n \"\"\"\n Plot lanes for existing street plot\n :param guideways:\n :param fig:\n :param ax:\n :param cropped_intersection:\n :param fig_height:\n :param fig_width:\n :param axis_off:\n :param edge_linewidth:\n :param margin:\n :param bgcolor:\n :param edge_color:\n :return:\n \"\"\"\n\n if fig is None or ax is None:\n if cropped_intersection is None:\n return None, None\n return None, None\n\n for guideway_data in guideways:\n if 'destination_lane' in guideway_data and guideway_data['destination_lane'][\n 'lane_type'] == 'cycleway':\n fcolor = '#00FF00'\n ecolor = '#00FF00'\n else:\n fcolor = fc\n ecolor = ec\n ax.add_patch(get_polygon_from_guideway(guideway_data, alpha=alpha, fc=fcolor, ec=ecolor))\n\n return fig, ax\n\n\ndef relative_cut(guideway_data, relative_distance, starting_point=\"b\"):\n \"\"\"\n Reduce guideway by relative distance from either end. The distance is in the range [0;1].\n The starting point can be either 'b' or 'e'; The guideway left and right borders and median will truncated.\n For example, if relative_distance = 0.3 and starting_point_for_cut=\"b\", \n then the function returns 30% of the original length starting from the beginning of the guideway.\n If relative_distance = 0.3 and starting_point_for_cut=\"e\", \n then the function returns 30% of the original length adjacent to the end of the guideway.\n In addition this function sets the new guideway length. The origin and destination lane lengths are preserved \n in the lane meta data sections.\n :param guideway_data: guideway dictionary\n :param relative_distance: relative length\n :param starting_point: string, either 'b' or 'e'\n :return: guideway dictionary with reduced borders and median\n \"\"\"\n\n if guideway_data is None:\n return None\n\n cut_guideway = copy.deepcopy(guideway_data)\n if 'cut_history' in cut_guideway:\n cut_guideway['cut_history'].append(str(relative_distance) + '_' + starting_point)\n else:\n cut_guideway['cut_history'] = [str(relative_distance) + '_' + starting_point]\n\n if starting_point == \"b\":\n median = guideway_data['median']\n left_border = guideway_data['left_border']\n right_border = guideway_data['right_border']\n else:\n median = guideway_data['median'][::-1]\n left_border = guideway_data['left_border'][::-1]\n right_border = guideway_data['right_border'][::-1]\n\n cut_median = cut_line_by_relative_distance(median, relative_distance)\n cut_left_border = cut_border_by_point(left_border, cut_median[-1])\n cut_right_border = cut_border_by_point(right_border, cut_median[-1])\n\n if starting_point == \"b\":\n cut_guideway['median'] = cut_median\n cut_guideway['left_border'] = cut_left_border\n cut_guideway['right_border'] = cut_right_border\n else:\n cut_guideway['median'] = cut_median[::-1]\n cut_guideway['left_border'] = cut_left_border[::-1]\n cut_guideway['right_border'] = cut_right_border[::-1]\n\n set_guideway_length(cut_guideway)\n return cut_guideway\n","sub_path":"source_code/guideway.py","file_name":"guideway.py","file_ext":"py","file_size_in_byte":25089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"554277720","text":"from TwitterSearch import *\ndef GeoBlocked():\n # try:\n tso = TwitterSearchOrder()\n tso.set_keywords(['geoblocking', 'geoblocked'])\n tso.set_language('en')\n tso.set_include_entities(False)\n tso.verify = False\n\n ts = TwitterSearch(\n consumer_key = 'aaabbb',\n consumer_secret = 'cccddd',\n access_token = '111222',\n access_token_secret = '333444'\n )\n for tweet in ts.search_tweets_iterable(tso):\n print ('@%s tweeted: %s' % ( tweet['user']['screen_name'], tweet['text'] ) )\n #except TwitterSearchException as e:\n #print(e)\n return\n","sub_path":"GeoBlocked2.py","file_name":"GeoBlocked2.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"80498268","text":"class Solution(object):\n def customSortString(self, S, T):\n \"\"\"\n :type S: str\n :type T: str\n :rtype: str\n \"\"\"\n ret = \"\"\n for x in S:\n ret += x * T.count(x)\n T = T.replace(x, '')\n ret += T\n return ret\n\n\ns = Solution()\nprint(s.customSortString(\"cba\", \"abcd\"))\n","sub_path":"LeetCode/791. Custom Sort String.py","file_name":"791. Custom Sort String.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"209538805","text":"##############################################################################################\n## This module contains classes for working with Lab equipment ##\n## In order to use this module, you need to install pyvisa library ##\n## Author: Zvi Karp ##\n## Date: 15/11/16 ##\n## Edited by: Bar Kristal, 18/12/16 ## \n##############################################################################################\n\n#Errors:\n\nclass Error_connecting_device():\n\tdef __init__(self):\n\t\twrite_to_log(\"Error: failed connecting to device\" %(self.type))\n\n\n\n#Lab equipment classes:\n\nclass Agillent34401A():\n\tdef __init__(self,address):\n\t\tresource_manager = visa.ResourceManager()\n\t\tself.dev=resource_manager.open_resource(address)\n\t\tself.name=self.dev.query('*IDN?')[:-1]\n\t\tself.dev.timeout = 5000\n\n\tdef close(self):\n\t\tself.dev.close()\n\t\t#write_to_log ('The connection with: %s is now closed' %(self.name))\n\n\tdef send_command(self, command):\n\t#Send a visa command to the device.\n\t#This function and the next one can be used in order to send a command that doesn't covered by this module.\n\t\tself.dev.write(command)\n\n\tdef read_response(self, command):\n\t#read from the device. can be used after sending a query command to the device.\n\t\treturn self.dev.read()[-1]\n\n\tdef meas(self,meas):\n\t\tif meas == 'DCV':\n\t\t\tself.dev.write('MEAS:VOLT:DC?')\n\t\t\tresult = self.dev.read()[:-1]\n\t\t\twrite_to_log (\"DC Measurement: %s\" %(result))\n\t\telif meas == 'ACV':\n\t\t\tself.dev.write('MEAS:VOLT:AC?')\n\t\t\tresult = self.dev.read()[:-1]\n\t\t\twrite_to_log (\"AC Measurement: %s\" %(result))\n\t\telif meas == 'frequency':\n\t\t\tself.dev.write('MEAS:FREQ?')\n\t\t\tresult = self.dev.read()[:-1]\n\t\t\twrite_to_log (\"Frequency Measurement: %s\" %(result))\n\t\telif meas == 'resistance':\n\t\t\tself.dev.write('MEAS:REAS?')\n\t\t\tresult = self.dev.read()[:-1]\n\t\t\twrite_to_log (\"Resistance Measurement: %s\" %(result))\n\t\telif meas == 'DCI':\n\t\t\tself.dev.write('MEAS:CURR:DC?')\n\t\t\tresult = self.dev.read()[:-1]\n\t\t\twrite_to_log (\"DC Current Measurement: %s\" %(result))\n\t\telif meas == 'ACI':\n\t\t\tself.dev.write('MEAS:CURR:AC?')\n\t\t\tresult = self.dev.read()[:-1]\n\t\t\twrite_to_log (\"AC Current Measurement: %s\" %(result))\n\t\treturn result\n\n\n\nclass QL355TPPwrSply():\n\tdef __init__(self,address):\n\t\tresource_manager = visa.ResourceManager()\n\t\tself.dev=resource_manager.open_resource(address)\n\t\tself.dev.clear()\n\t\tself.name=self.dev.query('*IDN?')[:-1]\n\t\tself.dev.timeout = 5000\n\n\n\tdef close(self):\n\t\tself.dev.close()\n\t\twrite_to_log ('The connection with: %s is now closed' %(self.name))\n\n\tdef set_timeout(self, time):\n\t\ttime = int(time)\n\t\tself.dev.timeout = time\n\n\tdef send_command(self, command):\n\t#Send a visa command to the device.\n\t#This function and the next one can be used in order to send a command that doesn't covered by this module.\n\t\tself.dev.write(command)\n\n\tdef read_response(self, command):\n\t#read from the device. can be used after sending a query command to the device.\n\t\treturn self.dev.read()[-1]\n\n\tdef set_volt(self, channel, volt):\n\t\t#set the voltage output of the specified channel\n\t\tchannel = str(channel)\n\t\tself.dev.write(\"V%s %s\" %(channel , volt))\n\t\ttime.sleep(0.5)\n\t\tres = self.dev.query(\"V%s?\" %(channel))[:-1]\n\t\treturn res\n\n\tdef set_current_lim(self, channel, current):\n\t\t#set the current limit of the specified channel\n\t\tchannel = str(channel)\n\t\tself.dev.write(\"I%s %s\" %(channel ,current))\n\t\ttime.sleep(0.1)\n\t\tres = self.dev.query(\"I%s?\" %(channel))[:-1]\n\t\treturn res\n\n\tdef channel_on(self, channel):\n\t\t#set ON the specified channel\n\t\tchannel = str(channel)\n\t\tself.dev.write('OP%s 1' %(channel))\n\t\twrite_to_log('Channel %s is on' %(channel))\n\n\tdef channel_off(self, channel):\n\t\t#set OFF the specified channel\n\t\tchannel = str(channel)\n\t\tself.dev.write('OP%s 0' %(channel))\n\t\twrite_to_log('Channel %s is off' %(channel))\n\n\tdef increment_voltage(self, channel, step_size):\n\t\t#increment the channel's output voltage in a step_size voltage\n\t\tchannel = str(channel)\n\t\tself.dev.write('DELTAV%s %s' %(channel ,step_size))\n\t\tself.dev.write('INCV%s' %(channel))\n\t\t#write_to_log(\"Channel %s was incremented by %sV\" %(channel ,step_size))\n\t\tres = self.dev.write('V%s?' %(channel))\n\t\t#write_to_log(\"Channel %s volatge is now %sV\" %(channel ,self.dev.read()[3:]))\n\t\treturn res\n\n\tdef all_off(self):\n\t\t#set ALL channels OFF\n\t\tself.dev.write('OPALL 0')\n\t\t#write_to_log(\"All channels set OFF\")\n\n\tdef all_on(self):\n\t\t#set ALL channels ON\n\t\tself.dev.write('OPALL 1')\n\t\t#write_to_log(\"All channels set ON\")\n\n\tdef read_current(self, channel):\n\t\t#reads the current flows right now through the channel\n\t\tself.dev.write('I%sO?' %(str(channel)))\n\t\tcur = self.dev.read()[:-1]\n\t\t#write_to_log(\"The current at channel %s is: %s\" %(channel, cur))\n\t\treturn cur\n\n\tdef sense(self, channel, mode):\n\t#mode=0: local, mode=1: remote\n\t\tself.dev.write('SENSE%s %s' %(channel, mode))\n\t\tmod=\"local\" if mode == '0' else \"remote\"\n\t\t#write_to_log(\"Activated %s sense on channel %s\" %(mod, str(channel)))\n\n\nclass HP53131aFreqCounter():\n\tdef __init__(self,address):\n\t\tresource_manager = visa.ResourceManager()\n\t\tself.dev=resource_manager.open_resource(address)\n\t\tself.name=self.dev.query('*IDN?')[:-1]\n\t\tself.dev.timeout = 5000\n\n\tdef close(self):\n\t\tself.dev.close()\n\t\twrite_to_log ('The connection with: %s is now closed' %(self.name))\n\n\tdef send_command(self, command):\n\t#Send a visa command to the device.\n\t#This function and the next one can be used in order to send a command that doesn't covered by this module.\n\t\tself.dev.write(command)\n\n\tdef read_response(self, command):\n\t#read from the device. can be used after sending a query command to the device.\n\t\treturn self.dev.read()[-1]\n\n\t#Take one of the following measurement options.\n\t#Notice that the 'channel' argument is an option, only for 'frequency' mesurement, when the default is \"1\"\n\tdef meas(self, meas, channel=\"1\"):\n\t\tchannel = str(channel)\n\t\tif ((meas != \"frequency\" and meas != \"volt_max_peak\" and meas != \"volt_min_peak\") and (channel != \"1\")):\n\t\t\twrite_to_log(\"Error: %s measurement can be taken only from channel 1\" %(meas))\n\t\t\treturn \"\"\n\t\telse:\n\t\t\tif (meas == \"frequency\"):\n\t\t\t\tself.dev.write('MEAS%s:FREQ?' %(channel))\n\t\t\t\tresult = self.dev.read()[:-1]\n\t\t\t\twrite_to_log (\"%s measurement on channel %s: %s\" %(meas, channel, result))\n\t\t\telif (meas == \"rise_time\"):\n\t\t\t\tself.dev.write('MEAS:RTIME?')\n\t\t\t\tresult = self.dev.read()[:-1]\n\t\t\t\twrite_to_log (\"%s measurement on channel %s: %s\" %(meas, channel, result))\n\t\t\telif (meas == \"fall_time\"):\n\t\t\t\tself.dev.write('MEAS:FTIME?')\n\t\t\t\tresult = self.dev.read()[:-1]\n\t\t\t\twrite_to_log (\"%s measurement on channel %s: %s\" %(meas, channel, result))\n\t\t\telif (meas == \"period\"):\n\t\t\t\tself.dev.write('MEAS:PER?')\n\t\t\t\tresult = self.dev.read()[:-1]\n\t\t\t\twrite_to_log (\"%s measurement on channel %s: %s\" %(meas, channel, result))\n\t\t\telif (meas == \"pos_width\"):\n\t\t\t\tself.dev.write('MEAS:PWID?')\n\t\t\t\tresult = self.dev.read()[:-1]\n\t\t\t\twrite_to_log (\"%s measurement on channel %s: %s\" %(meas, channel, result))\n\t\t\telif (meas == \"neg_width\"):\n\t\t\t\tself.dev.write('MEAS:NWID?')\n\t\t\t\tresult = self.dev.read()[:-1]\n\t\t\t\twrite_to_log (\"%s measurement on channel %s: %s\" %(meas, channel, result))\n\t\t\telif (meas == \"duty_cycle\"):\n\t\t\t\tself.dev.write('MEAS:DCYC?')\n\t\t\t\tresult = self.dev.read()[:-1]\n\t\t\t\twrite_to_log (\"%s measurement on channel %s: %s\" %(meas, channel, result))\n\t\t\telif (meas == \"volt_max_peak\"):\n\t\t\t\tself.dev.write('MEAS%s:MAX?' %(channel))\n\t\t\t\tresult = self.dev.read()[:-1]\n\t\t\t\twrite_to_log (\"%s measurement on channel %s: %s\" %(meas, channel, result))\n\t\t\telif (meas == \"volt_min_peak\"):\n\t\t\t\tself.dev.write('MEAS%s:MIN?' %(channel))\n\t\t\t\tresult = self.dev.read()[:-1]\n\t\t\t\twrite_to_log (\"%s measurement on channel %s: %s\" %(meas, channel, result))\n\t\t\telif (meas == \"ratio\"):\n\t\t\t\tself.dev.write('MEAS:FREQ:RAT?')\n\t\t\t\tresult = self.dev.read()[:-1]\n\t\t\t\twrite_to_log (\"Ratio %s to %s: %s\" %(\"1\", \"2\", result))\n\t\t\telif (meas == \"phase\"):\n\t\t\t\tself.dev.write('MEAS:PHAS?')\n\t\t\t\tresult = self.dev.read()[:-1]\n\t\t\t\twrite_to_log (\"Phase %s to %s: %s\" %(\"1\", \"2\", result))\n\t\t\treturn result\n\n\nclass HP33120aWaveGen():\n\t'''Compatible also for Agilent33250A device'''\n\tdef __init__(self, address):\n\t\tresource_manager = visa.ResourceManager()\n\t\tself.dev=resource_manager.open_resource(address)\n\t\tself.name=self.dev.query('*IDN?')[:-1]\n\t\tself.dev.timeout = 5000\n\n\tdef close(self):\n\t\tself.dev.close()\n\t\twrite_to_log ('The connection with: %s is now closed' %(self.name))\n\n\tdef send_command(self, command):\n\t#Send a visa command to the device.\n\t#This function and the next one can be used in order to send a command that doesn't covered by this module.\n\t\tself.dev.write(command)\n\n\tdef read_response(self, command):\n\t#read from the device. can be used after sending a query command to the device.\n\t\treturn self.dev.read()[-1]\n\n\t#Generate a waveform in single command.\n\t#Example: self.generate(\"SIN\", 3000, 1.5, -1) generates a sine wave, 3KHz, 1.5Vpp, -1V offset.\n\tdef generate(self, wave, frequency, amplitude, offset):\n\t\tself.dev.write(\"APPL:%s %s, %s, %s\" %(wave, frequency, amplitude, offset))\n\n\t#Set specifiied shape : SINusoid|SQUare|TRIangle|RAMP|NOISe|DC|USER\n\tdef set_shape(self, shape):\n\t\tself.dev.write(\"FUNC:SHAP %s\" %(shape))\n\n\t#Set frequency\n\tdef set_frequency(self, frequency):\n\t\tself.dev.write(\"FREQ: %s\" %(frequency))\n\n\tdef set_amplitude(self, amplitude):\n\t\tself.dev.write(\"VOLT: %s\" %(amplitude))\n\n\t#Set the units of the amplitude: VPP|VRMS|DBM|DEFault\n\t#Do not affect the offset units, which stays V.\n\tdef set_amplitude_units(self, units):\n\t\tself.dev.write(\"VOLT:UNIT %s\" %(amplitude))\n\n\tdef set_offset(self, offset):\n\t\tself.dev.write(\"VOLT:OFFS %s\" %(offset))\n\n\tdef get_shape(self):\n\t\tresult = self.dev.query(\"FUNC:SHAP?\")[:-1]\n\t\twrite_to_log(\"Signal's shape is: %s\" %(result))\n\t\treturn result\n\n\tdef get_frequency(self):\n\t\tresult = self.dev.query(\"FREQ?\")[:-1]\n\t\twrite_to_log(\"Frequency is: %s\" %(result))\n\t\treturn result\n\n\tdef get_amplitude(self):\n\t\tresult = self.dev.query(\"VOLT?\")[:-1]\n\t\twrite_to_log(\"Amplitude is: %s\" %(result))\n\t\treturn result\n\n\tdef get_amplitude_unit(self):\n\t\tresult = self.dev.query(\"VOLT:UNIT?\")[:-1]\n\t\twrite_to_log(\"Amplitude units are: %s\" %(result))\n\t\treturn result\n\n\n\tdef get_offset(self):\n\t\tresult = self.dev.query(\"VOLT:OFFS?\")[:-1]\n\t\twrite_to_log(\"Offset is: %s\" %(result))\n\t\treturn result\n\n\t#Turn on the output channel. Doesn't necessary when using the generate() command,\n\t#because output channel is being turn on automatically.\n\tdef output_on(self):\n\t\tself.dev.write(\"OUTPUT ON\")\n\n\tdef output_off(self):\n\t\tself.dev.write(\"OUTPUT OFF\")\n\nclass KikusuiPLZ70UA():\n\tdef __init__(self, address):\n\t\tresource_manager = visa.ResourceManager()\n\t\tself.dev=resource_manager.open_resource(address)\n\t\tself.name=self.dev.query('*IDN?')[:-1]\n\t\tself.dev.timeout = 5000\n\n\t#Close the connection with the device\n\tdef close(self):\n\t\tself.dev.close()\n\t\twrite_to_log ('The connection with: %s is now closed' %(self.name))\n\n\tdef send_command(self, command):\n\t#Send a visa command to the device.\n\t#This function and the next one can be used in order to send a command that doesn't covered by this module.\n\t\tself.dev.write(command)\n\n\tdef read_response(self, command):\n\t#read from the device. can be used after sending a query command to the device.\n\t\treturn self.dev.read()[-1]\n\n\t#Reset the device to factory default settings.\n\tdef reset(self):\n\t\tself.dev.write(\"*RST\")\n\t\twrite_to_log ('%s configured to factory default settings' %(self.name[:-1]))\n\n\tdef load_on(self):\n\t\tself.dev.write(\"INP ON\")\n\t\tif (self.dev.query(\"INP?\") != '0'):\n\t\t\twrite_to_log(\"Load is on\")\n\n\tdef load_off(self):\n\t\tself.dev.write(\"INP OFF\")\n\t\tif (self.dev.query(\"INP?\") != '1'):\n\t\t\twrite_to_log(\"Load is off\")\n\n\t#mode=CC/CR/CV/CCCV/CRCV, when CC='constant current' CR='constant resistance' CV='constant voltage'\n\tdef set_constant_mode(self, channel, mode):\n\t\tself.dev.write(\"INST CH%s\" %channel)\n\t\tself.dev.write(\"FUNC %s\" %mode)\n\n\n\t#Set the conductance (in units of [S]). This funciton sets both of the channels together\n\tdef set_conductance(self, conductance):\n\t\tself.dev.write(\"COND %s\" %conductance)\n\n\t#Set the resistance (in unit of [ohm]) by first changing to conductance units. This funciton sets both of the channels together\n\tdef set_resistance(self, resistance):\n\t\tif (float(resistance) != 0):\n\t\t\tconductance = str(1/float(resistance))\n\t\t\tself.dev.write(\"COND %s\" %conductance)\n\n\t#Set current. This funciton sets both of the channels together\n\tdef set_current(self, current):\n\t\tself.dev.write(\"CURR %s\" %current)\n\n\t#Set voltage. This funciton sets both of the channels together\n\tdef set_voltage(self, channel, voltage):\n\t\tself.dev.write(\"INST CH%s\" %channel)\n\t\tself.dev.write(\"VOLT %s\" %voltage)\n\n\t#Read the conductance on the specified channel\n\tdef read_conductance(self, channel):\n\t\tself.dev.write(\"INST CH%s\" %channel)\n\t\tres = self.dev.query(\"MEAS:COND?\")[:-1]\n\t\twrite_to_log(\"The conductance on channel %s is: %sS\" %(channel, res))\n\t\treturn res\n\n\t#Read the conductance on the specified channel\n\tdef read_current(self, channel):\n\t\tself.dev.write(\"INST CH%s\" %channel)\n\t\tres = self.dev.query(\"MEAS:CURR?\")[:-1]\n\t\twrite_to_log(\"The current on channel %s is: %sA\" %(channel, res))\n\t\treturn res\n\n\t#Read the conductance on the specified channel\n\tdef read_voltage(self, channel):\n\t\tself.dev.write(\"INST CH%s\" %channel)\n\t\tres = self.dev.query(\"MEAS:VOLT?\")[:-1]\n\t\twrite_to_log(\"The voltage on channel %s is: %sV\" %(channel, res))\n\t\treturn res\n\n\n\n# The connection with this oven is a serial connection - rs232 - which is done using a usb-to-RS232 connector.\n# This connector appears as a virtual port with a specified 'COM'- this is the COM we need to enter when initializing the connection.\nclass VotschVT4002():\n\tdef __init__(self, com):\n\t\tself.name=\"VotschVT4002\"\n\t\tself.ser=serial.Serial()\n\t\tself.ser.close()\n\t\tself.ser.port = com\n\t\tself.ser.baudrate = 9600\n\t\tself.ser.bytesize = 8\n\t\tself.ser.parity = 'N'\n\t\tself.ser.stopbits = 1\n\t\tself.ser.timeout = 1\n\t\tself.ser.open()\n\n\n\t#Close the serial connection with the device\n\tdef close(self):\n\t\tself.ser.close()\n\n\t#Changing the serial connection's parameters:\n\tdef change_port(self, com):\n\t\tself.ser.port = com\n\t\twrite_to_log(\"{} port changed to {}\".format(self.name, com))\n\n\t#Sets the temperature and STARTS the chamber. temp can be from type int, float of str\n\tdef set_temp(self, temp):\n\t\ttyp = type(temp)\n\t\tif (typ == str):\n\t\t\ttemp = float(temp)\n\t\tneg = '0' if int(temp) >= 0 else '-'\n\t\tif (abs(temp) < 10):\n\t\t\ttemp = neg + '00' + str(round(abs(temp), 1))\n\t\telif (temp <= 100 and temp >= -50):\n\t\t\ttemp = neg + '0' +str(round(abs(temp), 1))\n\t\telse:\n\t\t\twrite_to_log(\"Error: temperature should be between -50C to 100C\")\n\t\t\treturn\n\t\tself.ser.write(\"$00E %s 0000.0 0000.0 0000.0 0000.0 010100000000111013\" %temp)\n\t\tself.ser.write(\"$00I\\r\\n\")\n\n\t#Return the temperature\n\tdef read_temp(self):\n\t\tself.ser.write(\"$00I\\r\\n\")\n\t\tres = self.ser.readline()\n\t\tres = res.split(\" \")[1]\n\t\tif (res[0] == '1'): #negative\n\t\t\tres = '-' + res[2:]\n\t\telse:\n\t\t\tres = res[2:]\n\t\t#write_to_log(\"Temperature is: %sC\" %res)\n\t\treturn res\n\n\t#Stops the function of the chamber\n\tdef stop_champer(self):\n\t\tself.ser.write(\"$00E 0000.0 0000.0 0000.0 0000.0 0000.0 000100000000111013\")\n\n\t#Sets a temperature, and waits until it gets to the desirable temp.\n\tdef wait_for_temp(self,temp):\n\t\tself.set_temp(temp)\n\t\ttime.sleep(0.5)\n\t\tcurrent_temp = float(self.read_temp())\n\t\twrite_to_log(\"wait for the temperature to reach %sC\" %temp)\n\t\ttemp = float(temp)\n\t\twhile (current_temp <= temp-1 or current_temp >= temp+1):\n\t\t\ttime.sleep(1)\n\t\t\tcurrent_temp = float(self.read_temp())\n\t\twrite_to_log(\"Temperature has reached the desirable value\")\n\n\tdef read_error(self):\n\t\tself.ser.write(\"$00F\\r\\n\")\n\t\ttime.sleep(1)\n\t\treturn self.ser.readline()\n\n\nclass Termotron3800():\n\tdef __init__(self,address):\n\t\tself.tcp_ip = address[0]\n\t\tself.port = address[1]\n\t\tself.buffer_size = 1024\n\t\tself.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\t\tself.sock.connect((self.tcp_ip, self.port))\n\t\tself.sock.send(\"IDEN?\\r\\n\") #ask for device identity\n\t\tself.name = self.read_line()\n\t\tself.sock.send(\"VRSN?\\r\\n\") #ask for software version\n\t\tself.version = self.read_line()\n\n\n\t#close connection with device\n\tdef close(self):\n\t\tself.sock.close()\n\n\t#read line from socket\n\tdef read_line(self):\n\t\tline = \"\"\n\t\twhile True:\n\t\t\tc = self.sock.recv(64)\n\t\t\tif c == \"\":\n\t\t\t\tbreak\n\t\t\telif \"\\r\" in c:\n\t\t\t\tline += c.split(\"\\r\")[0]\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tline += c\n\t\treturn line\n\n\t#before reading the device's answer:\n\tdef clear_buffer(self):\n\t\tc = self.sock.recv(1)\n\t\twhile (c != \"\"):\n\t\t\tc = self.sock.recv(16)\n\t\ttime.sleep(0.1)\n\n\t#stop chamber from working\n\tdef stop_chamber(self):\n\t\terr = \"0\"\n\t\tk = 0\n\t\twhile (err != \"5\" and k<3): #5 means that Termotron received the stop command\n\t\t\tself.sock.send(\"STOP\\r\\n\") #send the STOP command\n\t\t\tself.sock.send(\"SCOD?\\r\\n\") #check if the command had been received\n\t\t\terr = self.read_line()\n\t\t\tk += 1\n\n\t\tif (k == 10): #5 means that Termotron received the stop command\n\t\t\twrite_to_log(\"Error while sending STOP command to %s\" %self.name)\n\n\tdef run_chamber(self):\n\t\tself.sock.send(\"RUNM\\r\\n\")\n\n\n\tdef set_temp(self, temp):\n\t\tif type(temp != str):\n\t\t\ttemp = str(temp)\n\t\tself.sock.send(\"SETP1,%s\\r\\n\" %temp)\n\t\ttime.sleep(0.1)\n\t\tself.run_chamber()\n\n\t#read the current temperature of the chamber.\n\tdef read_temp(self):\n\t\tself.sock.send(\"PVAR1?\\r\\n\") #read the deviation from the configured value\n\t\ttime.sleep(0.1)\n\t\tcurrent_temp = self.read_line()\n\t\tcount = 0\n\t\twhile current_temp == '0' and count<3:\n\t\t\tself.sock.send(\"PVAR1?\\r\\n\")\n\t\t\tcurrent_temp = self.read_line()\n\t\t\tcount += 1\n\t\treturn float(current_temp)\n\n\n\tdef wait_for_temp(self, temp):\n\t\tself.set_temp(temp)\n\t\ttime.sleep(0.1)\n\t\tcurrent_temp = self.read_temp()\n\t\twhile (abs(current_temp) <= abs(temp*0.98) or abs(current_temp) >= abs(temp*1.02)):\n\t\t\ttime.sleep(1)\n\t\t\tcurrent_temp = self.read_temp()\n\t\twrite_to_log(\"Temperature has reached the desirable value\")\n\n\n\n\n","sub_path":"lab_equipment.py","file_name":"lab_equipment.py","file_ext":"py","file_size_in_byte":18096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"407995203","text":"#!/usr/bin/env python3\n\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\nimport numpy as np\nfrom mtcnn.mtcnn import MTCNN\nfrom copy import deepcopy\nfrom FPSmeter import *\nfrom utils import histogram_eq_color\nimport tensorflow as tf\ntf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)\nimport torch\nfrom preprocessing.augmentation import TTA_36_cropps, color_augumentor\nfrom metric import infer_test, infer_test_simple\n\n# TODO: use contants glbaly (including patch size of 48)\nRESIZE_SIZE = 112 # from data _helper import RESIZE_SIZE\n\n\nfont = cv2.FONT_HERSHEY_SIMPLEX\nTopLeftCornerOfPicture = (10, 40) # (left, up is origin)\nfontScale = 1\nfontColor = (0, 0, 255)\nlineType = 2\nfontColor2 = (0, 255, 0)\n\n# TODO: add mtcnn resolution modifier\n# TODO: play with MTCNN parameters\n\n\ndef main():\n # Capture device. Usually 0 will be webcam and 1 will be usb cam.\n video_capture = cv2.VideoCapture(0)\n\n # load model\n from model.FaceBagNet_model_A import Net\n net = Net(num_class=2, is_first_bn=True)\n net = torch.nn.DataParallel(net) # TODO: alternative?\n # net = net.cuda()\n # net = net.cpu()\n net = net.cuda()\n net.load_state_dict(torch.load(\"./models/model_A_color_48/checkpoint/global_min_acer_model.pth\",\n map_location=lambda storage, loc: storage))\n\n\n\n # if you want video instead of live webcam view:\n # video_capture = cv2.VideoCapture(\"/home/loki/Desktop/spoofing/Video/snimka4.mp4\")\n\n video_capture.set(3, 640)\n video_capture.set(4, 480)\n\n minsize = 25 # minimum size of face\n threshold = [0.6, 0.7, 0.7] # three steps's threshold\n factor = 0.709 # scale factor\n\n sess = tf.Session()\n with sess.as_default():\n # pnet, rnet, onet = detect_face.create_mtcnn(sess, None)\n\n detector = MTCNN()\n\n while (True):\n fps = FPSmeter()\n\n # this is currently a bottleneck\n # TODO: implement from https://gitlab.com/tloki/rpi-fejsanje/blob/master/RasPiCamera.py\n ret, frame = video_capture.read()\n if not ret:\n return\n\n frame2 = deepcopy(frame)\n frame_hist_eq = histogram_eq_color(frame2)\n\n # frame =\n\n detection = detector.detect_faces(frame)\n\n\n if detection:\n\n for i, bbox in enumerate(detection):\n bbox = bbox['box']\n pt1 = bbox[0], bbox[1]\n pt2 = bbox[0] + bbox[2], bbox[1] + int(bbox[3])\n\n cv2.rectangle(frame_hist_eq, pt1, pt2, color=(0, 255, 0), thickness=lineType)\n cv2.putText(frame_hist_eq, \"id: \"+ str(i), (bbox[0] , bbox[1] - 5), font, fontScale, fontColor,\n lineType)\n\n # TODO: do not hardcode face index\n if i == 0:\n crop_img = frame[bbox[1]:bbox[1]+bbox[3], bbox[0]:bbox[0]+bbox[2]]\n\n # infer_img = deepcopy(crop_img)\n infer_img = cv2.imread('/home/loki/Datasets/spoofing/BoKS/Detected/real/AA5742_id154_s0_112.jpg', 1)\n loaded_img = deepcopy(infer_img)\n try:\n infer_img = cv2.resize(infer_img, (RESIZE_SIZE, RESIZE_SIZE))\n except:\n continue\n\n # infer_img = color_augumentor(infer_img, target_shape=(48, 48, 3), is_infer=True)\n # n = len(infer_img)\n\n # infer_img = np.concatenate(infer_img, axis=0)\n # infer_img = np.transpose(infer_img, (0, 3, 1, 2))\n # infer_img = infer_img.astype(np.float32)\n # infer_img = infer_img.reshape([n, 3, 48, 48])\n # infer_img = infer_img / 255.0\n\n # inpt = torch.FloatTensor([infer_img])\n # inpt = torch.FloatTensor()\n # data = [[inpt, inpt]]\n\n # result = infer_test_simple(net, data)\n # result = result[0]\n # result = round(result)\n # result = bool(result)\n # result = \"OK\"*(result) + \"FAKE\"*(not result)\n # print(result)\n\n cv2.imshow(\"id: \"+ str(i), infer_img)\n\n cv2.putText(frame_hist_eq, 'Not ' * (not bool(detection)) +'Detected', TopLeftCornerOfPicture, font,\n fontScale, fontColor2 if detection else fontColor, lineType)\n\n fps.tick(frame_hist_eq)\n cv2.imshow('Hist EQ', frame_hist_eq)\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n video_capture.release()\n cv2.destroyAllWindows()\n\n\n\n\nif __name__ == '__main__':\n from time import time\n t = time()\n main()\n print(time() - t)\n","sub_path":"webcam.py","file_name":"webcam.py","file_ext":"py","file_size_in_byte":4932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"557960501","text":"import numpy as np\nimport cv2\n\nDEBUGGING = False #common flag to know if the main program is requesting debug (as metrics it's used everywhere)\nDEBUG_IMAGE = 255 * np.ones(shape=[15, 15, 3], dtype=np.uint8)\nDEBUG_IMG_LIST = []\n\ndef addDebugImage(img):\n global DEBUG_IMAGE\n global DEBUG_IMG_LIST\n #check size of new image\n height, width, channels = img.shape\n print ('New img was added with H: ' + str(height) + ', W: ' + str(width) + ', Ch: ' + str(channels))\n DEBUG_IMG_LIST.append(img)\n # Check the image that has less width\n w_min = min(im.shape[1] for im in DEBUG_IMG_LIST)\n im_list_resized = [cv2.resize(im, (w_min, int(im.shape[0] * w_min / im.shape[1])), cv2.INTER_CUBIC)\n for im in DEBUG_IMG_LIST]\n DEBUG_IMAGE = cv2.vconcat(im_list_resized)\n return DEBUG_IMAGE\n\ndef showDebugImage():\n cv2.imshow('Debug Image', DEBUG_IMAGE)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n\ndef setDebugMode(var):\n global DEBUGGING\n DEBUGGING = var\n return DEBUGGING\n\ndef isDebug():\n return DEBUGGING","sub_path":"week2/debug_utils.py","file_name":"debug_utils.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"11734283","text":"from collections import OrderedDict, Counter\n\nod = OrderedDict()\nod[2] = 2.2\nod[1] = 1.2\n\nfor i in od:\n print(\" i -> \", i)\n\nprint(\" od -> \", od)\nprint(\" pop last item added - LIFO \")\nitem = od.popitem(last=True)\nprint(\" 1. od -> \", od , \" item -> \",item)\n\n\nod[2]=3.1\nod[4]=5.1\nod[5]=6.1\nod[6]=7.1\nod[7]=8.1\n\n\nprint(\" 3. od -> \", od)\n\n# item2=od.popitem(last=False)\n# print(\" item2, FIFO -> \", item2)\n\nprint(list(od))\nitem3=od.pop(2)\nprint(\" item3 -> \", item3)\n\nctr = Counter([4, 4, 5, 7, 5, 9, 10, 10])\nctr1=sorted(ctr.items(), key=lambda x:x[1])\n\nprint(\" ctr1 -> \", ctr1)\n\nod_ctr= OrderedDict(ctr1)\nprint(\" od_ctr -> \", od_ctr)\n\nprint(\" type(ctr) -> \", type(ctr), \" type(ctr.item()) -> \", type(ctr.items()))","sub_path":"python_examples/Py_OrderedDict.py","file_name":"Py_OrderedDict.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"629743786","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Colaborador',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('nome', models.CharField(max_length=20)),\n ('funcao', models.SmallIntegerField(choices=[(1, b'Auxiliar'), (2, b'Estagiario'), (3, b'Assistente'), (4, b'Analista'), (5, b'Coordenador'), (6, b'Diretoria')])),\n ('saldo_horas', models.DecimalField(max_digits=5, decimal_places=2)),\n ('prorrogacoes', models.IntegerField()),\n ('antecipacoes', models.IntegerField()),\n ('faltas', models.IntegerField()),\n ('is_disabled', models.BooleanField(default=False)),\n ('coordenador', models.ForeignKey(related_name='coordena', to='hc.Colaborador')),\n ],\n ),\n ]\n","sub_path":"hc/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"112972119","text":"import KratosMultiphysics\nimport impose_vector_value_by_components_process\n\n## This proces sets the value of a vector variable component-by-component.\n## In this case, the fixicity is given by the user and some of the components may not be fixed.\n\ndef Factory(settings, Model):\n if(type(settings) != KratosMultiphysics.Parameters):\n raise Exception(\"expected input shall be a Parameters object, encapsulating a json string\")\n return ImposeVectorValueByComponentsOverTimeProcess(Model, settings[\"Parameters\"])\n\nfrom impose_vector_value_by_components_process import ImposeVectorValueByComponentsProcess as parent_process\nfrom KratosMultiphysics import Process as base_process\n\n## All the processes python processes should be derived from \"python_process\"\nclass ImposeVectorValueByComponentsOverTimeProcess(parent_process):\n def __init__(self, Model, settings ):\n base_process.__init__(self)\n##### \n# -- SAMPLE --\n# \"Parameters\" : {\n# \"model_part_name\" : \"el_model_part\",\n# \"mesh_id\" : 0,\n# \"variable_name\" : \"DISPLACEMENT\",\n# \"is_fixed_x\" : false,\n# \"is_fixed_y\" : true,\n# \"is_fixed_z\" : false,\n# \"value1\" : [0.0,-0.14,0.0],\n# \"value2\" : [0.0,-0.14,0.0],\n# \"interval\" : [0.0, 1.0],\n# \"step_type\" : \"linear\"\n# }\n#####\n\n self.Model = Model\n\n self.model_part = settings[\"model_part_name\"]\n self.mesh_id = settings[\"mesh_id\"]\n self.variable_name = settings[\"variable_name\"]\n self.is_fixed_x = settings[\"is_fixed_x\"]\n self.is_fixed_y = settings[\"is_fixed_y\"]\n self.is_fixed_z = settings[\"is_fixed_z\"]\n \n self.value1 = settings[\"value1\"]\n print( self.value1.PrettyPrintJsonString() )\n self.value2 = settings[\"value2\"]\n print( self.value2.PrettyPrintJsonString() )\n self.interval = settings[\"interval\"]\n self.step_type = settings[\"step_type\"]\n \n def ExecuteInitialize(self):\n pass\n \n def ExecuteInitializeSolutionStep(self):\n model_part = self.Model[self.model_part.GetString()]\n current_time = model_part.ProcessInfo[KratosMultiphysics.TIME]\n \n curr_value = KratosMultiphysics.Parameters('{ \"value\": [0.0, 0.0, 0.0] }')\n \n if( current_time < self.interval[0].GetDouble() ): # before interval\n print( \"\\033[93m :: Taking initial value :: \\033[0m\" )\n for i in range(2):\n curr_value[\"value\"][i].SetDouble( self.value1[0].GetDouble() )\n \n elif( current_time > self.interval[1].GetDouble() ): # after interval\n print( \"\\033[93m :: Taking final value :: \\033[0m\" )\n for i in range(2):\n curr_value[\"value\"][i].SetDouble( self.value2[0].GetDouble() )\n\n else: # within interval\n if( self.step_type.GetString() == \"constant\" ):\n print( \"\\033[93m :: CONSTANT: Taking initial value :: \\033[0m\" )\n for i in range(2):\n curr_value[\"value\"][i].SetDouble( self.value1[0].GetDouble() )\n \n elif( self.step_type.GetString() == \"linear\" ):\n print( \"\\033[93m :: LINEAR: Interpolating current value :: \\033[0m\" )\n for i in range(2):\n curr_value[\"value\"][i].SetDouble(\n self.value1[i].GetDouble()\n + current_time * (\n (self.value2[i].GetDouble() - self.value1[i].GetDouble())\n / \n (self.interval[1].GetDouble() - self.interval[0].GetDouble())\n )\n )\n else:\n raise Exception(\"Only constant and linear variation is implemented\")\n \n print( \"#####################################################\" )\n print( \"\\033[92m\", \"::: Time: \", current_time, \" :::\", \"\\033[0m\" )\n print( \"#####################################################\" )\n \n curr_step_params = KratosMultiphysics.Parameters(\"{}\")\n curr_step_params.AddValue(\"model_part_name\",self.model_part)\n curr_step_params.AddValue(\"mesh_id\",self.mesh_id)\n curr_step_params.AddValue(\"variable_name\",self.variable_name)\n curr_step_params.AddValue(\"is_fixed_x\",self.is_fixed_x)\n curr_step_params.AddValue(\"is_fixed_y\",self.is_fixed_y)\n curr_step_params.AddValue(\"is_fixed_z\",self.is_fixed_z)\n curr_step_params.AddValue(\"value\",curr_value[\"value\"])\n\n parent_process.__init__(self, self.Model, curr_step_params)\n parent_process.ExecuteInitialize(self)\n","sub_path":"kratos/applications/ContactStructuralMechanicsApplication/python_scripts/impose_vector_value_by_components_over_time_process.py","file_name":"impose_vector_value_by_components_over_time_process.py","file_ext":"py","file_size_in_byte":5135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"194797383","text":"__author__ = 'aarongary'\n\nimport json\n\nclass SimpleNode(object):\n def __init__(self, id=None, node_name=None, node_represents=None):\n self.return_this = {\n 'n': node_name,\n '@id': id,\n 'r': node_represents\n }\n\n def __str__(self):\n return json.dumps(self.return_this)\n","sub_path":"nicecxModel/cx/aspects/SimpleNode.py","file_name":"SimpleNode.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"114953573","text":"from django.core.management.base import BaseCommand, CommandError\n\nfrom base.sites import SITES\nfrom django.contrib.sites.models import Site\nfrom django.core.exceptions import ObjectDoesNotExist\n\nclass Command(BaseCommand):\n help = '''\n Grabs all sites from /base/sites.py and makes sure they are\n created in the database if they do not exist.\n '''\n\n def handle(self, *args, **options):\n self.stdout.write(self.style.SUCCESS(\"CREATING SITES from /base/sites.py...\"))\n\n for site in SITES.keys():\n try:\n checked_site = Site.objects.get(id=SITES[site]['SITE_ID'])\n if checked_site.name != SITES[site]['SITE_NAME'] or checked_site.domain != SITES[site]['SITE_DOMAIN']:\n checked_site.name = SITES[site]['SITE_NAME']\n checked_site.domain = SITES[site]['SITE_DOMAIN']\n checked_site.save()\n self.stdout.write('MODIFIED: %s site name and domain with current values.' % (SITES[site]['SITE_DOMAIN']))\n else:\n self.stdout.write('SITE ALREADY EXISTS: %s site name and domain unchanged.' % (checked_site.domain))\n except ObjectDoesNotExist:\n checked_site = Site(\n id = SITES[site]['SITE_ID'],\n name = SITES[site]['SITE_NAME'],\n domain = SITES[site]['SITE_DOMAIN']\n )\n checked_site.save()\n self.stdout.write('CREATED: %s site.' % (SITES[site]['SITE_DOMAIN']))\n\n self.stdout.write(self.style.SUCCESS('...DONE.\\n'))\n","sub_path":"base/management/commands/checksites.py","file_name":"checksites.py","file_ext":"py","file_size_in_byte":1622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"8426079","text":"from bika.lims import bikaMessageFactory as _, t\nfrom Products.CMFCore.utils import getToolByName\nfrom bika.lims.browser import BrowserView\nfrom Products.Five.browser.pagetemplatefile import ViewPageTemplateFile\nfrom plone.resource.utils import iterDirectoriesOfType, queryResourceDirectory\n\nimport os\nimport glob\n\n\nclass PrintForm(BrowserView):\n template = ViewPageTemplateFile(\"templates/print_form.pt\")\n _DEFAULT_TEMPLATE = 'default_form.pt'\n _TEMPLATES_DIR = 'templates/print'\n _TEMPLATES_ADDON_DIR = 'samplingrounds'\n _current_sr_index = 0\n _samplingrounds = []\n\n def __call__(self):\n if self.context.portal_type == 'SamplingRound':\n self._samplingrounds = [self.context]\n\n elif self.context.portal_type == 'SamplingRounds' \\\n and self.request.get('items', ''):\n uids = self.request.get('items').split(',')\n uc = getToolByName(self.context, 'uid_catalog')\n self._samplingrounds = [obj.getObject() for obj in uc(UID=uids)]\n\n else:\n # Warn and redirect to referer\n logger.warning('PrintView: type not allowed: %s' %\n self.context.portal_type)\n self.destination_url = self.request.get_header(\"referer\",\n self.context.absolute_url())\n\n # Generate PDF?\n if self.request.form.get('pdf', '0') == '1':\n return self._flush_pdf()\n else:\n return self.template()\n\n def getSamplingRoundObj(self):\n \"\"\"Returns the sampling round object\n \"\"\"\n return self.context\n\n def getSRTemplates(self):\n \"\"\"\n Returns a DisplayList with the available templates found in\n browser/samplingrpund/templates/\n \"\"\"\n this_dir = os.path.dirname(os.path.abspath(__file__))\n templates_dir = os.path.join(this_dir, self._TEMPLATES_DIR)\n tempath = '%s/%s' % (templates_dir, '*.pt')\n templates = [t.split('/')[-1] for t in glob.glob(tempath)]\n out = []\n for template in templates:\n out.append({'id': template, 'title': template[:-3]})\n for templates_resource in iterDirectoriesOfType(self._TEMPLATES_ADDON_DIR):\n prefix = templates_resource.__name__\n templates = [\n tpl for tpl in templates_resource.listDirectory()\n if tpl.endswith('.pt')\n ]\n for template in templates:\n out.append({\n 'id': '{0}:{1}'.format(prefix, template),\n 'title': '{0} ({1})'.format(template[:-3], prefix),\n })\n return out\n\n def getFormTemplate(self):\n \"\"\"Returns the current samplinground rendered with the template\n specified in the request (param 'template').\n Moves the iterator to the next samplinground available.\n \"\"\"\n templates_dir = self._TEMPLATES_DIR\n embedt = self.request.get('template', self._DEFAULT_TEMPLATE)\n if embedt.find(':') >= 0:\n prefix, embedt = embedt.split(':')\n templates_dir = queryResourceDirectory(self._TEMPLATES_ADDON_DIR, prefix).directory\n embed = ViewPageTemplateFile(os.path.join(templates_dir, embedt))\n reptemplate = \"\"\n try:\n reptemplate = embed(self)\n except:\n tbex = traceback.format_exc()\n wsid = self._samplingrounds[self._current_sr_index].id\n reptemplate = \"
%s - %s '%s':
%s
\" % (wsid, _(\"Unable to load the template\"), embedt, tbex)\n if self._current_sr_index < len(self._samplingrounds):\n self._current_sr_index += 1\n return reptemplate\n # Using default for now\n return ViewPageTemplateFile(\"templates/print/default_form.pt\")(self)\n\n def getCSS(self):\n \"\"\" Returns the css style to be used for the current template.\n \"\"\"\n this_dir = os.path.dirname(os.path.abspath(__file__))\n templates_dir = os.path.join(this_dir, self._TEMPLATES_DIR)\n path = '%s/%s.css' % (templates_dir, 'default')\n content_file = open(path, 'r')\n return content_file.read()\n\n def getAnalysisRequestTemplatesInfo(self):\n \"\"\"\n Returns a lost of dicts with the analysis request templates infomration\n [{'uid':'xxxx','id':'xxxx','title':'xxx','url':'xxx'}, ...]\n \"\"\"\n arts_list = []\n for art in self.context.ar_templates:\n pc = getToolByName(self.context, 'portal_catalog')\n contentFilter = {'portal_type': 'ARTemplate',\n 'UID': art}\n art_brain = pc(contentFilter)\n if len(art_brain) == 1:\n art_obj = art_brain[0].getObject()\n arts_list.append({\n 'uid': art_obj.UID(),\n 'id': art_obj.id,\n 'title': art_obj.title,\n 'url': art_obj.absolute_url(),\n })\n return arts_list\n\n def getAnalysisRequestBySample(self):\n \"\"\"\n Returns a list of dictionaries sorted by Sample Partition/Container\n [{'requests and partition info'}, ...]\n \"\"\"\n # rows will contain the data for each html row\n rows = []\n # columns will be used to sort and define the columns\n columns = {\n 'column_order': [\n 'sample_id',\n 'sample_type',\n 'sampling_point',\n 'sampling_date',\n 'partition',\n 'container',\n 'analyses',\n ],\n 'titles': {\n 'sample_id': _('Sample ID'),\n 'sample_type': _('Sample Type'),\n 'sampling_point': _('Sampling Point'),\n 'sampling_date': _('Sampling Date'),\n 'partition': _('Partition'),\n 'container': _('Container'),\n 'analyses': _('Analysis'),\n }\n }\n ars = self.context.getAnalysisRequests()\n for ar in ars:\n ar = ar.getObject()\n arcell = False\n numans = len(ar.getAnalyses())\n for part in ar.getPartitions():\n partcell = False\n container = part.getContainer().title \\\n if part.getContainer() else ''\n partans = part.getAnalyses()\n numpartans = len(partans)\n for analysis in partans:\n service = analysis.getService()\n row = {\n 'sample_id': {\n 'hidden': True if arcell else False,\n 'rowspan': numans,\n 'value': ar.getSample().id,\n },\n 'sample_type': {\n 'hidden': True if arcell else False,\n 'rowspan': numans,\n 'value': ar.getSampleType().title,\n },\n 'sampling_point': {\n 'hidden': True if arcell else False,\n 'rowspan': numans,\n 'value': ar.getSamplePoint().title,\n },\n 'sampling_date': {\n 'hidden': True if arcell else False,\n 'rowspan': numans,\n 'value': self.context.sampling_date,\n },\n 'partition': {\n 'hidden': True if partcell else False,\n 'rowspan': numpartans,\n 'value': part.id,\n },\n 'container': {\n 'hidden': True if partcell else False,\n 'rowspan': numpartans,\n 'value': container,\n },\n 'analyses': {\n 'title': service.title,\n 'units': service.getUnit(),\n },\n }\n rows.append(row)\n arcell = True\n partcell = True\n\n # table will contain the data that from where the html\n # will take the info\n table = {\n 'columns': columns,\n 'rows': rows,\n }\n return table\n\n def getLab(self):\n return self.context.bika_setup.laboratory.getLabURL()\n\n def getLogo(self):\n portal = self.context.portal_url.getPortalObject()\n return \"%s/logo_print.png\" % portal.absolute_url()\n","sub_path":"bika/lims/browser/samplinground/print.py","file_name":"print.py","file_ext":"py","file_size_in_byte":8794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"73804144","text":"'''\n Created March 30, 2016\n @author: James Cox\n The purpose of this class is to provide an object representing \n the detail of a single instance of a celestial observation \n'''\n\nfrom math import sqrt\nfrom math import tan\nfrom math import radians\nimport datetime\n\nclass Sighting(object):\n\n def __init__(self, body, date,\n time, altitude,\n height=0, temp=72,\n pressure=1010, artificialHorizon=False):\n if (not body):\n raise ValueError(\n str(self.__class__) + \"Sighting.__init__: invalid body\")\n elif (not(isinstance(body, str))):\n raise ValueError(\n str(self.__class__) + \"Sighting.__init__: invalid body\")\n elif (len(body) is 0):\n raise ValueError(\n str(self.__class__) + \"Sighting.__init__: invalid body\")\n \n if(not date):\n raise ValueError(\n str(self.__class__) + \"Sighting.__init__: invalid body\")\n elif(not(isinstance(date, datetime.date))):\n raise ValueError(\n str(self.__class__) + \"Sighting.__init__ invalid date\")\n \n if(not time):\n raise ValueError(\n str(self.__class__) + \"Sighting.__init__: invalid body\")\n elif(not(isinstance(time, datetime.time))):\n raise ValueError(\n str(self.__class__) + \"Sighting.__init__: invalid time\")\n \n if(not altitude):\n raise ValueError(\n str(self.__class__) + \"Sighting.__init__: invalid body\")\n elif(not(isinstance(altitude, tuple))):\n raise ValueError(\n str(self.__class__) + \"Sighting.__init__: invalid altitude\") \n elif(len(altitude) != 2):\n raise ValueError(\n str(self.__class__) + \"Sighting.__init__: invalid altitude\")\n elif(not(isinstance(altitude[0], int))):\n raise ValueError(\n str(self.__class__) + \"Sighting.__init__: invalid altitude\")\n elif(altitude[0] < 0 or altitude[0] >= 90):\n raise ValueError(\n str(self.__class__) + \"Sighting.__init__: invalid altitude\")\n elif(not(isinstance(altitude[1], float))):\n raise ValueError(\n str(self.__class__) + \"Sighting.__init__: invalid altitude\")\n elif(altitude[1] < 0 or altitude[1] >= 60):\n raise ValueError(\n str(self.__class__) + \"Sighting.__init__: invalid altitude\")\n \n if(not(isinstance(height, int))):\n raise ValueError(\n str(self.__class__) + \"Sighting.__init__: invalid height\")\n elif(height < 0):\n raise ValueError(\n str(self.__class__) + \"Sighting.__init__: invalid height\")\n \n if(not(isinstance(temp, int))):\n raise ValueError(\n str(self.__class__) + \"Sighting.__init__: invalid temperature\")\n elif(temp < -20 or temp > 120):\n raise ValueError(\n str(self.__class__) + \"Sighting.__init__: invalid temperature\")\n \n if(not(isinstance(pressure, int))):\n raise ValueError(\n str(self.__class__) + \"Sighting.__init__: invalid altitude\")\n elif(pressure < 100 or pressure > 1100):\n raise ValueError(\n str(self.__class__) + \"Sighting.__init__: invalid pressure\")\n \n if(not(isinstance(artificialHorizon, bool))):\n raise ValueError(\n str(self.__class__) + \"Sighting.__init__: invalid artificial horizon\")\n\n # obs => observation\n self.obs = list()\n self.obs.append(body)\n self.obs.append(date)\n self.obs.append(time)\n self.obs.append(altitude)\n self.obs.append(height)\n self.obs.append(temp)\n self.obs.append(pressure)\n self.obs.append(artificialHorizon)\n \n\n def getBody(self):\n return self.obs[0]\n\n def getDate(self):\n return self.obs[1]\n\n def getTime(self):\n return self.obs[2]\n\n def getAltitude(self): \n return (self.obs[3][0], self.roundMinutes(self.obs[3][1]))\n \n def getHeight(self):\n return self.obs[4]\n\n def getTemperature(self):\n return self.obs[5]\n\n def getPressure(self):\n return self.obs[6]\n\n def isArtificialHorizon(self):\n return self.obs[7]\n\n def getAltitudeCorrection(self):\n if(self.obs[3][0] == 0 and float(self.obs[3][1]) < 12.0):\n raise ValueError(\n str(self.__class__) + \"Sighting.getAltitudeCorrection: altitude is too small\")\n if(not(self.isArtificialHorizon())):\n dip = (-0.97 * sqrt(self.getHeight())) / 60\n else:\n dip = 0\n celcius = (self.getTemperature() - 32) * 5 / 9\n tangent = tan(radians(self.obs[3][0] + (self.obs[3][1]) / 60))\n refraction = (\n (-0.00452 * self.getPressure()) / (273 + celcius)) / tangent\n \n result = (self.obs[3][0] + (self.obs[3][1]) / 60) + dip + refraction \n degrees = int(result)\n minutes = (result % 1) * 60\n \n return (degrees, self.roundMinutes(minutes))\n\n\n# Check for missing parameter\n def getGHA(self, aries, stars):\n \n sightingDate = str(self.getDate())\n sightingDate = sightingDate.split('-')\n sightingDate = str(str(sightingDate[1]) + '/' + str(sightingDate[2]) + '/' + str(int(sightingDate[0]) - 2000))\n \n # aries.txt checks\n if(not(isinstance(aries, str))):\n raise ValueError(\n str(self.__class__) + \"Sighting.getGHA: invalid aries file\")\n elif(len(aries) != 9):\n raise ValueError(\n str(self.__class__) + \"Sighting.getGHA: invalid aries file\")\n elif(aries[aries.rfind('.'):] != \".txt\"):\n raise ValueError(\n str(self.__class__) + \"Sighting.getGHA: invalid aries file\")\n elif(aries[:aries.rfind('.')] != \"aries\"):\n raise ValueError(\n str(self.__class__) + \"Sighting.getGHA: invalid aries file\")\n \n # stars.txt checks \n if(not(isinstance(stars, str))):\n raise ValueError(\n str(self.__class__) + \"Sighting.getGHA: invalid stars file\")\n elif(len(stars) != 9):\n raise ValueError(\n str(self.__class__) + \"Sighting.getGHA: invalid stars file\")\n elif(stars[stars.rfind('.'):] != \".txt\"):\n raise ValueError(\n str(self.__class__) + \"Sighting.getGHA: invalid stars file\")\n elif(stars[:stars.rfind('.')] != \"stars\"):\n raise ValueError(\n str(self.__class__) + \"Sighting.getGHA: invalid stars file\")\n try:\n ariesFile = open(aries, 'r')\n starsFile = open(stars, 'r')\n except IOError:\n raise IOError(str(self.__class__) + \". getSightings: file does not exist\")\n \n ariesLines = ariesFile.readlines()\n starsLines = starsFile.readlines()\n earliest = None\n latest = None\n obs = list()\n \n for line in starsLines:\n obs = line.split('\\t')\n if(obs[0].strip() == self.getBody() and earliest is not None and latest is None):\n latest = obs \n break\n if(obs[0].strip() == self.getBody() and earliest is None):\n earliest = obs\n \n # Check if either of the first two entries are it \n sighting = list() \n if(earliest[1].strip() == sightingDate):\n sighting = earliest \n elif(latest[1].strip() == sightingDate):\n sighting = latest\n else: \n # Have first two entries at this point\n for line in starsLines:\n obs = line.split('\\t')\n\n if(obs[0] == self.getBody()):\n \n if(obs[1].strip() == sightingDate): # found exact match\n sighting = obs\n break\n elif(obs[1].strip() < sightingDate):\n earliest = latest\n latest = obs\n elif(obs[1].strip() > sightingDate and obs[1].strip() > str(latest[1])):\n sighting = latest\n break\n latitude = sighting[3].split('*') \n shaStar = sighting[2].split('*')\n hour = int(((str(self.getTime())).split(':'))[0]) \n GHA_A1 = 0.0\n GHA_A2 = 0.0\n \n for line in ariesLines:\n obs = line.split('\\t')\n if (obs[0].strip() == sightingDate and int(obs[1].strip()) == hour):\n temp = obs[2].split(\"*\")\n GHA_A1 = int(temp[0])\n GHA_A1 = GHA_A1 + float(temp[1]) / 60\n \n if(obs[0].strip() == sightingDate and int(obs[1].strip()) == (hour + 1)):\n temp = obs[2].split(\"*\")\n GHA_A2 = int(temp[0])\n GHA_A2 = GHA_A2 + float(temp[1]) / 60\n break\n\n sub = abs(GHA_A2 - GHA_A1) \n \n secPastHour = (int(((str(self.getTime())).split(':'))[1]) * 60) + int(((str(self.getTime())).split(':'))[2]) \n GHA_Aries = GHA_A1 + (sub * (secPastHour / 3600))\n GHA_Aries = str(GHA_Aries).split('.')\n GHA_Aries[1] = float('.' + GHA_Aries[1])\n \n ghaObs = list()\n ghaObs.append(int(GHA_Aries[0]) + int(shaStar[0])) # degrees\n tempMinutes = (float(GHA_Aries[1])) + (float(shaStar[1]) / 60) # minutes\n \n if(tempMinutes >= 1):\n ghaObs[0] += 1\n ghaObs.append((tempMinutes % 1) * 60)\n else:\n ghaObs.append(tempMinutes * 60)\n \n ghaObs = (ghaObs[0] + (ghaObs[1] / 60)) % 360\n ghaObs = str(int(ghaObs)) + '*' + str(round((ghaObs % 1) * 60, 1))\n latitude = str(latitude[0]) + '*' + latitude[1].strip()\n \n return (ghaObs, latitude)\n \n def roundMinutes(self, minutes): \n \n temp = int(minutes)\n \n if( (minutes - int(minutes)) % .1 < .05):\n minutes = str(minutes - int(minutes))\n minutes = float(minutes[0:3]) + temp\n else:\n minutes = str(minutes - int(minutes))\n if(minutes[2] is '9'):\n minutes = (temp + 1) + 0.0\n else: \n minutes = minutes[0:2] + str(int(minutes[2]) + 1)\n minutes = float(minutes) + temp\n\n return minutes\n \n \n \n \n\n","sub_path":"Class/Sighting.py","file_name":"Sighting.py","file_ext":"py","file_size_in_byte":10713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"617653892","text":"w, h = map(int, input().split())\nx, y = map(int, input().split())\nr = int(input())\nimport math\nr = r / 180.0 * math.pi\n\n# 斜率需要是有理数\n# 因为角度都是整数\n# 所以只需要检查四个角度\n\ndef step(w, h, x, y, r):\n up_t = (h-y)/math.sin(r)\n if up_t >= 0:\n up_x = x + up_t * math.cos(r)\n if 0 <= up_x <= w:\n return (w, h)\n\n down_t = -y/math.sin(r)\n if down_t >= 0:\n down_x = x + down_t * math.cos(r)\n if 0 <= down_x <= w:\n return (w, 0)\n\n left_t = -x / math.cos(r)\n if left_t >= 0:\n left_y = y + left_t * math.sin(r)\n if 0 <= left_y <= h:\n return (0, left_y)\n\n\ndef solve(w, h, x, y, r):\n\n if r == 0 or r == 180:\n return y == 0 or y == h\n if r == 90 or r == 270:\n return x == 0 or x == w\n","sub_path":"TCO/TCO 2019 China Regionals/Z.py","file_name":"Z.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"265717238","text":"#coding=utf-8\n# @author panzhenfu 2017/6/12\n# @email panzhenfu20@126.com\n\n\nimport numpy as np\nimport copy\nimport matplotlib.pyplot as plt\nimport scipy.io as sio\n\ndef Gaussian_DN(X,U_Mean,Cov):\n D = np.shape(X)[0]\n Y = X-U_Mean\n temp = Y.T * (Cov+np.eye(D)*0.01).I * Y\n result = (1.0/((2*np.pi)**(D/2)))*(1.0/(np.linalg.det(Cov+np.eye(D)*0.01)**0.5))*np.longfloat(np.exp(-0.5*temp))\n return result\n\n# 计算样本均值\ndef CalMean(X):\n D,N=np.shape(X)\n MeanVector=np.mat(np.zeros((D,1)))\n for d in range(D):\n for n in range(N):\n MeanVector[d,0] += X[d,n]\n MeanVector[d,0] /= float(N)\n return MeanVector\n\n# 计算似然函数值\ndef maxLikelyhood(Xn, Pik, Uk, Cov):\n D, N = np.shape(Xn)\n D_k, K = np.shape(Uk)\n if D != D_k:\n print ('dimension not equal, break')\n return\n probility_mat = np.zeros((N, K))\n Likelyhood = 0.0\n for n_iter in range(N):\n temp = 0\n for k_iter in range(K):\n gaussian = Gaussian_DN(Xn[:, n_iter], Uk[:, k_iter], Cov[k_iter])\n # print (\"temp :\", gaussian)\n probility_mat[n_iter, k_iter] = gaussian\n temp += Pik[0, k_iter] * gaussian\n Likelyhood += np.log(temp)\n return float(Likelyhood), probility_mat\n\ndef calgmm(Xn, Pik, Uk, Cov):\n D_k, K = np.shape(Uk)\n temp = 0;\n for k_iter in range(K):\n temp += Pik[0, k_iter]*Gaussian_DN(Xn, Uk[:, k_iter], Cov[k_iter])\n return temp\n\ndef EMforMixGaussian(InputData, K, MaxIter):\n # 初始化piK\n pi_Cof = np.mat(np.ones((1, K)) * (1.0 / float(K)))\n X = np.mat(InputData)\n X_mean = CalMean(X)\n print (X_mean)\n\n # 初始化uK,其中第k列表示第k个高斯函数的均值向量\n # X为D维,N个样本点\n D, N = np.shape(X)\n print (D, N)\n UK = np.mat(np.zeros((D, K)))\n for d_iter in range(D):\n for k_iter in range(K):\n UK[d_iter, k_iter] = X_mean[d_iter, 0] + np.random.uniform(-30, 30)\n print (UK)\n # 初始化k个协方差矩阵的列表\n List_cov = []\n\n for k_iter in range(K):\n List_cov.append(np.mat(np.eye(X[:, 0].size)))\n print (List_cov)\n\n Likelyhood_new = 0\n Likelyhood_old, _ = maxLikelyhood(X, pi_Cof, UK, List_cov)\n print (Likelyhood_old)\n currentIter = 0\n while True:\n currentIter += 1\n\n rZnk = np.mat(np.zeros((N, K)))\n denominator = np.mat(np.zeros((N, 1)))\n # rZnk=pi_k*Gaussian(Xn|uk,Cov_k)/sum(pi_j*Gaussian(Xn|uj,Cov_j))\n for n_iter in range(N):\n for k_iter in range(K):\n rZnk[n_iter, k_iter] = pi_Cof[0, k_iter] * Gaussian_DN(X[:, n_iter], UK[:, k_iter], List_cov[k_iter])\n denominator[n_iter, 0] += rZnk[n_iter, k_iter]\n for k_iter in range(K):\n rZnk[n_iter, k_iter] /= denominator[n_iter, 0]\n # print 'rZnk', rZnk[n_iter,k_iter]\n\n # Nk=sum(rZnk)\n Nk = np.mat(np.zeros((1, K)))\n pi_new = np.mat(np.zeros((1, K)))\n for k_iter in range(K):\n for n_iter in range(N):\n Nk[0, k_iter] += rZnk[n_iter, k_iter]\n pi_new[0, k_iter] = Nk[0, k_iter] / (float(N))\n # print 'pi_k_new',pi_new[0,k_iter]\n\n # uk_new= (1/sum(rZnk))*sum(rZnk*Xn)\n UK_new = np.mat(np.zeros((D, K)))\n for k_iter in range(K):\n for n_iter in range(N):\n UK_new[:, k_iter] += (1.0 / float(Nk[0, k_iter])) * rZnk[n_iter, k_iter] * X[:, n_iter]\n # print 'UK_new',UK_new[:,k_iter]\n\n List_cov_new = []\n for k_iter in range(K):\n X_cov_new = np.mat(np.zeros((D, D)))\n for n_iter in range(N):\n Temp = X[:, n_iter] - UK_new[:, k_iter]\n X_cov_new += (1.0 / float(Nk[0, k_iter])) * rZnk[n_iter, k_iter] * Temp * Temp.transpose()\n # print 'X_cov_new',X_cov_new\n List_cov_new.append(X_cov_new)\n\n Likelyhood_new, _ = maxLikelyhood(X, pi_new, UK_new, List_cov)\n print ('Likelyhood_new', Likelyhood_new, currentIter)\n\n if Likelyhood_old >= Likelyhood_new or currentIter > MaxIter:\n break\n UK = copy.deepcopy(UK_new)\n pi_Cof = copy.deepcopy(pi_new)\n List_cov = copy.deepcopy(List_cov_new)\n Likelyhood_old = Likelyhood_new\n return pi_Cof, UK, List_cov\n\n# 生成随机数据,4个高斯模型\ndef generate_data(sigma, N, mu1, mu2, mu3, mu4, alpha):\n\n X = np.zeros((N, 2)) # 初始化X,2行N列。2维数据,N个样本\n X = np.matrix(X)\n\n for i in range(N):\n if np.random.random(1) < alpha[0]: # 生成0-1之间随机数\n X[i, :] = np.random.multivariate_normal(mu1, sigma[0], 1) # 用第一个高斯模型生成2维数据\n elif alpha[0] <= np.random.random(1) < alpha[0]+alpha[1]:\n X[i, :] = np.random.multivariate_normal(mu2, sigma[1], 1) # 用第二个高斯模型生成2维数据\n elif alpha[0]+alpha[1]<= np.random.random(1) < alpha[0]+alpha[1]+alpha[2]:\n X[i, :] = np.random.multivariate_normal(mu3, sigma[2], 1) # 用第三个高斯模型生成2维数据\n else:\n X[i, :] = np.random.multivariate_normal(mu4, sigma[3], 1) # 用第四个高斯模型生成2维数据\n return X\n\n\nif __name__ == \"__main__\":\n N = 500 # 样本数目\n k = 4 # 高斯模型数\n probility = np.zeros(N) # 混合高斯分布\n u1 = [5, 35]\n u2 = [15, 60]\n u3 = [30, 50]\n u4 = [40, 20]\n sigma_list = [] # 协方差矩阵\n sigma_list.append(np.mat([[30, 0], [0, 10]]))\n sigma_list.append(np.mat([[25, 12], [12, 20]]))\n sigma_list.append(np.mat([[12, 5], [5, 15]]))\n sigma_list.append(np.mat([[45, 9], [9, 20]]))\n alpha = [0.1, 0.4, 0.3, 0.2] # 混合项系数\n X = generate_data(sigma_list, N, u1, u2, u3, u4, alpha) # 生成数据\n\n # 归一化\n # min = X.min(0)\n # max = X.max(0)\n # for n_iter in range(N):\n # X[n_iter, :] = (X[n_iter, :]-min)/(max - min)\n # 持久化\n np.savetxt(\"filename.txt\", X)\n\n iter_num = 5000 # 迭代次数\n Pi, Uk, list_cov = EMforMixGaussian(np.mat(X).T, k, iter_num)\n\n print (Uk)\n print (list_cov)\n\n print (Pi[0,0]+Pi[0,1]+Pi[0,2]+Pi[0,3])\n # 可视化结果\n # 画生成的原始数据\n plt.subplot(121)\n plt.scatter(X[:, 0], X[:, 1], c='g', s=25, alpha=0.4, marker='o') # T散点颜色,s散点大小,alpha透明度,marker散点形状\n plt.title('random generated data')\n plt.scatter(Uk[0, :], Uk[1, :],c='r', s=40, alpha=1, marker='x')\n\n energy_new, excep = maxLikelyhood(np.mat(X).T, Pi, Uk, list_cov)\n print (excep)\n # 画分类好的数据\n plt.subplot(122)\n plt.title('classified data through EM')\n order = np.zeros(N)\n color = ['b', 'r', 'k', 'y']\n for i in range(N):\n for j in range(k):\n if excep[i, j] == max(excep[i, :]):\n order[i] = j # 选出X[i,:]属于第几个高斯模型\n plt.scatter(X[i, 0], X[i, 1], c=color[int(order[i])], s=25, alpha=0.4, marker='o') # 绘制分类后的散点图\n plt.show()\n\n\n","sub_path":"GMM.py","file_name":"GMM.py","file_ext":"py","file_size_in_byte":7100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"641260580","text":"import hashlib\nBASE58_ALPHABET = \"12345678\"\n\n\ndef little_endiant_to_int(s: bytes) -> int:\n return int.from_bytes(s, \"little\")\n\n\ndef int_to_little_endiant(n: int, length: int) -> bytes:\n \"\"\"convert int to bytes in designated length\"\"\"\n return n.to_bytes(length, \"little\")\n\n\ndef read_variant(s: bytes) -> int:\n # able to understand bytes' length with first element\n i = s.read(1)[0]\n if i == 0xfd:\n return little_endiant_to_int(s.read(2))\n elif i == 0xfe:\n return little_endiant_to_int(s.read(4))\n elif i == 0xff:\n return little_endiant_to_int(s.read(8))\n elif type(s) == int:\n return i\n else:\n raise ValueError(\"input must be bytes\")\n\n\ndef encode_variant(i: int) -> bytes:\n \"\"\"encode integer as a variant.\"\"\"\n\n if i < 0xfd:\n # below 253,\n return bytes([i])\n elif i < 0x10000:\n return b'0xfd'+int_to_little_endiant(i, 2)\n elif i < 0x1:\n return b'0xff'+int_to_little_endiant(i, 4)\n elif i < 0x0000000000000000:\n return b'0xff'+int_to_little_endiant(i, 8)\n else:\n raise ValueError(\"integer too large:{}\".format(i))\n\n\ndef encode_base58(s: bytes) -> str:\n count: int = 0\n for c in s:\n if c == 0:\n count += 1\n else:\n break\n num: int = int.from_bytes(s, \"big\")\n prefix: str = \"1\"\n result: str = \"\"\n while num > 0:\n num, mod = divmod(num, 58)\n result: str = BASE58_ALPHABET[mod]+result\n return prefix+result\n\n\ndef hash160(s: str) -> str:\n # https://www.pebblewind.com/entry/2018/05/05/230100\n # s.encode('utf-8')にする必要がある?\n return hashlib.new(\"rpemd160\", hashlib.sha256(s).digest()).digest()\n\n\ndef hash256(s):\n '''two rounds of sha256'''\n return hashlib.sha256(hashlib.sha256(s.encode(\"utf-8\")).digest()).digest()\n\n\ndef encode_base58_checksum(b):\n return encode_base58(b+hash256(b)[:4])\n\n\nif __name__ == \"__main__\":\n print(int_to_little_endiant(123, 3))\n","sub_path":"chapter1/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":1980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"589740957","text":"from django.contrib.auth.decorators import login_required\nfrom django.shortcuts import redirect, render\nfrom recipes.models import Recipes\nfrom django.views.generic import View\nfrom django.conf.urls.static import static\nimport os\nfrom django.conf import settings\nfrom django.http import HttpResponse\nfrom django.template.loader import get_template\nfrom xhtml2pdf import pisa\nfrom django.contrib.staticfiles import finders\n# decorador\n\n\"\"\"Te redirige si estas logueado\"\"\"\n\n\n@login_required\ndef index(request):\n return render(request, 'recipes/home.html')\n\n\n\"\"\"Añade nueva recetas\"\"\"\n\n\ndef ingresar(request):\n \"\"\"Verica si es post\"\"\"\n if request.method == 'POST':\n title = request.POST['input_title']\n description = request.POST['input_description']\n ingredients = request.POST['input_ingredients']\n process = request.POST['input_proces']\n images = request.FILES['file_images']\n puntuation = request.POST['input_puntuation']\n\n recipe = Recipes.objects.create(\n title=title, description=description)\n recipe.ingredients = ingredients\n recipe.process = process\n recipe.images = images\n recipe.puntuation = puntuation\n recipe.save()\n return redirect('recipes:index')\n\n \"\"\"renderiza la vista aunque no sea post\"\"\"\n return render(request, 'recipes/recetas.html')\n\n\ndef recetario(request):\n recipes = Recipes.objects.all()\n return render(request, 'recipes/recetario.html', {'recipes': recipes})\n\n\ndef individual(request, numId):\n recipes = Recipes.objects.filter(id=numId)\n return render(request, 'recipes/individual.html', {'recipes': recipes})\n\n\nclass createPdf(View):\n def link_callback(self, uri, rel):\n \"\"\"\n Convert HTML URIs to absolute system paths so xhtml2pdf can access those\n resources\n \"\"\"\n result = finders.find(uri)\n if result:\n if not isinstance(result, (list, tuple)):\n result = [result]\n result = list(os.path.realpath(path) for path in result)\n path = result[0]\n else:\n sUrl = settings.STATIC_URL # Typically /static/\n sRoot = settings.STATIC_ROOT # Typically /home/userX/project_static/\n mUrl = settings.MEDIA_URL # Typically /media/\n mRoot = settings.MEDIA_ROOT # Typically /home/userX/project_static/media/\n\n if uri.startswith(mUrl):\n path = os.path.join(mRoot, uri.replace(mUrl, \"\"))\n elif uri.startswith(sUrl):\n path = os.path.join(sRoot, uri.replace(sUrl, \"\"))\n else:\n return uri\n\n # make sure that file exists\n if not os.path.isfile(path):\n raise Exception(\n 'media URI must start with %s or %s' % (sUrl, mUrl)\n )\n return path\n\n def get(self, request, *args, **kwargs):\n try:\n template = get_template('recipes/list.html')\n context = {\n 'recipes': Recipes.objects.filter(id=self.kwargs['Id']),\n 'image': '{}{}'.format(settings.STATIC_URL, 'images/aprenderRecetas.png')\n }\n html = template.render(context)\n response = HttpResponse(content_type='application/pdf')\n pisaStatus = pisa.CreatePDF(\n html, dest=response,\n link_callback=self.link_callback\n )\n return response\n except:\n pass\n","sub_path":"recipes/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"365395459","text":"from django.contrib.auth.models import User\r\nfrom django.db import transaction as django_transaction\r\nfrom rest_framework.views import APIView\r\nfrom rest_framework.response import Response\r\nfrom rest_framework import status\r\nfrom faucet import providers, utils\r\nfrom . import serializers, models\r\n\r\n\r\nclass DepositApiView(APIView):\r\n def post(self, request, *args, **kwargs):\r\n if request.META[\"REMOTE_HOST\"] != providers.cedsonhub_doamin:\r\n return Response({\"detail\":\"Invalid domain\"}, status=status.HTTP_400_BAD_REQUEST)\r\n\r\n deposit = serializers.DepositSerializer(data=request.data)\r\n if deposit.is_valid():\r\n self.handle_deposit(deposit)\r\n response = {\r\n \"username\": deposit.data.get(\"username\")\r\n }\r\n return Response(response)\r\n\r\n return Response(deposit.errors, status=status.HTTP_400_BAD_REQUEST)\r\n\r\n def handle_deposit(self, deposit):\r\n username = deposit.data.get(\"username\")\r\n currency = deposit.data.get(\"currency\")\r\n coins = deposit.data.get(\"amount_in_coins\")\r\n satoshis = deposit.data.get(\"amount_in_satoshis\")\r\n ex_id = deposit.data.get(\"deposit_id\")\r\n\r\n user = User.objects.filter(username=username).first()\r\n if user is not None:\r\n with django_transaction.atomic():\r\n balance = self.get_balance(user)\r\n models.Deposit.objects.create(\r\n user=user,\r\n currency=currency,\r\n coins=coins,\r\n satoshis=satoshis,\r\n external_id=ex_id\r\n )\r\n to_balance = utils.get_in_satoshis(coins, satoshis)\r\n balance.deposit(to_balance, currency)\r\n\r\n return None\r\n\r\n def get_balance(self, user):\r\n return models.Balance.objects.select_for_update().get(user=user)\r\n\r\n\r\n","sub_path":"ch_auth/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"588537120","text":"#!/usr/bin/scons\n\nenv = Environment(platform=\"win32\", tools=[\"mingw\"])\n\nCCFLAGS = [\n \"-Icontrib/win32/include\", \"-Iinclude\", \"-O2\", \"-DNeedFunctionPrototypes=1\"\n]\nLIBPATH = [\".\"]\nLIBS = []\n\nlibgsm_sources = [\n \"src/add.c\", \"src/code.c\", \"src/debug.c\", \"src/decode.c\",\n \"src/long_term.c\", \"src/lpc.c\", \"src/preprocess.c\", \"src/rpe.c\",\n \"src/gsm_destroy.c\", \"src/gsm_decode.c\", \"src/gsm_encode.c\",\n \"src/gsm_explode.c\", \"src/gsm_implode.c\", \"src/gsm_create.c\",\n \"src/gsm_print.c\", \"src/gsm_option.c\", \"src/short_term.c\",\n \"src/table.c\"\n]\n\nlibgsm = env.StaticLibrary(source=libgsm_sources, target=\"gsm\", CCFLAGS=CCFLAGS, LIBPATH=LIBPATH, LIBS=LIBS)\n\ntoast_sources = [\"src/toast.c\", \"src/toast_lin.c\", \"src/toast_ulaw.c\", \"src/toast_alaw.c\", \"src/toast_audio.c\"]\n\nLIBS += [\"gsm\"]\ntoast = env.Program(source=toast_sources, target=\"toast\", CCFLAGS=CCFLAGS, LIBPATH=LIBPATH, LIBS=LIBS)\n\nDefault([libgsm, toast])","sub_path":"SConstruct","file_name":"SConstruct","file_ext":"","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"286602018","text":"import random\n\nABBREVIATIONS = {'submarine': 'S', 'destroyer': 'D', 'cruiser': 'C', 'carrier': 'A'}\nBATTLESHIPS = {'S': (1, 1), 'D': (2, 1), 'C': (3, 1), 'A': (4, 1)} # Values are dimensions\n # (2, 1) means 1x2 or 2x1 positioning\n\n\nclass Battlefield:\n \"\"\"\n battlefield class\n After initialization holds the following data structures:\n 1) Precomputed possible pieces on board where every piece is the set of positions making up the piece positions\n on the board. Holds for each piece type (submarine etc.) a set of pieces that are not on the board and ready to be\n picked at random. once picked removed along with all overlapping pieces.\n 2) A matrix holding the board occupied positions, each position either empty or holds part of a piece indicated\n by the piece symbol (submarine -> S etc.).\n 3) Precomputed mapping between a piece and a 'buffered' piece that includes a spacing of one position in all\n directions. Cached for performance and used in overlapping calculation.\n\n TODO: some optimization for overlap calculation\n pre shuffling of free pieces which will effectively randomize in advance\n parameterize script with argparse providing parameters like board size , number of initial pieces etc.\n \"\"\"\n def __init__(self, n, m):\n \"\"\"\n Construct battlefield and all data structures\n :param n: number rows of battleship\n :param m: number of columns of battleship\n \"\"\"\n self.m = m\n self.n = n\n self.board = [row[:] for row in [[None] * m] * n]\n\n self.free_battleship_pieces = self.__generate_battleship_locations()\n self.buffered_battleship_pieces = self.__generate_battleship_with_buffer()\n\n def __generate_battleship_locations(self):\n \"\"\"\n Generate all potential pieces, each piece is represented by a set of position on battlefield\n :return: set of free pieces\n \"\"\"\n free_pieces = {}\n for battleship_type in BATTLESHIPS:\n dimension = BATTLESHIPS[battleship_type]\n free_pieces[battleship_type] = self.__get_battleship_type_pieces(dimension)\n if dimension[0] != dimension[1]: # switch orientation if necessary\n free_pieces[battleship_type] = free_pieces[battleship_type] | \\\n self.__get_battleship_type_pieces((dimension[1], dimension[0]))\n return free_pieces\n\n def __get_battleship_type_pieces(self, dimension):\n \"\"\"\n Generate all possible pieces for dimension\n :param dimension: represent a piece with specific orientation\n :return: set of free pieces \n \"\"\"\n x_size, y_size = dimension\n return {frozenset([(x_pos, y_pos)\n for x_pos in range(row, row + x_size)\n for y_pos in range(col, col + y_size)])\n for row in range(self.n - x_size + 1)\n for col in range(self.m - y_size + 1)}\n\n def __generate_buffered_piece(self, piece):\n \"\"\"\n Generate a piece that include a buffer surrounding original piece\n :param piece:\n :return: buffered_piece\n \"\"\"\n buffered_piece = set()\n for pos in piece:\n buffered_pos = {(pos[0] + x_delta, pos[1] + y_delta) for x_delta in (-1, 0, 1) for y_delta in (-1, 0, 1)\n if 0 <= (pos[0] + x_delta) < self.n and 0 <= (pos[1] + y_delta) < self.m}\n\n buffered_piece.update(buffered_pos)\n\n return buffered_piece\n\n def __generate_battleship_with_buffer(self):\n buffered_battleship_pieces = {piece: self.__generate_buffered_piece(piece)\n for battleship_type in self.free_battleship_pieces\n for piece in self.free_battleship_pieces[battleship_type]}\n return buffered_battleship_pieces\n\n def __str__(self):\n \"\"\"\n Generate a string with battlefield representation \n :return: board as string\n \"\"\"\n output = ''\n for row in range(self.n):\n for col in range(self.m):\n output += (self.board[row][col] if self.board[row][col] else '.')\n output += '\\n'\n return output\n\n def __place_in_board(self, piece, piece_symbol):\n \"\"\"\n Places piece on board for easy printing \n :param piece: \n :param piece_symbol: \n :return: \n \"\"\"\n for (row, col) in piece:\n self.board[row][col] = piece_symbol\n\n def __remove_overlapping_free_locations(self, piece):\n \"\"\"\n This will remove the placed piece itself and all other pieces whose locations overlaps with placed piece\n from free pieces pool\n \"\"\"\n buffered_piece = self.buffered_battleship_pieces[piece]\n for battleship_type in BATTLESHIPS:\n locations_to_discard = []\n for free_piece in self.free_battleship_pieces[battleship_type]:\n if free_piece & buffered_piece: # points in common means they overlap\n locations_to_discard.append(free_piece)\n self.free_battleship_pieces[battleship_type].difference_update(locations_to_discard)\n\n def place_battleship(self, battleship_type):\n \"\"\"\n Randomly chooses a battleship from free available pieces locations on battlefield\n places it on the board and removes it and overlapping available pieces locations\n :param battleship_type:\n :return: piece or None if no available space for battleship type on battlefield\n \"\"\"\n if len(self.free_battleship_pieces[battleship_type]) == 0:\n return None\n piece = random.choice(tuple(self.free_battleship_pieces[battleship_type]))\n self.__place_in_board(piece, battleship_type)\n self.__remove_overlapping_free_locations(piece)\n return piece\n\n def place_submarine(self):\n \"\"\"\n :return: submarine or None if no available space on battlefield\n \"\"\"\n return self.place_battleship('S')\n\n def place_destroyer(self):\n \"\"\"\n :return: destroyer or None if no available space on battlefield\n \"\"\"\n return self.place_battleship('D')\n\n def place_cruiser(self):\n \"\"\"\n :return: cruiser or None if no available space on battlefield\n \"\"\"\n return self.place_battleship('C')\n\n def place_carrier(self):\n \"\"\"\n :return: aircraft carrier or None if no available space on battlefield\n \"\"\"\n return self.place_battleship('A')\n\n\nif __name__ == '__main__':\n rows = 100 # Board x-size\n cols = 100 # Board y-size\n number_of_pieces = 500 # Number of pieces (might not all places if no free space)\n battlefield = Battlefield(rows, cols)\n for _ in range(number_of_pieces):\n battleship_type = random.choice(list(BATTLESHIPS.keys())) # randomly choose battleship type\n if battleship_type == 'S':\n battlefield.place_submarine()\n elif battleship_type == 'D':\n battlefield.place_destroyer()\n elif battleship_type == 'C':\n battlefield.place_cruiser()\n else: # 'A'\n battlefield.place_carrier()\n # Alternatively can just do\n # battlefield.place_battleship(battleship_type)\n print(battlefield)\n\n","sub_path":"battlefield.py","file_name":"battlefield.py","file_ext":"py","file_size_in_byte":7459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"136557908","text":"from django.http import HttpResponseRedirect\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom octo.app.forms import UploadFileForm\nfrom octo.app.models import SubmissionID\n\n\nimport urllib\nimport urllib2\nimport json\nimport os\n\ndef upload_file(request):\n if request.method == 'POST':\n form = UploadFileForm(request.POST, request.FILES)\n if form.is_valid():\n resp = handle_upload_file(request.FILES['file'])\n if not resp == None:\n return render_to_response('complete.html',resp)\n else:\n return render_to_response('error.html',{\n 'error':'Unable to recognize file type',\n })\n else:\n form = UploadFileForm()\n return render_to_response('submit.html',\n {'form':form},\n context_instance = RequestContext(request))\n\ndef _encode_multipart_form(fields):\n \"\"\"Encode files as 'multipart/form-data'.\n\n Fields are a dict of form name-> value. For files, value should\n be a file object. Other file-like objects might work and a fake\n name will be chosen.\n\n Returns (content_type, body) ready for httplib.HTTP instance.\n\n \"\"\"\n BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'\n CRLF = '\\r\\n'\n L = []\n for (key, value) in fields.items():\n if not value:\n continue\n L.append('--' + BOUNDARY)\n if hasattr(value, 'read') and callable(value.read):\n filename = getattr(value, 'name', '%s.jpg' % key)\n L.append(('Content-Disposition: form-data;'\n 'name=\"%s\";'\n 'filename=\"%s\"') % (key, filename))\n L.append('Content-Type: image/jpeg')\n value = value.read()\n else:\n L.append('Content-Disposition: form-data; name=\"%s\"' % key)\n L.append('')\n if isinstance(value, unicode):\n value = value.encode('ascii')\n L.append(value)\n L.append('--' + BOUNDARY + '--')\n L.append('')\n body = CRLF.join(L)\n content_type = 'multipart/form-data; boundary=%s' % BOUNDARY\n return content_type, body\n\ndef _get_program_language(name):\n \"\"\"\n Returns the language of the program\n \"\"\"\n if name.lower().endswith('.py'):\n return 'PYTHON'\n if name.lower().endswith('.c'):\n return 'C'\n if name.lower().endswith('.java'):\n return 'JAVA'\n return None\n\ndef handle_upload_file(files):\n \"\"\"\n Handle the uploaded files\n \"\"\"\n SAMPLE_INPUT_PATH='octo/app/sample/sample.input'\n\n lang = _get_program_language(files.name)\n if lang == None:\n return None\n\n source = files.read()\n\n FILE = open(SAMPLE_INPUT_PATH, 'r')\n input = FILE.read()\n FILE.close()\n\n args = dict(source=source, lang=lang, input=input)\n content_type, body = _encode_multipart_form(args)\n req = urllib2.Request('http://code.hackerearth.com/api/run', data=body)\n req.add_header(\"Content-type\", content_type)\n count = 0\n return return_response(req)\n\ndef return_response(req):\n \"\"\"\n Parses the generated response and create the\n SubmissionId Model\n \"\"\"\n\n resp = json.loads(urllib2.urlopen(req).read())\n status = resp['run_status']\n if status['status'] == 'AC':\n compile_status = unicode('Submission Successful')\n ht_class = False\n else:\n compile_status = unicode('Submission Unsuccessful')\n ht_class = True\n memory = status['memory_used']\n compile_time = status['time_used']\n compile_id = resp['id']\n output_html = status['output_html']\n\n subid = SubmissionID.objects.create(submission_id = compile_id,\n status = status['status'],\n output = output_html\n )\n\n return {\n 'status': compile_status,\n 'memory': memory,\n 'compile_time': compile_time,\n 'id': compile_id,\n 'ht_class': ht_class,\n 'output_html': output_html,\n }\n\ndef error(request, sub_id=None):\n \"\"\"\n Return the error message\"\n \"\"\"\n error = SubmissionID.objects.filter(submission_id__iexact=sub_id).values('output')[0]['output']\n return render_to_response('error.html',{\n 'error': error,\n })\n\n\n","sub_path":"octo/app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"361167508","text":"#YEAR 8 CODING INVESTIGATION MINIMUM REQUIREMENTS\n#######################################################################################################################\n#######################################################################################################################\n# In this code I will be determining the settings required for a camera based on inputted settings from the user in #\n# in order to allow for an effective and high quality photo to be accomplished. This code can determine aperture, #\n# shutterspeed and ISO based off the inputs of the previous three, while maintining a steady baseline. If a user #\n# enters values of which a brightness baseline cannot be achieved, the program will prompt the user to increase or #\n# decrease certain settings to accommodate a brightness baseline which is sought. In addition, this code is #\n# formidable against erroneous user inputs and will not crash at the plight of receiving a false or ill-typed entry. #\n#######################################################################################################################\n#IMPORTS AND ERRORS\n#IMPORTS\nimport time #Used for timing\nimport math #Used for math\nfrom collections import OrderedDict #Used for ordering dictionaries\nfrom PIL import Image #Used for image generation\nimport matplotlib.pyplot as plt; plt.rcdefaults() #Used for table output\nimport numpy as np #Used for table output\nimport matplotlib.pyplot as plt #Used for table output\nimport requests #Used for weather data\nfrom pprint import pprint #Used for weather data\nimport os #Used for the code to talk\nimport sys #Used for the code to talk\n\n#ERROR HANDLING\nEOFError = False\nFutureWarning = False\nArithmeticError = False\nAssertionError = False\nAttributeError = False\nBlockingIOError = False\nBrokenPipeError = False\nBufferError = False\nBytesWarning = False\nChildProcessError = False\nConnectionAbortedError = False\nConnectionError = False\nConnectionRefusedError = False\nConnectionResetError = False\nDeprecationWarning = False\nIndentationError = False\nImportError = False\nIndexError = False\nInterruptedError = False\nIOError = False\nIsADirectoryError = False\nKeyError = False\nLookupError = False\nMemoryError = False\nOSError = False\nKeyboardInterrupt = False\nNameError = False\nNotADirectoryError = False\nNotImplementedError = False\nOverflowError = False\nPermissionError = False\nProcessLookupError = False\nRecursionError = False\nReferenceError = False\nRuntimeError = False\nSyntaxError = False\nSystemError = False\nTabError = False\nTimeoutError = False\nTypeError = False\nUnboundLocalError = False\nUnicodeDecodeError = False\nUnicodeEncodeError = False\nUnicodeError = False\nUnicodeTranslateError = False\nValueError = False\nFileNotFoundError = False\nFileExistsError = False\nFloatingPointError = False\nWindowsError = False\nZeroDivisionError = False\n\n#######################################################################################################################\n#DICTIONARIES AND LISTS\nisosettings = [\"6400\", \"3200\",\"1600\",\"800\",\"400\",\"200\",\"100\",\"50\"] #List of all ISO settings\n\nshuuterspeedsettings = ['1/30s', '1/60s', '1/125s', '1/250s', '1/500s', '1/1000s', '1/2000s', '1/4000s'] #List of all shutterspeed settings\n\nAperturesettings = [\"f/2.0\",\"f/2.8\",\"f/4.0\", \"f/5.6\",\"f/8.0\",\"f/11\",\"f/16\",\"f/22\"] #List of all aperture settings\n\nlightingconditions = {\"1\": \"Dusk\", \"2\":\"Sunset/shade\", \"3\":\"Overcast\", \"4\":\"Cloudy\", \"5\":\"Lightly cloudy\", \"6\":\"Sunny\", \"7\":\"Snow/sand\"} #List of lighting conditions with corresponding reference numbers\n\nlightresult = {\"1\": \"21\", \"2\": \"18\", \"3\":\"15\", \"4\":\"12\", \"5\":\"9\", \"6\":\"6\", \"7\":\"3\"} #List of lighting condition reference numbers with assigned stop totals\n\n#######################################################################################################################\n#TABLE FUNCTION OF AVAILABLE SETTINGS\ndef availablesettings(): #Creating a table of available settings. This function can be called upon later.\n #Print a table\n print(\"+--------------+--------------+-----------------------+-------------------+\") #Prints the table\n print(\"| Stop Number: | ISO Settings | Shutterspeed Settings | Aperture settings |\")\n print(\"+--------------+--------------+-----------------------+-------------------+\")\n print(\"| 8th | 6400 | 1/30s | f/2.0 |\")\n print(\"| 7th | 3200 | 1/60s | f/2.8 |\") \n print(\"| 6th | 1600 | 1/125s | f/4.0 |\")\n print(\"| 5th | 800 | 1/250s | f/5.6 |\")\n print(\"| 4th | 400 | 1/500s | f/8.0 |\")\n print(\"| 3rd | 200 | 1/1000s | f/11 |\")\n print(\"| 2nd | 100 | 1/2000s | f/16 |\")\n print(\"| 1st | 50 | 1/4000s | f/22 |\")\n print(\"+--------------+--------------+-----------------------+-------------------+\")\n\n\n#######################################################################################################################\n#FUNCTION TO ASK ISO\ndef askiso(): #Creates a function of asking and verifying ISO. This saves many lines of code\n ISO = str(input(\"Please enter the ISO setting (e.g. 800): \")) #Ask the user to enter the ISO setting\n while ISO not in isosettings: #If the ISO setting entered is not in the allowed ISO setting list, ask the user to re-enter\n print(\"You did not enter a valid ISO setting. Please try again.\") #Inform the user of their error.\n time.sleep(1.5)\n ISO = str(input(\"Please enter the ISO setting (e.g. 800): \")) #Ask the user to re-enter the ISO setting\n return ISO #Returns the user's ISO\n\n#######################################################################################################################\n#FUNCTION TO ASK SHUTTERSPEED\ndef askshutterspeed(): #Creates a function of asking and verifying shutterspeed. This saves many lines of code\n shutterspeed = str(input(\"Please enter the shutterspeed setting (in the form 1/1000s): \")) #Ask the user to enter the shutterspeed setting\n while shutterspeed not in shuuterspeedsettings: #If the user entered a setting that is not an EXISTING SETTING, the user will be asked to re-enter.\n print(\"You did not enter a valid shutterspeed setting. Please try again.\") #Inform the user of their error\n time.sleep(1.5)\n shutterspeed = str(input(\"Please enter the shutterspeed setting (in the form 1/1000s): \")) #Ask the user a second time\n return shutterspeed #Returns the user's shutterspeed\n\n#######################################################################################################################\n#FUNCTION TO ASK APERTURE\ndef askaperture(): #Creates a function of asking and verifying aperture. This saves many lines of code\n aperture = str(input(\"Please enter the aperture setting (in the form f/16): \")) #Ask the user to enter the aperture setting\n while aperture not in Aperturesettings: #If the user entered a setting that is not an EXISTING SETTING, the user will be asked to re-enter.\n print(\"You did not enter a valid aperture setting. Please try again.\") #Inform the user of their error\n time.sleep(1.5)\n aperture = str(input(\"Please enter the aperture setting (in the form f/16): \")) #Ask the user a second time\n return aperture #Returns the user's aperture\n\n#######################################################################################################################\n#INTRODUCTION AND CODE CHOICE\nrunagain = \"Y\" #Assign a runagain variable which can be used to determine if the user wants to run the code again.\nprint(\"Welcome to this photography settings Python code. Follow the prompts on the screen. Enjoy! :)\") #Introduction to the code\ntime.sleep(1)\nprint(\"Here is a table of all the available settings. This will assist in choosing the correct ISO, shutterspeed and aperture.\") #Prove the user with a table of all available settings. The user can refer to this later.\ntime.sleep(1)\navailablesettings() #Runs the available settings function referenced above\ntime.sleep(1)\nwhile runagain in \"Y\": #Initially, runagain is true, so the code runs once. If runagain still equals yes, it will \"run again\".\n \n \n lc = input(\"What is the lighting condition? (A number between 1 and 7)? [1 - Dusk, 2 - Sunset/shade, 3 - Overcast, 4 - Cloudy, 5 - Lightly cloudy, 6 - Sunny, 7 - Snow/sand]: \") #Ask the user to enter the lighting condition\n \n allowedanswers = {'1', '2', '3', '4', '5', '6', '7'} #List of lighting condition reference numbers which are allowed\n while lc not in allowedanswers: #If the user entered a number that is not a referenced lighting condition, it will ask the user to re-enter the lighting condition. This stops errors.\n print(\"you did not enter a valid lighting condition. Please try again.\") #Inform the user of their error\n time.sleep(1.5)\n lc = input(\"What is the lighting condition? (A number between 1 and 7)? [1 - Dusk, 2 - Sunset/shade, 3 - Overcast, 4 - Cloudy, 5 - Lightly cloudy, 6 - Sunny, 7 - Snow/sand]: \") #Ask the user a second time\n \n lcr = int(lightresult.get(lc)) #Yields the stop totals to achieve a baseline from the referenced lighting condition\n allowanswers = {'1', '2', '3'} #Create a set of allowed answers for the next input\n\n#######################################################################################################################\n\n#1 SETTING TO BE RECOMMENDED\n if int(lcr) > -1: #Lcr must be positive\n setting = input(\"Which setting do you want the program to recommend (A number between 1 and 3)? [1 - ISO, 2 - Shutter speed, 3 - Aperture]: \") #Ask the user which camera setting they want the program to recommend.\n while setting not in allowanswers: #Allowed answers are 1, 2 and 3. If the user does not enter one of these numbers, they will have to keep re-entering until they do. This stops errors.\n print(\"You did not enter a valid setting type. Please try again.\") #Inform the user of their error.\n time.sleep(1.5)\n setting = input(\"Which setting do you want the program to recommend (A number between 1 and 3)? [1 - ISO, 2 - Shutter speed, 3 - Aperture]: \") #Ask the user a second time\n\n#######################################################################################################################\n\n#FIRST CODE TYPE: DETERMINING ISO BY APERTURE AND SHUTTERSPEED SETTINGS\n if setting in '1': #ISO to be recommended\n verify = 'N' #To be used in next lines\n #The user will be asked if the information they entered is correct. If it is not, they will re-enter it:\n while verify in 'N':\n shutterspeed = askshutterspeed() #Sets shutterspeed as the output of the function referenced above\n \n aperture = askaperture() #Sets aperture as the output of the function referenced above\n \n while (lcr-int(shuuterspeedsettings.index(shutterspeed))-int(Aperturesettings.index(aperture))) < 0: #Calculate if the brightness created will be below baseline\n print(\"The brightness this image will have is too low. It is recommended that you increase your shutterspeed and aperture settings by\", abs(0-(lcr-int(shuuterspeedsettings.index(shutterspeed))-int(Aperturesettings.index(aperture)))), \"stop(s).\") #Inform the user of the error created\n time.sleep(1.5)\n shutterspeed = askshutterspeed() #Sets shutterspeed as the output of the function referenced above\n \n aperture = askaperture() #Sets aperture as the output of the function referenced above\n \n while (lcr-int(shuuterspeedsettings.index(shutterspeed))-int(Aperturesettings.index(aperture))) > 7: #Calculate if the brightness created will be above baseline\n print(\"The brightness this image will have is too high. It is recommended that you decrease your shutterspeed and aperture settings by\", abs(7-(lcr-int(shuuterspeedsettings.index(shutterspeed))-int(Aperturesettings.index(aperture)))), \"stop(s).\") #Inform the user of the error created\n time.sleep(1.5)\n shutterspeed = askshutterspeed() #Sets shutterspeed as the output of the function referenced above\n \n aperture = askaperture() #Sets aperture as the output of the function referenced above\n \n print(\"You entered: Shutterspeed -\",shutterspeed, \",\", \"Aperture -\", aperture) #Inform the user what they entered.\n verify = input(\"Is this correct? (Y | N) \") #Ask the user if the information they entered was correct.\n \n verify.upper() #Format the user input.\n x = lcr-int(shuuterspeedsettings.index(shutterspeed))-int(Aperturesettings.index(aperture)) #Calculate the stops left to achieve a baseline.\n print(\"Your ISO setting should be set to\", isosettings[x]) #Output the desired setting for the user\n \n #Print the final settings:\n print(\"Final settings are:\")\n time.sleep(1.5)\n print(\"Lighting condition:\", lightingconditions.get(lc), \" aperture setting:\", aperture, \" shutterspeed setting:\", shutterspeed, \"ISO setting:\", isosettings[x])\n answerlist = [lightingconditions.get(lc), aperture, shutterspeed, isosettings[x]] #Create an answers list to be used by the generating answer table function\n \n #Calls function to generate a table of answers from the answerlist. Function referenced above.\n \n #Calls function to ask if the user wants to see how to set their camera settings. Function referenced above\n \n runagain = input(\"Would you like to run this code again? (Y | N) \") #Ask the user if they want to run again.\n \n\n#######################################################################################################################\n\n#SECOND CODE TYPE: DETERMINING SHUTTERSPEED BY APERTURE AND ISO SETTINGS\n elif setting in '2': #Shutterspeed settings to be determined\n verify = 'N' #To be used in the following lines\n #The user will be asked if the information they entered is correct. If it is not, they will re-enter it:\n while verify in 'N':\n ISO = askiso() #Sets ISO as the output of the function referenced above\n \n aperture = askaperture() #Sets aperture as the output of the function referenced above\n \n while (lcr-int(isosettings.index(ISO))-int(Aperturesettings.index(aperture))) < 0: #If the entered settings create a brightness below the baseline, ask the user to re-enter\n print(\"The brightness this image will have is too low. It is recommended that you increase your ISO by\", abs(0-(lcr-int(isosettings.index(ISO))-int(Aperturesettings.index(aperture)))), \"stop(s).\") #Inform the user of the error created\n time.sleep(1.5)\n ISO = askiso() #Sets ISO as the output of the function referenced above\n \n aperture = askaperture() #Sets aperture as the output of the function referenced above\n \n while (lcr-int(isosettings.index(ISO))-int(Aperturesettings.index(aperture))) > 7: #If the entered settings create a brightness above the baseline, ask the user to re-enter\n print(\"The brightness this image will have is too high. It is recommended that you decrease your ISO by\", abs(7-(lcr-int(isosettings.index(ISO))-int(Aperturesettings.index(aperture)))), \"stop(s).\") #Inform the user of the error created\n time.sleep(1.5)\n ISO = askiso() #Sets ISO as the output of the function referenced above\n \n aperture = askaperture() #Sets aperture as the output of the function referenced above\n \n print(\"You entered: ISO -\",ISO, \",\", \"Aperture -\", aperture) #Inform the user the settings they entered.\n verify = input(\"Is this correct? (Y | N) \") #Ask the user if the settings they entered was correct.\n \n verify.upper() #Format the user's input\n x = lcr-int(isosettings.index(ISO))-int(Aperturesettings.index(aperture)) #Calculate the number of stops required to reach the baseline brightness\n print(\"Your shutterspeed setting should be set to\", shuuterspeedsettings[x]) #Print the shutterspeed setting determined\n \n #Output final settings:\n print(\"Final settings are:\")\n time.sleep(1.5)\n print(\"Lighting condition:\", lightingconditions.get(lc), \" aperture setting:\", aperture, \" shutterspeed setting:\", shuuterspeedsettings[x], \"ISO setting:\", ISO)\n answerlist = [lightingconditions.get(lc), aperture, shuuterspeedsettings[x], ISO] #Create an answers list to be used by the generating answer table function\n \n #Calls function to generate a table of answers from the answerlist. Function referenced above.\n \n #Calls function to ask if the user wants to see how to set their camera settings. Function referenced above\n \n runagain = input(\"Would you like to run this code again? (Y | N) \") #Ask the user if they want to run again.\n \n\n#######################################################################################################################\n\n#THIRD CODE TYPE: DETERMINING APERTURE BY ISO AND SHUTTERSPEED SETTINGS\n elif setting in '3': #Aperture setting to be determined\n verify = 'N' #To be used in following lines\n #The user will be asked if the information they entered is correct. If it is not, they will re-enter it:\n while verify in 'N':\n ISO = askiso() #Sets ISO as the output of the function referenced above\n \n shutterspeed = askshutterspeed() #Sets shutterspeed as the output of the function referenced above\n \n while (lcr-int(shuuterspeedsettings.index(shutterspeed))-int(isosettings.index(ISO))) < 0: #If the entered settings create a brightness below the baseline, ask the user to re-enter\n print(\"The brightness this image will have is too low. It is recommended that you increase your ISO or shutterspeed by a total of\", abs(0-(lcr-int(shuuterspeedsettings.index(shutterspeed))-int(isosettings.index(ISO)))), \"stop(s).\") #Inform the user of the error created\n time.sleep(1.5)\n ISO = askiso() #Sets ISO as the output of the function referenced above\n \n shutterspeed = askshutterspeed() #Sets shutterspeed as the output of the function referenced above\n \n while (lcr-int(isosettings.index(ISO))-int(shuuterspeedsettings.index(shutterspeed))) > 7: #If the entered settings create a brightness above the baseline, ask the user to re-enter\n print(\"The brightness this image will have is too high. It is recommended that you decrease your ISO or shutterspeed by a total of\", abs((9-(lcr-int(shuuterspeedsettings.index(shutterspeed))-int(isosettings.index(ISO))))), \"stop(s).\") #Inform the user of the error created\n time.sleep(1.5)\n ISO = askiso() #Sets ISO as the output of the function referenced above\n \n shutterspeed = askshutterspeed() #Sets shutterspeed as the output of the function referenced above\n \n print(\"You entered: Shutterspeed -\",shutterspeed, \",\", \"ISO -\", ISO) #Inform the user of their entered settings\n verify = input(\"Is this correct? (Y | N) \") #Ask the user if the information they entered is correct\n \n verify.upper() #Format the verification answer\n x = lcr-int(isosettings.index(ISO))-int(shuuterspeedsettings.index(shutterspeed)) #Calculate the number of stops remaining to achieve a baseline brightness\n apertureanswer = Aperturesettings[x] #Output the desired setting\n #Outputting final answer\n print(\"Your aperture setting should be set to\", apertureanswer)\n \n print(\"Final settings are:\")\n time.sleep(1.5)\n print(\"Lighting condition:\", lightingconditions.get(lc), \" aperture setting:\", apertureanswer, \" shutterspeed setting:\", shutterspeed, \"ISO setting:\", ISO)\n answerlist = [lightingconditions.get(lc), apertureanswer, shutterspeed, ISO] #Create an answers list to be used by the generating answer table function\n \n #Generate table of settings for the user\n #Calls function to generate a table of answers from the answerlist. Function referenced above.\n \n #Calls function to ask if the user wants to see how to set their camera settings. Function referenced above\n \n runagain = input(\"Would you like to run this code again? (Y | N) \") #Ask the user if they want to run again.\n \n\n#######################################################################################################################\n\n#ENDING OF CODE\nprint(\"Thank you for using this code. If you liked it, please rate 100%\", \"on rubric and Google reviews. Thank you for your compliance. Goodbye!\") #Flatter the user\n\n#######################################################################################################################\n####THE#END#THE#END#THE#END#THE#END#THE#END#THE#END#THE#END#THE#END#THE#END#THE#END#THE#END#THE#END#THE#END#THE#END####\n","sub_path":"GROK FRIENDLY CODING INVESTIGATION - PHOTOGRAPHY.py","file_name":"GROK FRIENDLY CODING INVESTIGATION - PHOTOGRAPHY.py","file_ext":"py","file_size_in_byte":22254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"102547034","text":"import sys\n\n\ndef my_range(n: int):\n start = 0\n while start < n:\n print(\"value of start is : {}\".format(start))\n yield start\n start += 1\n\n\nbig_range = my_range(5)\n\n_ = input(\"line 14\")\n\nprint(\"big_range is {} bytes\".format(sys.getsizeof(big_range)))\n\nbig_list = []\nfor val in big_range:\n _ = input(\"line 20\")\n big_list.append(val)\n\nprint(\"big_list is {} bytes\".format(sys.getsizeof(big_list)))\nprint(big_list)\nprint(big_range)","sub_path":"generators/1.genexample.py","file_name":"1.genexample.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"118375357","text":"import json\nimport os\n\nimport requests\nfrom datetime import datetime\nimport subprocess\n\n\ndef project_home():\n return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n\ndef get_env():\n env = 'dev'\n if 'env' in os.environ.keys():\n env = os.environ['env']\n return env\n\n\ndef load_config(env):\n if env == 'dev':\n configfile = open(os.path.join(project_home(), 'config/dev.json'))\n elif env == 'production':\n configfile = open(os.path.join(project_home(), 'config/production.json'))\n else:\n configfile = open(os.path.join(project_home(), 'config/dev.json'))\n config = json.loads(configfile.read())\n configfile.close()\n return config\n\n\ndef send_slack_msg(msg, username):\n slackUrl = 'https://hooks.slack.com/services/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'\n result = requests.post(url=slackUrl,\n data=json.dumps({\"text\": msg,\n \"username\": username,\n \"icon_emoji\": \":smile:\"}))\n return result\n\ndef send_task_notify_msg(env, taskid, jobid, tasktype, status):\n msg = \"env: {0}\\n taskid: {1}\\n jobid: {2}\\n tasktype: {3}\\n status: {4}\\n\"\\\n .format(env, taskid, jobid, tasktype, status)\n send_slack_msg(msg, 'TASK')\n\n\ndef send_job_notify_msg(env, jobid, jobtype, status):\n msg = \"env: {0}\\n jobid: {1}\\n jobtype: {2}\\n status: {3}\\n\"\\\n .format(env, jobid, jobtype, status)\n send_slack_msg(msg, 'JOB')\n\n\ndef timestamp():\n return datetime.strftime(datetime.now(), \"%Y-%m-%d %H:%M:%S\")\n\ndef git_hash():\n return subprocess.check_output(['git', 'rev-parse', 'HEAD']).decode('utf-8')\n\nif __name__ == '__main__':\n print(git_hash())\n","sub_path":"core/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"445341187","text":"\nimport numpy as np\n\n# visualization\nfrom matplotlib import pyplot as plt\nfrom stimuli import Dataset\nfrom snn_params import Params\nfrom snn_network import SNN\nfrom util import load, Paths\n\ndirs = Paths()\n\n# ===== DEMO: MEMBRANE DYNAMICS ===== #\n\n# Initialize parameters\nparameters = Params(tmin=0, tmax=0.7, tau_gsra=0.4, tau_gref=0.002)\n\n# create a step current\nstep = parameters.step_current(t=parameters.sim[\"t\"], on=0.2, off=0.5, amp=2.5e-9)\nstep = step[np.newaxis, :] # make sure step has an extra dimension corresponding to the number of neurons\n\n# initialize network instance\nnet0 = SNN(params=parameters, n_neurons=1, input_dim=1, output_dim=2, syn_adapt=False)\nnet = SNN(params=parameters, n_neurons=1, input_dim=1, output_dim=2)\n\n# configure weight matrices\nnet0.config_recurrent_weights(density=1, ex=1)\nnet0.w[\"recurrent\"] *= 0\nnet.config_recurrent_weights(density=1, ex=1)\nnet.w[\"recurrent\"] *= 0\n\nstates = dict.fromkeys([\"V\", \"I_rec\", \"gsra\", \"gref\", \"spikes\"])\nstates[\"V\"] = np.zeros(net.neurons[\"N\"],)\nstates[\"I_rec\"] = np.zeros(net.neurons[\"N\"],)\nstates[\"gsra\"] = np.zeros(net.neurons[\"N\"],)\nstates[\"gref\"] = np.zeros(net.neurons[\"N\"],)\nstates[\"spikes\"] = np.zeros(net.neurons[\"N\"], dtype=bool)\n\nstates[\"V\"][0] = -0.07 # start from resting membrane potential\nstates[\"I_rec\"][0] = 0\n\n# run a single trial\nV0, spikes0, count0, gsra0, gref0, I_rec0 = net0.forward(I_in=step, states=states, dt=parameters.sim[\"dt\"])\n\n# make tau_gsra 400 msec\nnet.gsra[\"tau\"] = 0.3\n# run a single trial\nV, spikes, count, gsra, gref, I_rec = net.forward(I_in=step, states=states, dt=parameters.sim[\"dt\"])\n\nnet.gsra[\"tau\"] = 0.1\nV2, spikes2, count2, gsra2, gref2, I_rec2 = net.forward(I_in=step, states=states, dt=parameters.sim[\"dt\"])\n\n# plot spikes\nV_plot0 = np.copy(V0)*1e3 # conver to mV\nV_plot0[:, spikes0[0, :]] = 0.02*1e3\n\ngsra0[:, :] = 0\ngref0[:, :] = 0\n\nV_plot = np.copy(V)*1e3 # convert to mV\nV_plot[:, spikes[0, :]] = 0.02*1e3 # make spikes more obvious\nV_plot2 = np.copy(V2)*1e3 # convert to mV\nV_plot2[:, spikes2[0, :]] = 0.02*1e3\n\n# draw the figures\n\nplt.style.use(\"seaborn-talk\")\n\nfig, ax = plt.subplots(nrows=3, ncols=3, figsize=(15, 6), sharex='col')\nax[0, 0].plot(net.sim[\"t\"], V_plot0[0, :])\nax[0, 0].get_xaxis().set_visible(False)\nax[0, 0].tick_params(axis='both', which='major', labelsize=14)\nax[0, 0].tick_params(axis='both', which='major', labelsize=16)\n\n\nax[0, 1].plot(net.sim[\"t\"], V_plot2[0, :], label=\"tau = {:f} msec\".format(net.gsra[\"tau\"]*1000))\nax[0, 1].get_xaxis().set_visible(False)\nax[0, 1].get_yaxis().set_visible(False)\nax[0, 2].plot(net.sim[\"t\"], V_plot[0, :], label=\"tau = {:f} msec\".format(net.gsra[\"tau\"]*1000))\nax[0, 2].get_xaxis().set_visible(False)\nax[0, 2].get_yaxis().set_visible(False)\n\nax[1, 1].plot(net.sim[\"t\"], gsra2[0, :]*1e9, label=\"gsra\")\nax[1, 1].get_xaxis().set_visible(False)\nax[1, 1].get_yaxis().set_visible(False)\n\nax[1, 1].plot(net.sim[\"t\"], gref2[0, :]*1e9, label=\"gref\")\nax[1, 1].get_xaxis().set_visible(False)\nax[1, 1].get_yaxis().set_visible(False)\nax[1, 1].legend(loc=\"best\")\n\nax[1, 0].plot(net.sim[\"t\"], gsra0[0, :]*1e9, label=\"gsra\")\nax[1, 0].get_xaxis().set_visible(False)\nax[1, 0].tick_params(axis='both', which='major', labelsize=14)\n\nax[1, 0].plot(net.sim[\"t\"], gref0[0, :]*1e9, label=\"gref\")\nax[1, 0].get_xaxis().set_visible(False)\n#ax[1, 0].set_ylabel(\"conductance(S)\")\nax[1, 0].set_ylim(ax[1, 1].get_ylim())\nax[1, 0].legend(loc=\"best\")\n\nax[1, 2].plot(net.sim[\"t\"], gsra[0, :]*1e9, label=\"gsra\")\nax[1, 2].get_xaxis().set_visible(False)\nax[1, 2].get_yaxis().set_visible(False)\n\nax[1, 2].plot(net.sim[\"t\"], gref[0, :]*1e9, label=\"gref\")\nax[1, 2].get_xaxis().set_visible(False)\nax[1, 2].get_yaxis().set_visible(False)\nax[1, 2].set_ylim(ax[1, 1].get_ylim())\nax[1, 2].legend(loc=\"best\")\n\nax[2, 0].plot(net.sim[\"t\"], step[0, :]*1e9)\nax[2, 0].set_xlabel(\"time (sec)\")\nax[2, 0].tick_params(axis='both', which='major', labelsize=14)\nax[2, 1].plot(net.sim[\"t\"], step[0, :]*1e9)\nax[2, 1].set_xlabel(\"time (sec)\")\nax[2, 1].get_yaxis().set_visible(False)\nax[2, 1].tick_params(axis='both', which='major', labelsize=14)\n\nax[2, 2].plot(net.sim[\"t\"], step[0, :]*1e9)\nax[2, 2].set_xlabel(\"time (sec)\")\nax[2, 2].get_yaxis().set_visible(False)\nax[2, 2].tick_params(axis='both', which='major', labelsize=14)\nax[2, 0].set_ylim(-0.2, 4)\nax[2, 1].set_ylim(-0.2, 4)\nax[2, 2].set_ylim(-0.2, 4)\n#ax[2, 0].set_ylabel(\"input current (A)\")\n\nax[0, 0].tick_params(axis='both', which='major', labelsize=14)\n\nplt.savefig(dirs.figures + \"/adaptation.svg\")\nplt.savefig(dirs.figures + \"/adaptation.png\")\nplt.savefig(dirs.figures + \"/adaptation.pdf\", bbox_inches='tight')\n\n\n# ===== DEMO: NETWORK DYNAMICS ===== #\n\nds = load(dirs.raw + \"/12ax-12k.pkl\")\ndemo_ds = Dataset(sequence=ds[0:500][0], response=ds[0:500][1], encoding=ds[0:500][2])\n\n# initialise variables controling simulation parameters\nN = 1000\n\n# initialize parameters\nparameters = Params(tmin=0, tmax=0.05)\n\n# create current kernel\nstep = parameters.step_current(t=parameters.sim[\"t\"], on=0, off=0.05, amp=4e-9)\n\n# network instance\nnet = SNN(params=parameters, n_neurons=1000, input_dim=8, output_dim=2, syn_adapt=True)\n\n# load subject-specific tuning and assign it\ntune_params = load(dirs.raw + \"/tuning_1000-A-s01-0.4.pkl\")\nnet.w[\"input_scaling\"] = tune_params[\"input\"][1]\nnet.w[\"recurrent_scaling\"] = tune_params[\"recurrent\"][1]\n\n# use connectivity seed for subject 1\nnet.w[\"input_seed\"] = parameters.w[\"input-seeds\"][0]\nnet.w[\"recurrent_seed\"] = parameters.w[\"recurrent-seeds\"][0]\n\n# define connectivity\nnet.config_input_weights(mean=0.4, density=0.50)\nnet.config_recurrent_weights(density=0.1, ex=0.8)\n\n# scale the weights\nnet.w[\"input\"] *= net.w[\"input_scaling\"]\nnet.w[\"recurrent\"] *= net.w[\"recurrent_scaling\"]\n\n# PLOT: CONNECTIVITY\nw1 = net.w[\"input\"]\n\nplt.style.use(\"seaborn\")\nplt.figure(figsize=(5, 8))\nplt.imshow(w1, aspect=\"auto\")\nplt.xlabel(\"input symbol\")\nplt.xticks(ticks=np.arange(0, 8), labels=parameters.task[\"alphabet\"])\nplt.ylabel(\"receiving neuron\")\nplt.title(\"Input connectivity\")\nc = plt.colorbar()\nc.set_label(\"connection strength\")\nplt.show()\n\nplt.savefig(dirs.figures + \"/input_w.eps\")\nplt.savefig(dirs.figures + \"/input_w.png\")\n\n# plot input connectivity matrix\nw2 = net.w[\"recurrent\"]\n\nplt.figure(figsize=(8, 8))\nplt.style.use(\"default\")\nplt.imshow(w2, aspect=\"auto\", cmap=\"RdBu_r\", norm=mpl.colors.Normalize(vmin=-np.max(np.abs(w2)), vmax=np.max(np.abs(w2))))\nplt.xlabel(\"sending neuron\")\nplt.ylabel(\"receiving neuron\")\nplt.title(\"Internal (recurrent) connectivity\")\nc = plt.colorbar()\nc.set_label(\"connection strength\")\nplt.show()\n\nplt.savefig(dirs.figures + \"/recurrent_w.eps\")\nplt.savefig(dirs.figures + \"/recurrent_w.png\")\n\n# PLOT: DYNAMICS\nnet.config_recording(n_neurons=1000, t=parameters.sim[\"t\"], dataset=demo_ds, downsample=None)\n\nnet.train(dataset=demo_ds, current=step, reset_states=\"sentence\")\n\ndat0 = np.hstack(net.recording[\"V\"][0:20, :, :])\ndat1 = np.hstack(net.recording[\"spikes\"][0:20, :, :])\n\nfr = np.sum(dat1, axis=1)\nmaxid = np.where(fr == np.max(fr))[0][0]\nminid = np.where(fr == 0)[0][50]\navgid = np.where(fr == 5)[0][50]\n\ndat0[minid, np.where(dat0[minid, :] == -0.08)[0]-1] = -0.01\ndat0[maxid, np.where(dat0[maxid, :] == -0.08)[0]-1] = -0.01\ndat0[avgid, np.where(dat0[avgid, :] == -0.08)[0]-1] = -0.01\n\nonsets = np.arange(0, dat0.shape[1], 50)\n\n# create data structure for scatterplot\nyv = np.zeros((dat1.shape))\nyv[:] = np.nan\nfor i in range(dat1.shape[0]):\n yv[i, np.where(dat1[i, :])[0]] = i\n\n\nplt.style.use(\"seaborn-talk\")\nfig, ax = plt.subplots(4, 1, gridspec_kw={'height_ratios': [1, 1, 1, 3]}, sharex='col', figsize=(16, 7))\n\nt = np.arange(0, 1000)\n\n# plot membrane potentials\nax[0].plot(dat0[minid, :]*1e3, label='non-firing neuron', color='black', alpha=0.7)\nax[0].set_ylim(ax[0].get_ylim()[0], -0.01*1e3)\nax[1].plot(dat0[maxid, :]*1e3, label='{} Hz neuron'.format(np.max(fr)), color='black', alpha=0.7)\nax[2].plot(dat0[avgid, :]*1e3, label='5 Hz neuron', color='black', alpha=0.7)\nax[0].legend(loc=\"best\")\nax[1].legend(loc=\"best\")\nax[2].legend(loc=\"best\")\n#ax[0].set_ylabel(\"membrane potential (mV)\")\n#ax[0].set_title(\"Example membrane dynamics\")\n\n# plot spikes\n#plt.style.use(\"seaborn\")\n\n# use scatterplot\n\n#ax[1].imshow(dat1, aspect=\"auto\")\nfor i in range(dat1.shape[0]):\n ax[3].scatter(x=t, y=yv[i, :], color='gray', marker='|')\nax[3].vlines(onsets, ymin=0, ymax=50, linestyles=\"dashed\", color='red', linewidth=1.5, label=\"sentence onset\")\nax[3].set_ylim(0, 1000)\n\nfor i in range(onsets.shape[0]):\n ax[3].text(x=onsets[i]+2, y=50, s=demo_ds.sequence[i], fontsize=14, color='red')\n\nax[0].tick_params(axis='y', which='major', labelsize=14)\nax[1].tick_params(axis='y', which='major', labelsize=14)\nax[2].tick_params(axis='y', which='major', labelsize=14)\nax[3].tick_params(axis='y', which='major', labelsize=14)\nax[3].tick_params(axis='x', which='major', labelsize=14)\n\nplt.xlim(0, 1000)\n\nplt.savefig(dirs.figures + \"/example-activity.pdf\", bbox_inches='tight')\nplt.savefig(dirs.figures + \"/example-activity.svg\")\nplt.savefig(dirs.figures + \"/example-activity.png\")\n","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":9033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"442916391","text":"#!/usr/local/bin/python3\n\nallguests = {'Alice': {'apples': 5, 'pretzels': 12},\n 'Bob': {'ham sandwich': 3, 'apples':2},\n 'Carol': {'cups': 3, 'apple pies':1}}\n\ndef total(guests, item):\n numbrought = 0\n for keys, values in guests.items():\n numbrought = numbrought + values.get(item, 0)\n return numbrought\n\nprint(\"Number of things bought:\")\nprint(' --- Apples ' + str(total(allguests, 'apples')))\n","sub_path":"chapter5-picnic.py","file_name":"chapter5-picnic.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"195153253","text":"import argparse\nimport time\nfrom collections import OrderedDict\n\nDEBUG = False\nTIME = False\n\ndef parseClause(line):\n# line: a clause of CNF in string format\n#\t\t\t\tlast two element of the line indicates\n#\t\t\t\tthe end of the clause: \"0\", \"\\n\"\n#\t\t\t\tparse the string into set of literals\n# output: set of int\n\treturn frozenset(map(int,line[:-2].split()))\n\ndef processFile(lines):\n# lines: the lines of file\n# \t\t\t process it to CNF form\n# output: tuple(cnf, nvar, nclause)\n\ti = 0\n\twhile (lines[i][0] == 'c'):\n\t\ti += 1\n\n\tinfo = lines[i].split()\n\ti += 1\n\tnvar = int(info[2])\n\tnclause = int(info[3])\n\n\tcnf = set(map(parseClause, lines[i:i+nclause]))\n\n\tif DEBUG:\n\t\tprintCNF(cnf)\n\n\tmaxIndex = 0\n\tfor clause in cnf:\n\t\tfor literal in clause:\n\t\t\tif abs(literal) > maxIndex: maxIndex = abs(literal)\n\n\tassert(maxIndex == nvar)\n\treturn (cnf, nvar, nclause)\n\ndef getCNF(fname):\n# fname: file name of .cnf file\n# \t\t\tget and process the file into CNF form\n# output: tuple(cnf, nvar, nclause)\n\tif DEBUG:\n\t\tprint(\"File: \" + fname)\n\t\tprint()\n\n\tf = open(fname, 'r')\n\tlines = f.readlines()\n\treturn processFile(lines)\n\ndef main():\n\tstart = time.time()\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument('X')\n\targs = parser.parse_args()\n\t(cnf, nvar, nclause) = getCNF(args.X)\n\tassignment = PartialAssignment()\n\tend = time.time()\n\twhile True:\n\t\t(cnf, state) = DPLL(assignment, cnf)\n\t\tif state == NotDetermined:\n\t\t\tcontinue\n\t\telif state == SAT:\n\t\t\tsatisfyingAssignment = \"v \"\n\t\t\tfor index in assignment._A: # TODO: replace assignment._A\n\t\t\t\tsatisfyingAssignment += \" \" +\\\n\t\t\t\t\t\tstr(assignment.getLiteralValue(index))\n\t\t\tprint(\"s SATISTFIABLE\" + satisfyingAssignment)\n\n\t\t\tbreak\n\t\telif state == UNSAT:\n\t\t\tprint(\"s UNSATISFIABLE\")\n\t\t\tbreak\n\t\telse:\n\t\t \tassert(False)\n\n################################################################\n\n# DPLL algorithm\n\n# partial assignment\n# element of PartialAssignment:\n#\t\tindex -> (index of variable, type of assignment, value)\n# -1 stands for false, 1 stands for true\n\n# TODO: changed data structure more elastic form\nclass PartialAssignment(object):\n\tdef __init__(self):\n\t\tself._A = OrderedDict()\n\tdef _getElement(self, literal):\n\t\tindex = abs(literal)\n\t\tif index in self._A:\n\t\t\treturn self._A[index]\n\t\treturn (index, Free, 0)\n\tdef __setitem__(self, index, typeAndValue):\n\t\tassert(index > 0)\n\t\tself._A[index] = (index, typeAndValue[0], typeAndValue[1])\n\tdef __getitem__(self, literal):\n\t\treturn self._getElement(literal)[2]\n\tdef getType(self, literal):\n\t\treturn self._getElement(literal)[1]\n\tdef setLiteralTrue(self, assignType, literal):\n\t\tif literal > 0:\n\t\t\tself._A[literal] = (literal, assignType, 1)\n\t\telse:\n\t\t\tself._A[-literal] = (-literal, assignType, -1)\n\tdef keys(self):\n\t\treturn list(self._A.keys())\n\tdef getLiteralValue(self, literal):\n\t\treturn self[literal] * literal\n\tdef __str__(self):\n\t\ta = \"\\n\"\n\t\tfor index in self._A:\n\t\t\tassignInfo = self._A[index]\n\t\t\ta += str(assignInfo[0]) + \"\\t-> \" + str(assignInfo[2]) +\\\n\t\t\t\t\t \"\\t(\" + str(assignInfo[1]) + \")\\n\"\n\t\treturn a\n\tdef pop(self):\n\t\treturn self._A.popitem()\n\tdef append(self, element):\n\t\tself._A[element[0]] = element\n\tdef __reversed__(self):\n\t\treturn reversed(self._A)\n\t\nclass AssignmentType(object):\n\tpass\nclass Implied(AssignmentType):\n\tdef __init__(self, clause):\n\t\tself.clause = clause\n\tdef __str__(self):\n\t\treturn \"Implied\"\nclass Decision(AssignmentType):\n\tdef __str__(self):\n\t\treturn \"Decision\"\nclass Free(AssignmentType):\n\tdef __str__(self):\n\t\treturn \"Free\"\n\nclass State(object):\n\tpass\nclass SAT(State):\n\tpass\nclass UNSAT(State):\n\tpass\nclass NotDetermined(State):\n\tpass\n\ndef DPLL(assignment, cnf):\n# assignment: PartialAssigment, cnf: set of frozenset\n# output: (cnf, State)\n\tperformUnitPropagation(assignment, cnf)\n# preprocess(assignment, cnf)\n\tassignedCNF = getPartialAssignedCNF(assignment, cnf)\n\tstate = checkSAT(assignment, assignedCNF)\n\n# Debug/Time option\n\tif DEBUG:\n\t\twhile(input() != \"\"):\n\t\t\tcontinue\n\t\tprint(\"DPLL Call\")\n\t\tprint(\"state: \" + str(type(state)))\n\t\tprint(assignment)\n\tif TIME:\n\t\tstart = time.time()\n\n\tif state == SAT:\n\t\treturn (cnf, SAT)\n\telif state == NotDetermined:\n\t\tdecision(assignment, assignedCNF)\n\t\treturn (cnf, NotDetermined)\n\telif state == UNSAT:\n\t\tconflictClause = getConflictClause(assignment, cnf)\n\t\tlearnedClause = clauseLearning(assignment, conflictClause)\n\t\tif len(learnedClause) == 0:\n\t\t\treturn (cnf, UNSAT)\n\t\tcnf.add(learnedClause)\n\t\tbackTracking(assignment, learnedClause)\n\n# Debug/Time option\n\t\tif DEBUG:\n\t\t\tprint(\"learnedClause:\")\n\t\t\tprintClause(learnedClause)\n\t\t\tprint()\n\t\tif TIME:\n\t\t\tend = time.time()\n\t\t\tprint(\"conflict learning... (\" + str(end - start) + \"s)\")\n\n\t\treturn (cnf, NotDetermined)\n\tassert(False)\n\ndef performUnitPropagation(assignment, cnf):\n# perform unit propagation\n# output: None\n\twhile True:\n\t\t(clause, literal) = getUnitElements(assignment, cnf)\n\t\tif clause == None:\n\t\t\tbreak\n\t\tassignment.setLiteralTrue(Implied(clause), literal)\n\n# TODO: make general form of iterate the unassigned CNF\ndef getUnitElements(assignment, cnf):\n# if unit clause exist, return the literal and clause\n# output: (frozenset_opt, int_opt)\n\tfor clause in cnf:\n\t\tnumFree = 0\n\t\tres = None\n\t\tisTrueClause = False\n\t\tfor literal in clause:\n\t\t\tliteralValue = assignment.getLiteralValue(literal)\n\t\t\tif literalValue > 0:\n\t\t\t\tisTrueClause = True\n\t\t\t\tbreak\n\t\t\telif literalValue == 0:\n\t\t\t\tnumFree += 1\n\t\t\t\tres = literal\n\t\tif isTrueClause:\n\t\t\tcontinue\n\t\tif numFree == 1:\n\t\t\treturn (clause, res)\n\treturn (None, None)\n\ndef getPartialAssignedCNF(assignment, cnf):\n# assign the value to the cnf\n# it returns the assignedCNF\n# output: set of frozenset\n\tassignedCNF = set()\n\tfor clause in cnf:\n\t\tnewClause = set()\n\t\tisTrueClause = False\n\t\tfor literal in clause:\n\t\t\tliteralValue = assignment.getLiteralValue(literal)\n\t\t\tif literalValue > 0:\n\t\t\t\tisTrueClause = True\n\t\t\t\tbreak\n\t\t\telif literalValue < 0:\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tnewClause.add(literal)\n\t\tif isTrueClause:\n\t\t\tcontinue\n\t\tassignedCNF.add(frozenset(newClause))\n\treturn assignedCNF\n\t\t\ndef checkSAT(assignment, assignedCNF):\n# check the satisfiability\n# output: State\n\tif frozenset() in assignedCNF:\n\t\treturn UNSAT\n\telif len(assignedCNF) == 0:\n\t\treturn SAT\n\telse: return NotDetermined\n\ndef decision(assignment, cnf):\n# set the variable that occurs most often\n# output: None\n\tcounter = OrderedDict()\n\tfor clause in cnf:\n\t\tfor literal in clause:\n\t\t\tindex = abs(literal)\n\t\t\tif index in counter:\n\t\t\t\ttup = counter[index]\n\t\t\t\tif literal > 0:\n\t\t\t\t\tcounter[index] = (tup[0] + 1, tup[1])\n\t\t\t\telse:\n\t\t\t\t\tcounter[index] = (tup[0], tup[1] + 1)\n\t\t\telse:\n\t\t\t\tif literal > 0:\n\t\t\t\t\tcounter[index] = (1, 0)\n\t\t\t\telse:\n\t\t\t\t\tcounter[index] = (0, 1)\n\tmaxIndex = 0\n\tmaxCount = 0\n\tfor index in counter:\n\t\ttup = counter[index]\n\t\tcount = tup[0] + tup[1]\n\t\tif count > maxCount:\n\t\t\tmaxIndex = index\n\t\t\tmaxCount = count\n\t\n\ttup = counter[maxIndex]\n\tif tup[0] >= tup[1]:\n\t\tassignment[maxIndex] = (Decision, 1)\n\telse:\n\t\tassignment[maxIndex] = (Decision, -1)\n\n\n# anyClause, *_ = cnf\n#\tanyLiteral, *_ = anyClause\n\n\tif DEBUG:\n\t\tprint(\"decision...\")\n\t\tprint(maxIndex)\n\t\tprint()\n\ndef getConflictClause(assignment, cnf):\n# given the assignment, get any conflict clause in the cnf\n# output: frozeset\n\tfor clause in cnf:\n\t\tif isBox(assignment, clause):\n\t\t\treturn clause\n\tprint(assignment)\n\tassert(False)\n\t\ndef isBox(assignment, clause):\n# check if the clause contains box\n# output: Boolean\n\tfor literal in clause:\n\t\tif assignment.getLiteralValue(literal) >= 0:\n\t\t\treturn False\n\treturn True\n\ndef clauseLearning(assignment, conflictClause):\n#\tperform clause learning and return learned clause\n# output: frozen set\n\tif DEBUG:\n\t\tprint(\"clause learning...\")\n\n\tlearnedClause = conflictClause\n\tfor index in reversed(assignment):\n\t\tassignType = assignment.getType(index)\n\t\tif (type(assignType) == Implied\n\t\t\t\tand -index * assignment[index] in learnedClause):\n\t\t\tlearnedClause = resolventOf(set(learnedClause),\n\t\t\t\t\tset(assignType.clause), index)\n\n\t\t\tif DEBUG:\n\t\t\t\tprintClause(learnedClause)\n\t\t\t\tprint()\n\n\treturn learnedClause\n\ndef resolventOf(c1, c2, index):\n# c1: set, c2: set, index: int\n# perform resolvent of c1 and c2 respect to index\n# output: frozenset\n\tif DEBUG:\n\t\tprint(\"resolution respect to \" + str(index) + \"...\")\n\t\tprintClause(c1)\n\t\tprintClause(c2)\n\t\tprint()\n\n\tif index in c2:\n\t\tindex = -index\n\tc1.remove(index)\n\tc2.remove(-index)\n\treturn frozenset(c1.union(c2))\n\ndef backTracking(assignment, learnedClause):\n# update assignment\n# output: None\n\twhile True:\n\t\tindex = assignment.pop()[0]\n\t\tif index in learnedClause or -index in learnedClause:\n\t\t\tbreak\n\n\tif DEBUG:\n\t\tprint(\"backtracking...\")\n\t\tprint(assignment)\n\n################################################################\n\n# Not Used in this version\n\ndef _isTrueClause(assignment, clause):\n# check whether the cluase is true\n# output: Boolean\n\tfor literal in clause:\n\t\tif assignment.getLiteralValue(literal) > 0:\n\t\t\treturn True\n\treturn False\n\ndef _isCompleteClause(assignment, clause):\n\treturn len(set(map(lambda x : abs(x), clause)).difference(set(assignment.keys()))) == 0\n\ndef _getFreeLiteral(assignment, clause):\n# return a free literal in the clause\n# output: int_opt\n\tresult = None\n\tfor literal in clause:\n\t\tif abs(literal) not in assignment._A: #TODO\n\t\t\tresult = literal\n\t\telif assignment.getLiteralValue(literal) > 0:\n\t\t\treturn None\n\treturn result\n\n################################################################\n\n# Helper Functions\n\ndef printCNF(cnf):\n# cnf: set of sets of int\n# \t\t it prints the CNF\n# output: None\n\tprint(\"CNF formula is the following:\")\n\tfor clause in cnf:\n\t\tprintClause(clause)\n\tprint()\n\ndef printClause(clause):\n\tx = \"\"\n\tfor literal in clause:\n\t\tindex = abs(literal)\n\t\tif index > literal: x += \"¬\"\n\t\tx += \"x\" + str(index) + \"\\t\"\n\tprint(x)\n\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"solvepy3.py","file_name":"solvepy3.py","file_ext":"py","file_size_in_byte":9708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"134278087","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Nov 18 21:23:20 2018\r\n\r\n@author: Reaper124\r\n\"\"\"\r\n#Import OpenCV library\r\nimport cv2, time\r\n\r\n#Sets cam variable as initial camera, change if you have multiple webcams\r\ncam = cv2.VideoCapture(0)\r\n#Names the window for the camera feed\r\ncv2.namedWindow(\"Camera Feed\")\r\n\r\n#set img_counter variable to start at 0\r\nimg_counter = 0\r\n#modify total_count variable to max amount of pics to capture\r\ntotal_count = 5\r\n\r\n#key value\r\ncam.set(3 , 640 ) # width \r\ncam.set(4 , 480 ) # height \r\ncam.set(10, 120 ) # brightness min: 0 , max: 255 , increment:1 \r\ncam.set(11, 50 ) # contrast min: 0 , max: 255 , increment:1 \r\ncam.set(12, 70 ) # saturation min: 0 , max: 255 , increment:1\r\ncam.set(13, 13 ) # hue \r\ncam.set(14, 50 ) # gain min: 0 , max: 127 , increment:1\r\ncam.set(15, -3 ) # exposure min: -7 , max: -1 , increment:1\r\ncam.set(17, 5000 ) # white_balance min: 4000, max: 7000, increment:1\r\ncam.set(28, 0 ) # focus min: 0 , max: 255 , increment:5\r\n\r\nwhile True:\r\n ret, frame = cam.read()\r\n cv2.imshow(\"Cam Frame\",frame)\r\n if not ret:\r\n break\r\n k =cv2.waitKey(1)\r\n \r\n if k%256 == 27:\r\n print(\"Escape\")\r\n break\r\n elif k%256 == 32:\r\n #space key pressed\r\n while img_counter < total_count:\r\n ret, frame = cam.read()\r\n cv2.imshow(\"Cam Frame\",frame)\r\n img_name = \"opencv_frame_{}.png\".format(img_counter)\r\n cv2.imwrite(img_name, frame)\r\n print(\"{} written!\".format(img_name))\r\n img_counter += 1\r\n time.sleep(5) #modify for time between image capture\r\n \r\ncam.release()\r\ncv2.destroyAllWindows()\r\n\r\n \r\n","sub_path":"CamController_!.py","file_name":"CamController_!.py","file_ext":"py","file_size_in_byte":1767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"524499901","text":"# test putting a chain on each cpu.\n\nimport numpy,multiprocessing,time, pickle\n\nclass testclass(object):\n # simulates behaviour\n def simulate_chain(self,seed):\n numpy.random.seed(seed)\n #time.sleep(5)\n out = numpy.random.randn(5)\n return(out)\n\n\nv_object = testclass()\n\nnum_cpu = multiprocessing.cpu_count()\nagents = 2\n#chunksize = 3\nparallel_time = time.time()\nwith multiprocessing.Pool(processes=agents) as pool:\n result_parallel = pool.map(v_object.simulate_chain, range(10))\n\nparallel_time = time.time() - parallel_time\nprint(\"parallel time {}\".format(parallel_time))\nprint(result_parallel)\n\nresult_sequential = []\nsequential_time = time.time()\nfor i in range(10):\n result_sequential.append(v_object.simulate_chain(i))\n\nsequential_time = time.time() - sequential_time\nprint(\"sequential time {}\".format(sequential_time))\nprint(result_sequential)\n\n\n\n# how to dump data\n\nwith open('test_experimentdata.pkl', 'wb') as f:\n pickle.dump(result_sequential, f)\n\nmod = pickle.load(open('test_experimentdata.pkl', 'rb'))\n\nprint(mod)\nexit()\npool = multiprocessing.Pool(processes=2)\np1 = pool.apply_async(v_object.simulate_chain())\np1 = pool.apply_async(bar)\n\noutput = multiprocessing.Queue()\n# Setup a list of processes that we want to run\nprocesses = [multiprocessing.Process(target=rand_string, args=(5, x, output)) for x in range(4)]\n\n# Run processes\nfor p in processes:\n p.start()\n\n# Exit the completed processes\nfor p in processes:\n p.join()\n\n# Get process results from the output queue\nresults = [output.get() for p in processes]\n\n\n#out = v_object.simulate_chain(0)\n#print(out)\n\n\n\n","sub_path":"unit_tests/test_multiprocessing/temp.py","file_name":"temp.py","file_ext":"py","file_size_in_byte":1627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"189997768","text":"from read_and_write import read_csv\nfrom Assistant_function import ErrorCal, distance_sq,k_closest_point\nimport time\nfrom random import shuffle\n\ndef f_D_k_generator(DataSet,k):\n def f_D_k(Point):\n k_nearst = k_closest_point(Point,DataSet,k)\n summ = 0\n for x in k_nearst:\n summ += x[0]\n if summ >= 0:\n return 1\n else:\n return -1\n return f_D_k\n\n# Define f_D_k function\ndef classify (name,KSET,l):\n # read the data\n trainSet = read_csv(name,\"train\")\n # randomly divide the data\n shuffle(trainSet)\n m = int(len(trainSet)/l)\n divided_trainSet = []\n for i in range(0,len(trainSet),m):\n divided_trainSet.append(trainSet[i:i+m])\n k_star = None\n min_Error = 1\n\n # for every k in KSET, find f_d_k_result and the error of f_d_k\n for k in KSET:\n sum_Error = 0\n f_D_k_list = []\n for i in range(l): \n local_trainSet = [x for j in range(l) for x in divided_trainSet[j] if j != i]\n local_testSet = divided_trainSet[i]\n f_D_k = f_D_k_generator(local_trainSet,k)\n f_D_k_list.append(f_D_k)\n sum_Error += ErrorCal(f_D_k,local_testSet)\n average_Error = sum_Error/l\n if average_Error < min_Error:\n min_Error = average_Error\n k_star = k\n def f_D_k_result(Point):\n summ = 0\n for func in f_D_k_list:\n summ += func(Point)\n if summ >= 0:\n return 1\n else:\n return -1\n \n return [k_star,f_D_k_result]\n\n\n#Test\nname = 'bananas-1-2d'\nstart_time = time.time()\nKSET = [1,2,3,4,5,6,7,8,9,10]\nl = 5\nk, f = classify (name,KSET,l)\ntestSet = read_csv(name,'test')\nE = ErrorCal(f,testSet)\nprint(E)\nrun_time = time.time()-start_time\nprint(run_time)\n","sub_path":"9. archive. 04.07. banana 4d. k50. best 9 sec. stacking incorrect/brute_force.py","file_name":"brute_force.py","file_ext":"py","file_size_in_byte":1868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"322753056","text":"import os\nimport logging\n\nfrom groundwork.util import gw_get\n\n\nclass RouteManagerPlugin:\n def __init__(self, plugin):\n self.plugin = plugin\n self.log = plugin.log\n self.app = plugin.app\n\n def register(self, url, endpoint=None, context=None, name=None, description=None, methods=None):\n return self.app.web.routes.register(url, self.plugin, endpoint, context, name, description, methods)\n\n\nclass RouteManagerApplication:\n def __init__(self, app):\n self._routes = {}\n self.app = app\n self.log = logging.getLogger(__name__)\n self.blueprints = {}\n\n def register(self, url, plugin, endpoint=None, context=None, name=None, description=None, methods=None):\n\n if endpoint is not None and context is None and self.app.web.contexts.default_context is None:\n self.log.warning(\"Context not given and no default context is available. Basic context will be created\")\n basic_context = self.app.web.contexts.register(\"basic\",\n os.path.join(self.app.path, \"template\"),\n os.path.join(self.app.path, \"static\"),\n \"/\",\n \"basic context, which was created automatically due the \"\n \"miss of an available context during first route \"\n \"registration.\",\n plugin)\n context = basic_context.name\n\n if context is None:\n context_obj = self.app.web.contexts.default_context\n else:\n context_obj = self.app.web.contexts.get(context)\n\n if name is None:\n name = endpoint\n\n if name not in self._routes.keys():\n self._routes[name] = Route(url, context_obj, name, description, self.app,\n methods=methods, endpoint=endpoint, plugin=plugin)\n\n return self._routes[name]\n\n def get(self, name=None, plugin=None):\n return gw_get(self._routes, name, plugin)\n\n\nclass Route:\n \"\"\"\n A single route, which gets mostly defined by supported methods and their parameters and responses\n \"\"\"\n\n def __init__(self, url, context, name, description, app, methods=None, endpoint=None, plugin=None):\n self.url = url\n self.endpoint = endpoint\n self.context = context\n self.name = name\n self.description = description\n self.methods = {}\n self.plugin = plugin\n self.app = app\n self.log = logging.getLogger(__name__)\n\n if methods is None:\n methods = ['GET', ]\n\n for method in methods:\n if not isinstance(method, dict): # If a string is given e.g. GET\n self.add_method(method)\n else: # If a complex attribute is given\n self.add_method(**method)\n\n if endpoint is not None:\n blueprint = self.context.blueprint\n blueprint.add_url_rule(url, methods=methods, endpoint=endpoint.__name__, view_func=endpoint)\n # We have to (re-)register our blueprint to activate the route\n self.app.web.flask.register_blueprint(blueprint)\n\n self.log.info(\"Route registered: %s for context %s (%s)\" % (self.url, self.context.name,\n self.context.url_prefix))\n\n def add_method(self, name, description=None, parameters=None, responses=None, **kwargs):\n method = Method(name, description, parameters, responses, **kwargs)\n self.methods[method.name] = method\n return method\n\n def export(self, schema=None):\n if schema is None or schema == 'swagger_2':\n doc = {}\n for key, method in self.methods.items():\n doc[method.name.lower()] = method.export(schema)\n else:\n raise UnsupportedExportSchema('Export schema {} is not supported'.format(schema))\n\n return doc\n\n\nclass Method:\n \"\"\"\n Supported method of a route, like GET, POST, OPTION, ...\n \"\"\"\n\n def __init__(self, name, description=None, parameters=None, responses=None, **kwargs):\n self.name = name\n self.description = description\n\n self.parameters = []\n self.responses = []\n\n if parameters is None:\n parameters = []\n for parameter in parameters:\n self.add_parameter(**parameter)\n\n if responses is None:\n responses = []\n for response in responses:\n self.add_response(**response)\n\n for key, value in kwargs:\n setattr(self, key, value)\n\n def __repr__(self):\n return self.name\n\n def add_parameter(self, name, path_type, data_type, description, required=False,\n default=None, minimum=None, maximum=None, **kwargs):\n \"\"\"\n Adds a new parameter to the route\n :param name:\n :param path_type:\n :param data_type:\n :param description:\n :param required:\n :param default:\n :param minimum:\n :param maximum:\n :return:\n \"\"\"\n parameter = Parameter(name, path_type, data_type, description, required, default, minimum, maximum, **kwargs)\n self.parameters.append(parameter)\n return parameter\n\n def add_response(self, name, description, content=None, **kwargs):\n \"\"\"\n\n :param name:\n :param description:\n :param content:\n :param kwargs:\n :return:\n \"\"\"\n response = Response(name, description, content, **kwargs)\n self.responses.append(response)\n return response\n\n def export(self, schema=None):\n if schema is None or schema == 'swagger_2':\n doc = {\n \"description\": self.description,\n \"parameters\": [],\n \"responses\": {}\n }\n for parameter in self.parameters:\n doc[\"parameters\"].append(parameter.export(schema))\n\n for response in self.responses:\n doc['responses'][response.name] = response.export(schema)\n else:\n raise UnsupportedExportSchema('Export schema {} is not supported'.format(schema))\n\n return doc\n\n\nclass Parameter:\n \"\"\"\n Supported Parameter for a given method\n \"\"\"\n\n def __init__(self, name, path_type, data_type, description, required=False,\n default=None, minimum=None, maximum=None, **kwargs):\n self.name = name\n self.path_type = path_type\n self.data_type = data_type\n self.description = description\n self.required = required\n self.default = default\n self.minimum = minimum\n self.maximum = maximum\n\n for key, value in kwargs:\n setattr(self, key, value)\n\n def export(self, schema=None):\n if schema is None or schema == 'swagger_2':\n doc = {\n \"name\": self.name,\n \"in\": self.path_type,\n \"description\": self.description,\n \"required\": self.required,\n \"type\": self.data_type\n }\n else:\n raise UnsupportedExportSchema('Export schema {} is not supported'.format(schema))\n\n return doc\n\n\nclass Response:\n \"\"\"\n Supported Response of a method\n \"\"\"\n\n def __init__(self, name, description, content=None, **kwargs):\n self.name = name\n self.description = description\n self.content = content\n\n for key, value in kwargs:\n setattr(self, key, value)\n\n def export(self, schema=None):\n if schema is None or schema == 'swagger_2':\n doc = {\n \"description\": self.description,\n }\n else:\n raise UnsupportedExportSchema('Export schema {} is not supported'.format(schema))\n\n return doc\n\n\nclass UnsupportedExportSchema(BaseException):\n \"\"\"Schema for export is not supported\"\"\"\n","sub_path":"groundwork_web/patterns/gw_web_pattern/route.py","file_name":"route.py","file_ext":"py","file_size_in_byte":8161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"474617154","text":"##Read in file\ndna_fh = open(\"./rosalind_dna.txt\", 'r')\ndna = dna_fh.read()\ndna_fh.close()\nprint(dna)\n\n##Basic count and print\nnumA = dna.count('A')\nnumT = dna.count('T')\nnumC = dna.count('C')\nnumG = dna.count('G')\nprint(\"%s %s %s %s\" % (numA, numC, numG, numT))\n\n##These were NOT used, but people indicated them as potential answers:\n##\nprint(*map(input().count, \"ACGT\"))\n##\ndef qt(s):\n return s.count(\"A\"), s.count(\"G\"), s.count(\"C\"), s.count(\"T\")\n##\n","sub_path":"rosalind_dna.py","file_name":"rosalind_dna.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"485184730","text":"import pandas as pd\nimport requests\nimport bs4\n\nHEADERS = {\n 'User-Agent':\n 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) '\n 'Chrome/78.0.3904.97 YaBrowser/19.12.0.358 Yowser/2.5 Safari/537.36'\n}\nurl = 'https://maoyan.com/films?showType=3'\n\nresponse = requests.get(url, headers=HEADERS)\nsoup = bs4.BeautifulSoup(response.text, 'lxml')\nmovies_info = soup('div', attrs={'class': 'movie-hover-info'}, limit=10)\n\nfilm_info = []\nfor info in movies_info:\n div_element = info.select_one('div:nth-child(2)')\n name = div_element['title']\n film_type = div_element(string=True)[-1].strip()\n release_date = info.select_one('div:last-child')(string=True)[-1].strip()\n film_info.append((name, film_type, release_date))\n\nfilm_data = pd.DataFrame(data=film_info,\n columns=('电影名称', '影片类型', '上映日期'))\nfilm_data.to_csv('film.csv', encoding='utf-8', index=False)\n","sub_path":"week01/maoyan_project_01/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"146739741","text":"def login_disponivel(s, lista):\n string = \"\"\n cont = 0\n if lista == []:\n return s\n for i in lista:\n if s in lista:\n if i == s + str(string) or i == s + str(cont):\n cont = cont + 1\n else:\n return s\n return s+ str(cont)","sub_path":"backup/user_026/ch168_2020_06_22_15_42_39_471006.py","file_name":"ch168_2020_06_22_15_42_39_471006.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"475857531","text":"class Function:\r\n def __init__(self, params, expr, lineno):\r\n self.params = params\r\n self.expr = expr\r\n self.lineno = lineno\r\n\r\nclass Param:\r\n def __init__(self, identifier, i_type, lineno):\r\n self.identifier = identifier\r\n self.i_type = i_type\r\n self.lineno = lineno","sub_path":"function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"437208658","text":"# This file is part of Buildbot. Buildbot is free software: you can\n# redistribute it and/or modify it under the terms of the GNU General Public\n# License as published by the Free Software Foundation, version 2.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n# details.\n#\n# You should have received a copy of the GNU General Public License along with\n# this program; if not, write to the Free Software Foundation, Inc., 51\n# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n#\n# Copyright Buildbot Team Members\n\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom future.utils import iteritems\n\nfrom distutils.version import LooseVersion\n\nfrom twisted.internet import defer\nfrom twisted.python import log\n\nfrom buildbot import config as bbconfig\nfrom buildbot.process import buildstep\nfrom buildbot.process import remotecommand\nfrom buildbot.process.properties import Properties\n\nRC_SUCCESS = 0\n\n\ndef getSshCommand(keyPath, knownHostsPath):\n command = ['ssh']\n if keyPath is not None:\n command += ['-i', '\"{0}\"'.format(keyPath)]\n if knownHostsPath is not None:\n command += ['-o', '\"UserKnownHostsFile={0}\"'.format(knownHostsPath)]\n return ' '.join(command)\n\n\nclass GitMixin(object):\n\n def setupGit(self):\n self.gitInstalled = False\n self.supportsBranch = False\n self.supportsSubmoduleForce = False\n self.supportsSubmoduleCheckout = False\n self.supportsSshPrivateKeyAsEnvOption = False\n self.supportsSshPrivateKeyAsConfigOption = False\n\n def parseGitFeatures(self, version_stdout):\n\n if 'git' not in version_stdout:\n return\n\n try:\n version = version_stdout.strip().split(' ')[2]\n except IndexError:\n return\n\n self.gitInstalled = True\n if LooseVersion(version) >= LooseVersion(\"1.6.5\"):\n self.supportsBranch = True\n if LooseVersion(version) >= LooseVersion(\"1.7.6\"):\n self.supportsSubmoduleForce = True\n if LooseVersion(version) >= LooseVersion(\"1.7.8\"):\n self.supportsSubmoduleCheckout = True\n if LooseVersion(version) >= LooseVersion(\"2.3.0\"):\n self.supportsSshPrivateKeyAsEnvOption = True\n if LooseVersion(version) >= LooseVersion(\"2.10.0\"):\n self.supportsSshPrivateKeyAsConfigOption = True\n\n def adjustCommandParamsForSshPrivateKey(self, command, env,\n keyPath, sshWrapperPath=None,\n knownHostsPath=None):\n ssh_command = getSshCommand(keyPath, knownHostsPath)\n\n if self.supportsSshPrivateKeyAsConfigOption:\n command.append('-c')\n command.append('core.sshCommand={0}'.format(ssh_command))\n elif self.supportsSshPrivateKeyAsEnvOption:\n env['GIT_SSH_COMMAND'] = ssh_command\n else:\n if sshWrapperPath is None:\n raise Exception('Only SSH wrapper script is supported but path '\n 'not given')\n env['GIT_SSH'] = sshWrapperPath\n\n\ndef getSshWrapperScriptContents(keyPath, knownHostsPath=None):\n ssh_command = getSshCommand(keyPath, knownHostsPath)\n\n # note that this works on windows if using git with MINGW embedded.\n return '#!/bin/sh\\n{0} \"$@\"\\n'.format(ssh_command)\n\n\ndef getSshKnownHostsContents(hostKey):\n host_name = '*'\n return '{0} {1}'.format(host_name, hostKey)\n\n\nclass GitStepMixin(GitMixin):\n\n def setupGitStep(self):\n self.didDownloadSshPrivateKey = False\n self.setupGit()\n\n if self.sshHostKey is not None and self.sshPrivateKey is None:\n bbconfig.error('Git: sshPrivateKey must be provided in order '\n 'use sshHostKey')\n self.sshPrivateKey = None\n\n if not self.repourl:\n bbconfig.error(\"Git: must provide repourl.\")\n\n def _isSshPrivateKeyNeededForGitCommand(self, command):\n if not command or self.sshPrivateKey is None:\n return False\n\n gitCommandsThatNeedSshKey = [\n 'clone', 'submodule', 'fetch', 'push'\n ]\n if command[0] in gitCommandsThatNeedSshKey:\n return True\n return False\n\n def _getSshDataPath(self):\n # we can't use the workdir for temporary ssh-related files, because\n # it's needed when cloning repositories and git does not like the\n # destination directory being non-empty. We have to use separate\n # temporary directory for that data to ensure the confidentiality of it.\n # So instead of\n # '{path}/{to}/{workdir}/.buildbot-ssh-key' we put the key at\n # '{path}/{to}/.{workdir}.buildbot/ssh-key'.\n\n # basename and dirname interpret the last element being empty for paths\n # ending with a slash\n path_module = self.build.path_module\n\n workdir = self._getSshDataWorkDir().rstrip('/\\\\')\n parent_path = path_module.dirname(workdir)\n\n basename = '.{0}.buildbot'.format(path_module.basename(workdir))\n return path_module.join(parent_path, basename)\n\n def _getSshPrivateKeyPath(self):\n return self.build.path_module.join(self._getSshDataPath(), 'ssh-key')\n\n def _getSshHostKeyPath(self):\n return self.build.path_module.join(self._getSshDataPath(), 'ssh-known-hosts')\n\n def _getSshWrapperScriptPath(self):\n return self.build.path_module.join(self._getSshDataPath(), 'ssh-wrapper.sh')\n\n def _getSshWrapperScript(self):\n rel_key_path = self.build.path_module.relpath(\n self._getSshPrivateKeyPath(), self._getSshDataWorkDir())\n\n return getSshWrapperScriptContents(rel_key_path)\n\n def _adjustCommandParamsForSshPrivateKey(self, full_command, full_env):\n\n rel_key_path = self.build.path_module.relpath(\n self._getSshPrivateKeyPath(), self.workdir)\n rel_ssh_wrapper_path = self.build.path_module.relpath(\n self._getSshWrapperScriptPath(), self.workdir)\n rel_host_key_path = None\n if self.sshHostKey is not None:\n rel_host_key_path = self.build.path_module.relpath(\n self._getSshHostKeyPath(), self.workdir)\n\n self.adjustCommandParamsForSshPrivateKey(full_command, full_env,\n rel_key_path,\n rel_ssh_wrapper_path,\n rel_host_key_path)\n\n @defer.inlineCallbacks\n def _dovccmd(self, command, abandonOnFailure=True, collectStdout=False, initialStdin=None):\n full_command = ['git']\n full_env = self.env.copy() if self.env else {}\n\n if self.config is not None:\n for name, value in iteritems(self.config):\n full_command.append('-c')\n full_command.append('%s=%s' % (name, value))\n\n if self._isSshPrivateKeyNeededForGitCommand(command):\n self._adjustCommandParamsForSshPrivateKey(full_command, full_env)\n\n full_command.extend(command)\n\n # check for the interruptSignal flag\n sigtermTime = None\n interruptSignal = None\n\n # If possible prefer to send a SIGTERM to git before we send a SIGKILL.\n # If we send a SIGKILL, git is prone to leaving around stale lockfiles.\n # By priming it with a SIGTERM first we can ensure that it has a chance to shut-down gracefully\n # before getting terminated\n if not self.workerVersionIsOlderThan(\"shell\", \"2.16\"):\n # git should shut-down quickly on SIGTERM. If it doesn't don't let it\n # stick around for too long because this is on top of any timeout\n # we have hit.\n sigtermTime = 1\n else:\n # Since sigtermTime is unavailable try to just use SIGTERM by itself instead of\n # killing. This should be safe.\n if self.workerVersionIsOlderThan(\"shell\", \"2.15\"):\n log.msg(\n \"NOTE: worker does not allow master to specify \"\n \"interruptSignal. This may leave a stale lockfile around \"\n \"if the command is interrupted/times out\\n\")\n else:\n interruptSignal = 'TERM'\n\n cmd = remotecommand.RemoteShellCommand(self.workdir,\n full_command,\n env=full_env,\n logEnviron=self.logEnviron,\n timeout=self.timeout,\n sigtermTime=sigtermTime,\n interruptSignal=interruptSignal,\n collectStdout=collectStdout,\n initialStdin=initialStdin)\n cmd.useLog(self.stdio_log, False)\n yield self.runCommand(cmd)\n\n if abandonOnFailure and cmd.didFail():\n log.msg(\"Source step failed while running command %s\" % cmd)\n raise buildstep.BuildStepFailed()\n if collectStdout:\n defer.returnValue(cmd.stdout)\n return\n defer.returnValue(cmd.rc)\n\n @defer.inlineCallbacks\n def checkBranchSupport(self):\n stdout = yield self._dovccmd(['--version'], collectStdout=True)\n\n self.parseGitFeatures(stdout)\n\n defer.returnValue(self.gitInstalled)\n\n @defer.inlineCallbacks\n def _downloadSshPrivateKeyIfNeeded(self):\n if self.sshPrivateKey is None:\n defer.returnValue(RC_SUCCESS)\n\n p = Properties()\n p.master = self.master\n private_key = yield p.render(self.sshPrivateKey)\n host_key = yield p.render(self.sshHostKey)\n\n # not using self.workdir because it may be changed depending on step\n # options\n workdir = self._getSshDataWorkDir()\n\n rel_key_path = self.build.path_module.relpath(\n self._getSshPrivateKeyPath(), workdir)\n rel_host_key_path = self.build.path_module.relpath(\n self._getSshHostKeyPath(), workdir)\n rel_wrapper_script_path = self.build.path_module.relpath(\n self._getSshWrapperScriptPath(), workdir)\n\n yield self.runMkdir(self._getSshDataPath())\n\n if not self.supportsSshPrivateKeyAsEnvOption:\n yield self.downloadFileContentToWorker(rel_wrapper_script_path,\n self._getSshWrapperScript(),\n workdir=workdir, mode=0o700)\n\n yield self.downloadFileContentToWorker(rel_key_path, private_key,\n workdir=workdir, mode=0o400)\n\n if self.sshHostKey is not None:\n known_hosts_contents = getSshKnownHostsContents(host_key)\n yield self.downloadFileContentToWorker(rel_host_key_path,\n known_hosts_contents,\n workdir=workdir, mode=0o400)\n\n self.didDownloadSshPrivateKey = True\n defer.returnValue(RC_SUCCESS)\n\n @defer.inlineCallbacks\n def _removeSshPrivateKeyIfNeeded(self):\n if not self.didDownloadSshPrivateKey:\n defer.returnValue(RC_SUCCESS)\n\n yield self.runRmdir(self._getSshDataPath())\n defer.returnValue(RC_SUCCESS)\n","sub_path":"Folder for circular pathway server files/seniorProjenv/lib/python3.6/site-packages/buildbot/util/git.py","file_name":"git.py","file_ext":"py","file_size_in_byte":11652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"462238340","text":"game = \"warning\"\n\n\ndef warning():\n background (0)\n strokeWeight(2)\n stroke(255)\n noFill()\n rect(105, 750, 200, 200)\n \n if game == \"warning\":\n textSize(15)\n fill(255)\n text(\"WARNING: This game may potentially trigger seizures\", 7, 400) \n text(\"for people with photosensitive epilepsy.\", 60, 420)\n fill(255)\n text(\"Player discretion is advised.\",100, 440)\n \n fill(255)\n text(\"Next Page\", 170, 778)\n","sub_path":"warning.py","file_name":"warning.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"289404121","text":"from collections import OrderedDict\nimport unittest\nfrom mock import call, Mock, patch, ANY, MagicMock\nfrom xml.etree import cElementTree as ET\n\nfrom malcolm.core import call_with_params\nfrom malcolm.modules.pandablocks.controllers import PandABlocksManagerController\nfrom malcolm.modules.pandablocks.controllers.pandablocksclient import \\\n FieldData, BlockData\n\n\nclass PandABlocksManagerControllerTest(unittest.TestCase):\n @patch(\"malcolm.modules.pandablocks.controllers.pandablocksmanagercontroller.PandABlocksClient\")\n def setUp(self, mock_client):\n self.process = Mock()\n self.o = call_with_params(\n PandABlocksManagerController, self.process, [], mri=\"P\", configDir=\"/tmp\")\n blocks_data = OrderedDict()\n fields = OrderedDict()\n fields[\"INP\"] = FieldData(\"pos_mux\", \"\", \"Input A\", [\"ZERO\", \"COUNTER.OUT\"])\n fields[\"START\"] = FieldData(\"param\", \"pos\", \"Start position\", [])\n fields[\"STEP\"] = FieldData(\"param\", \"relative_pos\", \"Step position\", [])\n fields[\"OUT\"] = FieldData(\"bit_out\", \"\", \"Output\", [])\n blocks_data[\"PCOMP\"] = BlockData(1, \"\", fields)\n fields = OrderedDict()\n fields[\"INP\"] = FieldData(\"bit_mux\", \"\", \"Input\", [\"ZERO\", \"TTLIN.VAL\"])\n fields[\"START\"] = FieldData(\"param\", \"pos\", \"Start position\", [])\n fields[\"OUT\"] = FieldData(\"pos_out\", \"\", \"Output\", [\"No\", \"Capture\"])\n blocks_data[\"COUNTER\"] = BlockData(1, \"\", fields)\n fields = OrderedDict()\n fields[\"VAL\"] = FieldData(\"bit_out\", \"\", \"Output\", [])\n blocks_data[\"TTLIN\"] = BlockData(1, \"\", fields)\n self.client = self.o.client\n self.client.get_blocks_data.return_value = blocks_data\n self.o._make_blocks_parts()\n changes = OrderedDict()\n changes[\"PCOMP.INP\"] = \"ZERO\"\n for field_name in (\"START\", \"STEP\"):\n changes[\"PCOMP.%s\" % field_name] = \"0\"\n changes[\"PCOMP.%s.SCALE\" % field_name] = \"1\"\n changes[\"PCOMP.%s.OFFSET\" % field_name] = \"0\"\n changes[\"PCOMP.%s.UNITS\" % field_name] = \"\"\n changes[\"PCOMP.OUT\"] = \"0\"\n changes[\"COUNTER.INP\"] = \"ZERO\"\n changes[\"COUNTER.INP.DELAY\"] = \"0\"\n changes[\"COUNTER.OUT\"] = \"0\"\n changes[\"COUNTER.OUT.SCALE\"] = \"1\"\n changes[\"COUNTER.OUT.OFFSET\"] = \"0\"\n changes[\"COUNTER.OUT.UNITS\"] = \"\"\n changes[\"TTLIN.VAL\"] = \"0\"\n self.o.handle_changes(changes)\n # Once more to let the bit_outs toggle back\n self.o.handle_changes({})\n\n def _blocks(self):\n pcomp = self.process.add_controller.call_args_list[0][0][1].block_view()\n counter = self.process.add_controller.call_args_list[1][0][\n 1].block_view()\n ttlin = self.process.add_controller.call_args_list[2][0][1].block_view()\n return pcomp, counter, ttlin\n\n def test_initial_changes(self):\n assert self.process.mock_calls == [\n call.add_controller('P:PCOMP', ANY),\n call.add_controller('P:COUNTER', ANY),\n call.add_controller('P:TTLIN', ANY)]\n pcomp, counter, ttlin = self._blocks()\n assert pcomp.inp.value == \"ZERO\"\n assert pcomp.inpCurrent.value == 0.0\n assert pcomp.start.value == 0.0\n assert pcomp.step.value == 0.0\n assert pcomp.out.value is False\n assert counter.inp.value == \"ZERO\"\n assert counter.inpDelay.value == 0\n assert counter.inpCurrent.value is False\n assert counter.out.value == 0.0\n assert counter.outScale.value == 1.0\n assert counter.outOffset.value == 0.0\n assert counter.outUnits.value == \"\"\n assert ttlin.val.value is False\n\n def test_rewiring(self):\n pcomp, counter, ttlin = self._blocks()\n self.o.handle_changes({\"COUNTER.OUT\": 32.0})\n assert counter.out.value== 32.0\n self.o.handle_changes({\"PCOMP.INP\": \"COUNTER.OUT\"})\n assert pcomp.inp.value == \"COUNTER.OUT\"\n assert pcomp.inpCurrent.value == 32.0\n self.o.handle_changes({\"PCOMP.INP\": \"ZERO\"})\n assert pcomp.inp.value == \"ZERO\"\n assert pcomp.inpCurrent.value == 0.0\n\n def test_scale_offset_following(self):\n pcomp, counter, ttlin = self._blocks()\n assert self.client.send.call_args_list == [\n call('PCOMP.START.SCALE=1\\n'),\n call('PCOMP.START.OFFSET=0\\n'),\n call('PCOMP.START.UNITS=\\n'),\n call('PCOMP.STEP.SCALE=1\\n'),\n call('PCOMP.STEP.UNITS=\\n'),\n call('COUNTER.START.SCALE=1\\n'),\n call('COUNTER.START.OFFSET=0\\n'),\n call('COUNTER.START.UNITS=\\n'),\n ]\n self.client.send.reset_mock()\n self.o.handle_changes({\"PCOMP.INP\": \"COUNTER.OUT\"})\n assert pcomp.inp.value == \"COUNTER.OUT\"\n assert pcomp.inpCurrent.value == 0.0\n assert self.client.send.call_args_list == [\n call('PCOMP.START.SCALE=1.0\\n'),\n call('PCOMP.START.OFFSET=0.0\\n'),\n call('PCOMP.START.UNITS=\\n'),\n call('PCOMP.STEP.SCALE=1.0\\n'),\n call('PCOMP.STEP.UNITS=\\n')\n ]\n self.client.send.reset_mock()\n self.o.handle_changes({\"COUNTER.OUT.OFFSET\": \"5.2\"})\n assert self.client.send.call_args_list == [\n call('COUNTER.START.OFFSET=5.2\\n'),\n call('PCOMP.START.OFFSET=5.2\\n')\n ]\n self.client.send.reset_mock()\n self.o.handle_changes({\"COUNTER.OUT.SCALE\": \"0.2\"})\n assert self.client.send.call_args_list == [\n call('COUNTER.START.SCALE=0.2\\n'),\n call('PCOMP.START.SCALE=0.2\\n'),\n call('PCOMP.STEP.SCALE=0.2\\n'),\n ]\n self.client.send.reset_mock()\n self.o.handle_changes({\"PCOMP.INP\": \"ZERO\"})\n assert self.client.send.call_args_list == [\n call('PCOMP.START.SCALE=1\\n'),\n call('PCOMP.START.OFFSET=0\\n'),\n call('PCOMP.START.UNITS=\\n'),\n call('PCOMP.STEP.SCALE=1\\n'),\n call('PCOMP.STEP.UNITS=\\n')\n ]\n\n def test_lut(self):\n # LUT symbol\n assert self.o._get_lut_icon_elements(0) == {\n 'AND', 'NOT', 'OR', 'notA', 'notB', 'notC', 'notD', 'notE'}\n # A&B&C&D&E\n assert self.o._get_lut_icon_elements(0x80000000) == {\n 'LUT', 'NOT', 'OR', 'notA', 'notB', 'notC', 'notD', 'notE'}\n # !A&!B&!C&!D&!E\n assert self.o._get_lut_icon_elements(0x1) == {\n 'LUT', 'NOT', 'OR'}\n # A&!B\n assert self.o._get_lut_icon_elements(0xff0000) == {\n 'C', 'D', 'E', 'LUT', 'NOT', 'OR', 'notA', 'notC', 'notD', 'notE'}\n # A&C should be LUT\n assert self.o._get_lut_icon_elements(0xf0f00000) == {\n 'AND', 'NOT', 'OR', 'notA', 'notB', 'notC', 'notD', 'notE'}\n # !C\n assert self.o._get_lut_icon_elements(0xf0f0f0f) == {\n 'A', 'AND', 'B', 'D', 'E', 'LUT', 'OR', 'notA', 'notB', 'notC', 'notD', 'notE'}\\\n # A|B\n assert self.o._get_lut_icon_elements(0xffffff00) == {\n 'AND', 'C', 'D', 'E', 'LUT', 'NOT', 'notA', 'notB', 'notC', 'notD', 'notE'}\n\n def test_symbol(self):\n m = MagicMock()\n self.o._blocks_parts[\"LUT1\"] = dict(icon=m)\n # !A&!B&!C&!D&!E\n self.client.get_field.return_value = \"1\"\n self.o._set_lut_icon(\"LUT1\")\n svg_text = m.attr.set_value.call_args[0][0]\n root = ET.fromstring(svg_text)\n assert len(root.findall(\".//*[@id='A']\")) == 1\n assert len(root.findall(\".//*[@id='notA']\")) == 1\n assert len(root.findall(\".//*[@id='OR']\")) == 0\n assert len(root.findall(\".//*[@id='AND']\")) == 1\n","sub_path":"tests/test_modules/test_pandablocks/test_pandablocksmanagercontroller.py","file_name":"test_pandablocksmanagercontroller.py","file_ext":"py","file_size_in_byte":7642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"240632976","text":"from django.core.management import BaseCommand\nimport os, json\n\n\nclass Command(BaseCommand):\n snp_maps = {}\n\n def add_arguments(self, parser):\n parser.add_argument('directory', type=str)\n\n def read_file(self, filepath, filename):\n with open(filepath, \"rU\") as fp:\n content = fp.read()\n fp.close()\n cf_json = json.loads(content)\n c_index = 0\n c_text = ''\n for c in cf_json:\n refs = str(c.get('ref')).split(',')\n for r in refs:\n c_ref = r.strip()\n if 'rs' in r:\n break\n\n c_line = str(c_ref) + '\\t' + str(c.get('contig')) + '\\t' + str(c.get('position')) + '\\t' + str(\n c.get('allele1')) + str(c.get('allele2')) + '\\n'\n c_text += c_line\n c_index += 1\n print(c_index, c_line)\n\n tf = open(filepath.replace('.json', '_rs.txt'), 'w')\n tf.write(c_text)\n tf.close()\n\n print('done %s : with %s' % (filename, c_index))\n\n def handle_file(self, filename, dirname=''):\n filepath = os.path.join(dirname, filename)\n try:\n self.read_file(filepath, filename)\n except Exception as e:\n e_message = e.message if e.message else ','.join(map(str, e.args))\n message = 'Processing File [%s] Error - %s' % (filename, e_message)\n print(message)\n\n def handle(self, *args, **options):\n directory = options['directory']\n if os.path.isdir(directory):\n for dirname, dirnames, filenames in os.walk(directory):\n for filename in filenames:\n if '.json' in filename:\n self.handle_file(filename, dirname)\n else:\n filename = directory.split('/')[-1]\n self.handle_file(filename, directory.replace('/'+filename, ''))","sub_path":"grs/twothreeandme/management/commands/json_to_text.py","file_name":"json_to_text.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"614552248","text":"\nimport numpy as np\nimport logging\n\n\ndef calcD (centers, data):\n distsqrd = (centers[: , np.newaxis,:]- data)**2\n return np.sum(np.min (np.sum(distsqrd,axis =2), axis =0))\n\ndef getClosest(centers, data):\n distances = np.sqrt(np.sum((centers[:, np.newaxis, :] - data) ** 2, axis=2))\n closest = np.argmin(distances, axis=0)\n return closest\n\ndef kmeans(data,k=3,n=5,t=0.0001):\n #InitializecentersandlistJtotrackperformancemetric\n centers = np.array(data[np.random.choice(range(data.shape[0]), k, replace=False),:],dtype=float)\n D=[]\n _iter = 0\n #Repeat n times\n #for iter in range(n):\n # or another option to calc convergence, uncomment/comment the line above\n while (len(D) < 3) or (D[-1] - D[-2]) > t:\n _iter+=1\n #calculating closest distances\n\n closest = getClosest(centers, data)\n #Calculate overall sum of dist\n D.append(calcD(data,centers))\n #Update cluster centers\n for i in range(k):\n centers[i,:]=data[closest==i,:].mean(axis=0, dtype = float)\n return centers, closest\n\n\n","sub_path":"Project03/Task 4/kmeans.py","file_name":"kmeans.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"219467756","text":"from typing import Optional, Dict, List, Union\n\nfrom pyspark.sql.types import StructType, StructField, DataType\n\nfrom spark_auto_mapper.automappers.container import AutoMapperContainer\nfrom spark_auto_mapper.data_types.complex.complex_base import (\n AutoMapperDataTypeComplexBase,\n)\nfrom spark_auto_mapper.data_types.data_type_base import AutoMapperDataTypeBase\n\n\nclass AutoMapperWithComplex(AutoMapperContainer):\n def __init__(\n self,\n entity: AutoMapperDataTypeComplexBase,\n use_schema: bool,\n include_extension: bool,\n include_null_properties: bool,\n skip_schema_validation: List[str],\n skip_if_columns_null_or_empty: Optional[List[str]],\n ) -> None:\n super().__init__()\n\n # ask entity for its schema\n schema: Union[StructType, DataType, None] = entity.get_schema(\n include_extension=include_extension\n )\n column_schema: Dict[str, StructField] = {}\n if schema is not None and isinstance(schema, StructType):\n # if entity has an extension then ask the extension for its schema\n column_name: str\n mapper: AutoMapperDataTypeBase\n for column_name, mapper in entity.get_child_mappers().items():\n if column_name == \"extension\":\n extension_schema: Union[StructType, DataType, None]\n extension_schema = mapper.get_schema(\n include_extension=include_extension\n )\n if extension_schema is not None:\n if (\n isinstance(extension_schema, StructType)\n and len(extension_schema.fields) > 0\n ):\n schema = StructType(\n [f for f in schema.fields if f.name != \"extension\"]\n + [extension_schema.fields[0]]\n )\n column_schema = (\n {f.name: f for f in schema.fields} if schema and use_schema else {}\n )\n\n self.generate_mappers(\n mappers_dict={\n key: value for key, value in entity.get_child_mappers().items()\n },\n column_schema=column_schema,\n include_null_properties=include_null_properties or use_schema,\n skip_schema_validation=skip_schema_validation,\n skip_if_columns_null_or_empty=skip_if_columns_null_or_empty,\n )\n","sub_path":"spark_auto_mapper/automappers/complex.py","file_name":"complex.py","file_ext":"py","file_size_in_byte":2516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"630546908","text":"import json\nimport zipfile\nimport pickle\nfrom datetime import datetime\n\nairlines = {\"KLM\": 56377143, \"AirFrance\": 106062176, \"British_Airways\": 18332190, \"AmericanAir\": 22536055, \"Lufthansa\": 124476322,\n \"AirBerlin\": 26223583, \"Airberlin Assist\": 2182373406, \"easyJet\": 38676903, \"RyanAir\": 1542862735,\n \"SingaporeAir\": 253340062, \"Qantas\": 218730857, \"EtihadAirways\": 45621423, \"VirginAtlantic\": 20626359}\n\n\ndef get_airline_data(json_name):\n dir_name = \"C:/Users/20184025/OneDrive - TU Eindhoven/Documents/2018-2019/Q4/DBL Data Challenge/\"\n json_dir = dir_name + json_name\n airline_data = []\n with open(json_dir) as handle:\n for line in handle:\n airline_data.append(json.loads(line))\n airline_data = airline_data[0]\n print(airline_data[0])\n print(airline_data[-1])\n if airline_data[-1]['in_reply_to_status_id'] is None:\n print('correct')\n else:\n print('Wrong')\n print(len(airline_data))\n return airline_data\n\n\ndef split_tweets(airline_data):\n '''\n\n :param airline_data: list of tweets from one airline_name\n :return:\n '''\n original_tweets = []\n reply_tweets = []\n for tweet in airline_data:\n if \"in_reply_to_user_id\" in tweet.keys(): # does this work for original tweets, since this parameter might not exist\n reply_tweets.append(tweet)\n else:\n original_tweets.append(tweet)\n return (original_tweets, reply_tweets)\n\n\ndef get_conversations_old(original_tweets, reply_tweets):\n conversations = []\n # got to all original tweets and look for conversations\n for tweet in original_tweets:\n conversation_temp = [tweet]\n other_replies = []\n for reply_tweet in reply_tweets:\n # check if reply is reply to the tweet\n if reply_tweet[\"in_reply_to_user_id\"] == tweet[\"id\"]:\n conversation_temp.append(reply_tweet)\n other_replies = check_multiple_replies(other_replies, reply_tweets, reply_tweet)\n reply_tweets.drop(other_replies)\n for dropable in other_replies:\n reply_tweets.drop(dropable)\n for i in other_replies:\n conversation_temp.append(i)\n conversations.append(conversation_temp)\n return conversations\n\n\ndef check_multiple_replies(other_replies, reply_tweets, last_reply):\n for tweet in reply_tweets:\n if last_reply[\"id\"] == tweet[\"in_reply_to_user_id\"]:\n other_replies.append(tweet)\n last_reply = tweet\n check_multiple_replies(other_replies, reply_tweets, last_reply)\n return other_replies\n\n\ndef create_conversations(airline_data):\n # go to tweets backwards\n conversations = []\n conversations_done = []\n for tweet in reversed(airline_data):\n # check if tweet is part of a existing conversations\n conversation_not_exists = True\n # print(conversations_done)\n for conv in reversed(conversations):\n # print(conv)\n if conv[-1][\"in_reply_to_status_id\"] == tweet['id']:\n # then add to conversation\n conv.append(tweet)\n conversation_not_exists = False\n # check if tweet is the origanel\n if tweet['in_reply_to_status_id'] is None:\n # move conversation to done\n # print(conv)\n conversations_done.append(conv)\n conversations.remove(conv)\n\n # else make new conversation\n if conversation_not_exists:\n conversations.append([tweet])\n\n # cap the number of conversations to 4000 fith a 200 tweet margin\n if len(conversations) > 16200:\n # delete first hundred\n conversations = conversations[200:]\n\n print(len(conversations))\n # print(conversations)\n\n return conversations_done\n\n\ndef clean_conversations(convs):\n for conversation in reversed(convs): # reversed because it doesnt work other wise\n # if conversation is of length 1 drop it\n if len(conversation) == 1:\n convs.remove(conversation)\n\n return convs\n\n\ndef create_conversations_better(airline_data):\n \"\"\"\n\n :param airline_data: list of tweets of airline_data\n :return:\n \"\"\"\n conversations = []\n tweets_done = []\n for index, tweet in reversed(list(enumerate(airline_data))):\n # check if tweet is not origanel\n if tweet['in_reply_to_status_id'] is None:\n # continue because single tweets aren't conversations\n continue\n if tweet['id'] not in tweets_done:\n # create new conversations\n conversation = [tweet]\n # again loop throw all tweets and search for reply tweets\n for origanel in reversed(airline_data[:index]):\n if conversation[-1]['in_reply_to_status_id'] == origanel['id']:\n # add tweet to conversation and id to done's\n conversation.append(origanel)\n tweets_done.append(origanel['id'])\n if origanel['in_reply_to_status_id'] is None:\n # add conversations to list and break because, we reached the origanel tweet\n conversations.append(conversation)\n break\n # # check if conversations has properly finished\n # if conversation[-1]['in_reply_to_status_id'] is not None:\n # # this sh\n # print(conversation)\n if index % 1000 == 0:\n print(index)\n\n return conversations\n\n\ndef get_conversations():\n # get data\n airline_data = get_airline_data()\n # sort data on time\n startTime2 = datetime.now()\n airline_data_sorted = sorted(airline_data, key=lambda k: k['timestamp_ms'])\n print('Time to sort: ' + str(datetime.now() - startTime2))\n\n # create the conversations\n convs = create_conversations(airline_data_sorted)\n # cleane conversations of wrong ones\n cleaned_conversations = clean_conversations(convs)\n return cleaned_conversations\n\n\ndef get_conversations2(json_name):\n # get data\n airline_data = get_airline_data(json_name)\n # sort data on time\n startTime2 = datetime.now()\n airline_data_sorted = sorted(airline_data, key=lambda k: k['timestamp_ms'])\n print('Time to sort: ' + str(datetime.now() - startTime2))\n\n # create the conversations\n convs = create_conversations_better(airline_data_sorted)\n # cleane conversations of wrong ones\n # cleaned_conversations = clean_conversations(convs)\n return convs\n\n\ndef main(json_name):\n # conversations = get_conversations(split_tweets(get_airline_data()))\n startTime = datetime.now()\n conversations = get_conversations2(json_name + '.json')\n print('Time taken: ' + str(datetime.now() - startTime))\n\n # write to file\n with open(json_name + '_better', 'wb') as fp:\n pickle.dump(conversations, fp)\n\n # calculate length\n lenghts = []\n for conversation in conversations:\n # print(len(conversation))\n lenghts.append(len(conversation))\n\n print(len(lenghts))\n print(sum(lenghts) / len(lenghts))\n\n\ndef check_create_better():\n airline_data = [{'id': 1, 'in_reply_to_status_id': None},\n {'id': 3, 'in_reply_to_status_id': 1},\n {'id': 4, 'in_reply_to_status_id': None},\n {'id': 6, 'in_reply_to_status_id': 3}]\n conversations = create_conversations_better(airline_data)\n print(conversations)\n\n\nif __name__ == '__main__':\n # check_create_better()\n # main('KLM')\n for airline in airlines:\n main(airline)\n","sub_path":"Camiel/conversations.py","file_name":"conversations.py","file_ext":"py","file_size_in_byte":7687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"491740411","text":"from keras import layers\nfrom keras import models\nfrom keras.models import load_model\n\nfrom keras import optimizers\nfrom keras.preprocessing.image import ImageDataGenerator\nimport keras.applications as applications\n\nimport matplotlib.pyplot as plt \nimport os \n\n\"\"\"\nDESCRIPTION OF MODEL:\nCNN model with VGG16 as base. \nFine-tune the last 3 convolutional layers\nNo regularization or dropout of any sort, yet\nTrainined on small images, no weighting of luminosity population\n\"\"\"\n\n\n# (A) Define parameters for model\ninput_shape = (34, 34)\nsource_data = \"../../data_processing/lagos_p34_z1\"\nbatch_size = 100\nsteps_per_epoch = 300\nepochs = 30\nvalidation_steps = 150\nmod_name = \"cnn_1\"\ntest_steps = 150\n\nconv_base = applications.VGG16(weights='imagenet', include_top=False)\ntune_layer_treshold = \"block5_conv1\"\n\n\n# (B) Build layers of model on top of the convolutional base\nmodel = models.Sequential()\nmodel.add(conv_base)\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(512, activation='relu'))\nmodel.add(layers.Dense(3, activation='softmax'))\n\n# (C) Freeze conv base, compile, and Optimization\nconv_base.trainable = False\nmodel.compile(loss='categorical_crossentropy', optimizer=optimizers.RMSprop(lr=1e-4), metrics=['acc'])\n\n\n# (D.a) Training/validation with the newly added dense layer then save model to .h5 file\ntrain_datagen = ImageDataGenerator(rescale=1./255)\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\ntrain_dir = source_data + \"/training\"\nvalidation_dir = source_data + \"/validation\"\n\ntrain_generator = train_datagen.flow_from_directory(\n train_dir,\n target_size= input_shape,\n batch_size = batch_size,\n class_mode = 'categorical')\n\nvalidation_generator = test_datagen.flow_from_directory(\n validation_dir,\n target_size= input_shape,\n batch_size = batch_size,\n class_mode = 'categorical')\n\nhistory = model.fit_generator(\n train_generator, steps_per_epoch=steps_per_epoch, epochs=epochs, \n validation_data=validation_generator, validation_steps=validation_steps)\n\nsave_to = \"output/{}/\".format(mod_name)\n\nif not os.path.exists(save_to):\n os.makedirs(save_to)\n\nmodel.save(save_to+'cnn_base.h5')\n\n# (E) Save out graphs of training/validation loss & accuracy\nacc = history.history['acc']\nval_acc = history.history['val_acc']\n\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(1, len(acc)+1)\n\nplt.plot(epochs, acc, 'bo', label='Training acc')\nplt.plot(epochs, val_acc, 'b', label='Validation acc')\nplt.title('Training and validation accuracy - new FC layer')\nplt.legend()\n\nplt.figure()\n\nplt.plot(epochs, loss, 'bo', label='Training loss')\nplt.plot(epochs, val_loss, 'b', label='Validation loss')\nplt.title('Training and validation loss - new FC layer')\nplt.legend()\n\nplt.savefig(save_to + 'performance_base.png')\n\n# (D.b) Unfreeze some of the conv base\nconv_base.trainable = True \n\nset_trainable = False \nfor layer in conv_base.layers:\n if layer.name == tune_layer_treshold:\n set_trainable = True \n if set_trainable:\n layer.trainable = True \n else:\n layer.trainable = False\n\n# (D.c) Retrain the unfrozen base and new layer, with a slow learning rate\nmodel.compile(loss='categorical_crossentropy', optimizer=optimizers.RMSprop(lr=1e-5), metrics=['acc'])\n\nhistory_final = model.fit_generator(\n train_generator, steps_per_epoch=steps_per_epoch, epochs=epochs, \n validation_data=validation_generator, validation_steps=validation_steps)\n\nmodel.save(save_to+'cnn.h5')\n\nacc_final = history_final.history['acc']\nval_acc_final = history_final.history['val_acc']\n\nloss_final = history_final.history['loss']\nval_loss_final = history_final.history['val_loss']\n\nepochs = range(1, len(acc)+1)\n\nplt.plot(epochs, acc_final, 'bo', label='Training acc')\nplt.plot(epochs, val_acc_final, 'b', label='Validation acc')\nplt.title('Training and validation accuracy - finetune')\nplt.legend()\n\nplt.figure()\n\nplt.plot(epochs, loss_final, 'bo', label='Training loss')\nplt.plot(epochs, val_loss_final, 'b', label='Validation loss')\nplt.title('Training and validation loss - finetune')\nplt.legend()\n\nplt.savefig(save_to + 'performance_full.png')\n\n\n# (F) Save a summary of the model structure along with performance\ntest_generator = test_datagen.flow_from_directory(\n test_dir,\n target_size=input_shape,\n batch_size=batch_size,\n class_mode='categorical')\n\ntest_loss, test_acc = model.evaluate_generator(test_generator, steps=test_steps)\n\nwith open(save_to + 'structure.txt', 'w') as f:\n\n\n b = conv_base.summary()\n f.write(b)\n f.write('\\n\\n')\n\n s = model.summary()\n f.write(s)\n f.write('\\n\\n')\n f.write(\"TEST ACCURACY: {}\\n\".format(test_acc))\n f.write(\"TEST LOSS: {}\\n\".format(test_loss))\n\n\n\n\n# (F) Discard the last fully-connected layer\n # F.1 - calculate the feature vectors for each of the DHS observations\n # F.2 - run a regression of wealth index ~ feature vectors\n","sub_path":"modeling/cnn/cnn_1.py","file_name":"cnn_1.py","file_ext":"py","file_size_in_byte":4894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"507632281","text":"#!/usr/bin/python3\n# -*- coding:utf-8 -*-\n\nimport epd4in2b\nimport hashlib\nimport json\nimport os\nimport time\nimport traceback\nfrom PIL import Image,ImageDraw,ImageFont\nfrom datetime import datetime, timedelta, timezone\nfrom icalevents.icalevents import events\nfrom icalevents.icalparser import Event\n\ncurrentEvent = None\nnextEvent = None\ncalendarCache = []\n\ndef eventsequal(eventA: Event, eventB: Event) -> bool:\n return eventA.uid == eventB.uid and eventA.start == eventB.start and eventA.end == eventB.end\n\ndef updatedisplay(reloadit=False, clearfirst=False):\n try:\n global currentEvent, nextEvent, calendarCache\n path = os.path.dirname(os.path.abspath(__file__))\n epd = epd4in2b.EPD()\n epd.init()\n if clearfirst:\n epd.Clear()\n epd.sleep()\n reloadit = True\n unsetNext = True\n try:\n icalurl=open(path+\"/ICAL_URL\", \"r\")\n calendar=events(icalurl.readline())\n calendarCache=calendar\n except:\n calendar=calendarCache\n index = 0\n calendar.sort(key=lambda x: x.start)\n for event in calendar:\n if index == 0:\n if event.start < datetime.now(timezone.utc): # room is occupied at the moment, event is current event\n reloadit = reloadit or currentEvent == None or not eventsequal(event, currentEvent)\n currentEvent = event\n else: # room is free, event is next event\n if currentEvent: # old event still in cache\n currentEvent = None\n reloadit = True\n unsetNext = False\n reloadit = reloadit or nextEvent == None or not eventsequal(event, nextEvent)\n nextEvent = event\n break\n if index == 1:\n reloadit = reloadit or nextEvent == None or not eventsequal(event, nextEvent)\n nextEvent = event\n unsetNext = False\n break\n index=index+1\n if unsetNext and nextEvent:\n nextEvent = None\n reloadit = True\n if (nextEvent or currentEvent) and len(calendar) == 0:\n nextEvent = None\n currentEvent = None\n reloadit = True\n HBlackimage = Image.new('1', (epd4in2b.EPD_HEIGHT, epd4in2b.EPD_WIDTH), 255)\n HRedimage = Image.new('1', (epd4in2b.EPD_HEIGHT, epd4in2b.EPD_WIDTH), 255)\n drawblack = ImageDraw.Draw(HBlackimage)\n drawred = ImageDraw.Draw(HRedimage)\n fontTiny = ImageFont.truetype(path+'/ProggyTiny.ttf', 16)\n fontSmall = ImageFont.truetype(path+'/ProggyClean.ttf', 16)\n fontBig = ImageFont.truetype(path+'/Roboto-Regular.ttf', 32)\n fontHuge = ImageFont.truetype(path+'/Roboto-Regular.ttf', 44)\n meetingimage = Image.open(path+'/meeting.bmp')\n if currentEvent:\n drawred.rectangle((1, 1, epd4in2b.EPD_HEIGHT - 2, epd4in2b.EPD_WIDTH - 41), fill = 0)\n x=20\n y=4\n drawred.text((x+48, y-2), 'BELEGT', font = fontBig, fill=1)\n drawred.bitmap(bitmap=meetingimage, xy=(x,y), fill=1)\n circimage = Image.open(path+'/circ14.bmp')\n drawred.bitmap(bitmap=circimage, xy=(x+10,y+0), fill=1)\n wrongwayimage = Image.open(path+'/wrongway.bmp')\n drawblack.bitmap(bitmap=wrongwayimage, xy=(x+11,y+1))\n drawred.text((8, epd4in2b.EPD_WIDTH-63), 'Noch bis ' + currentEvent.end.replace(tzinfo=timezone.utc).astimezone(tz=None).strftime(\"%H:%M\"), font = fontTiny, fill=1)\n if currentEvent.private:\n drawred.text((8, epd4in2b.EPD_WIDTH-52), 'privater Termin', font = fontTiny, fill=1)\n else:\n drawred.text((8, epd4in2b.EPD_WIDTH-52), currentEvent.summary[:32], font = fontTiny, fill=1)\n else:\n x=30\n y=14\n drawblack.bitmap(bitmap=meetingimage, xy=(x,y), fill=0)\n checkimage = Image.open(path+'/check.bmp')\n drawblack.bitmap(bitmap=checkimage, xy=(x+10,y+3), fill=0)\n drawblack.text((x+54, y-7), 'FREI', font = fontHuge, fill=0)\n drawblack.rectangle((0, 0, epd4in2b.EPD_HEIGHT - 1, epd4in2b.EPD_WIDTH - 40), outline = 0)\n if nextEvent:\n hourstillevent = (nextEvent.start - datetime.now(timezone.utc)).seconds // 3600\n minutestillevent = (nextEvent.start - datetime.now(timezone.utc)).seconds // 60 % 60\n if nextEvent.private:\n drawblack.text((8, epd4in2b.EPD_WIDTH - 18), 'privater Termin', font = fontSmall)\n else:\n drawblack.text((8, epd4in2b.EPD_WIDTH - 18), nextEvent.summary[:28], font = fontSmall)\n if hourstillevent == 0 and minutestillevent <= 15:\n reloadit = True\n drawblack.text((8, epd4in2b.EPD_WIDTH - 32), 'Nächste Belegung in', font = fontTiny)\n drawred.text((8, epd4in2b.EPD_WIDTH - 32), ' ' + str(minutestillevent) + ' Minuten', font = fontTiny)\n drawred.text((9, epd4in2b.EPD_WIDTH - 32), ' ' + str(minutestillevent), font = fontTiny)\n else:\n drawblack.text((8, epd4in2b.EPD_WIDTH - 32), 'Nächste Belegung um ' + nextEvent.start.replace(tzinfo=timezone.utc).astimezone(tz=None).strftime(\"%H:%M\"), font = fontTiny)\n else:\n drawblack.text((8, epd4in2b.EPD_WIDTH - 26), 'Demnächst keine Belegung', font = fontSmall)\n if reloadit:\n epd.display(epd.getbuffer(HBlackimage.rotate(180)), epd.getbuffer(HRedimage.rotate(180)))\n epd.sleep()\n\n except:\n print('traceback.format_exc():\\n%s',traceback.format_exc())\n exit()\n\nupdatedisplay(True)\nwhile True:\n time.sleep(30)\n updatedisplay(clearfirst=(datetime.now().minute % 60 == 0))\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"457434073","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n :copyright: (C) 2010-2013 by Contrail Consortium.\n\"\"\"\n\nfrom threading import Thread\nfrom xml.dom import minidom\nfrom tempfile import mkdtemp\nfrom shutil import rmtree\nimport zipfile, tempfile, stat, os.path\n\nfrom conpaas.services.webservers.manager.config import CodeVersion, JavaServiceConfiguration\nfrom conpaas.services.webservers.agent import client\nfrom conpaas.services.webservers.misc import archive_open, archive_get_members\nfrom conpaas.core.https.server import HttpErrorResponse, HttpJsonResponse\n\nfrom . import BasicWebserversManager, ManagerException\nfrom conpaas.core.expose import expose\nfrom conpaas.core import git\n\nclass JavaManager(BasicWebserversManager):\n \n def __init__(self, config_parser, **kwargs):\n BasicWebserversManager.__init__(self, config_parser)\n if kwargs['reset_config']:\n self._create_initial_configuration()\n \n def _update_code(self, config, nodes):\n for serviceNode in nodes:\n # Push the current code version via GIT if necessary\n if config.codeVersions[config.currentCodeVersion].type == 'git':\n _, err = git.git_push(git.DEFAULT_CODE_REPO, serviceNode.ip)\n if err:\n self.logger.debug('git-push to %s: %s' % (serviceNode.ip, err))\n\n try:\n if serviceNode.isRunningBackend: ## UPLOAD TOMCAT CODE TO TOMCAT\n client.updateTomcatCode(serviceNode.ip, 5555, config.currentCodeVersion, config.codeVersions[config.currentCodeVersion].type, os.path.join(self.code_repo, config.currentCodeVersion))\n if serviceNode.isRunningProxy or serviceNode.isRunningWeb:\n client.updatePHPCode(serviceNode.ip, 5555, config.currentCodeVersion, config.codeVersions[config.currentCodeVersion].type, os.path.join(self.code_repo, config.currentCodeVersion))\n except client.AgentException:\n self.logger.exception('Failed to update code at node %s' % str(serviceNode))\n self._state_set(self.S_ERROR, msg='Failed to update code at node %s' % str(serviceNode))\n return\n \n def _start_proxy(self, config, nodes):\n kwargs = {\n 'web_list': config.getWebTuples(),\n 'tomcat_list': config.getBackendTuples(),\n 'tomcat_servlets': self._get_servlet_urls(config.currentCodeVersion),\n }\n \n for proxyNode in nodes:\n try:\n if config.currentCodeVersion != None:\n client.createHttpProxy(proxyNode.ip, 5555,\n config.proxy_config.port,\n config.currentCodeVersion,\n **kwargs)\n except client.AgentException:\n self.logger.exception('Failed to start proxy at node %s' % str(proxyNode))\n self._state_set(self.S_ERROR, msg='Failed to start proxy at node %s' % str(proxyNode))\n raise\n \n def _update_proxy(self, config, nodes):\n kwargs = {\n 'web_list': config.getWebTuples(),\n 'tomcat_list': config.getBackendTuples(),\n 'tomcat_servlets': self._get_servlet_urls(config.currentCodeVersion),\n }\n \n for proxyNode in nodes:\n try:\n if config.currentCodeVersion != None:\n client.updateHttpProxy(proxyNode.ip, 5555,\n config.proxy_config.port,\n config.currentCodeVersion,\n **kwargs)\n except client.AgentException:\n self.logger.exception('Failed to update proxy at node %s' % str(proxyNode))\n self._state_set(self.S_ERROR, msg='Failed to update proxy at node %s' % str(proxyNode))\n raise\n \n def _start_backend(self, config, nodes):\n for serviceNode in nodes:\n try:\n client.createTomcat(serviceNode.ip, 5555, config.backend_config.port)\n except client.AgentException:\n self.logger.exception('Failed to start Tomcat at node %s' % str(serviceNode))\n self._state_set(self.S_ERROR, msg='Failed to start Tomcat at node %s' % str(serviceNode))\n raise\n \n def _stop_backend(self, config, nodes):\n for serviceNode in nodes:\n try: client.stopTomcat(serviceNode.ip, 5555)\n except client.AgentException:\n self.logger.exception('Failed to stop Tomcat at node %s' % str(serviceNode))\n self._state_set(self.S_ERROR, msg='Failed to stop Tomcat at node %s' % str(serviceNode))\n raise\n \n @expose('GET')\n def get_service_info(self, kwargs):\n if len(kwargs) != 0:\n return HttpErrorResponse(ManagerException(ManagerException.E_ARGS_UNEXPECTED, kwargs.keys()).message)\n return HttpJsonResponse({'state': self._state_get(), 'type': 'JAVA'})\n\n @expose('GET')\n def get_configuration(self, kwargs):\n if len(kwargs) != 0:\n return HttpErrorResponse(ManagerException(ManagerException.E_ARGS_UNEXPECTED, kwargs.keys()).message)\n config = self._configuration_get()\n return HttpJsonResponse({'codeVersionId': config.currentCodeVersion})\n\n @expose('POST') \n def update_java_configuration(self, kwargs):\n if 'codeVersionId' not in kwargs:\n return HttpErrorResponse(ManagerException(ManagerException.E_ARGS_MISSING, 'at least one of \"codeVersionId\"').message)\n codeVersionId = kwargs.pop('codeVersionId')\n config = self._configuration_get()\n \n if len(kwargs) != 0:\n return HttpErrorResponse(ManagerException(ManagerException.E_ARGS_UNEXPECTED, kwargs.keys()).message)\n \n dstate = self._state_get()\n if dstate == self.S_INIT or dstate == self.S_STOPPED:\n if codeVersionId: config.currentCodeVersion = codeVersionId\n self._configuration_set(config)\n elif dstate == self.S_RUNNING:\n self._state_set(self.S_ADAPTING, msg='Updating configuration')\n Thread(target=self.do_update_configuration, args=[config, codeVersionId]).start()\n else:\n return HttpErrorResponse(ManagerException(ManagerException.E_STATE_ERROR).message)\n return HttpJsonResponse()\n \n def _get_servlet_urls_from_webxml(self, webxml_filename):\n ret = []\n doc = minidom.parse(webxml_filename)\n mappers = doc.getElementsByTagName('servlet-mapping')\n for m in mappers:\n url = m.getElementsByTagName('url-pattern')[0].firstChild.wholeText\n ret.append(url)\n return ret\n\n def _get_servlet_urls(self, codeVersionId):\n ret = []\n archname = os.path.join(self.code_repo, codeVersionId)\n\n if os.path.isfile(archname):\n # File-based code upload\n arch = archive_open(archname)\n filelist = archive_get_members(arch)\n if 'WEB-INF/web.xml' in filelist:\n tmp_dir = mkdtemp()\n arch.extract('WEB-INF/web.xml', path=tmp_dir)\n ret = self._get_servlet_urls_from_webxml(os.path.join(tmp_dir, 'WEB-INF', 'web.xml'))\n rmtree(tmp_dir, ignore_errors=True)\n\n return ret\n\n # git-based code upload\n webxml_filename = os.path.join(archname, 'WEB-INF', 'web.xml')\n if os.path.isfile(webxml_filename):\n ret = self._get_servlet_urls_from_webxml(webxml_filename)\n\n return ret\n \n def do_update_configuration(self, config, codeVersionId):\n if codeVersionId != None:\n config.prevCodeVersion = config.currentCodeVersion\n config.currentCodeVersion = codeVersionId\n self._update_code(config, config.serviceNodes.values())\n self._update_web(config, config.getWebServiceNodes())\n self._update_proxy(config, config.getProxyServiceNodes())\n \n self._state_set(self.S_RUNNING)\n self._configuration_set(config)\n \n def _create_initial_configuration(self):\n config = JavaServiceConfiguration()\n config.backend_count = 0\n config.web_count = 0\n config.proxy_count = 1\n \n if not os.path.exists(self.code_repo):\n os.makedirs(self.code_repo)\n \n fileno, path = tempfile.mkstemp()\n fd = os.fdopen(fileno, 'w')\n fd.write('''\n \n Welcome to ConPaaS!\n \n \n

Welcome to ConPaaS!

\n \n ''')\n fd.close()\n os.chmod(path, stat.S_IRWXU | stat.S_IROTH | stat.S_IXOTH)\n \n if len(config.codeVersions) > 0: return\n zfile = zipfile.ZipFile(os.path.join(self.code_repo,'code-default'), mode='w')\n zfile.write(path, 'index.html')\n zfile.close()\n os.remove(path)\n config.codeVersions['code-default'] = CodeVersion('code-default', 'code-default.war', 'zip', description='Initial version')\n config.currentCodeVersion = 'code-default'\n self._configuration_set(config)\n self._state_set(self.S_INIT)\n","sub_path":"conpaas-services/src/conpaas/services/webservers/manager/internal/java.py","file_name":"java.py","file_ext":"py","file_size_in_byte":8517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"349072259","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n\n\ndef main():\n t = np.arange(0, 1.0, 0.01)\n s = np.sin(2 * np.pi * t)\n plt.rcParams['lines.color'] = 'pink'\n plt.plot(t, s)\n \n c = np.cos(2 * np.pi * t)\n plt.rcParams['lines.linewidth'] = 4\n plt.plot(t, c)\n\n plt.show()\n\n\nif __name__ == \"__main__\":\n main()\n\n\n\n\n# vim:cin:et:ts=4:sts=4:sw=4:tw=98:ft=python:ff=unix:fenc=utf-8:\n# EOF\n\n","sub_path":"python/pdvc/01-Preparing/mpl_args.py","file_name":"mpl_args.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"469622032","text":"from collections import Counter, defaultdict\n\n\n'''Strings: Making Anagrams'''\n\n\ndef makeAnagram(a, b):\n\n a = Counter(a)\n b = Counter(b)\n return sum(((a | b) - (a & b)).values())\n\n\n'''Alternating Characters'''\n\n\ndef alternatingCharacters(s):\n count = 0\n lst = [i for i in s]\n for i in range(len(lst)-1):\n if lst[i] != lst[i+1]:\n continue\n else:\n count += 1\n\n return count\n\n\n'''Sherlock and the Valid String'''\n\n\ndef isValid(s):\n c = Counter(s)\n count = 0\n l = []\n for v in c.values():\n l.append(v)\n for i in range(len(l) - 1):\n if l[0] == l[i+1]:\n continue\n else:\n count += 1\n return ('YES' if count <= 1 else 'NO')\n\n\n'''Special String Again'''\n\n\ndef substrCount(n, s):\n answer = 0\n same_char = [0]*n\n i = 0\n while (i < n):\n same_char_count = 1\n j = i+1\n while(j < n):\n if(s[i] != s[j]):\n break\n same_char_count += 1\n j += 1\n answer += int(same_char_count*(same_char_count+1)/2)\n same_char[i] = same_char_count\n i = j\n for j in range(1, n):\n if (s[j] == s[j-1]):\n same_char[j] = same_char[j-1]\n if (j > 0 and j < (n-1) and (s[j-1] == s[j+1] and s[j] != s[j-1])):\n answer += (same_char[j-1] if (same_char[j-1] <\n same_char[j+1]) else same_char[j+1])\n return answer\n\n\n'''Common Child'''\n\n# switch to Pypy3 to pass all cases.\n\n\ndef commonChild(s1, s2):\n\n z = [[0 for j in range(len(s2)+1)] for i in range(len(s1)+1)]\n for i, a in enumerate(s1):\n for j, b in enumerate(s2):\n if a == b:\n z[i+1][j+1] = z[i][j] + 1\n else:\n z[i+1][j+1] = \\\n max(z[i+1][j], z[i][j+1])\n return z[-1][-1]\n","sub_path":"h-rank_strings.py","file_name":"h-rank_strings.py","file_ext":"py","file_size_in_byte":1867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"415896361","text":"# input = [4, 6, 2, 9, 1]\n\n\n# def bubble_sort(array):\n# for i in range(len(input)-1):\n# for j in range(len(input) - i -1):\n# if input[j] > input[j+1]:\n# input[j], input[j+1] = input[j+1],input[j]\n# return\n\n\n# bubble_sort(input)\n# print(input) # [1, 2, 4, 6, 9] 가 되어야 합니다!\n\n\n\n# input = [4, 6, 2, 9, 1]\n# n= len(input)\n\n\n# def selection_sort(array):\n# for i in range(n-1):\n# min_index=i \n# for j in range(n-i):\n# if array[i+j] < array[min_index]:\n# min_index = i+j\n# array[min_index], array[i] = array[i] , array[min_index]\n\n# return\n\n\n# selection_sort(input)\n# print(input) # [1, 2, 4, 6, 9] 가 되어야 합니다!\n\n\n\n\n# input = [4, 6, 2, 9, 1]\n# n= len(input)\n\n# def selection_sort(array):\n# for i in range(1, n):\n# for j in range(i): #i가 늘어날 때마다 j에서 반복하는 횟수가 증가\n# if array[i-j-1] > array[i-j]:\n# array[i - j- 1], array[i-j] = array[i-j] , array[i-j-1]\n# else:\n# break\n\n# return\n\n\n# selection_sort(input)\n# print(input) # [1, 2, 4, 6, 9] 가 되어야 합니다!\n\n\n\n\n\narray_a = [1, 2, 3, 5]\narray_b = [4, 6, 7, 8]\n\n\ndef merge(array1, array2):\n array_c=[]\n array1_index = 0\n array2_index = 0\n while array1_index < len(array1) and array2_index < len(array2):\n if array1[array1_index] < array2[array2_index]:\n array_c.append(array1[array1_index])\n array1_index += 1\n else:\n array_c.append(array2[array2_index])\n array2_index += 1\n if array1_index == len(array1):\n while array2_index < len(array2):\n array_c.append(array2[array2_index])\n array2_index += 1\n\n if array2_index == len(array2):\n while array1_index < len(array1):\n array_c.append(array1[array1_index])\n array1_index += 1\n\n return array_c\n\n\nprint(merge(array_a, array_b)) # [1, 2, 3, 4, 5, 6, 7, 8] 가 되어야 합니다!\n\n","sub_path":"bubblesort.py","file_name":"bubblesort.py","file_ext":"py","file_size_in_byte":2052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"120589070","text":"import warnings\n\nfrom keras.callbacks import ModelCheckpoint\nfrom tensorflow.python.lib.io import file_io\n\n'''Taken from and modified:\nhttps://github.com/keras-team/keras/blob/tf-keras/keras/callbacks.py\n'''\n\n\nclass ModelCheckpointGC(ModelCheckpoint):\n\n def on_epoch_end(self, epoch, logs=None):\n logs = logs or {}\n self.epochs_since_last_save += 1\n if self.epochs_since_last_save >= self.period:\n self.epochs_since_last_save = 0\n filepath = self.filepath.filepath.format(epoch=epoch, **logs)\n if self.save_best_only:\n current = logs.get(self.monitor)\n if current is None:\n warnings.warn('Can save best model only with %s available, '\n 'skipping.' % (self.monitor), RuntimeWarning)\n else:\n if self.monitor_op(current, self.best):\n if self.verbose > 0:\n print('Epoch %05d: %s improved from %0.5f to %0.5f,'\n ' saving model to %s'\n % (epoch, self.monitor, self.best,\n current, filepath))\n self.best = current\n if self.save_weights_only:\n self.model.save_weights(filepath, overwrite=True)\n else:\n self.model.save(filepath.split(\"/\")[-1])\n with file_io.FileIO(filepath.split(\"/\")[-1], mode='rb') as input_f:\n with file_io.FileIO(filepath, mode='wb+') as output_f:\n output_f.write(input_f.read())\n else:\n if self.verbose > 0:\n print('Epoch %05d: %s did not improve' %\n (epoch, self.monitor))\n else:\n if self.verbose > 0:\n print('Epoch %05d: saving model to %s' % (epoch, filepath))\n if self.save_weights_only:\n self.model.save_weights(filepath, overwrite=True)\n else:\n self.model.save(filepath.split(\"/\")[-1])\n with file_io.FileIO(filepath.split(\"/\")[-1], mode='rb') as input_f:\n with file_io.FileIO(filepath, mode='wb+') as output_f:\n output_f.write(input_f.read())","sub_path":"trainer/util/ModelCheckpointGc.py","file_name":"ModelCheckpointGc.py","file_ext":"py","file_size_in_byte":2486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"394385987","text":"from __future__ import absolute_import\n\nfrom django.conf import settings\nfrom django.core.exceptions import ObjectDoesNotExist, ValidationError\nfrom django.db import models\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.auth.decorators import user_passes_test\nfrom django.shortcuts import get_object_or_404, render_to_response\nfrom django.template import RequestContext\nfrom django.template.response import TemplateResponse\nfrom django.http import Http404, HttpResponse, HttpResponseNotAllowed, HttpResponseRedirect\nfrom django.utils.encoding import force_text\nfrom django.utils.html import escape\nfrom django.views.decorators.csrf import csrf_protect\nfrom django.views.decorators.http import require_POST\n\nimport comments\nfrom comments import signals\nfrom comments import utils\nfrom comments.views.utils import next_redirect, confirmation_view\nfrom comments.utils import CommentPostBadRequest\n\nCOMMENT_MODEL = comments.get_model()\nCOMMENT_FORM = comments.get_form()\n\ndef view(request, comment_pk=None, *args, **kwargs):\n comment_url = utils.get_comment_url(comment_pk=comment_pk, request=request)\n if comment_url:\n return HttpResponseRedirect(comment_url)\n else:\n raise Http404\n\n@csrf_protect\ndef edit(request, comment_pk=None, parent_pk=None, content_type=None, object_pk=None, next=None, *args, **kwargs):\n \"\"\"\n Edit or create a comment.\n Displays and processes the comment model form\n\n If HTTP POST is present it processes and adds / edits comment.\n If ``POST['submit'] == \"preview\"`` or if there are\n errors a preview template, ``comments/preview.html``, will be rendered.\n\n \"\"\"\n\n is_ajax = request.GET.get('is_ajax') and '_ajax' or ''\n\n if request.POST:\n form_data = request.POST.copy()\n\n next = form_data.get(\"next\", next)\n\n try:\n form = COMMENT_FORM(data=form_data,\n comment_pk=comment_pk,\n parent_pk=parent_pk,\n ctype=content_type,\n object_pk=object_pk,\n request=request,\n **kwargs)\n except COMMENT_MODEL.DoesNotExist:\n return HttpResponse(\"Comment does not exist\", status=404)\n\n # Make sure user has correct permissions to change the comment,\n # or return a 401 Unauthorized error.\n if form.is_new():\n if not form.can_create():\n return HttpResponse(\"Unauthorized\", status=401)\n else:\n if not form.can_edit():\n return HttpResponse(\"Unauthorized\", status=401)\n\n if form.security_errors():\n # NOTE: security hash fails!\n return CommentPostBadRequest(\n \"The comment form failed security verification: %s\" % \\\n escape(str(form.security_errors())))\n\n # If there are errors, or if a preview is requested\n if form.errors:\n app_label, model_name = (form.instance.content_type.app_label, form.instance.content_type.model)\n template_list = [\n \"comments/%s_%s_edit_form%s.html\" % (app_label, model_name, is_ajax),\n \"comments/%s_edit_form%s.html\" % (app_label, is_ajax),\n \"comments/edit_form%s.html\" % is_ajax,\n ]\n\n return render_to_response(\n template_list, {\n \"comment_obj\": form.instance,\n \"comment\": form.data.get(\"comment\", \"\"),\n \"form\": form,\n \"next\": next,\n },\n RequestContext(request, {})\n )\n\n if form.is_valid():\n # Save the comment and signal that it was saved\n result = form.save()\n # Get comment url\n if not next:\n next = utils.get_comment_url(comment_pk=result._get_pk_val(), request=request)\n return next_redirect(request, fallback=next)\n #_get_pk_val()\n else:\n # If we got here, raise Bad Request error.\n return CommentPostBadRequest(\"Could not complete request!\")\n\n else:\n title = 'Post a reply'\n # Construct the initial comment form\n try:\n form = COMMENT_FORM(request=request,\n comment_pk=comment_pk,\n parent_pk=parent_pk,\n ctype=content_type,\n object_pk=object_pk,\n **kwargs)\n except COMMENT_MODEL.DoesNotExist:\n return HttpResponse(\"Comment does not exist\", status=404)\n\n\n app_label, model_name = (form.instance.content_type.app_label, form.instance.content_type.model)\n template_list = [\n \"comments/%s_%s_edit_form%s.html\" % (app_label, model_name, is_ajax),\n \"comments/%s_edit_form%s.html\" % (app_label, is_ajax),\n \"comments/edit_form%s.html\" % is_ajax,\n ]\n return TemplateResponse(request, template_list, {\n \"form\" : form\n })\n\ncomment_done = confirmation_view(\n template=\"comments/posted.html\",\n doc=\"\"\"Display a \"comment was posted\" success page.\"\"\"\n)\n","sub_path":"comments/views/comment.py","file_name":"comment.py","file_ext":"py","file_size_in_byte":5284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"352709523","text":"import torch\nimport torch.nn as nn\nfrom src.models.MLP import MLP\n\nclass RelationNetwork(nn.Module):\n\n def __init__(self, query_dim, hidden_dims_g, output_dim_g, drops_g, drop_prob_g, hidden_dims_f, output_dim_f, drops_f, drop_prob_f, batch_size, device):\n '''\n :param object_dim: Equal to LSTM hidden dim. Dimension of the single object to be taken into consideration from g.\n '''\n\n super(RelationNetwork, self).__init__()\n\n self.query_dim = query_dim\n self.input_dim_g = self.query_dim # this changed for LSTM\n\n self.hidden_dims_g = hidden_dims_g\n self.output_dim_g = output_dim_g\n self.drops_g = drops_g\n self.drop_prob_g = drop_prob_g\n \n self.input_dim_f = self.output_dim_g\n self.hidden_dims_f = hidden_dims_f\n self.output_dim_f = output_dim_f\n self.drops_f = drops_f\n self.drop_prob_f = drop_prob_f\n\n self.batch_size = batch_size\n self.device = device\n\n self.g = MLP(self.input_dim_g, self.hidden_dims_g, self.output_dim_g, self.drops_g, nonlinear=True, drop_prob=self.drop_prob_g)\n self.f = MLP(self.input_dim_f, self.hidden_dims_f, self.output_dim_f, self.drops_f, nonlinear=True, drop_prob=self.drop_prob_f)\n\n def forward(self, q=None):#, objectNums=0):\n '''\n :param q: (batch, length_q) query, optional.\n '''\n g = self.g(q)\n out = self.f(g) # (output_dim_f)\n\n return out\n","sub_path":"src/models/RN_image_for_LSTM.py","file_name":"RN_image_for_LSTM.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"576852975","text":"import utitls\nimport time\nimport traceback\nimport os\nimport signal\n\nfrom login import login\nfrom bilibiliProxy import BilibiliProxy\nfrom subprocessOp import _forwardStream_sync, _getYoutube_m3u8_sync, async_forwardStream\nimport questInfo\nfrom myRequests import subscribe\n\ndef bilibiliStartLive(channelId, room_title, area_id=None):\n curSub = utitls.getSubInfoWithSubChannelId(channelId)\n curBiliAccCookie = curSub.get('bilibili_cookiesStr', \"\")\n\n tmp_area_id = area_id\n if tmp_area_id == None:\n tmp_area_id = curSub.get('bilibili_areaid', '33')\n\n b = BilibiliProxy(curBiliAccCookie)\n if b.getAccInfo() == None:\n #relogin\n if curSub['login_type'] == 'account':\n tmp_username, tmp_password = curSub.get('username'), curSub.get('password')\n if tmp_username and tmp_password:\n curSub['bilibili_cookiesStr'] = login(tmp_username, tmp_password)\n utitls.setSubInfoWithSubChannelId(channelId, curSub)\n bilibiliStartLive(channelId, room_title, area_id)\n return #retry the StartLive. TODO Maybe limit the retry time?\n\n t_room_id = b.getLiveRoomId()\n # b.stopLive(t_room_id) #Just don't care the Live status, JUST STARTLIVE\n # b.updateRoomTitle(t_room_id, room_title) #Maybe just ignore changing the title\n rtmp_link = b.startLive(t_room_id, tmp_area_id)\n\n if curSub.get('auto_send_dynamic') and rtmp_link and questInfo._getObjWithRTMPLink(rtmp_link) is None:\n if curSub.get('dynamic_template'):\n b.send_dynamic(curSub['dynamic_template']).replace('${roomUrl}', 'https://live.bilibili.com/' + t_room_id)\n else:\n b.send_dynamic('转播开始了哦~')\n return b, t_room_id, rtmp_link\n\n__g_try_get_youtube_list = []\ndef Async_forwardToBilibili(channelId, link, room_title='Testing Title', area_id=None, isSubscribeQuest=True):\n utitls.runFuncAsyncThread(_forwardToBilibili_Sync, (channelId, link, room_title, area_id, isSubscribeQuest))\ndef _forwardToBilibili_Sync(channelId, link, room_title, area_id=None, isSubscribeQuest=True):\n global __g_try_get_youtube_list\n if link in __g_try_get_youtube_list:\n return\n\n __g_try_get_youtube_list.append(link)\n resloveURLOK = False\n tmp_retryTime = 30\n while tmp_retryTime > 0:\n if 'youtube.com/' in link or 'youtu.be/' in link:\n m3u8Link, title, err, errcode = _getYoutube_m3u8_sync(link)\n if errcode == 999:\n # this is just a video upload, so just finish it\n __g_try_get_youtube_list.remove(link)\n return\n elif errcode == 0:\n # link = m3u8Link #just to check is can use, _forwardStream_sync will access the title and questInfo\n resloveURLOK = True\n break\n else:\n tmp_retryTime -= 1\n time.sleep(60)\n else:\n utitls.myLogger('_forwardToBilibili_Sync LOG: Unsupport ForwardLink:' + link)\n __g_try_get_youtube_list.remove(link)\n return\n __g_try_get_youtube_list.remove(link)\n\n if resloveURLOK:\n b, t_room_id, rtmp_link = bilibiliStartLive(channelId, room_title, area_id)\n if rtmp_link: #kill the old proccess\n tmp_quest = questInfo._getObjWithRTMPLink(rtmp_link)\n if tmp_quest != None:\n try:\n os.kill(tmp_quest.get('pid', None), signal.SIGKILL)\n except Exception:\n utitls.myLogger(traceback.format_exc())\n questInfo.removeQuest(rtmp_link)\n # force stream\n _forwardStream_sync(link, rtmp_link, isSubscribeQuest)\n\n\n\ndef Async_subscribeTheList():\n utitls.runFuncAsyncThread(subscribeTheList_sync, ())\ndef subscribeTheList_sync():\n time.sleep(10) #wait the server start preparing\n while True:\n subscribeList = utitls.configJson().get('subscribeList', [])\n ip = utitls.configJson().get('serverIP')\n port = utitls.configJson().get('serverPort')\n for item in subscribeList:\n tmp_subscribeId = item.get('youtubeChannelId', \"\")\n if tmp_subscribeId != \"\":\n tmp_callback_url = 'http://{}:{}/subscribe'.format(ip, port)\n subscribe(tmp_callback_url, tmp_subscribeId)\n time.sleep(3600 * 24 * 4) #update the subscribe every 4 Days\n\n\ndef restartOldQuests():\n for quest in questInfo._getQuestList():\n rtmp_link = quest.get('rtmpLink')\n questInfo.updateQuestInfo('isRestart', True, rtmp_link)\n async_forwardStream(\n quest.get('forwardLinkOrign'),\n rtmp_link,\n quest.get('isSubscribeQuest')\n )\n","sub_path":"AutoOperate.py","file_name":"AutoOperate.py","file_ext":"py","file_size_in_byte":4730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"419756315","text":"import sys\nimport os\n\nPACKAGE_PARENT = '..'\nSCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))\nsys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))\nimport shutil\nfrom hyperParaTuner.randSearch import RandomSearchJob\n\ndef remove_all_files(dirpath):\n for filename in os.listdir(dirpath):\n filepath = os.path.join(dirpath, filename)\n try:\n shutil.rmtree(filepath)\n except OSError:\n os.remove(filepath)\n\ndef HypeParameterSpace():\n hop_score_name = {'name': 'hop_model_name', 'type': 'fixed', 'value': 'DotProduct'}\n learning_rate = {'name': 'learning_rate', 'type': 'choice', 'values': [2e-5, 3e-5, 4e-5, 5e-5]}\n batch_size = {'name': 'batch_size', 'type': 'fixed', 'value': 8}\n accu_grad_batch = {'name': 'accu_grad_size', 'type': 'choice', 'values': [1]}\n sent_threshold = {'name': 'sent_threshold', 'type': 'choice', 'values': [0.925, 0.95]}\n task_name = {'name': 'task_name', 'type': 'choice', 'values': ['doc_sent_ans']} ##\n frozen_layer_num = {'name': 'frozen_layer', 'type': 'choice', 'values': [0]} #1, 2\n answer_span_weight = {'name': 'span_weight', 'type': 'choice', 'values': [0.2, 0.5, 1.0]}\n pair_score_weight = {'name': 'pair_score_weight', 'type': 'choice', 'values': [0]} #0.1, 0.2, 0.5, 1.0\n train_data_filtered = {'name': 'train_data_type', 'type': 'choice', 'values': [0]} # 0, 1, 2\n train_data_shuffler = {'name': 'train_shuffle', 'type': 'choice', 'values': [0]} # 0, 1\n with_graph_training = {'name': 'with_graph_training', 'type': 'choice', 'values': [0]}# 0, 1\n epochs = {'name': 'epoch', 'type': 'choice', 'values': [6]}\n #++++++++++++++++++++++++++++++++++\n search_space = [learning_rate, hop_score_name, with_graph_training, batch_size, epochs,\n sent_threshold, answer_span_weight, pair_score_weight, accu_grad_batch,\n task_name, frozen_layer_num, train_data_filtered, train_data_shuffler]\n search_space = dict((x['name'], x) for x in search_space)\n return search_space\n\ndef generate_random_search_bash(task_num):\n bash_save_path = '../gold_hotpot_jobs/'\n if os.path.exists(bash_save_path):\n remove_all_files(bash_save_path)\n if bash_save_path and not os.path.exists(bash_save_path):\n os.makedirs(bash_save_path)\n search_space = HypeParameterSpace()\n random_search_job =RandomSearchJob(search_space=search_space)\n for i in range(task_num):\n task_id, parameter_id = random_search_job.single_task_trial(42+i)\n with open(bash_save_path + 'gold_qa_run_' + task_id +'.sh', 'w') as rsh_i:\n command_i = 'bash goldqarun.sh ' + parameter_id\n rsh_i.write(command_i)\n print('{} jobs have been generated'.format(task_num))\n\nif __name__ == '__main__':\n generate_random_search_bash(task_num=5)","sub_path":"hyperParaTuner/goldhotpotRandSearchJob.py","file_name":"goldhotpotRandSearchJob.py","file_ext":"py","file_size_in_byte":2887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"206121949","text":"# forms.py\n\nfrom django import forms\nfrom django.forms import ModelForm\n\nfrom django.contrib.contenttypes.models import ContentType\n\nfrom .models import PretestAccount, PretestUser, PretestQuestionResponse, PretestUserCompletion\n\nclass LoginTokenForm(forms.Form):\n email = forms.EmailField()\n token = forms.CharField()\n\n def clean(self):\n data = super(LoginTokenForm, self).clean()\n try:\n pretester = PretestUser.objects.filter(email=data['email']).get(access_token=data['token'])\n except:\n raise forms.ValidationError('email and/or token were invalid.', code='invalid_creds')\n\n\nclass TokenGeneratorForm(forms.Form):\n account = forms.ModelChoiceField(queryset=PretestAccount.objects.all())\n num_tokens = forms.IntegerField(min_value=1)\n \n class Meta:\n fields = ['account', 'num_tokens']\n\n\nclass LanguageChoiceForm(ModelForm):\n\n def clean(self):\n data = super(LanguageChoiceForm, self).clean()\n if data['language_pref'] == None:\n raise forms.ValidationError('A language preference must be indicated.')\n\n class Meta:\n model = PretestUser\n fields = ['language_pref']\n\n\nclass PretestUserUpdateForm(ModelForm):\n account_selector = forms.ChoiceField(choices=[], required=False)\n \n def __init__(self, *args, **kwargs):\n super(PretestUserUpdateForm, self).__init__(*args, **kwargs)\n self.fields['email'].required = True\n if self.initial['users']:\n self.fields['account_selector'].choices = [(' ','--')] + [(i.id, str(i.first_name + ' ' + i.last_name + ', ' + i.email)) for i in self.initial['users']]\n self.fields['account_selector'].label = 'Choose an examinee from a list of users that are part of your organization. (optional):'\n else:\n del self.fields['account_selector']\n\n class Meta:\n model = PretestUser\n fields = ['account_selector', 'email', 'first_name', 'last_name', 'program_id']\n labels = {'email': 'Enter a valid email address for a pretest examinee.', 'program_id': 'Program ID (optional)'}\n\n\nclass PretestCompleteConfirmForm(ModelForm):\n\n class Meta:\n model = PretestUserCompletion\n fields = ['confirm_completed']\n widgets = {'confirm_completed': forms.HiddenInput(),}\n\n\nclass PretestQuestionResponseForm(ModelForm):\n def __init__(self, *args, **kwargs):\n super(PretestQuestionResponseForm, self).__init__(*args, **kwargs)\n try:\n self.fields['response'] = self.initial['question'].get_input_widget()\n except Exception as e:\n return\n \n class Meta:\n model = PretestQuestionResponse\n fields = ['pretestuser', 'content_type', 'object_id', 'response']\n widgets = {\n 'pretestuser': forms.HiddenInput(),\n 'content_type': forms.HiddenInput(),\n 'object_id': forms.HiddenInput()\n }\n\n\nclass PretestResponseGradeForm(ModelForm):\n class Meta:\n model = PretestQuestionResponse\n fields = ['score']","sub_path":"pretests/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"375308674","text":"\"\"\"\nVoorbeelden gebruik van CBS Open Data v3 in Python\nhttps://www.cbs.nl/nl-nl/onze-diensten/open-data\nAuteur: Jolien Oomens\nCentraal Bureau voor de Statistiek\n\nIn dit voorbeeld worden gemeentegrenzen gekoppeld aan geboortecijfers om een \nthematische kaart te maken.\n\"\"\"\n\nimport pandas as pd\nimport geopandas as gpd\nimport cbsodata\n\n# Zoek op welke data beschikbaar is\nmetadata = pd.DataFrame(cbsodata.get_meta('83765NED', 'DataProperties'))\n\n\n# Download geboortecijfers en verwijder spaties uit regiocodes\ndata = pd.DataFrame(cbsodata.get_data('83765NED', select = ['WijkenEnBuurten', 'Codering_3', 'GeboorteRelatief_25']))\ndata['Codering_3'] = data['Codering_3'].str.strip()\n\n# Download geboortecijfers en verwijder spaties uit regiocodes\ndata = pd.DataFrame(cbsodata.get_data('83765NED', select = ['WijkenEnBuurten', 'Codering_3', 'GeboorteRelatief_25']))\ndata['Codering_3'] = data['Codering_3'].str.strip()\n\n# Haal de kaart met gemeentegrenzen op van PDOK\ngeodata_url = 'https://geodata.nationaalgeoregister.nl/cbsgebiedsindelingen/wfs?request=GetFeature&service=WFS&version=2.0.0&typeName=cbs_gemeente_2017_gegeneraliseerd&outputFormat=json'\ngemeentegrenzen = gpd.read_file(geodata_url)\n\n# Koppel CBS-data aan geodata met regiocodes\ngemeentegrenzen = pd.merge(gemeentegrenzen, data,\n left_on = \"statcode\", right_on = \"Codering_3\")\n\n# Maak een thematische kaart\np = gemeentegrenzen.plot(column='GeboorteRelatief_25', figsize = (10,8))\np.axis('off')\np.set_title('Levend geborenen per 1000 inwoners, 2017')\n","sub_path":"Python/thematic_map.py","file_name":"thematic_map.py","file_ext":"py","file_size_in_byte":1536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"596947288","text":"#Create a dictionary (in your file) of names and birthdays. \n#When you run your program it should ask the user to enter a name, \n#and return the birthday of that person back to them.\n\nbdaydict = {\n \"Kru\": \"September 19, 1988\",\n \"John\": \"September 20, 1988\",\n \"James\": \"June 12, 1908\"\n}\n\nname = input(\"We have Kru, John and James' birthdays. Who's would you like to look up?: \")\n\nprint (\"%s's birthday is %s.\" % (name, str(bdaydict[name])))","sub_path":"bday-dictionaries.py","file_name":"bday-dictionaries.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"335301237","text":"from flask import Flask, render_template, request, redirect, url_for, flash, jsonify\nfrom RestaurantDB import RestaurantDB\nfrom database_setup import Restaurant, MenuItem\n\napp = Flask(__name__)\n\ndb = RestaurantDB('sqlite:///restaurantmenu.db')\n\n@app.route('/restaurants/json', methods=['GET'])\ndef getRestaurants():\n items = db.getAllRestaurants()\n return jsonify(Restaurants=[i.serialize for i in items])\n\n@app.route('/restaurants//menu/json', methods=['GET'])\ndef getRestaurantMenuItems(restaurantId):\n items = db.filterMenuItems(restaurant_id = restaurantId)\n return jsonify(MenuItems=[i.serialize for i in items])\n\n@app.route('/restaurants//menu//json', methods=['GET'])\ndef getMenuItem(restaurantId, menuId):\n item = db.filterMenuItems(restaurant_id = restaurantId, id = menuId)[0]\n return jsonify(item.serialize)\n\n@app.route('/restaurants//', methods=['GET'])\ndef restaurantMenu(restaurantId):\n restaurant = db.filterRestaurants(id = restaurantId)[0]\n items = db.filterMenuItems(restaurant_id = restaurant.id)\n return render_template('menu.html', restaurant = restaurant, items = items)\n\n@app.route('/restaurants//new/', methods=['GET', 'POST'])\ndef newMenuItem(restaurantId):\n if request.method == 'POST':\n if request.form['name']:\n db.addMenuItem(MenuItem(name = request.form['name'], restaurant_id = restaurantId))\n flash(\"Menu Item created\")\n return redirect(url_for('restaurantMenu', restaurantId = restaurantId))\n else:\n return render_template('NewMenuItem.html', restaurantId = restaurantId)\n\n@app.route('/restaurants///edit/', methods=['GET', 'POST'])\ndef editMenuItem(restaurantId, menuId):\n editedItem = db.filterMenuItems(id = menuId)[0]\n if request.method == 'POST':\n if request.form['name']:\n editedItem.name = request.form['name']\n db.addMenuItem(editedItem)\n flash(\"Menu Item updated\")\n return redirect(url_for('restaurantMenu', restaurantId = restaurantId))\n else:\n return render_template('EditMenuItem.html', restaurantId = restaurantId, menuId = menuId, item = editedItem)\n\n@app.route('/restaurants///delete/', methods=['GET', 'POST'])\ndef deleteMenuItem(restaurantId, menuId):\n item = db.filterMenuItems(id = menuId)[0]\n if request.method == 'POST':\n db.removeMenuItem(item)\n flash(\"Menu Item deleted\")\n return redirect(url_for('restaurantMenu', restaurantId = restaurantId))\n else:\n return render_template('DeleteMenuItem.html', item = item)\n\nif __name__ == '__main__':\n app.secret_key = 'secretKey'\n app.debug = True\n app.run(host = '0.0.0.0', port = 5000)","sub_path":"vagrant/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":2812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"447726236","text":"import numpy as np\nimport pandas as pd\n\nnlag = 30\nxnames = []\nfor j in range(0, nlag + 1):\n xnames.append(\"Speed[\" + str(-j) + \"]\")\nfor j in range(0, nlag + 1):\n xnames.append(\"FcwRange[\" + str(-j) + \"]\")\ncolnames = list(xnames)\ncolnames += [\"Brake\"]\n\nnpc = 8\n\nmaxid = 108\n\nfor cid in range(1, maxid + 1):\n id_pad = '{:03d}'.format(cid)\n dir = pd.read_csv('data/directions_' + str(npc) + 'pc.txt',\n index_col=0,\n header=0)\n dcur = pd.read_csv('data/smproj_8pc_' + id_pad + '.txt',\n header=0, \n usecols=colnames, \n engine='c')\n# Inner product of kinematics and direction loadings, add brake column\n dcur = dcur[xnames].dot(dir.loc[xnames]).assign(Brake=dcur.Brake)\n dcur.to_csv('data/scores_' + str(npc) + 'pc_py_' + id_pad + '.txt',\n index = False)\n","sub_path":"get_scores.py","file_name":"get_scores.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"113876301","text":"\"\"\"\nTest the bbcnews module's functions: extract_data, reshape. \n\"\"\"\nfrom unittest import TestCase\nfrom pathlib import Path\nimport sys; sys.path.insert(0, \n Path(__file__).parents[1]\n )\nfrom corpus4classify.bbcnews import extract_data, reshape\n\nclass Usage(TestCase):\n @classmethod\n def setUpClass(cls):\n cls.EXTRACT = extract_data()\n \n def test_extract_data(self):\n '''Should traverse the directory; load all files into a dict \n with 5 keys corresponding to the 5 folders under \"data/\".\n '''\n self.assertEqual(set(Usage.EXTRACT.keys()),\n {'tech', 'sports', 'politics', 'business', 'entertainment'}\n )\n\n def test_reshape(self):\n '''Should convert a wide dataframe to a narrow dataframe through the use of an\n indicator column (the 2nd column here).\n '''\n DATA = {'arts': [4],\n 'tech': [6, 9]\n }\n self.assertTrue(reshape(DATA) == ([4, 6, 9], \n [0, 1, 1]\n )\n )","sub_path":"test/test_bbcnews.py","file_name":"test_bbcnews.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"219687970","text":"\n\nclass DnC_AI():\n sym = (\"X\", \"O\")\n\n pSym = (sym[0], sym[1])\n MAP = {(0, 0): \"_\", (1, 0): \"_\", (2, 0): \"_\",\n (0, 1): \"_\", (1, 1): \"_\", (2, 1): \"_\",\n (0, 2): \"_\", (1, 2): \"_\", (2, 2): \"_\"}\n\n def __init__(self, situations={}, FreeMarker='_', ):\n self.FreeMarker = FreeMarker\n self.situations = situations\n\n def FindPossibilities(self):\n MAP = self.MAP\n possibilities = []\n for key in MAP:\n if MAP[key] is self.FreeMarker:\n possibilities.append(key)\n return(possibilities)\n\n def MAP2String(self):\n MAP = self.MAP\n MapString = '{}{}{}{}{}{}{}{}{}'.format(MAP[(0, 0)], MAP[(1, 0)], MAP[(2, 0)],\n MAP[(0, 1)], MAP[(1, 1)], MAP[(2, 1)],\n MAP[(0, 2)], MAP[(1, 2)], MAP[(2, 2)])\n return MapString\n\n def CreateSituation(self):\n situations = self.situations\n MAPString = self.MAP2String()\n possibilities = self.FindPossibilities()\n n = len(possibilities)\n # print(possibilities)\n\n situations[MAPString] = {}\n for i in possibilities:\n situations[MAPString][i] = 1/n\n print(situations)\n\n def choose(self, player):\n MAP = self.MAP\n condition = True\n # n for debug\n Ncondition = 0\n while condition:\n Ncondition += 1\n print(\" Ncondition: \", Ncondition)\n\n choiceSTR = input(\"place your %s: \" % (player))\n conditionLen = (len(choiceSTR) == 3)\n if conditionLen:\n\n choiceX, choiceY = int(choiceSTR[0])-1, int(choiceSTR[2])-1\n conditionX = (choiceX > 0-1) and (choiceX < 4-1)\n conditionY = (choiceY > 0-1) and (choiceY < 4-1)\n\n if conditionX and conditionY:\n print(\"condition-X/Y passed\")\n conditionTaken = (MAP[(choiceX, choiceY)] == \"_\")\n condition = not conditionTaken\n # print(\"MAP(x,y) \\n\", MAP[(choiceX, choiceY)], MAP[(choiceX, choiceY)] == \"_\" )\n\n if not conditionTaken:\n print(\"That spot is not free.\")\n if condition:\n print(\"your imput is not valid\")\n else:\n if not conditionX:\n print(\"conditionX: 1 <=x<= 3 and int\")\n if not conditionY:\n print(\"conditionY: 1 <=y<= 3 and int\")\n\n else:\n print(\"conditionLen: Len of input must be 3\")\n print(len(choiceSTR))\n\n choice = [int(choiceSTR[0])-1, int(choiceSTR[2])-1]\n choiceX, choiceY = choice[0], choice[1]\n MAP[choiceX, choiceY] = player\n return MAP\n\n def win(self):\n MAP = self.MAP\n\n # winposibilities\n XXX______ = MAP[(0, 0)] == \"X\" and MAP[(1, 0)] == \"X\" and MAP[(2, 0)] == \"X\"\n ___XXX___ = MAP[(0, 1)] == \"X\" and MAP[(1, 1)] == \"X\" and MAP[(2, 1)] == \"X\"\n ______XXX = MAP[(0, 2)] == \"X\" and MAP[(1, 2)] == \"X\" and MAP[(2, 2)] == \"X\"\n\n X__X__X__ = MAP[(0, 0)] == \"X\" and MAP[(0, 1)] == \"X\" and MAP[(0, 2)] == \"X\"\n _X__X__X_ = MAP[(1, 0)] == \"X\" and MAP[(1, 1)] == \"X\" and MAP[(1, 2)] == \"X\"\n __X__X__X = MAP[(2, 0)] == \"X\" and MAP[(2, 1)] == \"X\" and MAP[(2, 2)] == \"X\"\n\n __X_X_X__ = MAP[(2, 0)] == \"X\" and MAP[(1, 1)] == \"X\" and MAP[(0, 2)] == \"X\"\n X___X___X = MAP[(0, 0)] == \"X\" and MAP[(1, 1)] == \"X\" and MAP[(2, 2)] == \"X\"\n\n Xwinn = XXX______ or ___XXX___ or ______XXX or X__X__X__ or _X__X__X_ or __X__X__X or __X_X_X__ or X___X___X\n\n OOO______ = MAP[(0, 0)] == \"O\" and MAP[(1, 0)] == \"O\" and MAP[(2, 0)] == \"O\"\n ___OOO___ = MAP[(0, 1)] == \"O\" and MAP[(1, 1)] == \"O\" and MAP[(2, 1)] == \"O\"\n ______OOO = MAP[(0, 2)] == \"O\" and MAP[(1, 2)] == \"O\" and MAP[(2, 2)] == \"O\"\n\n O__O__O__ = MAP[(0, 0)] == \"O\" and MAP[(0, 1)] == \"O\" and MAP[(0, 2)] == \"O\"\n _O__O__O_ = MAP[(1, 0)] == \"O\" and MAP[(1, 1)] == \"O\" and MAP[(1, 2)] == \"O\"\n __O__O__O = MAP[(2, 0)] == \"O\" and MAP[(2, 1)] == \"O\" and MAP[(2, 2)] == \"O\"\n\n __O_O_O__ = MAP[(2, 0)] == \"O\" and MAP[(1, 1)] == \"O\" and MAP[(0, 2)] == \"O\"\n O___O___O = MAP[(0, 0)] == \"O\" and MAP[(1, 1)] == \"O\" and MAP[(2, 2)] == \"O\"\n\n Owinn = OOO______ or ___OOO___ or ______OOO or O__O__O__ or _O__O__O_ or __O__O__O or __O_O_O__ or O___O___O\n\n if Xwinn:\n return self.pSym[0]\n self.PRINT()\n elif Owinn:\n return self.pSym[1]\n self.PRINT()\n else:\n return None\n\n def weighted_random_by_dct(self, dct):\n # from stack overflow\n import random as r\n rand_val = r.random()\n total = 0\n for k, v in dct.items():\n total += v\n if rand_val <= total:\n return k\n assert False, 'unreachable'\n\n def AIchoose(self, symbol):\n print(\"AIchoose\")\n GameChoices = self.GameChoices = []\n MAP = self.MAP\n MAPString = self.MAP2String()\n # if this situation never has happend creat the situation\n if not (MAPString in self.situations):\n self.CreateSituation()\n #print('situations', self.situations, '\\n')\n choice = self.weighted_random_by_dct(self.situations[MAPString])\n #print('choice, {}'.format(choice))\n choice.append(GameChoices)\n MAP[choice] = symbol\n\n def AIlearn(self):\n situations, MAPString, GameChoices = self.situations, self.MAPString, self.Game\n\n def PRINT(self):\n MAP = self.MAP\n print(\"\"\"\n %s | %s | %s\n ---|---|---\n %s | %s | %s\n ---|---|---\n %s | %s | %s\"\"\" % (MAP[(0, 0)], MAP[(1, 0)], MAP[(2, 0)],\n MAP[(0, 1)], MAP[(1, 1)], MAP[(2, 1)],\n MAP[(0, 2)], MAP[(1, 2)], MAP[(2, 2)]))\n","sub_path":"AI/run/TryOneFIleDnC.py","file_name":"TryOneFIleDnC.py","file_ext":"py","file_size_in_byte":6025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"340350353","text":"#!/usr/bin/env python\nfrom __future__ import print_function\nimport gc\nfrom casacore import tables\nimport numpy as np\nimport math\nimport multiprocessing\nimport itertools\nimport datetime\nimport argparse\nimport os.path\nimport logging\nimport pyrap.tables as pt\nimport warnings\n\nwarnings.filterwarnings(\"ignore\")\n\ndef antialias_visibilities(vis, subband_response, nconv):\n \"\"\"\n Perform AAF correction\n\n Args:\n vis (np.array): input spectrum, which is supposed from raw MS (visibility),\n datatype complex numbers, shape(num_subbands*64, number of correlations (4: xx, xy, yx, yy)0\n subband_response: filter frequency response, see annotation in the main function\n nconv: deconvolution length\n\n Returns:\n np.array: AAF corrected spectrum, same shape and datatype as vis\n \"\"\"\n # 1. Preparation before antialias_msation AAF\n\n # Calculate spectrum's subbands numbers, correlator numbers\n ncorr = vis.shape[1]\n num_channels = 64\n num_subbands = vis.shape[0] / 64\n\n # Calculate the power spectrum, reshape spectrum\n ob_spec = abs(vis)\n ob_spec = np.reshape(ob_spec, (num_subbands, num_channels, ncorr))\n # Estimate missing subbands\n # Find missing subbands and create an array to record the location of missing subbands\n sumspec = np.sum(ob_spec, axis=1)\n zeros = np.where(sumspec == 0)\n flag = np.zeros(ob_spec.shape)\n flag[zeros[0], :, zeros[1]] = 1\n # Use linear interpolation to estimate the missing subbands\n ob_spec1 = list((np.swapaxes(ob_spec, 0, 2)).reshape(ob_spec.shape[1] * ob_spec.shape[2], ob_spec.shape[0]))\n ob_spec2 = np.swapaxes(np.array(\n [np.interp(np.arange(0, ob_spec.shape[0], 1), np.where(x > 0)[0], x[np.where(x > 0)]) if (np.sum(x)>0) else np.zeros(x.size) for x in\n ob_spec1]).reshape(ob_spec.shape[2], ob_spec.shape[1], ob_spec.shape[0]), 0, 2)\n ob_spec = ob_spec2.copy()\n\n # 2. Actual AAF calibration:\n\n # Create and initialize a new array to store AAF corrected spectrum\n corr_spec = np.empty_like(ob_spec)\n corr_spec[:] = np.nan\n \n # Begin with the most central 3 channel, suppose these 3 central channels of each subband are not influenced by aliasing effect\n corr_spec[:, num_channels / 2, :] = ob_spec[:, num_channels / 2, :] / subband_response[1, num_channels / 2]\n corr_spec[:, num_channels / 2 - 1, :] = ob_spec[:, num_channels / 2 - 1, :] / subband_response[1, num_channels / 2 - 1]\n corr_spec[:, num_channels / 2 + 1, :] = ob_spec[:, num_channels / 2 + 1, :] / subband_response[1, num_channels / 2 + 1] \n # From central channels downwards,ignore response of previous subband (for a certain subband, channel1 to channel 30\n # was mostly influenced by next subband's channel1 to channel30)\n for chidx in np.arange(num_channels / 2 - 2, 0, -1):\n ratio = -1. * subband_response[2, chidx] / subband_response[1, chidx]\n f_corr = ratio ** (np.arange(nconv - 1, -1, -1)) / subband_response[1, chidx]\n for corri in np.arange(0, ncorr, 1):\n corr_spec[:, chidx, corri] = (np.convolve(ob_spec[:, chidx, corri], f_corr))[nconv - 1:]\n # compensate for missing sample\n if chidx < nconv:\n f_corr = f_corr * ratio\n # estimate of missing data, use neighbouring channel as initial estimate\n ini_spec = corr_spec[:, chidx + 1, :]\n dmissing = np.ones(ncorr)\n for corri in np.arange(0, ncorr, 1):\n # this for-loop is somehow unavoidable, because np.linalg.lstsq only accept one-dimensional array while\n # our data array is too deep.\n dmissing[corri] = np.linalg.lstsq(\n np.transpose(np.mat(f_corr)),\n np.transpose(np.mat(ini_spec[num_subbands - nconv:, corri] -\n corr_spec[num_subbands - nconv:, chidx, corri])),\n rcond=None)[0][0, 0]\n corr_spec[num_subbands - nconv:, chidx, corri] = corr_spec[num_subbands - nconv:, chidx, corri] + \\\n np.dot(f_corr, dmissing[corri])\n # From central channel upwards, ignore response of next subband (for a certain subband, channel34 to channel 63\n # were mostly influenced by previous subband's channel34 to channel63)\n for chidx in np.arange(num_channels / 2 + 2, num_channels, 1):\n ratio = -1. * subband_response[0, chidx] / subband_response[1, chidx]\n f_corr = ratio ** (np.arange(0, nconv, 1)) / subband_response[1, chidx]\n for corri in np.arange(0, ncorr, 1):\n corr_spec[:, chidx, corri] = (np.convolve(ob_spec[:, chidx, corri], f_corr))[0:num_subbands]\n if chidx > num_channels - nconv - 1:\n f_corr = f_corr * ratio\n # Estimate of missing data,use neighbouring channel as initial estimate\n ini_spec = corr_spec[:, chidx - 1, :]\n for corri in np.arange(0, ncorr, 1):\n dmissing[corri] = np.linalg.lstsq(\n np.transpose(np.mat(f_corr)),\n np.transpose(np.mat(ini_spec[0:nconv, corri] - corr_spec[0:nconv, chidx, corri])),\n rcond=None)[0][0, 0]\n corr_spec[0:nconv, chidx, corri] = corr_spec[0:nconv, chidx, corri] + np.dot(\n np.reshape(f_corr, (1, f_corr.size)), dmissing[corri])\n\n # Dealing with the first channels, since eventually we'll just ignore or flag first channels, so it's okay to\n # disable this block, might save some time\n #nedge = 3\n #chidx = 0\n #ratio = -1. * subband_response[2, chidx] / subband_response[1, chidx]\n #f_corr = ratio ** (np.arange(num_subbands - 1, -1, -1)) / subband_response[1, chidx]\n ## estimate missing data,use average of first and last channel as initial estimate\n #ini_spec = (corr_spec[:, 1, :] + np.roll(corr_spec[:, num_channels - 1, :], 1, axis=0)) / 2.\n #ini_spec[0, :] = corr_spec[0, 1, :]\n #dmissing = np.ones(ncorr)\n #for corri in np.arange(0, ncorr, 1):\n # corr_spec[:, chidx, corri] = (np.convolve(ob_spec[:, chidx, corri], f_corr))[np.size(f_corr) - 1:]\n #f_corr = ratio * f_corr\n #for corri in np.arange(0, ncorr, 1):\n # dmissing[corri] = np.linalg.lstsq(np.transpose(np.mat(f_corr[nedge:num_subbands - nedge])),\n # np.transpose(np.mat(ini_spec[nedge:num_subbands - nedge, corri] -\n # corr_spec[nedge:num_subbands - nedge, chidx, corri])),\n # rcond=None)[0][0, 0]\n # corr_spec[:, chidx, corri] = corr_spec[:, chidx, corri] + np.dot(f_corr, dmissing[corri])\n\n\n\n\n\n\n # 3. Flag and reshape AAF corrected spectrum, transform power spectrum back to visibility complex numbers\n\n # The above algorithm also did a bandpass calibration, since AperCal will do bandpass calibration anyway, here we just undo the bandpass calibration. \n bandpass=subband_response[1,:]\n #Flag the missing subbands and negative values. flag channel 0 of every subband\n #Here by flagging, I mean turn these values into zero, since Aoflagger will by default clip zero values.\n corr_spec=corr_spec*bandpass[np.newaxis,:,np.newaxis]\n corr_spec[np.where(corr_spec < 0)] = 0\n corr_spec[np.where(flag == 1)] = 0\n corr_spec[:,0,:]=0 \n # Reshape spectrum\n corr_spec = np.reshape(corr_spec, (corr_spec.size / ncorr, ncorr))\n\n # Rransform the power spectrum back to visibility complex numbers, we assume that phase of complex numbers remains\n # the same throughout AAF.\n corr_spec = vis * (corr_spec / np.reshape(ob_spec, (ob_spec.size / ncorr, ncorr)))\n corr_spec[np.isnan(corr_spec)]=0 \n return corr_spec\n\n\n\n\ndef antialias_list(arg_list):\n return antialias_visibilities(*arg_list)\n\ndef antialias_ms(msname, tol, outputcolname=\"DATA\"):\n \"\"\"\n Apply an anti aliasing filter in a parallel way to a measurement set\n\n Params:\n msname (str): Name of measurement set\n tol (float): Filter response below this limit will be ignored\n outputcolname (str): Name of column to write corrected visibilities to (will be added to MS if necessary)\n\n Returns:\n None\n \"\"\"\n logger = logging.getLogger(\"aaf\")\n logging.basicConfig(level=logging.INFO)\n logger.info(\"Anti-aliasing measurement set \" + msname)\n # 1. Open MS and read subtable 'DATA',\n t1 = datetime.datetime.now()\n ms = tables.table(msname, readonly=False, ack=False)\n nrows = ms.nrows()\n ini_data = tables.tablecolumn(ms, 'DATA')\n \n\n\n # 2. Calculate function antialias_visibilities()'s two arguments: subband_response and nconv\n\n # Fixed parameters: Number of channels per subband; Total number of subbands in polyphase filter bank\n num_channels = 64\n num_subbands = 1024\n\n # Load filter coefficients, pad with zero\n dir=os.path.abspath(__file__)\n dirup1=os.path.split(dir)\n dirup2=os.path.split(dirup1[0])\n coeff = np.loadtxt(dirup2[0] +'/Coeffs16384Kaiser-quant.dat')\n coeff = np.append(coeff, np.zeros(num_channels * num_subbands - coeff.size))\n\n # Get filter frequency response by doing FFT on filter coefficients\n frequency_response = np.abs(np.fft.fft(coeff)) ** 2\n\n # Scaling\n frequency_response = frequency_response / np.sum(frequency_response) * num_channels\n\n # We only consider aliasing influence from the neighbouring two bands\n subband_response = np.roll(frequency_response, int(1.5 * num_channels))\n subband_response = np.reshape(subband_response[0:3 * num_channels], (3, num_channels))\n\n # Tolerance, filter response below that is ignored\n # maximum de-convolution length\n nconv = int(math.ceil(math.log(tol, subband_response[2, 1] / subband_response[1, 1])))\n\n\n\n\n # 3. Do AAF calibration concurrently (parallel)\n num_cpus = multiprocessing.cpu_count()\n pool = multiprocessing.Pool(processes=num_cpus-1)\n # Here itertools and the function antialias_list() are just bridges between pool.map and function antialias_visibilities(), because pool.map\n # is not suitable for function that has multi arguments.\n #silence all the RuntimeWarnings\n warnings.filterwarnings(\"ignore\")\n aafdata = pool.imap(antialias_list, itertools.izip(ini_data[0:nrows], itertools.repeat(subband_response), itertools.repeat(nconv)))\n # 4. Write AAF corrected data to MS table \"DATA\"\n #!!!!raw data will be covered by calibrated data!!!\n rowi=0\n for x in aafdata:\n ms.putcell(outputcolname,rowi,x)\n rowi=rowi+1\n t2 = datetime.datetime.now()\n pool.close()\n pool.join()\n log_msg = \"Performed anti-aliasing on MS, total execution time :\"+ str((t2 - t1).total_seconds())+\"seconds, wrote result to column \" + outputcolname\n pt.taql('INSERT INTO {}::HISTORY SET MESSAGE=\"{}\", APPLICATION=\"apercal\"'.format(msname, log_msg))\n logger.info(log_msg)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"Apertif Anti-aliasing filter.\")\n parser.add_argument(\"msname\", help=\"Name of Measurement Set\")\n parser.add_argument(\"-t\", \"--tolerance\", help=\"Filter response below this limit will be ignored\", type=float,\n default=0.00001)\n args = parser.parse_args()\n\n logging.basicConfig(level=logging.INFO)\n antialias_ms(args.msname, args.tolerance)\n","sub_path":"aaf/aaf.py","file_name":"aaf.py","file_ext":"py","file_size_in_byte":11466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"433627624","text":"\"\"\" My example 3 \"\"\"\n# โปรแกรมหาค่าเฉลี่ย\ndef cal_average():\n \"\"\" Calculator age average \"\"\"\n age = [10, 14, 25, 20, 40, 15, 12]\n total_age = sum(age)\n count = len(age)\n\n result = (total_age / count)\n\n print(int(result))\n\ncal_average()\n","sub_path":"example3.py","file_name":"example3.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"79256415","text":"#!/usr/bin/env python3\n\ndef sumtree(L):\n tot = 0\n for x in L:\n print(x, end='; ')\n if not isinstance(x, list):\n tot += x\n else:\n tot += sumtree(x)\n return tot\n\n\nL = [1, [2, [3, 4], 5], 6, [7, 8]]\n\n\n# print(sumtree(L))\n# Версии zip(seqs...) и map(None, seqs...) в Python2.6\n# страница 579\ndef myzip(*seqs):\n seqs = [list(S) for S in seqs]\n print('seqs = ', seqs)\n res = []\n while all(seqs):\n res.append(tuple(S.pop(0) for S in seqs))\n print(res, end=' ')\n print('')\n return res\n\n\ndef mymapPad(*seqs, pad=None):\n seqs = [list(S) for S in seqs]\n res = []\n while any(seqs):\n res.append(tuple((S.pop(0) if S else pad) for S in seqs))\n return res\n\n\nS1, S2 = 'abc', 'xyz123'\nprint('zip1: ', myzip(S1, S2))\n\nL = (x for x in [1, 2, 3, 4])\n\n","sub_path":"script-11.py","file_name":"script-11.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"559946501","text":"# Average, Maximum, Minimum\n\nlist1 = [7, 4, 16, 3, 2, -6, 15, 8, 7, -11, 10, -2]\ncnteven, sumeven = 0, 0\ncntodd, sumodd = 0, 0\nfor n in list1:\t\t\t# get list1 elements to n.\n if n % 2 == 0:\t\t# if value of n is even\n sumeven += n\n cnteven += 1\n else:\t\t\t# otherwise, value of n is odd\n sumodd += n\n cntodd += 1\naveeven = sumeven/cnteven\naveodd = sumodd/cntodd\nprint(\"Number of even numbers:\", cnteven, \" Sum=\", sumeven, \" Average=\", aveeven)\nprint(\"Number of odd numbers:\", cntodd, \" Sum=\", sumodd, \" Average =\", aveodd)\nprint(\"==========\")\n\n# Find the maximum number in a list of numbers.\nlist2 = [7, 4, 16, 3, 2, 6, 15, 8, 7, 11, 1, 10, 9, 5]\nmax = list2[0]\t\t# assume first member of list is max\nfor n in list2:\t\t# get list2 elements to n.\n if n > max:\t\t# if n > previous max, then\n max = n\t\t# set max to n.\nprint(\"Maximum is:\", max)\nprint(\"==========\")\n\n# Find the minimum number in a list of numbers.\nlist3 = [7, 4, 16, 3, 2, 12, 6, 15, 8, 14, 7, 11, 1, 10, 9, 5]\nmin = list3[0]\t\t# assume first member of list is min\nfor n in list3:\t\t# get list3 elements to n.\n if n < min:\t\t# if n < previous min, then\n min = n\t\t# set min to n.\nprint(\"Minimum is:\", min)\nprint(\"==========\")\n\n# Find the maximum and minimum numbers in a list of numbers.\nlist4 = [7, 4, 16, 3, 2, 12, 6, 15, 8, 14, 7, 11, 1, 10, 9, 5]\nmax = list4[0]\t\t# assume first member of list is max\nmin = list4[0]\t\t# assume first member of list is min\nfor n in list4:\t\t# get list2 elements to n.\n if n > max:\t\t# if n > previous max, then\n max = n\t\t# set max to n.\n if n < min:\t\t# if n < previous min, then\n min = n\t\t# set min to n.\nprint(\"Maximum is:\", max)\nprint(\"Minimum is:\", min)\nprint(\"==========\")\n\n# Find the maximum and minimum numbers in a list of numbers.\nlist4 = [7, 4, 16, 3, 2, 12, 6, 15, 8, 14, 7, 11, 1, 10, 9, 5]\ncnt, sum = 0, 0\nmax = list4[0]\t\t# assume first member of list is max\nmin = list4[0]\t\t# assume first member of list is min\nfor n in list4:\t\t# get list2 elements to n.\n cnt += 1\n sum += n\n if n > max:\t\t# if n > previous max, then\n max = n\t\t# set max to n.\n if n < min:\t\t# if n < previous min, then\n min = n\t\t# set min to n.\nprint(\"Count =\", cnt)\nprint(\"Sum =\", sum)\nprint(\"Average =\", sum/cnt)\nprint(\"Maximum is:\", max)\nprint(\"Minimum is:\", min)\nprint(\"==========\")\n\n","sub_path":"scripts/p356_for.py","file_name":"p356_for.py","file_ext":"py","file_size_in_byte":2366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"329680949","text":"import urllib2\n\nclass SentryService():\n def __init__(self):\n self.method='POST'\n def sendRequest(self,url,data,options={'Content-Type': 'application/json'}):\n req=urllib2.Request(url,data,options)\n f=urllib2.urlopen(req)\n for x in f:\n print(x)\n f.close()","sub_path":"code/Service/SentryService.py","file_name":"SentryService.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"72214501","text":"'''\nCreated on 25 Aug 2020\n\n@author: dkr85djo\n'''\nimport struct\n\nfield_static = [ \n [b'1based', b''],\n [b':authority', b''],\n [b':method', b'GET'],\n [b':method', b'POST'],\n [b':path', b'/'],\n [b':path', b'/index.html'],\n [b'scheme', b'http'],\n [b'scheme', b'https'],\n [b'status', b'200'],\n [b'status', b'204'],\n [b'status', b'206'],\n [b'status', b'304'],\n [b'status', b'400'],\n [b'status', b'404'],\n [b'status', b'500'],\n [b'accept-charset', b''],\n [b'accept-encoding', b'gzip,deflate'],\n [b'accept-language', b''],\n [b'accept-ranges', b''],\n [b'accept', b''],\n [b'access-control-allow-origin', b''],\n [b'age', b''],\n [b'allow', b''],\n [b'authorization', b''],\n [b'cache-control', b''],\n [b'content-disposition', b''],\n [b'content-encoding', b''],\n [b'content-langauge', b''],\n [b'content-length', b''],\n [b'content-location', b''],\n [b'content-range', b''],\n [b'content-type', b''],\n [b'cookie', b''],\n [b'date', b''],\n [b'etag', b''],\n [b'expect', b''],\n [b'expires', b''],\n [b'from', b''],\n [b'host', b''],\n [b'if-match', b''],\n [b'if-modified-since', b''],\n [b'if-none-match', b''],\n [b'if-range', b''],\n [b'if-unmodified-since', b''],\n [b'last-modified', b''],\n [b'link', b''],\n [b'location', b''],\n [b'max-forwards', b''],\n [b'proxy-authenticate', b''],\n [b'proxy-authorization', b''],\n [b'range', b''],\n [b'referer', b''],\n [b'refresh', b''],\n [b'retry-after', b''],\n [b'server', b''],\n [b'set-cookie', b''],\n [b'strict-transport-security', b''],\n [b'transfer-encoding', b''],\n [b'user-agent', b''],\n [b'vary', b''],\n [b'via', b''],\n [b'www-authenticate', b''] \n ]\n\nclass h2int:\n # basically, implements BIGINT\n def __init__(self, initv=0, octet_offset=0):\n self.v = initv\n self.N = 8 - octet_offset\n \n def encode(self):\n rbuffer = bytearray(8)\n i = 0\n \n if self.v < 2**(self.N)-1:\n struct.pack_into(\"B\", rbuffer, i, self.v)\n else: \n struct.pack_into(\"B\", rbuffer, i, 2**(self.N)-1)\n i += 1\n self.v -= (2**(self.N)-1)\n\n while (self.v >= 128):\n struct.pack_into(\"B\", rbuffer, i, (self.v % 128) + 128)\n i += 1\n self.v = round(self.v / 128)\n \n \n struct.pack_into(\"B\", rbuffer, i, self.v) \n \n return rbuffer \n \n \n def decode(self, ibuffer):\n rval = 0\n i = 0\n m = 0\n next_octet = b''\n \n (rval,) = struct.unpack_from(\"B\", ibuffer, i) \n i += 1\n rval = rval & (0xff - 2**(self.N))\n \n if rval < 2**(self.N)-1:\n return rval\n else: \n (next_octet,) = struct.unpack_from(\"B\", ibuffer, i)\n i += 1\n rval += ((next_octet & 127) * (2**m))\n m += 7\n \n while (next_octet & 128 == 128):\n (next_octet,) = struct.unpack_from(\"B\", ibuffer, i)\n i += 1\n rval += ((next_octet & 127) * 2**m)\n m += 7\n \n return rval\n \nclass h2str:\n def __init__(self, initv=\"\"):\n self.v = initv\n \n def encode(self, huffman=0x00): # or 0x01\n rbuffer = bytearray(1 + len(self.v)) \n strlen = h2int(initv=huffman + len(self.v), octet_offset=0)\n \n struct.pack_into(\"B\", rbuffer, 0, strlen.encode()[0])\n \n if huffman > 0:\n pass # encode huffman\n else: \n struct.pack_into(\"\" + str(len(self.v)) + \"s\", rbuffer, 1, self.v.encode())\n \n return rbuffer\n \n def decode(self, ibuffer):\n (rlen,) = struct.unpack_from(\"B\", ibuffer, 0)\n \n if (rlen & 0x80):\n pass # decode huffman\n else:\n return struct.unpack_from(str(rlen & 0x7f) + \"s\", ibuffer, 1)\n \n \nclass h2hf:\n def __init__(self, hname=\"\", hval=\"\", hindex=0):\n self.name_index = hindex # + dynamic offset\n self.name_literal = hname\n self.value_literal = hval\n \n \n # literal + indexing, index = 0100 (0x2) + index | 0 (new_name)\n # index(dynamic) + literal_name + literal_value\n # literal (no indexing), index = 0000 + index | 0 (new_name)\n # index(static) + literal_value\n # literal (protected), index = 0001 (0x8) + index | 0 (new_name)\n # literal_name + literal_value\n # indexed, index = 1 (0x1) + index\n # index(static)\n \n \n def encode(self, htype):\n rbuffer = None\n hfindex = None\n hfname = None\n hfvalue = None\n \n if (htype == 0x01): # indexed\n rbuffer = bytearray(1)\n hfindex = h2int(initv=htype + self.name_index, octet_offset=0) \n \n struct.pack_into(\"B\", rbuffer, 0, hfindex.encode()[0]) \n \n return rbuffer\n \n elif (htype == 0x02): # literal \n rbuffer = bytearray(3 + len(self.value_literal) + len(self.name_literal))\n hfindex = h2int(initv=htype + self.name_index, octet_offset=0)\n hfvalue = h2str(initv=self.value_literal)\n hfname = h2str(initv=self.name_literal) \n i = 0 \n \n struct.pack_into(\"B\", rbuffer, 0, hfindex.encode()[0])\n i += 1\n struct.pack_into(str(len(hfname.encode())) + \"s\", rbuffer, i, hfname.encode())\n i += len(hfname.encode())\n struct.pack_into(str(len(hfvalue.encode())) + \"s\", rbuffer, i, hfvalue.encode())\n \n return rbuffer \n \n def decode(self, ibuffer):\n hfindex = None\n hfname = None\n hfvalue = None\n i = 0\n \n (hfindex, ) = struct.unpack_from(\"B\", ibuffer, i)\n i += struct.calcsize(\"B\")\n # 0 1 2 3 4 5 6 7\n #B1 0 0 0 0 0 0 0\n #X1 0\n # but in spec examples, yields x80, WHY? \n if (hfindex & 0x80):\n hfindex = hfindex - 0x01\n \n if hfindex > 0:\n hfname = field_static[hfindex][0]\n hfvalue = field_static[hfindex][1]\n \n return (hfname, hfvalue)\n else:\n pass # ERROR \n \n elif (hfindex & 0x40):\n hfindex = hfindex - 0x02\n \n if hfindex > 0: \n (dlen,) = struct.unpack_from(\"B\", ibuffer, i)\n i += struct.calcsize(\"B\")\n (hfname,) = struct.unpack_from(str(dlen & 0x7f) + \"s\", ibuffer, i)\n i += dlen & 0x7f\n (dlen,) = struct.unpack_from(\"B\", ibuffer, i)\n i += struct.calcsize(\"B\")\n (hfvalue,) = struct.unpack_from(str(dlen & 0x7f) + \"s\", ibuffer, i)\n \n return (hfname, hfvalue, hfindex)\n \nclass h2hpack:\n def __init__(self):\n self.field = [b'', b'']\n self.field_dyn = [] # compression dynamic header table\n self.header_list = [] # decoded header list\n self.header_block = b''\n self.protected_headers = [] # no compression headers\n \n \n \n \nclass _TestHPack:\n def __init__(self):\n pass\n \n def int_at(self, v, o):\n i = h2int(initv=v, octet_offset=o)\n \n for x in i.encode():\n if x == 0:\n break\n print(format(x, \"0>8b\"))\n \n print (\"Decoded: \" + str(i.decode(i.encode())))\n \n def hf(self, hname, hval, htype): \n hf = h2hf(hname, hval, 62)\n \n print(hf.encode(htype).hex(sep=' ', bytes_per_sep=2)) \n print(\"Decoded: \" + str(hf.decode(hf.encode(htype))))\n \n \ntest_hpack = _TestHPack()\ntest_hpack.int_at(1337, 3)\ntest_hpack.int_at(42, 0)\ntest_hpack.hf(\"custom-key\", \"custom-header\", 0x02)\n ","sub_path":"src/moddem/modealhpack.py","file_name":"modealhpack.py","file_ext":"py","file_size_in_byte":9439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"18061401","text":"\"\"\"\nkmeans mit Euklidischer Distanz\n\n\"\"\"\n\n\nimport os\n\nfrom sklearn.cluster import KMeans\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\nfrom numpy.random import choice\nfrom PIL import Image\nimport ot\nimport scipy as sp\nimport numpy as np\nimport matplotlib.pylab as pl\nfrom mpl_toolkits.mplot3d import Axes3D # noqa\nfrom scipy.spatial import distance_matrix\nfrom scipy.sparse.linalg import eigs, eigsh\nimport sys\nfrom sklearn.metrics import confusion_matrix\nimport random\n\n\ndef heatmap_to_rel_coord(im):\n \"\"\"Transform Relevance map to list of coordinates and relevances per pixel in the range of [0,1]\n\n Input:\n -------\n im: 2D image with one channel\n\n Returns:\n -----------\n xy = list of tuples (x,y)\n r = list of mass per point\n \"\"\"\n\n x = []\n y = []\n r = []\n xy = []\n for i in range(32):\n for j in range(32):\n x.append(i)\n y.append(j)\n r.append(im[i][j])\n xy.append([i, j])\n xy = np.asarray(xy)\n x = np.asarray(x)\n y = np.asarray(y)\n r = np.asarray(r)\n\n # Normalize \"by hand\"\n max = r.max()\n min = r.min()\n r = (r-min)/(max-min)\n\n # Division by total mass\n r = r/r.sum()\n\n return xy, x, y, r\n\n\ndef compute_GWD_matrix(heatmap_array, method='GWD', verbose=False):\n\n # Initialize matrix:\n GWD = np.zeros((heatmap_array.shape[0], heatmap_array.shape[0]))\n # Iterate through matrix(we only need upper oder lower triangle since distances are symmetric\n for i in tqdm(range(heatmap_array.shape[0])):\n for j in range(i-1):\n im1 = heatmap_array[i]\n im2 = heatmap_array[j]\n xy1, x1, y1, r1 = heatmap_to_rel_coord(im1)\n xy2, x2, y2, r2 = heatmap_to_rel_coord(im2)\n\n C1 = sp.spatial.distance.cdist(xy1, xy1)\n C2 = sp.spatial.distance.cdist(xy2, xy2)\n\n C1 /= C1.max()\n C2 /= C2.max()\n\n if method == 'GWD':\n gw, log = ot.gromov.gromov_wasserstein(\n C1, C2, r1, r2, 'square_loss', verbose=verbose, log=True)\n elif method == 'EGWD':\n gw, log = ot.gromov.entropic_gromov_wasserstein(\n C1, C2, r1, r2, 'square_loss', epsilon=5e-4, log=True, verbose=verbose)\n else:\n print('METHOD not implemented.')\n\n GWD[i][j] = log['gw_dist']\n\n #Use symmetry\n GWD[j][i] = GWD[i][j]\n\n\n # Setze Diagonalelement =0\n GWD[i][i] = 0\n\n return GWD\n\n\nif __name__ == '__main__':\n y_true = [0, 0, 0, 1, 1, 1, 1, 1]\n y_pred = [0, 1, 0, 1, 0, 1, 0, 1]\n\n print(1- np.asarray(y_true))\n a,b,c,d = confusion_matrix(y_true, y_pred).ravel()\n #a,b,c,d = confusion_matrix(poison_labels, clustering_result).ravel()\n #specificity = tn / (tn+fp)\n #print(tn, fp, fn, tp)\n print(a,b,c,d)\n\n #sys.exit()\n # Open images of suspicious class\n #path = '/home/lukasschulth/Documents/MA-Detection-of-Poisoning-Attacks/coding/LRP_Outputs/incv3_matthias_v2e-rule/relevances/00026/'\n path = '/home/lukasschulth/Documents/MA-Detection-of-Poisoning-Attacks/coding/LRP_Outputs/incv3_20_epochs_normalizede-rule/relevances/00005/'\n\n\n relevances =[]\n heatmaps = []\n poison_labels =[]\n for root, dirs, files in os.walk(path):\n\n for name in files:\n\n #print(name)\n # Save poison labels\n\n if name.endswith(\"_poison.npy\"):\n poison_labels.append(int(1))\n else:\n poison_labels.append(int(0))\n\n\n # Load .npy file\n with open(str(root) + \"/\" + str(name), 'rb') as f:\n\n d = np.load(f)\n\n # Sum over color channels\n d = np.sum(d, axis=0)\n\n # Save 2D heatmap for input to OT library\n dd = d\n # Transform 32x32 Heatmap into 1024x1 Heatmap\n d = d.reshape((d.shape[0] * d.shape[1]))\n\n # Save all Heatmaps in one array\n heatmaps.append(dd)\n relevances.append(d)\n\n # Convert list of relevances to numpy array\n rel_array = np.asarray(relevances)\n\n #Plot heatmap\n #for i in range(20):\n # plt.imshow(heatmaps[i])\n # plt.show()\n\n print('relarray.shape: ', rel_array.shape)\n\n #Normalize relevance maps to [0,1] before computing pw. L2 dist:\n\n rel_array_normalized = []\n for i in range(rel_array.shape[0]):\n r = rel_array[i]\n min = r.min()\n max = r.max()\n\n # Normalize \"by hand\"\n r = (r-min)/(max-min)\n\n # Division by total mass\n r = r/r.sum()\n\n rel_array_normalized.append(r)\n\n rel_array_normalized = np.asarray(rel_array_normalized)\n\n # Zeige normalisierte Heatmap\n #plt.imshow(rel_array_normalized[0].reshape(32,32))\n #plt.show()\n # Remark: Heatmap und normalisierte HEatmap sehen im plot identisch aus\n \n \n #rel_array = np.concatenate(rel_array, axis=2)\n #print(rel_array.shape)\n \n #### Compute distance matrices\n \n # L2-Distance\n \n \n l2_dist = distance_matrix(rel_array_normalized, rel_array_normalized) # Distanzmatrix der pw. Distanzen zwischen den Heatmaps\n print('max: ', l2_dist.max())\n print('min: ', l2_dist.min())\n \n ##### Berechne Distanzen mithilfe von Gromov-Wasserstein\n \n #Wähle erste und zweite Heatmap aus der Liste aus:\n heatmap_array = np.asarray(heatmaps)\n print(heatmap_array.shape)\n im1 = heatmap_array[0]\n im2 = heatmap_array[19]\n \n print('l2:', l2_dist[0][19])\n # Berechne GW-Distanz zwischen beiden Heatmaps\n #n_samples = 32*32\n \n # Speichere Pixelkoordinaten als (x,y)\n # Speichere zusaätzlich Relevanz r passen zum Koordinatenpunkt\n\n\n\n\n\n xy1, x1, y1, r1 = heatmap_to_rel_coord(im1)\n xy2, x2, y2, r2 = heatmap_to_rel_coord(im2)\n \n # Compute distance kernels, normalize them and then display\n \n C1 = sp.spatial.distance.cdist(xy1, xy1)\n C2 = sp.spatial.distance.cdist(xy2, xy2)\n \n C1 /= C1.max()\n C2 /= C2.max()\n \n # Compute Gromov-Wasserstein plans and distance\n # https://pythonot.github.io/gen_modules/ot.gromov.html#ot.gromov.gromov_wasserstein\n \n \n #print(gw0,log0)\n # Compute distance matrices for GWD and EGWD:\n \n \n # GWD-Matrix:\n \n \n \n #GWD = compute_GWD_matrix(heatmap_array, method='GWD')\n #EGWD = compute_GWD_matrix(heatmap_array, method='EGWD')\n \n fname_to_save = '/home/lukasschulth/Documents/MA-Detection-of-Poisoning-Attacks/coding/LRP_Outputs/incv3_20_epochs_normalizede-rule/EGWD' + \".npy\"\n #with open(fname_to_save, 'wb') as f:\n #\n # np.save(f, EGWD)\n \n # ----------------------------------------------------------------------------------------------------------------------\n \n \n # Compute Affinity matrices/Transformation of distance matrices: -------------------------------------------------------\n #### Compute pw (binary) affinity scores using kNN\n k = 10\n #Ohne kNN: Sortiere jeden Zeile und merke die k Indices(ungleich der Diagonalen) mit der niedrigsten Distanz.\n ind = np.argsort(l2_dist, axis=1)\n #ind = np.argsort(GWD, axis=1)\n #ind = np.argsort(EGWD, axis=1)\n \n #Reduziere die Inidces zeilenweise auf die ersten 10+1 Indices, da der identische Punkt immer mit Abstand 0 dazugehört\n ind = ind[:, 0:k]\n \n #print(ind)\n #print(ind.shape)\n #print(ind.shape[0])\n A = np.zeros_like(l2_dist)\n \n # Setze 1's an die passenden Stellen in A\n for i in range(0, ind.shape[0]): # Zeilen\n for j in range(0, ind.shape[1]): # Spalten\n # Man sollte sich lieber die Indices in ind anschauen und dann\n # an der richtigen Stelle in A einen Eintrag setzen\n #print(i, j)\n A[i, ind[i, j]] = 1\n \n \n # Die Summe über jede Zeile von A ist nun 10, d.h. die 10 nächst gelegenen Punkte sind pro Zeile mit einer 1 vermerkt\n #print(np.sum(A, 1))\n \n # Erzeuge eine symmetrische Affinitätsmatrix\n A = 0.5 * (A + np.transpose(A))\n \n # ----------------------------------------------------------------------------------------------------------------------\n \n # Compute spectral embedding: ------------------------------------------------------------------------------------------\n # compute the symmetrized and normalized p.s.d. graph laplacian\n # COmpute D:\n D = np.zeros_like(A)\n Dinv = np.zeros_like(A)\n #A = np.array([[1,2],[3,4]])\n rowwise_sum = A.sum(1)\n \n \n for i in range(D.shape[0]):\n D[i][i] = A.sum(1)[i]\n Dinv[i][i] = np.sqrt(A.sum(1)[i])\n \n L = D-A\n \n Lsym = Dinv*L*Dinv\n \n \n # Eigenvalue Decomposition of Lsym:\n #TODO: Wahl von k und q?\n #TODO: eigsh vs eigs? #eigsh gibt nur relle Eigenwerte zurück\n l = 30\n \n vals, vecs = eigsh(Lsym, k=l)\n print(vals)\n x = range(1, l+1)\n y = np.sort(np.real(vals))\n \n plt.plot(x, y, 'o')\n plt.title(r'Absolute values of first ' + str(l) + ' eigenvalues of $L_{sym}$ with ' + str(k) + '-nearest neighbours')\n #plt.xlim([0, 25])\n #plt.show()\n\n kmeans = KMeans(n_clusters=2, random_state=0).fit_predict(rel_array_normalized)\n print(kmeans.sum())\n # kmeans wirft 2036 Bilder in die eine Klasse, bei 2463 Bildern entspricht das 82.66 Prozent bzw. 27.33 Prozent\n print(kmeans)\n\n # Tausche labels, sodass die kleinere Klasse das poison_label=1 besitzt\n clustering_result = 1-np.asarray(kmeans)\n print(clustering_result.sum())\n \n \n print(set(clustering_result))\n print(set(poison_labels))\n # Auswertung des Clusterings für zwei Klassen\n from sklearn.metrics import confusion_matrix\n \n a,b,c,d = confusion_matrix(poison_labels, clustering_result).ravel()\n #specificity = tn / (tn+fp)\n #print(tn, fp, fn, tp)\n # 1650 0 386 427\n print(a, b, c, d)\n\n #kmeans++ mit euklidischer Distanz\n\n\n\n rel_array_normalized = rel_array_normalized\n #print(poison_labels[0:nn])\n\n # Suppose we only have to clusters labeled as 0 and 1\n # Choose first index randomly\n n = rel_array_normalized.shape[0] #number of vectors to cluster\n cluster = np.zeros(n)\n seq = list(range(0, n))\n idx1 = random.sample(seq, k=1)[0]\n print('idx1: ', idx1)\n\n # Compute distances of every other sample to the firt chosen center\n distances_to_first_center = []\n for i in range(n):\n d = np.linalg.norm(rel_array_normalized[idx1]-rel_array_normalized[i])\n distances_to_first_center.append(d)\n\n distances_to_first_center = np.asarray(distances_to_first_center)\n print(distances_to_first_center.shape)\n print('done.')\n\n # Set probabilities of choosing next cluster center:\n p = np.square(distances_to_first_center)\n p /= p.sum()\n p[idx1] = 0\n p /= p.sum()\n\n idx2 = choice(seq, size=1, p=p)[0]\n print('idx_2: ', idx2)\n\n clustering = np.empty(shape=(n,))\n clustering[:] = np.nan\n\n clustering[idx1] = 0\n clustering[idx2] = 1\n\n iter = 0\n max_iter = 5\n print(' ==> Starting k-means++-iterations')\n break_while = False\n\n #Initialize cluster centers:\n cc = {0: rel_array_normalized[idx1],\n 1: rel_array_normalized[idx2]}\n\n while iter < max_iter:\n\n print('iter: ', iter)\n print('==> Recalculate distances to each barycenter')\n\n distances_to_cluster_centers = np.empty(shape=(n, 2))\n distances_to_cluster_centers[:][:] = np.nan\n\n for i in range(0, n):\n #print('i: ', i)\n\n distances_to_cluster_centers[i][0] = np.linalg.norm(cc[0] - rel_array_normalized[i])\n distances_to_cluster_centers[i][1] = np.linalg.norm(cc[1] - rel_array_normalized[i])\n\n #print('==> Update Clustering')\n #print(distances_to_cluster_centers[i])\n #print(distances_to_cluster_centers[i].argmin())\n if distances_to_cluster_centers[i].argmin() == 0:\n clustering[i] = 0\n if distances_to_cluster_centers[i].argmin() == 1:\n clustering[i] = 1\n\n if iter > 0:\n #Check if clustering has changed in the last iteration:\n if (clustering_old-clustering).sum() == 0:\n #Clustering didnt get updated -> Stop k-means iteration:\n break_while = True\n\n #print(clustering.sum())\n clustering_old = clustering\n print('Clustering: ', clustering)\n\n if break_while:\n # break while loop\n print('k-means Clustering didnt change and is being stopped.')\n print('after iteration', iter)\n break\n\n # Compute new barycenters\n for j in [0, 1]:\n idx = np.where(clustering == j)\n new_cc = rel_array_normalized[idx[0]].mean(axis=0)\n cc[j] = new_cc\n\n iter += 1\n\n # Cluster Auswertung:\n if clustering.sum() > clustering.shape[0]/2:\n clustering = 1 - clustering\n\n print('final_CLustering: ', clustering)\n print(clustering.sum())\n # Evaluate clustering:\n a, b, c, d = confusion_matrix(poison_labels, clustering).ravel()\n #specificity = tn / (tn+fp)\n #print(tn, fp, fn, tp)\n # 1650 0 386 427\n print('(tn, fp, fn, tp): ', a, b, c, d)\n","sub_path":"coding/main_file_lukasschulth_2.py","file_name":"main_file_lukasschulth_2.py","file_ext":"py","file_size_in_byte":13474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"253149166","text":"DEBUG = True\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql_psycopg2',\n 'NAME': 'jmbo',\n 'USER': 'postgres',\n 'PASSWORD': '',\n 'HOST': '',\n 'PORT': '',\n }\n}\n\nINSTALLED_APPS = (\n 'jmbo_analytics',\n 'djcelery'\n)\n\nROOT_URLCONF = 'jmbo_analytics.urls'\n\n# Disable celery\nCELERY_ALWAYS_EAGER = True\nBROKER_BACKEND = 'memory'\n\nJMBO_ANALYTICS = {\n \"google_analytics_id\": \"xxx\"\n}\n","sub_path":"test_settings.py","file_name":"test_settings.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"618310365","text":"input_num_year = int(input(\"Years: \"))\n\nyears_in_float = float(input_num_year)\n\npopulation = 307357870\n\nseconds_of_years: float = 31536000.0 * years_in_float\n\n# value of all rates are in seconds\nbirth_rate: float = 7.0\ndeath_rate: float = 13.0\nimmigration_rate: float = 35.0\n\nbirths_per_year = seconds_of_years // birth_rate\ndeaths_per_year = seconds_of_years // death_rate\nimmigration_per_year = seconds_of_years // immigration_rate\n\nif years_in_float > 0.0:\n increase_of_population = births_per_year + immigration_per_year - deaths_per_year\n print(\"New population after\" , input_num_year , \"years is\" , int(population + increase_of_population))\n\nelif years_in_float == 0.0:\n print(\"New population after\" , input_num_year , \"years is\" , int(population))\n\nelse:\n\tprint(\"Invalid input!\")\n \n\n\n","sub_path":"Heimaverkefni/Project 1 - Population/population.py","file_name":"population.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"150782744","text":"import cv2\nimport numpy as np\nimport os\nimport stacked_images as si\n\n\ndef process(img):\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n blur = cv2.GaussianBlur(gray, (5, 5), 1)\n canny = cv2.Canny(blur, 100, 100)\n kernel = np.ones((5, 5))\n canny_dilation = cv2.dilate(canny, kernel, iterations=2)\n canny_erode = cv2.erode(canny_dilation, kernel, iterations=1)\n return canny_erode\n\n\ndef find_contour(img):\n points = np.array([])\n max_area = 0\n contours, _ = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\n\n for cvt in contours:\n area = cv2.contourArea(cvt)\n if area > 3000:\n perimeter = cv2.arcLength(cvt, True)\n approx = cv2.approxPolyDP(cvt, 0.02*perimeter, True)\n # find max counter with rectangle in shape\n if area > max_area and len(approx) == 4:\n points = approx\n max_area = area\n return points\n\n\ndef warp(points):\n\n x1, y1 = points[0][0][0], points[0][0][1]\n x2, y2 = points[1][0][0], points[1][0][1]\n x3, y3 = points[2][0][0], points[2][0][1]\n x4, y4 = points[3][0][0], points[3][0][1]\n\n height = int(np.sqrt(np.square(x1 - x2) + np.square(y2 - y1)))\n width = int(np.sqrt(np.square(x4 - x1) + np.square(y4 - y1)))\n precision = 10\n # height = doc_copy.shape[0]\n # width = doc_copy.shape[1]\n\n from_points = np.float32([[x1 + precision, y1 + precision], [x2 + precision, y2 - precision],\n [x3 - precision, y3 - precision], [x4 - precision, y4 + precision]])\n to_points = np.float32([[0, 0], [0, height], [width, height], [width, 0]])\n\n matrix = cv2.getPerspectiveTransform(from_points, to_points)\n warp_image = cv2.warpPerspective(src=doc_copy, M=matrix, dsize=(width, height))\n\n return warp_image\n\n\ndef enhance_doc(img):\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n blur = cv2.GaussianBlur(gray, (5, 5), 5)\n enhanced_img = cv2.adaptiveThreshold(src=blur, maxValue=255, adaptiveMethod=cv2.ADAPTIVE_THRESH_MEAN_C,\n thresholdType=cv2.THRESH_BINARY, blockSize=5, C=2)\n return enhanced_img\n\ndef save_file(img):\n height, width = img.shape[0], img.shape[1]\n path, dir, files = next(os.walk('resources/saves'))\n total_files = len(files)\n cv2.imwrite('resources/saves/scanned_doc_{}.jpg'.format(total_files + 1), img)\n\n cv2.rectangle(img, (0, height // 2 - 80), (width, height // 2 + 40), (0, 255, 0), cv2.FILLED)\n cv2.putText(img, 'Saved...', (width // 2 - 20, height // 2 - 10), cv2.FONT_HERSHEY_COMPLEX, 1.2,\n (255, 255, 255), 2)\n\n images = si.stacked_images(0.5, [img])\n cv2.imshow('doc', images)\n cv2.waitKey(2000)\n\nwhile True:\n doc = cv2.imread('resources/doc.jpg')\n doc_copy = doc.copy()\n processed_img = process(doc)\n warp_points = find_contour(processed_img)\n if len(warp_points) == 4:\n warp_img = warp(warp_points)\n enhanced_image = enhance_doc(warp_img)\n\n if cv2.waitKey(0) == ord('s'):\n save_file(enhanced_image.copy())\n\n images = si.stacked_images(0.5, [enhanced_image])\n cv2.imshow('doc', images)\n\n if cv2.waitKey(0) == ord('q'):\n break\n\n else:\n print(\"Failed... Make sure all corners of the doc is visible in the image\")\n break\n\n cv2.waitKey(0)\n","sub_path":"Document Scanner.py","file_name":"Document Scanner.py","file_ext":"py","file_size_in_byte":3361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"176063001","text":"# -*- coding: utf-8 -*-\n\n# =============================================================================\n# =======概述\n# 创建日期:2018-05-17\n# 编码人员:王学良\n# 简述:参数窗口类\n#\n# =======使用说明\n# 。。。\n#\n# =======日志\n# 1.2018-05-17 王学良创建文件\n# =============================================================================\n\n# =============================================================================\n# Qt imports\n# =============================================================================\nfrom PyQt5.QtCore import Qt, pyqtSignal\nfrom PyQt5.QtGui import QCloseEvent\nfrom PyQt5.QtWidgets import (QWidget, QDockWidget, QStackedWidget, QLineEdit,\n QTreeWidget, QTreeWidgetItem, QSizePolicy,\n QVBoxLayout, QAbstractItemView)\n\n# =============================================================================\n# Stacked Widget\n# =============================================================================\nclass ParalistDock(QDockWidget):\n signal_close = pyqtSignal()\n \n def __init__(self):\n QStackedWidget.__init__(self)\n \n def setup(self):\n sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())\n self.setSizePolicy(sizePolicy)\n self.layout_paralist_dock = QWidget(self)\n self.layout_paralist_dock.setObjectName(\"layout_paralist_dock\")\n self.vlayout_paralist_dock = QVBoxLayout(self.layout_paralist_dock)\n self.vlayout_paralist_dock.setContentsMargins(1, 1, 1, 1)\n self.vlayout_paralist_dock.setSpacing(2)\n self.vlayout_paralist_dock.setObjectName(\"vlayout_paralist_dock\")\n self.line_edit_search_para = QLineEdit(self.layout_paralist_dock)\n self.line_edit_search_para.setToolTip(\"\")\n self.line_edit_search_para.setInputMask(\"\")\n self.line_edit_search_para.setText(\"\")\n self.line_edit_search_para.setMaxLength(32766)\n self.line_edit_search_para.setFrame(True)\n self.line_edit_search_para.setEchoMode(QLineEdit.Normal)\n self.line_edit_search_para.setAlignment(Qt.AlignLeading|Qt.AlignLeft|Qt.AlignVCenter)\n self.line_edit_search_para.setReadOnly(False)\n self.line_edit_search_para.setObjectName(\"line_edit_search_para\")\n self.vlayout_paralist_dock.addWidget(self.line_edit_search_para)\n self.tree_widget_display_datafile = QTreeWidget(self.layout_paralist_dock)\n self.tree_widget_display_datafile.setObjectName(\"tree_widget_display_datafile\")\n self.tree_widget_display_datafile.headerItem().setText(0, \"1\")\n self.tree_widget_display_datafile.header().setVisible(False)\n self.vlayout_paralist_dock.addWidget(self.tree_widget_display_datafile)\n self.setWidget(self.layout_paralist_dock)\n\n def display(self, file_name):\n if file_name: #file_name is a list\n for each_file in file_name:\n self.tree_widget_display_datafile.setSelectionMode(QAbstractItemView.ExtendedSelection)\n root=QTreeWidgetItem(self.tree_widget_display_datafile) #QTreeWidgetItem object: root\n root.setText(0,each_file) #set text of treewidget\n para_list= file_name[each_file]#ndarray to list\n for i in range(len(para_list)):\n child=QTreeWidgetItem(root) #child of root\n child.setText(0,para_list[i])\n\n\n# 重载关闭事件,需要增加一个关闭的信号让视图的勾选去掉 \n def closeEvent(self, event: QCloseEvent):\n event.accept()\n self.signal_close.emit()\n ","sub_path":"lib/views/paralist_dock.py","file_name":"paralist_dock.py","file_ext":"py","file_size_in_byte":3783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"125336413","text":"import random\r\n\r\n\r\ndef random_phrase():\r\n lines = open('phrases.txt').read().splitlines()\r\n myline = random.choice(lines)\r\n return myline\r\n\r\n\r\ndef random_noun():\r\n nouns = open('nouns.txt').read().splitlines()\r\n mynoun = random.choice(nouns)\r\n return mynoun\r\n\r\n\r\ndef pluralnoun(a):\r\n pn = a\r\n\r\n if pn[-1:] == \"y\":\r\n if pn == \"Kennedy\":\r\n pn = pn + \"s\"\r\n return pn\r\n if pn[-2:] == \"ay\" or pn[-2:] == \"ey\" or pn[-2:] == \"iy\" or pn[-2:] == \"oy\" or pn[-2] == \"uy\":\r\n pn = pn + \"s\"\r\n return pn\r\n else:\r\n pn = pn[:-1] + \"ies\"\r\n return pn\r\n if pn == \"mouse\":\r\n pn = \"mice\"\r\n return pn\r\n if pn == \"woman\":\r\n pn = \"women\"\r\n return pn\r\n if pn == \"man\":\r\n pn = \"men\"\r\n return pn\r\n if pn == \"person\":\r\n pn = \"people\"\r\n return pn\r\n if pn == \"blood\" or pn == \"money\" or pn == \"meat\" or pn == \"police\" or pn == \"dead\" or pn == \"bread\" or pn == \"milk\" or pn == \"sheep\" or pn == \"scum\":\r\n pn = pn\r\n return pn\r\n\r\n if pn[-1:] == \"s\" or pn[-1:] == \"x\" or pn[-2:] == \"sh\" or pn[-2:] == \"ch\":\r\n pn = pn + \"es\"\r\n return pn\r\n\r\n pn = pn + \"s\"\r\n return pn\r\n\r\n\r\ndef random_verb():\r\n verbs = open('verbs.txt').read().splitlines()\r\n myverb = random.choice(verbs)\r\n return myverb\r\n\r\n\r\ndef verb_ing():\r\n ing = random_verb()\r\n if ing != \"reap\" and ing != \"sleep\" and ing != \"fight\" and ing != \"scream\" and ing != \"shoot\" and ing != \"start\" and ing != \"stomp\" and ing != \"burn\" and ing != \"weep\" and ing != \"disgust\":\r\n if ing[-1:] == \"t\" or ing[-1:] == \"p\" or ing[-1:] == \"g\" or ing[-1:] == \"m\" or ing[-1:] == \"n\" or ing[-1:] == \"z\":\r\n ing = ing + ing[-1:] + \"ing\"\r\n return ing\r\n if ing[-1:] == \"e\":\r\n ing = ing[:-1] + \"ing\"\r\n return ing\r\n ing = ing + \"ing\"\r\n return ing\r\n\r\n\r\ndef verb_er():\r\n er = random_verb()\r\n if er != \"reap\" and er != \"sleep\" and er != \"fight\" and er != \"scream\" and er != \"shoot\" and er != \"start\" and er != \"stomp\" and er != \"burn\" and er != \"weep\" and er != \"disgust\":\r\n if er[-1:] == \"t\" or er[-1:] == \"p\" or er[-1:] == \"g\" or er[-1:] == \"m\" or er[-1:] == \"n\" or er[-1:] == \"z\":\r\n er = er + er[-1:] + \"er\"\r\n return er\r\n if er[-1:] == \"y\":\r\n if er[-2:] != \"ay\" and er[-2:] != \"ey\" and er[-2:] != \"iy\" and er[-2:] != \"oy\" and er[-2:] != \"uy\":\r\n er = er[:-1] + \"ier\"\r\n return er\r\n else:\r\n er = er + \"er\"\r\n return er\r\n if er[-1:] == \"e\":\r\n er = er + \"r\"\r\n return er\r\n er = er + \"er\"\r\n return er\r\n\r\n\r\ndef verb_s():\r\n pv = random_verb()\r\n if pv[-1:] == \"s\" or pv[-1:] == \"x\" or pv[-2:] == \"sh\" or pv[-2:] == \"ch\":\r\n pv = pv + \"es\"\r\n return pv\r\n if pv[-1:] == \"y\":\r\n if pv[-2:] == \"ay\" or pv[-2:] == \"ey\" or pv[-2:] == \"iy\" or pv[-2:] == \"iy\" or pv[-2:] == \"oy\" or pv[-2:] == \"uy\":\r\n pv = pv + \"s\"\r\n return pv\r\n else:\r\n pv = pv[:-1] + \"ies\"\r\n return pv\r\n pv = pv + \"s\"\r\n return pv\r\n\r\n\r\ndef verb_ed():\r\n ed = random_verb()\r\n if ed == \"catch\":\r\n ed = \"caught\"\r\n return ed\r\n if ed == \"fly\":\r\n ed = \"flew\"\r\n return ed\r\n if ed == \"drive\":\r\n ed = \"drove\"\r\n return ed\r\n if ed == \"fight\":\r\n ed = \"fought\"\r\n return ed\r\n if ed == \"get\":\r\n ed = \"got\"\r\n return ed\r\n if ed == \"give\":\r\n ed = \"gave\"\r\n return ed\r\n if ed == \"know\":\r\n ed = \"knew\"\r\n return ed\r\n if ed == \"run\":\r\n ed = \"ran\"\r\n return ed\r\n if ed == \"shoot\":\r\n ed = \"shot\"\r\n return ed\r\n if ed == \"sleep\":\r\n ed = \"slept\"\r\n return ed\r\n if ed == \"cut\" or ed == \"hit\" or ed == \"shit\":\r\n ed = ed\r\n return ed\r\n if ed != \"reap\" and ed != \"sleep\" and ed != \"fight\" and ed != \"scream\" and ed != \"shoot\" and ed != \"start\" and ed != \"stomp\" and ed != \"burn\" and ed != \"weep\" and ed != \"disgust\":\r\n if ed[-1:] == \"t\" or ed[-1:] == \"p\" or ed[-1:] == \"g\" or ed[-1:] == \"m\" or ed[-1:] == \"n\" or ed[-1:] == \"z\":\r\n ed = ed + ed[-1:] + \"ed\"\r\n if ed[-1:] == \"y\":\r\n if ed[-2:] != \"ay\" and ed[-2:] != \"ey\" and ed[-2:] != \"iy\" and ed[-2:] != \"oy\" and ed[-2:] != \"uy\":\r\n ed = ed[:-1] + \"ied\"\r\n return ed\r\n else:\r\n ed = ed + \"ed\"\r\n return ed\r\n if ed[-1:] == \"e\":\r\n ed = ed + \"d\"\r\n return ed\r\n ed = ed + \"ed\"\r\n return ed\r\n\r\n\r\ndef random_adjective():\r\n adjectives = open('adjectives.txt').read().splitlines()\r\n myadjective = random.choice(adjectives)\r\n return myadjective\r\n\r\n\r\ndef random_city():\r\n cities = open('cities.txt').read().splitlines()\r\n mycity = random.choice(cities)\r\n return mycity\r\n\r\n\r\ndef random_firstname():\r\n firstnames = open('first_names.txt').read().splitlines()\r\n myfirstname = random.choice(firstnames)\r\n return myfirstname\r\n\r\n\r\ndef random_lastname():\r\n lastnames = open('last_names.txt').read().splitlines()\r\n mylastname = random.choice(lastnames)\r\n return mylastname\r\n\r\n\r\ndef gen():\r\n phrase = random_phrase()\r\n phrase2 = \"\"\r\n while phrase2 != phrase:\r\n phrase2 = phrase\r\n phrase = phrase.replace(\"#noun#\", random_noun().capitalize(), 1)\r\n phrase = phrase.replace(\"#noun.s#\", pluralnoun(random_noun()).capitalize(), 1)\r\n phrase = phrase.replace(\"#verb#\", random_verb().capitalize(), 1)\r\n phrase = phrase.replace(\"#verb.er#\", verb_er().capitalize(), 1)\r\n phrase = phrase.replace(\"#verb.ers#\", pluralnoun(verb_er()).capitalize(), 1)\r\n phrase = phrase.replace(\"#verb.ing#\", verb_ing().capitalize(), 1)\r\n phrase = phrase.replace(\"#verb.ed#\", verb_ed().capitalize(), 1)\r\n phrase = phrase.replace(\"#verb.s#\", verb_s().capitalize(), 1)\r\n phrase = phrase.replace(\"#adjective#\", random_adjective().capitalize(), 1)\r\n phrase = phrase.replace(\"#city#\", random_city(), 1)\r\n phrase = phrase.replace(\"#firstname#\", random_firstname(), 1)\r\n phrase = phrase.replace(\"#lastname#\", random_lastname(), 1)\r\n phrase = phrase.replace(\"#number#\", str(random.randint(1, 1000)), 1)\r\n print(phrase)\r\n return phrase\r\n\r\n\r\ngen()\r\n","sub_path":"generate_phrase.py","file_name":"generate_phrase.py","file_ext":"py","file_size_in_byte":6368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"642158134","text":"import csv\n\nfrom keras.callbacks import Callback\nimport numpy as np\nfrom keras.engine.saving import load_model\nfrom keras.utils import np_utils\nfrom Datas.Datasets import Datasets\nfrom Model.CNN.CnnModel import CNNModel\nfrom Pipeline.cnn.Alone.Metricss import Metricss\nfrom Pipeline.util.tools import calculate_performace\nfrom Result.Alone.EvalModel import EvalModel\n\n\nclass AloneTest(Metricss):\n\n def __init__(self):\n pass\n\n @staticmethod\n def train_model():\n winlist = [8]\n for w in winlist:\n\n pssm_train,pssm_trainlabel=Datasets.getPSSM('DBv5',size=w)\n phychem_train,phychem_trainlabel=Datasets.getPhyChem('DBv5',size=w)\n psaia_train,psaia_trainlabel=Datasets.getPSAIA('DBv5',size=w)\n pssm_test, pssm_testlabel = Datasets.getPSSM('CAPRI', size=w)\n phychem_test,phychem_testlabel=Datasets.getPhyChem('CAPRI',size=w)\n psaia_test,psaia_testlabel=Datasets.getPSAIA('CAPRI',size=w)\n trainData=np.concatenate([pssm_train,phychem_train,psaia_train],axis=-1)\n testData=np.concatenate([pssm_test,phychem_test,psaia_test],axis=-1)\n # pssm_train =pssm_train.reshape(((-1,17,20,1)))\n # pssm_test = pssm_test.reshape(((-1, 17, 20, 1)))\n \n model=CNNModel.CNN1D(shape=(17,20))\n me=Metricss()\n model.fit(pssm_train,pssm_trainlabel,batch_size=50,epochs=400,\n verbose=1,\n callbacks=[me])\n @staticmethod\n def load_model_test():\n w=8\n test_data, test_label = Datasets.getPSSM('CAPRI', size=w)\n eval=EvalModel(8)\n model=load_model('trainedmodel directory')\n y_pro=model.predict(test_data)\n y_class = [int(prob > 0.5) for prob in y_pro.flatten()]\n tp, fp, tn, fn, accuracy, precision, sensitivity, specificity, MCC, f1_score = \\\n calculate_performace(len(y_class), y_class, test_label)\n print('acc:{},pre:{},rec:{},f1:{},MCC:{}'.format(accuracy,precision,sensitivity,f1_score,MCC))\n\nif __name__ == '__main__':\n AloneTest.load_model_test()\n\n","sub_path":"Pipeline/capri-alone/Pssm+phychem+psaia.py","file_name":"Pssm+phychem+psaia.py","file_ext":"py","file_size_in_byte":2115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"333170307","text":"from bs4 import BeautifulSoup\nimport requests\nimport re\nimport urllib.request\nimport os\nimport json\ndef get_soup(url):\n return BeautifulSoup(urllib.request.urlopen(url),'html.parser')\n\nquery = input(\"Artist name : \")\nquery.split()\nquery=query.replace(' ','+')\nurl = 'https://www.google.com/search?rlz=1C1SQJL_koKR812KR812&tbm=isch&q='+query+'&chips=q:'+query+',g_1:painting:' \nprint(url)\nDIR=\"Pictures\"\n\nsoup = get_soup(url)\n\nActualImages=[]\nfor a in soup.findall(\"div\",{\"class\":\"rg_meta\"}):\n link , Type =json.loads(a.text)[\"ou\"] ,json.loads(a.text)[\"ity\"]\n ActualImages.append((link,Type))\nprint(\"there are total\" , len(ActualImages),\"images\")","sub_path":"mini_pro_crawling/google_images_down.py","file_name":"google_images_down.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"418831979","text":"from collections import Counter\nfrom collections import OrderedDict\nfrom datetime import datetime\nfrom itertools import chain\nimport json\nimport logging\nimport os\n\nfrom flask import current_app as app\nimport xlsxwriter\n\nfrom testrail_reporting.testrail.models import (\n Users, Projects, Milestones, Plans, Suites, Runs, Sections, Cases, Tests,\n Results, CaseTypes, Statuses, Priorities, Configs, Reports)\n\nlog = logging.getLogger(__name__)\n\n\nclass ExcelReport(object):\n def __init__(self, filename):\n self.filename = filename\n self.workbook = None\n\n def _calc_column_width(self, val):\n length = 8\n max_length = 60\n if isinstance(val, int):\n length += len(str(val))\n elif isinstance(val, str):\n length += len(val.encode('ascii', 'ignore'))\n return length if length < max_length else max_length\n\n def _build_worksheet(self, title, field_names, data):\n style_bold = self.workbook.add_format({'bold': True})\n worksheet = self.workbook.add_worksheet(title)\n for col, field in enumerate(field_names):\n width = self._calc_column_width(field)\n worksheet.set_column(col, col, width=width)\n worksheet.write(0, col, field, style_bold)\n worksheet.freeze_panes(1, 0)\n\n for row, record in enumerate(data, start=1):\n for col, field in enumerate(record):\n value = field\n if isinstance(value, datetime):\n value = value.isoformat()\n elif isinstance(value, list):\n value = json.dumps(value)\n\n width = self._calc_column_width(value)\n worksheet.set_column(col, col, width=width)\n worksheet.write(row, col, value)\n\n def build_workbook(self):\n raise NotImplementedError()\n\n def generate(self):\n log.info('Generating report...')\n filename = os.path.join(app.config['REPORTS_PATH'], self.filename)\n self.workbook = xlsxwriter.Workbook(filename)\n self.build_workbook()\n self.workbook.close()\n\n report = Reports(filename=self.filename)\n report.save()\n log.info('Report %s has been generated!', filename)\n return report\n\n\nclass MainReport(ExcelReport):\n def __init__(self, filename):\n super(MainReport, self).__init__(filename)\n\n # TODO(rsalin): getting cached data via API\n self.users = {\n d.pk: '{0} ({1})'.format(d.name, d.email)\n for d in Users.objects.no_cache().only('id', 'name', 'email')}\n\n self.projects = {\n d.pk: d.name\n for d in Projects.objects.no_cache().only('id', 'name')}\n\n self.milestones = {\n d.pk: d.name\n for d in Milestones.objects.no_cache().only('id', 'name')}\n\n self.suites = {\n d.pk: d.name\n for d in Suites.objects.no_cache().only('id', 'name')}\n\n self.priorities = {\n d.pk: d.name\n for d in Priorities.objects.no_cache().only('id', 'name')}\n\n self.case_types = {\n d.pk: d.name\n for d in CaseTypes.objects.no_cache().only('id', 'name')}\n\n self.statuses = {\n d.pk: d.label\n for d in Statuses.objects.no_cache().only('id', 'label')}\n\n def _get_replaced_ids(self, row_data):\n additional_fields = OrderedDict()\n for k, v in row_data.items():\n if k == 'project_id':\n additional_fields.update({'project': self.projects.get(v)})\n elif k == 'milestone_id':\n additional_fields.update({'milestone': self.milestones.get(v)})\n elif k == 'assignedto_id':\n additional_fields.update({'assignedto': self.users.get(v)})\n elif k == 'suite_id':\n additional_fields.update({'suite': self.suites.get(v)})\n elif k == 'priority_id':\n additional_fields.update({'priority': self.priorities.get(v)})\n elif k == 'type_id':\n additional_fields.update({'case_type': self.case_types.get(v)})\n elif k == 'status_id':\n additional_fields.update({'status': self.statuses.get(v)})\n elif k == 'created_by' or k == 'updated_by':\n additional_fields.update({k: self.users.get(v)})\n return additional_fields\n\n def _build_data_sheets(self):\n collections = [Users, CaseTypes, Statuses, Priorities, Projects,\n Milestones, Plans, Configs, Suites, Cases, Sections,\n Runs, Tests, Results]\n limit = 1000\n\n for collection in collections:\n field_names = collection.report_fields\n documents = collection.objects \\\n .limit(limit) \\\n .order_by('id') \\\n .no_cache()\n data = []\n for document in documents:\n row_data = []\n row_data_map = OrderedDict(document.to_mongo())\n additional_rows = self._get_replaced_ids(row_data_map)\n row_data_map.update(additional_rows)\n for field in field_names:\n value = row_data_map.get(field)\n row_data.append(value)\n data.append(row_data)\n\n self._build_worksheet(collection.__name__, field_names, data)\n\n def _build_test_runs_sheet(self):\n field_names = ['QA team', 'Run ID', 'Run', 'Run Configuration',\n 'Milestone', 'Passed', 'ProdFailed', 'TestFailed',\n 'InfraFailed', 'Skipped', 'Other', 'Failed', 'Blocked',\n 'In progress', 'Fixed', 'Regression', 'Untested']\n\n case_teams = Cases.objects.only('id', 'custom_qa_team')\n case_teams_map = {}\n for case_team in case_teams:\n case_teams_map[case_team['id']] = getattr(case_team,\n 'custom_qa_team', None)\n\n run_tests = Tests.objects \\\n .only('run_id', 'status_id', 'case_id') \\\n .aggregate(\n {\n \"$group\": {\n \"_id\": {\n \"run_id\": \"$run_id\",\n \"status_id\": \"$status_id\",\n },\n \"cases\": {\"$push\": \"$case_id\"},\n \"count\": {\"$sum\": 1},\n },\n },\n {\n \"$group\": {\n \"_id\": \"$_id.run_id\",\n \"statuses\": {\n \"$push\": {\n \"status\": \"$_id.status_id\",\n \"count\": \"$count\",\n }\n },\n \"cases\": {\"$push\": \"$cases\"},\n }\n },\n )\n tests_map = {}\n for test in run_tests:\n statuses = {}\n for test_status in test['statuses']:\n statuses[self.statuses.get(\n test_status['status'])] = test_status['count']\n\n teams = [case_teams_map.get(t) for t in\n list(chain.from_iterable(test['cases']))\n if case_teams_map.get(t) is not None]\n\n team = None\n try:\n team = Counter(teams).most_common(1)[0][0]\n except IndexError:\n pass\n tests_map[test['_id']] = {\n 'statuses': statuses,\n 'team': team,\n }\n\n data = []\n runs = Runs.objects \\\n .order_by('-id') \\\n .only('id', 'name', 'config', 'milestone_id')\n for run in runs:\n run_id = run['id']\n if run_id in tests_map:\n data.append([\n tests_map[run_id]['team'],\n 'R{0}'.format(run_id),\n getattr(run, 'name', None),\n getattr(run, 'config', None),\n self.milestones.get(getattr(run, 'milestone_id', None)),\n tests_map[run_id]['statuses'].get('Passed', 0),\n tests_map[run_id]['statuses'].get('ProdFailed', 0),\n tests_map[run_id]['statuses'].get('TestFailed', 0),\n tests_map[run_id]['statuses'].get('InfraFailed', 0),\n tests_map[run_id]['statuses'].get('Skipped', 0),\n tests_map[run_id]['statuses'].get('Other', 0),\n tests_map[run_id]['statuses'].get('Failed', 0),\n tests_map[run_id]['statuses'].get('Blocked', 0),\n tests_map[run_id]['statuses'].get('In progress', 0),\n tests_map[run_id]['statuses'].get('Fixed', 0),\n tests_map[run_id]['statuses'].get('Regression', 0),\n tests_map[run_id]['statuses'].get('Untested', 0),\n ]),\n\n self._build_worksheet('Test Runs Report', field_names, data)\n\n def _build_tc_automation_sheet(self):\n field_names = ['QA team', 'Milestone', 'Automated',\n 'Automation in Progress', 'Manual', 'Smoke', 'Core',\n 'Advanced']\n data = []\n\n self._build_worksheet('TC Automation Report', field_names, data)\n\n def build_workbook(self):\n self._build_data_sheets()\n self._build_test_runs_sheet()\n self._build_tc_automation_sheet()\n","sub_path":"testrail_reporting/testrail/reports.py","file_name":"reports.py","file_ext":"py","file_size_in_byte":9522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"388632764","text":"\"\"\"euler #18\"\"\"\n\nimport numpy as np\n\n\"\"\"pretty simple...\nsince we can use brute force, from each point we can drop to index = current\nor we can drop to index = current + 1\"\"\"\n\ntriangle = ([\n[75],\n[95,64],\n[17,47,82],\n[18,35,87,10],\n[20,4,82,47,65],\n[19,1,23,75,3,34],\n[88,2,77,73,7,63,67],\n[99,65,4,28,6,16,70,92],\n[41,41,26,56,83,40,80,70,33],\n[41,48,72,33,47,32,37,16,94,29],\n[53,71,44,65,25,43,91,52,97,51,14],\n[70,11,33,28,77,73,17,78,39,68,17,57],\n[91,71,52,38,17,14,91,43,58,50,27,29,48],\n[63,66,4,68,89,53,67,30,73,16,69,87,40,31],\n[4,62,98,27,23,9,70,98,73,93,38,53,60,4,23]\n])\n\nassert(triangle[1]) == [95,64]\nassert(triangle[3]) == [18,35,87,10]\n\nassert(triangle[0][0]) == 75\nassert(triangle[1][1]) == 64\nassert(triangle[3][3]) == 10\n\nmini_triangle = ([\n[75],\n[95,64],\n[17,47,82],\n[18,35,87,10],\n[20,4,82,47,65],\n])\n\n\"\"\"\ndef brute_search_tree(max_ = 0, curr = 0, row = 0, col= 0):\n \"\"\"\"\"\"just binary search through the tree/triangle\"\"\"\"\"\"\n curr += mini_triangle[row][col]\n if curr > max_:\n max_ = curr\n for branch in [mini_triangle[row + 1][col], mini_triangle[row + 1][col + 1]]:\n try:\n brute_search_tree(branch)\n except IndexError:\n return max_\n\nprint(brute_search_tree())\"\"\"\n\n\ndef greedy_reversed(reversed_tree = list(reversed(mini_triangle))):\n \"\"\"couldn't work out stuff 100-percent and referenced the internet...\"\"\"\n \"\"\"will return to this, eventually, perhaps...\"\"\"\n (print(reversed_tree))\n if len(reversed_tree) == 1:\n return max(reversed_tree[0])\n for col in range(len(reversed_tree[0])):\n try:\n reversed_tree[0][col] = reversed_tree[0][col]+max(\n reversed_tree[1][col], reversed_tree[1][col+1])\n except IndexError:\n pass\n print(\"Reached end of row.\")\n try:\n del reversed_tree[1]\n except IndexError:\n print(\"Value at reversed_tree[1] DNE.\")\n return greedy_reversed(reversed_tree)\n\nprint(greedy_reversed())\n","sub_path":"max_path_sum.py","file_name":"max_path_sum.py","file_ext":"py","file_size_in_byte":1982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"380976907","text":"class Tree:\n def __init__(self, l, r, m=0, left=None, right=None):\n self.l = l\n self.r = r\n self.m = m\n self.left = left\n self.right = right\n\n def __str__(self):\n return str(self.val)\n\n\nclass Solution:\n def maximumSegmentSum(self, nums, removeQueries):\n n = len(nums)\n pre = [0] * (n + 1)\n for i in range(n):\n pre[i + 1] = pre[i] + nums[i]\n root = Tree(0, n - 1, pre[n])\n\n def dfs(idx, node, count):\n ans = 0\n if node.left:\n if node.left.l <= idx <= node.left.r:\n v = dfs(idx, node.left, count - 1)\n ans = max(v, node.right.m)\n else:\n v = dfs(idx, node.right, count - 1)\n ans = max(v, node.left.m)\n else:\n sl, sr = pre[idx] - pre[node.l], pre[node.r + 1] - pre[idx + 1]\n node.left, node.right = Tree(node.l, idx - 1, sl), Tree(idx + 1, node.r, sr)\n ans = max(sl, sr)\n node.m = ans\n return ans\n\n res = [0] * n\n for i, x in enumerate(removeQueries):\n res[i] = dfs(x, root, i)\n\n return res\n\n\ns = Solution()\nprint(s.maximumSegmentSum([500, 822, 202, 707, 298, 484, 311, 680, 901, 319, 343, 340],\n [6, 4, 0, 5, 2, 3, 10, 8, 7, 9, 1, 11]))\n# print(s.maximumSegmentSum([1, 2, 5, 6, 1], [0, 3, 2, 4, 1]))\n","sub_path":"leetcode/2022/bicontest/bcontest-085/bContest4_slow.py","file_name":"bContest4_slow.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"582500685","text":"#!/usr/bin/python3\n#-*-coding:utf-8;-*-\nimport sys\nimport index as cpdaily\nimport yaml\nimport json\nimport requests\nimport uuid\n\nlog = cpdaily.login.log\n\ndef getTaskList(yaml_file='tasks.yml'):\n file_data = '[]'\n with open(yaml_file, 'r', encoding=\"utf-8\") as f:\n file_data = f.read()\n tasks = yaml.load(file_data, Loader=yaml.SafeLoader)\n return tasks\n\ndef ReloadCpdailyLogin(config_file):\n # Ugly hack :(\n # 全局配置\n cpdaily.login.config = cpdaily.login.getYmlConfig(config_file)\n cpdaily.login.session = requests.session()\n cpdaily.login.user = cpdaily.login.config['user']\n # Cpdaily-Extension\n cpdaily.login.extension = {\n \"lon\": cpdaily.login.user['lon'],\n \"model\": \"PCRT00\",\n \"appVersion\": \"8.0.8\",\n \"systemVersion\": \"4.4.4\",\n \"userId\": cpdaily.login.user['username'],\n \"systemName\": \"android\",\n \"lat\": cpdaily.login.user['lat'],\n \"deviceId\": str(uuid.uuid1())\n }\n cpdaily.login.CpdailyInfo = cpdaily.login.DESEncrypt(json.dumps(cpdaily.login.extension))\n cpdaily.login.apis = cpdaily.login.getCpdailyApis(cpdaily.login.user)\n cpdaily.login.host = cpdaily.login.apis['host']\n\ndef ReloadCpdaily(config_file, session_file):\n ReloadCpdailyLogin(config_file)\n cpdaily.config = cpdaily.getYmlConfig(config_file)\n cpdaily.user = cpdaily.config['user']\n cpdaily.restoreSessionFromYml(session_file)\n\ndef main():\n count = 0\n for task in getTaskList():\n count += 1\n try:\n log(\"Reloading config for Task #{} ...\".format(count))\n config_file, session_file = task['config'], task['session']\n ReloadCpdaily(config_file, session_file)\n data = {\n 'sessionToken': cpdaily.sessionToken\n }\n cpdaily.login.getModAuthCas(data)\n params = cpdaily.getUnSignedTasks()\n # log(params)\n task = cpdaily.getDetailTask(params)\n # log(task)\n form = cpdaily.fillForm(task)\n # log(form)\n cpdaily.submitForm(form)\n except Exception as e:\n log(\"Error in task {}: {}\".format(count, str(e)))\n raise e\n\nif __name__ == '__main__':\n main()\n","sub_path":"currency/multiple.py","file_name":"multiple.py","file_ext":"py","file_size_in_byte":2240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"531123972","text":"# ---IMPORTS---\nfrom turtle import Turtle\nfrom random import choice\nfrom constants import *\n\n# ---CONSTANTS---\n\n\nclass Food(Turtle):\n\n def __init__(self):\n super().__init__()\n self.shape(FOOD_SHAPE)\n self.width(FOOD_SIZE)\n self.color(FOOD_COLOR)\n self.speed(FOOD_SPEED)\n self.penup()\n self.refresh()\n\n def refresh(self):\n max_x = int(SCREEN_WIDTH / 2 - self.width() - self.width() / 2)\n max_y = int(SCREEN_HEIGHT / 2 - self.width() - self.width() / 2)\n positions_x = range(-max_x, max_x + 1, self.width())\n positions_y = range(-max_y, max_y + 1, self.width())\n random_x = choice(positions_x)\n random_y = choice(positions_y)\n self.goto(random_x, random_y)\n","sub_path":"food.py","file_name":"food.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"370690875","text":"import pandas as pd\ndf = pd.read_csv(\"POS_tag_sentence.csv\")\nPOS = df['0'].tolist()\nPOS_tag = [tag.split() for tag in POS]\n\n\ndef read_data(file_name):\n df = pd.read_csv(file_name)\n Sentences = ' '.join(df.Sentence.tolist()).split(' . ')\n word = ' '.join(df.Sentence.tolist()).split(' ')\n try:\n target = ' '.join(df.NER.tolist()).split(' ')\n\n except:\n target = df.NER.tolist()\n train = [sentence.strip().split() + ['.'] for sentence in Sentences]\n train[-1] = train[-1][:-1]\n i = 0\n tags = []\n for sentence in train:\n tag = target[i:i + len(sentence)]\n tags.append(tag)\n i += len(sentence)\n print(\"data has been loaded!\")\n return train, tags\n\n\ndef read_test_data(file_name):\n df = pd.read_csv(file_name)\n Sentences = ' '.join(df.Sentence.tolist()).split(' . ')\n word = ' '.join(df.Sentence.tolist()).split(' ')\n train = [sentence.strip().split() + ['.'] for sentence in Sentences]\n train[-1] = train[-1][:-1]\n print(\"test data has been loaded!\")\n return train\n\n\ntrain_data, target_y_train = read_data(\"train.csv\")\nvalidation_data, target_y_validation = read_data(\"val.csv\")\ntest_data = read_test_data('test.csv')\n\ndef tf_idf(data):\n import numpy as np\n DF = {}\n\n for tokensized_doc in data:\n # get each unique word in the doc - we need to know whether the word is appeared in the document\n for term in np.unique(tokensized_doc):\n try:\n DF[term] += 1\n except:\n DF[term] = 1\n\n from nltk.corpus import stopwords\n from nltk.tokenize import word_tokenize\n from collections import Counter\n import math\n\n tf_idf = {}\n\n # total number of documents\n N = len(data)\n\n doc_id = 0\n # get each tokenised doc\n for tokensized_doc in data:\n # initialise counter for the doc\n counter = Counter(tokensized_doc)\n # calculate total number of words in the doc\n total_num_words = len(tokensized_doc)\n\n # get each unique word in the doc\n for term in np.unique(tokensized_doc):\n # calculate Term Frequency\n tf = counter[term] / total_num_words\n\n # calculate Document Frequency\n df = DF[term]\n\n # calculate Inverse Document Frequency\n idf = math.log(N / (df + 1)) + 1\n\n # calculate TF-IDF\n tf_idf[doc_id, term] = tf * idf\n\n doc_id += 1\n\n TF_doc=[]\n for i in range(N):\n temp=[]\n for word in data[i]:\n temp.append(tf_idf[(i,word)])\n TF_doc.append(temp)\n\n return TF_doc\n\nword_to_ix = {}\nfor sentence in train_data+validation_data+test_data:\n for word in sentence:\n word = word.lower()\n if word not in word_to_ix:\n word_to_ix[word] = len(word_to_ix)\nword_list = list(word_to_ix.keys())\n\nSTART_TAG = \"\"\nSTOP_TAG = \"\"\ntag_to_ix = {START_TAG:0, STOP_TAG:1}\nfor tags in target_y_train+target_y_validation:\n for tag in tags:\n if tag not in tag_to_ix:\n tag_to_ix[tag] = len(tag_to_ix)\n\npos_to_ix = {START_TAG:0, STOP_TAG:1}\nfor tags in POS_tag:\n for tag in tags:\n if tag not in pos_to_ix:\n pos_to_ix[tag] = len(pos_to_ix)\n\nimport gensim.downloader as api\nimport numpy as np\nword_emb_model = api.load(\"glove-twitter-50\")\nprint(\"=\"*89)\nprint(\"pre-trained word embedding model has been loaded!\")\nprint(\"=\"*89)\nEMBEDDING_DIM = 50\n\nembedding_matrix = []\nfor word in word_list:\n try:\n embedding_matrix.append(word_emb_model.wv[word])\n except:\n embedding_matrix.append([0]*EMBEDDING_DIM)\nembedding_matrix = np.array(embedding_matrix)\nembedding_matrix.shape\n\ntrain_pos = POS_tag[:len(train_data)]\nval_pos = POS_tag[len(train_data):(len(train_data+validation_data))]\ntest_pos = POS_tag[-len(test_data):]\n\ndef to_index(data, to_ix):\n input_index_list = []\n for sent in data:\n input_index_list.append([to_ix[w] for w in sent])\n return input_index_list\n\ntrain_input_index = to_index(train_data,word_to_ix)\ntrain_pos_index = to_index(train_pos,pos_to_ix)\ntrain_output_index = to_index(target_y_train,tag_to_ix)\nval_input_index = to_index(validation_data,word_to_ix)\nval_pos_index = to_index(val_pos,pos_to_ix)\nval_output_index = to_index(target_y_validation,tag_to_ix)\ntest_input_index = to_index(test_data,word_to_ix)\ntest_pos_index = to_index(test_pos,pos_to_ix)\n\ntrain_tf_idf_index = tf_idf(train_data)\nval_tf_idf_index = tf_idf(validation_data)\ntest_tf_idf_index = tf_idf(test_data)\n#test_output_index = to_index(target_y_test,tag_to_ix)\n\nimport torch\nimport torch.autograd as autograd\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\n\ntorch.manual_seed(1)\n\n\ndef argmax(vec):\n # return the argmax as a python int\n _, idx = torch.max(vec, 1)\n return idx.item()\n\n\n# Compute log sum exp in a numerically stable way for the forward algorithm\ndef log_sum_exp(vec):\n max_score = vec[0, argmax(vec)]\n max_score_broadcast = max_score.view(1, -1).expand(1, vec.size()[1])\n return max_score + \\\n torch.log(torch.sum(torch.exp(vec - max_score_broadcast)))\n\n\nimport torch\nimport torch.autograd as autograd\nimport torch.nn as nn\nimport torch.optim as optim\n\ntorch.manual_seed(1)\n\n\ndef argmax(vec):\n # return the argmax as a python int\n _, idx = torch.max(vec, 1)\n return idx.item()\n\n\n# Compute log sum exp in a numerically stable way for the forward algorithm\ndef log_sum_exp(vec):\n max_score = vec[0, argmax(vec)]\n max_score_broadcast = max_score.view(1, -1).expand(1, vec.size()[1])\n return max_score + \\\n torch.log(torch.sum(torch.exp(vec - max_score_broadcast)))\n\n\nclass BiLSTM_CRF(nn.Module):\n\n def __init__(self, vocab_size, tag_to_ix, pos_to_ix, embedding_dim, hidden_dim,num_layers=2,method='ATTN_TYPE_DOT_PRODUCT'):\n super(BiLSTM_CRF, self).__init__()\n self.method = method\n self.num_layers = num_layers\n self.embedding_dim = embedding_dim\n self.hidden_dim = hidden_dim\n self.vocab_size = vocab_size\n self.tag_to_ix = tag_to_ix\n self.tagset_size = len(tag_to_ix)\n self.pos_to_ix = pos_to_ix\n self.posset_size = len(pos_to_ix)\n\n self.word_embeds = nn.Embedding(vocab_size, embedding_dim)\n\n \"\"\"Here we use the embedding matrix as the initial weights of nn.Embedding\"\"\"\n self.word_embeds.weight.data.copy_(torch.from_numpy(embedding_matrix))\n\n self.lstm = nn.LSTM((embedding_dim + len(pos_to_ix) + 1)*2, hidden_dim // 2,\n num_layers=self.num_layers, bidirectional=True)\n\n # Maps the output of the LSTM into tag space.\n self.hidden2tag = nn.Linear(hidden_dim*2, self.tagset_size)\n\n # Matrix of transition parameters. Entry i,j is the score of\n # transitioning *to* i *from* j.\n self.transitions = nn.Parameter(\n torch.randn(self.tagset_size, self.tagset_size))\n\n # These two statements enforce the constraint that we never transfer\n # to the start tag and we never transfer from the stop tag\n self.transitions.data[tag_to_ix[START_TAG], :] = -10000\n self.transitions.data[:, tag_to_ix[STOP_TAG]] = -10000\n\n self.hidden = self.init_hidden()\n\n def init_hidden(self):\n return (torch.randn(2*self.num_layers, 1, self.hidden_dim // 2).to(device),\n torch.randn(2*self.num_layers, 1, self.hidden_dim // 2).to(device))\n\n def _forward_alg(self, feats):\n # Do the forward algorithm to compute the partition function\n init_alphas = torch.full((1, self.tagset_size), -10000.).to(device)\n # START_TAG has all of the score.\n init_alphas[0][self.tag_to_ix[START_TAG]] = 0.\n\n # Wrap in a variable so that we will get automatic backprop\n forward_var = init_alphas\n\n # Iterate through the sentence\n for feat in feats:\n alphas_t = [] # The forward tensors at this timestep\n for next_tag in range(self.tagset_size):\n # broadcast the emission score: it is the same regardless of\n # the previous tag\n emit_score = feat[next_tag].view(\n 1, -1).expand(1, self.tagset_size)\n # the ith entry of trans_score is the score of transitioning to\n # next_tag from i\n trans_score = self.transitions[next_tag].view(1, -1)\n # The ith entry of next_tag_var is the value for the\n # edge (i -> next_tag) before we do log-sum-exp\n next_tag_var = forward_var + trans_score + emit_score\n # The forward variable for this tag is log-sum-exp of all the\n # scores.\n alphas_t.append(log_sum_exp(next_tag_var).view(1))\n forward_var = torch.cat(alphas_t).view(1, -1)\n terminal_var = forward_var + self.transitions[self.tag_to_ix[STOP_TAG]]\n alpha = log_sum_exp(terminal_var)\n return alpha\n\n\n def _cal_attention(self, hiddens, method):\n attention_result = torch.zeros(hiddens.size()[0], hiddens.size()[-1] * 2, device=device)\n if method == 'ATTN_TYPE_DOT_PRODUCT':\n # bmm: https://pytorch.org/docs/master/generated/torch.bmm.html\n for i in range(hiddens.size()[0]):\n hidden = hiddens[i]\n attn_weights = F.softmax(torch.bmm(hidden.unsqueeze(0).unsqueeze(0), hiddens.T.unsqueeze(0)), dim=-1)\n attn_output = torch.bmm(attn_weights, hiddens.unsqueeze(0))\n concat_output = torch.cat((hidden.unsqueeze(0),attn_output[0]), 1)\n attention_result[i] = concat_output.squeeze(0)\n elif method == 'ATTN_TYPE_SCALE_DOT_PRODUCT':\n for i in range(hiddens.size()[0]):\n hidden = hiddens[i]\n attn_weights = F.softmax(1/np.sqrt(self.hidden_dim)*torch.bmm(hidden.unsqueeze(0).unsqueeze(0), hiddens.T.unsqueeze(0)), dim=-1)\n attn_output = torch.bmm(attn_weights, hiddens.unsqueeze(0))\n concat_output = torch.cat((hidden.unsqueeze(0),attn_output[0]), 1)\n attention_result[i] = concat_output.squeeze(0)\n return attention_result\n def _get_lstm_features(self, sentence, pos_tagging,tf_idf):\n self.hidden = self.init_hidden()\n embeds = self.word_embeds(sentence).view(len(sentence), -1)\n pos = torch.eye(self.posset_size).to(device)[pos_tagging]\n tf_idf = torch.tensor(np.array(tf_idf),dtype=torch.float).unsqueeze(1)\n combined = torch.cat((embeds, pos,tf_idf), 1).view(len(sentence), 1, -1)\n att_out = self._cal_attention(combined.squeeze(1), self.method)\n lstm_out, self.hidden = self.lstm(att_out.unsqueeze(1), self.hidden)\n lstm_out = lstm_out.view(len(sentence), self.hidden_dim)\n return lstm_out\n def _score_sentence(self, feats, tags):\n # Gives the score of a provided tag sequence\n score = torch.zeros(1).to(device)\n tags = torch.cat([torch.tensor([self.tag_to_ix[START_TAG]], dtype=torch.long).to(device), tags])\n for i, feat in enumerate(feats):\n score = score + \\\n self.transitions[tags[i + 1], tags[i]] + feat[tags[i + 1]]\n score = score + self.transitions[self.tag_to_ix[STOP_TAG], tags[-1]]\n return score\n\n def _viterbi_decode(self, feats):\n backpointers = []\n\n # Initialize the viterbi variables in log space\n init_vvars = torch.full((1, self.tagset_size), -10000.).to(device)\n init_vvars[0][self.tag_to_ix[START_TAG]] = 0\n\n # forward_var at step i holds the viterbi variables for step i-1\n forward_var = init_vvars\n for feat in feats:\n bptrs_t = [] # holds the backpointers for this step\n viterbivars_t = [] # holds the viterbi variables for this step\n\n for next_tag in range(self.tagset_size):\n # next_tag_var[i] holds the viterbi variable for tag i at the\n # previous step, plus the score of transitioning\n # from tag i to next_tag.\n # We don't include the emission scores here because the max\n # does not depend on them (we add them in below)\n next_tag_var = forward_var + self.transitions[next_tag]\n best_tag_id = argmax(next_tag_var)\n bptrs_t.append(best_tag_id)\n viterbivars_t.append(next_tag_var[0][best_tag_id].view(1))\n # Now add in the emission scores, and assign forward_var to the set\n # of viterbi variables we just computed\n forward_var = (torch.cat(viterbivars_t) + feat).view(1, -1)\n backpointers.append(bptrs_t)\n\n # Transition to STOP_TAG\n terminal_var = forward_var + self.transitions[self.tag_to_ix[STOP_TAG]]\n best_tag_id = argmax(terminal_var)\n path_score = terminal_var[0][best_tag_id]\n\n # Follow the back pointers to decode the best path.\n best_path = [best_tag_id]\n for bptrs_t in reversed(backpointers):\n best_tag_id = bptrs_t[best_tag_id]\n best_path.append(best_tag_id)\n # Pop off the start tag (we dont want to return that to the caller)\n start = best_path.pop()\n assert start == self.tag_to_ix[START_TAG] # Sanity check\n best_path.reverse()\n return path_score, best_path\n\n def neg_log_likelihood(self, sentence, pos_tagging,tf_idf, tags):\n lstm_out = self._get_lstm_features(sentence, pos_tagging,tf_idf)\n\n attention_feats = self._cal_attention(lstm_out, self.method)\n forward_score = self._forward_alg(attention_feats)\n gold_score = self._score_sentence(attention_feats, tags)\n return forward_score - gold_score\n\n def forward(self, sentence, pos_tagging,tf_idf): # dont confuse this with _forward_alg above.\n # Get the emission scores from the BiLSTM\n lstm_out = self._get_lstm_features(sentence, pos_tagging,tf_idf)\n\n attention_feats = self._cal_attention(lstm_out, self.method)\n attention_feats = self.hidden2tag(attention_feats)\n\n # Find the best path, given the features.\n\n score, tag_seq = self._viterbi_decode(attention_feats)\n return score, tag_seq,attention_feats\n\n\n\nimport numpy as np\nfrom sklearn.metrics import accuracy_score\ndef cal_acc(model, input_index,pos_index,tf_idf_index, output_index):\n ground_truth = []\n predicted = []\n for i in range(len(input_index)):\n input_sent = input_index[i]\n output_tag = output_index[i]\n pos_tag = pos_index[i]\n tf_idf = tf_idf_index[i]\n input_sent = torch.tensor(input_sent, dtype=torch.long).to(device)\n pos_tag = torch.tensor(pos_tag, dtype=torch.long).to(device)\n tf_idf = torch.tensor(tf_idf,dtype=torch.long).to(device)\n _,prediction,_ = model(input_sent,pos_tag,tf_idf)\n predicted = predicted + prediction\n ground_truth = ground_truth + output_tag\n accuracy = float((np.array(predicted)==np.array(ground_truth)).astype(int).sum())/float(len(ground_truth))\n return ground_truth, predicted, accuracy\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nHIDDEN_DIM = 128\nHIDDEN_LAYER=1\nmethod = 'ATTN_TYPE_DOT_PRODUCT'\n\n\nmodel = BiLSTM_CRF(len(word_to_ix), tag_to_ix, pos_to_ix ,EMBEDDING_DIM, HIDDEN_DIM,HIDDEN_LAYER,method).to(device)\noptimizer = optim.SGD(model.parameters(), lr=0.01, weight_decay=1e-4)\n\n\"\"\"Each epoch will take about 1-2 minutes\"\"\"\nprint(\"=\"*89)\nprint(\"start training!\")\nprint(\"=\"*89)\nimport datetime\n\nfor epoch in range(20):\n time1 = datetime.datetime.now()\n train_loss = 0\n\n model.train()\n for i, idxs in enumerate(train_input_index):\n tags_index = train_output_index[i]\n pos_index = train_pos_index[i]\n tf_idf_index = train_tf_idf_index[i]\n\n # Step 1. Remember that Pytorch accumulates gradients.\n # We need to clear them out before each instance\n model.zero_grad()\n\n # Step 2. Get our inputs ready for the network, that is,\n # turn them into Tensors of word indices.\n sentence_in = torch.tensor(idxs, dtype=torch.long).to(device)\n pos_in = torch.tensor(pos_index, dtype=torch.long).to(device)\n tf_idf_in = torch.tensor(tf_idf_index,dtype=torch.float).to(device)\n targets = torch.tensor(tags_index, dtype=torch.long).to(device)\n\n # Step 3. Run our forward pass.\n loss = model.neg_log_likelihood(sentence_in,pos_in,tf_idf_in , targets)\n\n\n # Step 4. Compute the loss, gradients, and update the parameters by\n # calling optimizer.step()\n loss.backward()\n optimizer.step()\n\n train_loss+=loss.item()\n\n model.eval()\n _, _, train_acc = cal_acc(model,train_input_index,train_pos_index,train_tf_idf_index,train_output_index)\n _, _, val_acc = cal_acc(model,val_input_index,val_pos_index,val_tf_idf_index,val_output_index)\n\n val_loss = 0\n for i, idxs in enumerate(val_input_index):\n tags_index = val_output_index[i]\n sentence_in = torch.tensor(idxs, dtype=torch.long).to(device)\n pos_index = val_pos_index[i]\n pos_in = torch.tensor(pos_index, dtype=torch.long).to(device)\n tf_idf_index = val_tf_idf_index[i]\n tf_idf_in = torch.tensor(tf_idf_index,dtype=torch.float).to(device)\n targets = torch.tensor(tags_index, dtype=torch.long).to(device)\n loss = model.neg_log_likelihood(sentence_in,pos_in,tf_idf_in, targets)\n val_loss+=loss.item()\n time2 = datetime.datetime.now()\n\n print(\"Epoch:%d, Training loss: %.2f, train acc: %.4f, val loss: %.2f, val acc: %.4f, time: %.2fs\" %(epoch+1, train_loss,train_acc, val_loss, val_acc, (time2-time1).total_seconds()))\ntorch.save(model,\"NER_pos_tfidf.pt\")\ny_true,y_pred,_ = cal_acc(model,val_input_index,val_pos_index,val_tf_idf_index,val_output_index)\n\ndef decode_output(output_list):\n ix_to_tag = {v:k for k,v in tag_to_ix.items()}\n return [ix_to_tag[output] for output in output_list]\n\ny_true_decode = decode_output(y_true)\ny_pred_decode = decode_output(y_pred)\n\nfrom sklearn.metrics import classification_report\nprint(classification_report(y_true_decode,y_pred_decode,digits=4))\ntest_pos_index[-1]=test_pos_index[-1][:-1]\nground_truth = []\npredicted = []\nfor i in range(len(test_input_index)):\n input_sent = test_input_index[i]\n\n pos_tag = test_pos_index[i]\n tf_idf = test_tf_idf_index[i]\n input_sent = torch.tensor(input_sent, dtype=torch.long).to(device)\n pos_tag = torch.tensor(pos_tag, dtype=torch.long).to(device)\n tf_idf = torch.tensor(tf_idf, dtype=torch.long).to(device)\n _, prediction, _ = model(input_sent, pos_tag, tf_idf)\n predicted = predicted + prediction\n\nprint(predicted)\ntest_output = decode_output(predicted)\n\noutput_file = pd.DataFrame(columns=['Id','Predicted'])\noutput_file['Predicted'] = test_output\noutput_file['Id'] = np.arange(0,len(test_output))\noutput_file.to_csv('predicted.csv', index=False)","sub_path":"ASS2_2att.py","file_name":"ASS2_2att.py","file_ext":"py","file_size_in_byte":19055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"253685845","text":"import pygame\nimport sys\nimport numpy as np\nimport pickle\nimport time\nfrom pathplan import PathPlanner\nfrom visualizer import Visualizer\nfrom collisiondetect import CollisionDetector\nsys.setrecursionlimit(5000)\n\n# Initial Config\nq_init = (100.0, 500.0, 0.0)\nq_goal = (700.0, 500.0, -2.15)\n\n# Define and convert obstacles\nvizer = Visualizer()\nvizer.draw_square(q_init)\nvizer.draw_square(q_goal, color=vizer.RED)\nobstcls = vizer.define_obstacles()\ncd = CollisionDetector(obstcls)\nobstcls_aabb = cd.compute_AABB()\n\n# Plan path using q_init and obstacles\nplanner = PathPlanner(q_init, cd)\n\nstart = time.time()\n# Call algorithm\nrrt_tree = planner.build_rrtstar(K=2000, epsilon=5)\nend = time.time()\nprint('Time taken: %f' % (end - start))\n\n\n# Holonomic\nq_nearest, dist, _ = planner.nearest_neighbour(q_goal, np.array(rrt_tree.vertexMap.keys()))\nq_goal_vtx = planner.reach_goal(rrt_tree, q_goal)\nvizer.plot_graph(rrt_tree, q_init)\nvizer.trace_path(q_goal_vtx)\n\nvizer.draw_square(q_init)\nvizer.draw_square(q_goal, color=vizer.RED)\nwhile True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n","sub_path":"rmp-master/demo3.py","file_name":"demo3.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"595680721","text":"#coding=utf-8\r\n\r\nfrom zope.interface import implementer\r\n\r\nfrom caesar_interface import ICaesarCipher\r\n\r\n@implementer(ICaesarCipher)\r\nclass CaesarCipher():\r\n \"\"\"\r\n\r\n \"\"\"\r\n\r\n @classmethod\r\n def get_cipher_text(cls, filepath='caesar_cipher_text.txt')-> str:\r\n \"\"\"\r\n\r\n :param filepath: path to file with cipher text\r\n :return: string variable with cipher_text from file\r\n :rtype: str\r\n\r\n \"\"\"\r\n with open(filepath, \"r\") as f:\r\n cipher_text = f.read()\r\n return cipher_text\r\n\r\n @classmethod\r\n def create_letter_table(cls,)->list:\r\n \"\"\"\r\n\r\n :return: list with standard order of letters in English\r\n :rtype: list\r\n\r\n \"\"\"\r\n alphabet = [chr(letter) for letter in range(97, 123)]\r\n return alphabet\r\n\r\n @classmethod\r\n def change_letter_offset(cls, elements: list, offset=3)->list:\r\n \"\"\"\r\n\r\n :param elements: list of elements\r\n :param offset: offset for\r\n :return: alphabet letter with offset\r\n :rtype: list\r\n\r\n \"\"\"\r\n return elements[offset:] + elements[:offset]\r\n\r\n @classmethod\r\n def change_letter_in_text(cls, cipher_text=None, alphabet=None , offset=None)->str:\r\n \"\"\"\r\n\r\n :param cipher_text: cipher text str\r\n :param alphabet: list wit letters in alphabet order\r\n :param offset: offset for list alphabet\r\n :return: cipher_text with changed order of letter\r\n \"\"\"\r\n alphabet = cls.create_letter_table() if not alphabet else alphabet\r\n offset = 3 if not offset else offset\r\n alphabet_with_offset = cls.change_letter_offset(alphabet, offset)\r\n cipher_text = cls.get_cipher_text() if not cipher_text else cipher_text\r\n\r\n output = ''\r\n for cipher_letter in cipher_text:\r\n if cipher_letter.isalpha():\r\n index_in_alphabet = alphabet.index(cipher_letter)\r\n output += alphabet_with_offset[index_in_alphabet]\r\n else:\r\n output += ' '\r\n\r\n return output\r\n\r\n @classmethod\r\n def show_all_caesar_permutation(cls, cipher_text=None, alphabet=None):\r\n alphabet = cls.create_letter_table() if not alphabet else alphabet\r\n for offset in range(len(alphabet)):\r\n output = cls.change_letter_in_text(cipher_text=cipher_text, alphabet=alphabet, offset=offset)\r\n print(\"OFFSET: \", offset)\r\n print(output)\r\n print(\"----------------------------\\n\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n CaesarCipher().show_all_caesar_permutation()\r\n","sub_path":"lab1_ad1/caesar_cipher.py","file_name":"caesar_cipher.py","file_ext":"py","file_size_in_byte":2596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"630657810","text":"from django.urls import path\nfrom . import views\n\n\nurlpatterns = [\n path('mdashboard', views.mdashboard, name=\"mdashboard\"),\n path('users', views.users, name=\"users\"),\n path('post_question',views.post_question,name=\"post_question\"),\n path('post_csv_question',views.post_csv_question,name=\"post_csv_question\"),\n path('edit_question',views.edit_question,name=\"edit_question\"),\n path('delete_question',views.delete_question,name=\"delete_question\"),\n]","sub_path":"maintainer/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"309882576","text":"\"\"\"\nThe equilibrium module defines routines for interacting with\ncalculated phase equilibria.\n\"\"\"\nfrom __future__ import print_function\nimport pycalphad.variables as v\nfrom pycalphad.core.utils import broadcast_to\nfrom pycalphad.core.utils import unpack_kwarg\nfrom pycalphad.core.utils import sizeof_fmt\nfrom pycalphad.core.utils import unpack_condition, unpack_phases\nfrom pycalphad import calculate, Model\nfrom pycalphad.constraints import mole_fraction\nfrom pycalphad.core.lower_convex_hull import lower_convex_hull\nfrom pycalphad.core.autograd_utils import build_functions\nfrom sympy import Add, Mul, Symbol\n\nimport xray\nimport numpy as np\nfrom collections import namedtuple, OrderedDict\nimport itertools\ntry:\n set\nexcept NameError:\n from sets import Set as set #pylint: disable=W0622\n\n# Maximum number of solver iterations\nMAX_ITERATIONS = 100\n# Maximum number of backtracking iterations\nMAX_BACKTRACKING = 5\n# Maximum number of Newton steps to take\nMAX_NEWTON_ITERATIONS = 50\n# If the max of the potential difference between iterations is less than\n# MIN_PROGRESS J/mol-atom, stop the refinement\nMIN_PROGRESS = 1e-4\n# Minimum norm of a Newton direction before it's \"zero\"\nMIN_DIRECTION_NORM = 1e-12\n# Force zero values to this amount, for numerical stability\nMIN_SITE_FRACTION = 1e-16\n# initial value of 'alpha' in Newton-Raphson procedure\nINITIAL_STEP_SIZE = 1.\n\nPhaseRecord = namedtuple('PhaseRecord', ['variables', 'grad', 'hess', 'plane_grad', 'plane_hess'])\n\nclass EquilibriumError(Exception):\n \"Exception related to calculation of equilibrium\"\n pass\n\ndef equilibrium(dbf, comps, phases, conditions, **kwargs):\n \"\"\"\n Calculate the equilibrium state of a system containing the specified\n components and phases, under the specified conditions.\n Model parameters are taken from 'dbf'.\n\n Parameters\n ----------\n dbf : Database\n Thermodynamic database containing the relevant parameters.\n comps : list\n Names of components to consider in the calculation.\n phases : list or dict\n Names of phases to consider in the calculation.\n conditions : dict or (list of dict)\n StateVariables and their corresponding value.\n verbose : bool, optional (Default: True)\n Show progress of calculations.\n grid_opts : dict, optional\n Keyword arguments to pass to the initial grid routine.\n\n Returns\n -------\n Structured equilibrium calculation.\n\n Examples\n --------\n None yet.\n \"\"\"\n active_phases = unpack_phases(phases) or sorted(dbf.phases.keys())\n comps = sorted(comps)\n indep_vars = ['T', 'P']\n grid_opts = kwargs.pop('grid_opts', dict())\n verbose = kwargs.pop('verbose', True)\n phase_records = dict()\n callable_dict = kwargs.pop('callables', dict())\n grad_callable_dict = kwargs.pop('grad_callables', dict())\n hess_callable_dict = kwargs.pop('hess_callables', dict())\n points_dict = dict()\n maximum_internal_dof = 0\n conds = OrderedDict((key, unpack_condition(value)) for key, value in sorted(conditions.items(), key=str))\n str_conds = OrderedDict((str(key), value) for key, value in conds.items())\n indep_vals = list([float(x) for x in np.atleast_1d(val)]\n for key, val in str_conds.items() if key in indep_vars)\n components = [x for x in sorted(comps) if not x.startswith('VA')]\n # Construct models for each phase; prioritize user models\n models = unpack_kwarg(kwargs.pop('model', Model), default_arg=Model)\n if verbose:\n print('Components:', ' '.join(comps))\n print('Phases:', end=' ')\n for name in active_phases:\n mod = models[name]\n if isinstance(mod, type):\n models[name] = mod = mod(dbf, comps, name)\n variables = sorted(mod.energy.atoms(v.StateVariable).union({key for key in conditions.keys() if key in [v.T, v.P]}), key=str)\n site_fracs = sorted(mod.energy.atoms(v.SiteFraction), key=str)\n maximum_internal_dof = max(maximum_internal_dof, len(site_fracs))\n # Extra factor '1e-100...' is to work around an annoying broadcasting bug for zero gradient entries\n #models[name].models['_broadcaster'] = 1e-100 * Mul(*variables) ** 3\n out = models[name].energy\n undefs = list(out.atoms(Symbol) - out.atoms(v.StateVariable))\n for undef in undefs:\n out = out.xreplace({undef: float(0)})\n callable_dict[name], grad_callable_dict[name], hess_callable_dict[name] = \\\n build_functions(out, [v.P, v.T] + site_fracs)\n\n # Adjust gradient by the approximate chemical potentials\n hyperplane = Add(*[v.MU(i)*mole_fraction(dbf.phases[name], comps, i)\n for i in comps if i != 'VA'])\n plane_obj, plane_grad, plane_hess = build_functions(hyperplane, [v.MU(i) for i in comps if i != 'VA']+site_fracs)\n phase_records[name.upper()] = PhaseRecord(variables=variables,\n grad=grad_callable_dict[name],\n hess=hess_callable_dict[name],\n plane_grad=plane_grad,\n plane_hess=plane_hess)\n if verbose:\n print(name, end=' ')\n if verbose:\n print('[done]', end='\\n')\n\n # 'calculate' accepts conditions through its keyword arguments\n grid_opts.update({key: value for key, value in str_conds.items() if key in indep_vars})\n if 'pdens' not in grid_opts:\n grid_opts['pdens'] = 100\n\n coord_dict = str_conds.copy()\n coord_dict['vertex'] = np.arange(len(components))\n grid_shape = np.meshgrid(*coord_dict.values(),\n indexing='ij', sparse=False)[0].shape\n coord_dict['component'] = components\n if verbose:\n print('Computing initial grid', end=' ')\n\n grid = calculate(dbf, comps, active_phases, output='GM',\n model=models, callables=callable_dict, fake_points=True, **grid_opts)\n\n if verbose:\n print('[{0} points, {1}]'.format(len(grid.points), sizeof_fmt(grid.nbytes)), end='\\n')\n\n properties = xray.Dataset({'NP': (list(str_conds.keys()) + ['vertex'],\n np.empty(grid_shape)),\n 'GM': (list(str_conds.keys()),\n np.empty(grid_shape[:-1])),\n 'MU': (list(str_conds.keys()) + ['component'],\n np.empty(grid_shape)),\n 'points': (list(str_conds.keys()) + ['vertex'],\n np.empty(grid_shape, dtype=np.int))\n },\n coords=coord_dict,\n attrs={'iterations': 1},\n )\n # Store the potentials from the previous iteration\n current_potentials = properties.MU.copy()\n\n for iteration in range(MAX_ITERATIONS):\n if verbose:\n print('Computing convex hull [iteration {}]'.format(properties.attrs['iterations']))\n # lower_convex_hull will modify properties\n lower_convex_hull(grid, properties)\n progress = np.abs(current_potentials - properties.MU).values\n converged = (progress < MIN_PROGRESS).all(axis=-1)\n if verbose:\n print('progress', progress.max(), '[{} conditions updated]'.format(np.sum(~converged)))\n if progress.max() < MIN_PROGRESS:\n if verbose:\n print('Convergence achieved')\n break\n current_potentials[...] = properties.MU.values\n if verbose:\n print('Refining convex hull')\n # Insert extra dimensions for non-T,P conditions so GM broadcasts correctly\n energy_broadcast_shape = grid.GM.values.shape[:len(indep_vals)] + \\\n (1,) * (len(str_conds) - len(indep_vals)) + (grid.GM.values.shape[-1],)\n driving_forces = np.einsum('...i,...i',\n properties.MU.values[..., np.newaxis, :].astype(np.float),\n grid.X.values[np.index_exp[...] +\n (np.newaxis,) * (len(str_conds) - len(indep_vals)) +\n np.index_exp[:, :]].astype(np.float)) - \\\n grid.GM.values.view().reshape(energy_broadcast_shape)\n\n for name in active_phases:\n dof = len(models[name].energy.atoms(v.SiteFraction))\n current_phase_indices = (grid.Phase.values == name).reshape(energy_broadcast_shape[:-1] + (-1,))\n # Broadcast to capture all conditions\n current_phase_indices = np.broadcast_arrays(current_phase_indices,\n np.empty(driving_forces.shape))[0]\n # This reshape is safe as long as phases have the same number of points at all indep. conditions\n current_phase_driving_forces = driving_forces[current_phase_indices].reshape(\n current_phase_indices.shape[:-1] + (-1,))\n # Note: This works as long as all points are in the same phase order for all T, P\n current_site_fractions = grid.Y.values[..., current_phase_indices[(0,) * len(str_conds)], :]\n if np.sum(current_site_fractions[(0,) * len(indep_vals)][..., :dof]) == dof:\n # All site fractions are 1, aka zero internal degrees of freedom\n # Impossible to refine these points, so skip this phase\n points_dict[name] = current_site_fractions[(0,) * len(indep_vals)][..., :dof]\n continue\n # Find the N points with largest driving force for a given set of conditions\n # Remember that driving force has a sign, so we want the \"most positive\" values\n # N is the number of components, in this context\n # N points define a 'best simplex' for every set of conditions\n # We also need to restrict ourselves to one phase at a time\n trial_indices = np.argpartition(current_phase_driving_forces,\n -len(components), axis=-1)[..., -len(components):]\n trial_indices = trial_indices.ravel()\n statevar_indices = np.unravel_index(np.arange(np.multiply.reduce(properties.GM.values.shape + (len(components),))),\n properties.GM.values.shape + (len(components),))[:len(indep_vals)]\n points = current_site_fractions[np.index_exp[statevar_indices + (trial_indices,)]]\n points.shape = properties.points.shape[:-1] + (-1, maximum_internal_dof)\n # The Y arrays have been padded, so we should slice off the padding\n points = points[..., :dof]\n #print('Starting points shape: ', points.shape)\n #print(points)\n if len(points) == 0:\n if name in points_dict:\n del points_dict[name]\n # No nearly stable points: skip this phase\n continue\n\n num_vars = len(phase_records[name].variables)\n plane_grad = phase_records[name].plane_grad\n plane_hess = phase_records[name].plane_hess\n statevar_grid = np.meshgrid(*itertools.chain(indep_vals), sparse=True, indexing='ij')\n # TODO: A more sophisticated treatment of constraints\n num_constraints = len(dbf.phases[name].sublattices)\n constraint_jac = np.zeros((num_constraints, num_vars-len(indep_vars)))\n # Independent variables are always fixed (in this limited implementation)\n #for idx in range(len(indep_vals)):\n # constraint_jac[idx, idx] = 1\n # This is for site fraction balance constraints\n var_idx = 0#len(indep_vals)\n for idx in range(len(dbf.phases[name].sublattices)):\n active_in_subl = set(dbf.phases[name].constituents[idx]).intersection(comps)\n constraint_jac[idx,\n var_idx:var_idx + len(active_in_subl)] = 1\n var_idx += len(active_in_subl)\n\n newton_iteration = 0\n while newton_iteration < MAX_NEWTON_ITERATIONS:\n flattened_points = points.reshape(points.shape[:len(indep_vals)] + (-1, points.shape[-1]))\n grad_args = itertools.chain([i[..., None] for i in statevar_grid],\n [flattened_points[..., i] for i in range(flattened_points.shape[-1])])\n grad = np.array(phase_records[name].grad(*grad_args), dtype=np.float)\n # Remove derivatives wrt T,P\n grad = grad[..., len(indep_vars):]\n grad.shape = points.shape\n grad[np.isnan(grad).any(axis=-1)] = 0 # This is necessary for gradients on the edge of space\n hess_args = itertools.chain([i[..., None] for i in statevar_grid],\n [flattened_points[..., i] for i in range(flattened_points.shape[-1])])\n hess = np.array(phase_records[name].hess(*hess_args), dtype=np.float)\n # Remove derivatives wrt T,P\n hess = hess[..., len(indep_vars):, len(indep_vars):]\n hess.shape = points.shape + (hess.shape[-1],)\n hess[np.isnan(hess).any(axis=(-2, -1))] = np.eye(hess.shape[-1])\n plane_args = itertools.chain([properties.MU.values[..., i][..., None] for i in range(properties.MU.shape[-1])],\n [points[..., i] for i in range(points.shape[-1])])\n cast_grad = np.array(plane_grad(*plane_args), dtype=np.float)\n # Remove derivatives wrt chemical potentials\n cast_grad = cast_grad[..., properties.MU.shape[-1]:]\n grad = grad - cast_grad\n plane_args = itertools.chain([properties.MU.values[..., i][..., None] for i in range(properties.MU.shape[-1])],\n [points[..., i] for i in range(points.shape[-1])])\n cast_hess = np.array(plane_hess(*plane_args), dtype=np.float)\n # Remove derivatives wrt chemical potentials\n cast_hess = cast_hess[..., properties.MU.shape[-1]:, properties.MU.shape[-1]:]\n cast_hess = -cast_hess + hess\n hess = cast_hess.astype(np.float, copy=False)\n try:\n e_matrix = np.linalg.inv(hess)\n except np.linalg.LinAlgError:\n print(hess)\n raise\n current = calculate(dbf, comps, name, output='GM',\n model=models, callables=callable_dict,\n fake_points=False,\n points=points.reshape(points.shape[:len(indep_vals)] + (-1, points.shape[-1])),\n **grid_opts)\n current_plane = np.multiply(current.X.values.reshape(points.shape[:-1] + (len(components),)),\n properties.MU.values[..., np.newaxis, :]).sum(axis=-1)\n current_df = current.GM.values.reshape(points.shape[:-1]) - current_plane\n #print('Inv hess check: ', np.isnan(e_matrix).any())\n #print('grad check: ', np.isnan(grad).any())\n dy_unconstrained = -np.einsum('...ij,...j->...i', e_matrix, grad)\n #print('dy_unconstrained check: ', np.isnan(dy_unconstrained).any())\n proj_matrix = np.dot(e_matrix, constraint_jac.T)\n inv_matrix = np.rollaxis(np.dot(constraint_jac, proj_matrix), 0, -1)\n inv_term = np.linalg.inv(inv_matrix)\n #print('inv_term check: ', np.isnan(inv_term).any())\n first_term = np.einsum('...ij,...jk->...ik', proj_matrix, inv_term)\n #print('first_term check: ', np.isnan(first_term).any())\n # Normally a term for the residual here\n # We only choose starting points which obey the constraints, so r = 0\n cons_summation = np.einsum('...i,...ji->...j', dy_unconstrained, constraint_jac)\n #print('cons_summation check: ', np.isnan(cons_summation).any())\n cons_correction = np.einsum('...ij,...j->...i', first_term, cons_summation)\n #print('cons_correction check: ', np.isnan(cons_correction).any())\n dy_constrained = dy_unconstrained - cons_correction\n #print('dy_constrained check: ', np.isnan(dy_constrained).any())\n # TODO: Support for adaptive changing independent variable steps\n new_direction = dy_constrained\n #print('new_direction', new_direction)\n #print('points', points)\n # Backtracking line search\n if np.isnan(new_direction).any():\n print('new_direction', new_direction)\n #print('Convergence angle:', -(grad*new_direction).sum(axis=-1) / (np.linalg.norm(grad, axis=-1) * np.linalg.norm(new_direction, axis=-1)))\n new_points = points + INITIAL_STEP_SIZE * new_direction\n alpha = np.full(new_points.shape[:-1], INITIAL_STEP_SIZE, dtype=np.float)\n alpha[np.all(np.linalg.norm(new_direction, axis=-1) < MIN_DIRECTION_NORM, axis=-1)] = 0\n negative_points = np.any(new_points < 0., axis=-1)\n while np.any(negative_points):\n alpha[negative_points] *= 0.5\n new_points = points + alpha[..., np.newaxis] * new_direction\n negative_points = np.any(new_points < 0., axis=-1)\n # Backtracking line search\n # alpha now contains maximum possible values that keep us inside the space\n # but we don't just want to take the biggest step; we want the biggest step which reduces energy\n new_points = new_points.reshape(new_points.shape[:len(indep_vals)] + (-1, new_points.shape[-1]))\n candidates = calculate(dbf, comps, name, output='GM',\n model=models, callables=callable_dict,\n fake_points=False, points=new_points, **grid_opts)\n candidate_plane = np.multiply(candidates.X.values.reshape(points.shape[:-1] + (len(components),)),\n properties.MU.values[..., np.newaxis, :]).sum(axis=-1)\n energy_diff = (candidates.GM.values.reshape(new_direction.shape[:-1]) - candidate_plane) - current_df\n new_points.shape = new_direction.shape\n bad_steps = energy_diff > alpha * 1e-4 * (new_direction * grad).sum(axis=-1)\n backtracking_iterations = 0\n while np.any(bad_steps):\n alpha[bad_steps] *= 0.5\n new_points = points + alpha[..., np.newaxis] * new_direction\n #print('new_points', new_points)\n #print('bad_steps', bad_steps)\n new_points = new_points.reshape(new_points.shape[:len(indep_vals)] + (-1, new_points.shape[-1]))\n candidates = calculate(dbf, comps, name, output='GM',\n model=models, callables=callable_dict,\n fake_points=False, points=new_points, **grid_opts)\n candidate_plane = np.multiply(candidates.X.values.reshape(points.shape[:-1] + (len(components),)),\n properties.MU.values[..., np.newaxis, :]).sum(axis=-1)\n energy_diff = (candidates.GM.values.reshape(new_direction.shape[:-1]) - candidate_plane) - current_df\n #print('energy_diff', energy_diff)\n new_points.shape = new_direction.shape\n bad_steps = energy_diff > alpha * 1e-4 * (new_direction * grad).sum(axis=-1)\n backtracking_iterations += 1\n if backtracking_iterations > MAX_BACKTRACKING:\n break\n biggest_step = np.max(np.linalg.norm(new_points - points, axis=-1))\n if biggest_step < 1e-2:\n if verbose:\n print('N-R convergence on mini-iteration', newton_iteration, '[{}]'.format(name))\n points = new_points\n break\n if verbose:\n #print('Biggest step:', biggest_step)\n #print('points', points)\n #print('grad of points', grad)\n #print('new_direction', new_direction)\n #print('alpha', alpha)\n #print('new_points', new_points)\n pass\n points = new_points\n newton_iteration += 1\n new_points = points.reshape(points.shape[:len(indep_vals)] + (-1, points.shape[-1]))\n new_points = np.concatenate((current_site_fractions[..., :dof], new_points), axis=-2)\n points_dict[name] = new_points\n\n if verbose:\n print('Rebuilding grid', end=' ')\n grid = calculate(dbf, comps, active_phases, output='GM',\n model=models, callables=callable_dict,\n fake_points=True, points=points_dict, **grid_opts)\n if verbose:\n print('[{0} points, {1}]'.format(len(grid.points), sizeof_fmt(grid.nbytes)), end='\\n')\n properties.attrs['iterations'] += 1\n\n # One last call to ensure 'properties' and 'grid' are consistent with one another\n lower_convex_hull(grid, properties)\n ravelled_X_view = grid['X'].values.view().reshape(-1, grid['X'].values.shape[-1])\n ravelled_Y_view = grid['Y'].values.view().reshape(-1, grid['Y'].values.shape[-1])\n ravelled_Phase_view = grid['Phase'].values.view().reshape(-1)\n # Copy final point values from the grid and drop the index array\n # For some reason direct construction doesn't work. We have to create empty and then assign.\n properties['X'] = xray.DataArray(np.empty_like(ravelled_X_view[properties['points'].values]),\n dims=properties['points'].dims + ('component',))\n properties['X'].values[...] = ravelled_X_view[properties['points'].values]\n properties['Y'] = xray.DataArray(np.empty_like(ravelled_Y_view[properties['points'].values]),\n dims=properties['points'].dims + ('internal_dof',))\n properties['Y'].values[...] = ravelled_Y_view[properties['points'].values]\n # TODO: What about invariant reactions? We should perform a final driving force calculation here.\n # We can handle that in the same post-processing step where we identify single-phase regions.\n properties['Phase'] = xray.DataArray(np.empty_like(ravelled_Phase_view[properties['points'].values]),\n dims=properties['points'].dims)\n properties['Phase'].values[...] = ravelled_Phase_view[properties['points'].values]\n del properties['points']\n return properties\n","sub_path":"pycalphad/core/equilibrium.py","file_name":"equilibrium.py","file_ext":"py","file_size_in_byte":23292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"302650266","text":"from odoo import models,fields,api\nimport base64\nimport datetime as DT\n\nclass StockProductionLot(models.Model):\n _inherit = 'stock.production.lot'\n\n expiry_days = fields.Integer('expiry Days before', default=7)\n\n @api.model\n def sent_email_expiry(self):\n Mail = self.env['mail.mail']\n email_template = self.env['ir.model.data'].get_object('product_expiry_notification',\n 'email_template_product_expiry')\n today = DT.date.today()\n lots = self.search([('life_date', '!=', False)])\n expired_lots = 'Recapitulation of all list lot of product thats already expired
'\n for lot in lots:\n expiry_days = 7\n life_date = DT.datetime.strptime(lot.life_date, \"%Y-%m-%d %H:%M:%S\")\n if lot.expiry_days:\n expiry_days = lot.expiry_days\n notification_date = life_date - DT.timedelta(days=expiry_days)\n if notification_date.date() <= today:\n expired_lots += ''+ lot.name + ' of product name ' + lot.product_id.name + '
'\n\n values = {\n 'model': 'stock.production.lot',\n 'res_id': False,\n 'subject': email_template.subject,\n 'body': '',\n 'body_html': email_template.body_html + expired_lots,\n 'parent_id': None,\n 'email_from': email_template.email_from,\n # 'auto_delete': True,\n 'email_to': email_template.email_to,\n 'email_cc': email_template.email_cc\n }\n Mail.create(values).send()\n","sub_path":"product_expiry_notification/models/stock_production_lot.py","file_name":"stock_production_lot.py","file_ext":"py","file_size_in_byte":1642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"646560133","text":"# coding: utf-8\nfrom django.db import connection, transaction\n\n@transaction.atomic()\ndef raw_save(record):\n\n cursor = connection.cursor()\n\n sql = [\"UPDATE %s SET\" % record._meta.db_table]\n args = []\n for j, field in enumerate(record._meta.fields):\n sql.extend(['\"%s\"' % field.column, ' = ', '%s'])\n args.append(field.get_prep_value(getattr(record, field.attname)))\n if j != len(record._meta.fields) - 1:\n sql.append(',')\n\n sql.append('WHERE id = %s')\n args.append(record.id)\n sql = ' '.join(sql)\n\n cursor.execute(sql, args)\n","sub_path":"dext/common/utils/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"500751866","text":"#!/usr/bin/env python3\nimport os\nfrom setuptools import setup\nfrom os import walk, path\n\nURL = \"https://github.com/OpenVoiceOS/skill-ovos-hello-world\"\nSKILL_CLAZZ = \"HelloWorldSkill\" # needs to match __init__.py class name\nPYPI_NAME = \"ovos-skill-hello-world\" # pip install PYPI_NAME\n\n# below derived from github url to ensure standard skill_id\nSKILL_AUTHOR, SKILL_NAME = URL.split(\".com/\")[-1].split(\"/\")\nSKILL_PKG = SKILL_NAME.lower().replace('-', '_')\nPLUGIN_ENTRY_POINT = f'{SKILL_NAME.lower()}.{SKILL_AUTHOR.lower()}={SKILL_PKG}:{SKILL_CLAZZ}'\n# skill_id=package_name:SkillClass\n\n\ndef find_resource_files():\n resource_base_dirs = (\"locale\", \"ui\", \"vocab\", \"dialog\", \"regex\", \"skill\")\n base_dir = path.dirname(__file__)\n package_data = [\"*.json\"]\n for res in resource_base_dirs:\n if path.isdir(path.join(base_dir, res)):\n for (directory, _, files) in walk(path.join(base_dir, res)):\n if files:\n package_data.append(\n path.join(directory.replace(base_dir, \"\").lstrip('/'),\n '*'))\n return package_data\n\n\nwith open(\"README.md\", \"r\") as f:\n long_description = f.read()\n\n\ndef get_version():\n \"\"\" Find the version of this skill\"\"\"\n version_file = os.path.join(os.path.dirname(__file__), 'version.py')\n major, minor, build, alpha = (None, None, None, None)\n with open(version_file) as f:\n for line in f:\n if 'VERSION_MAJOR' in line:\n major = line.split('=')[1].strip()\n elif 'VERSION_MINOR' in line:\n minor = line.split('=')[1].strip()\n elif 'VERSION_BUILD' in line:\n build = line.split('=')[1].strip()\n elif 'VERSION_ALPHA' in line:\n alpha = line.split('=')[1].strip()\n\n if ((major and minor and build and alpha) or\n '# END_VERSION_BLOCK' in line):\n break\n version = f\"{major}.{minor}.{build}\"\n if int(alpha):\n version += f\"a{alpha}\"\n return version\n\n\nsetup(\n name=PYPI_NAME,\n version=get_version(),\n long_description=long_description,\n url=URL,\n author=SKILL_AUTHOR,\n description='OVOS hello world skill plugin',\n author_email='jarbasai@mailfence.com',\n license='Apache-2.0',\n package_dir={SKILL_PKG: \"\"},\n package_data={SKILL_PKG: find_resource_files()},\n packages=[SKILL_PKG],\n include_package_data=True,\n keywords='ovos skill plugin',\n entry_points={'ovos.plugin.skill': PLUGIN_ENTRY_POINT}\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"47909029","text":"from person import *\nimport pickle\n\nman1 = Manager('Mechael Dodo', 20000)\nman2 = Person('Joji')\nfile = open(r'C:\\Users\\admin\\AppData\\Local\\Programs\\Python\\Python37-32\\mypyt\\first_work_with_classes\\dodo.pkl','wb')\narr = [man1, man2]\npickle.dump(arr, file)\nfile.close()\n\n\nman3 = Person('Stepan Veteran', 'dancer', 7000)\nimport shelve\ndb = shelve.open('personshelvedb')\nfor obj in (man1, man2, man3):\n db[obj.name] = obj\ndb.close()\n\nimport glob\nprint(glob.glob('pers*'))\n","sub_path":"mypyt/first_work_with_classes/testdb.py","file_name":"testdb.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"103883002","text":"import argparse\nimport csv\nimport json\n\nfrom core_data_modules.cleaners import PhoneCleaner\nfrom core_data_modules.logging import Logger\nfrom core_data_modules.util import PhoneNumberUuidTable\nfrom id_infrastructure.firestore_uuid_table import FirestoreUuidTable\nfrom storage.google_cloud import google_cloud_utils\n\nfrom src.lib import PipelineConfiguration\n\nlog = Logger(__name__)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"De-identifies a CSV by converting the phone numbers in \"\n \"the specified column to avf phone ids\")\n\n parser.add_argument(\"csv_input_path\", metavar=\"recovered-csv-input-url\",\n help=\"Path to a CSV file to de-identify a column of\")\n parser.add_argument(\"pipeline_configuration_file_path\", metavar=\"pipeline-configuration-file\",\n help=\"Path to the pipeline configuration json file\")\n parser.add_argument(\"google_cloud_credentials_file_path\", metavar=\"google-cloud-credentials-file-path\",\n help=\"Path to a Google Cloud service account credentials file to use to access the \"\n \"credentials bucket\")\n\n parser.add_argument(\"column_to_de_identify\", metavar=\"column-to-de-identify\",\n help=\"Name of the column containing phone numbers to be de-identified\")\n parser.add_argument(\"de_identified_csv_output_path\", metavar=\"de-identified-csv-output-path\",\n help=\"Path to write the de-identified CSV to\")\n\n args = parser.parse_args()\n\n csv_input_path = args.csv_input_path\n pipeline_configuration_file_path = args.pipeline_configuration_file_path\n google_cloud_credentials_file_path = args.google_cloud_credentials_file_path\n column_to_de_identify = args.column_to_de_identify\n de_identified_csv_output_path = args.de_identified_csv_output_path\n\n # Read the settings from the configuration file\n log.info(\"Loading Pipeline Configuration File...\")\n with open(pipeline_configuration_file_path) as f:\n pipeline_configuration = PipelineConfiguration.from_configuration_file(f)\n\n log.info(\"Downloading Rapid Pro access token...\")\n rapid_pro_token = google_cloud_utils.download_blob_to_string(\n google_cloud_credentials_file_path, pipeline_configuration.rapid_pro_token_file_url).strip()\n\n log.info(\"Downloading Firestore UUID Table credentials...\")\n firestore_uuid_table_credentials = json.loads(google_cloud_utils.download_blob_to_string(\n google_cloud_credentials_file_path,\n pipeline_configuration.phone_number_uuid_table.firebase_credentials_file_url\n ))\n\n phone_number_uuid_table = FirestoreUuidTable(\n pipeline_configuration.phone_number_uuid_table.table_name,\n firestore_uuid_table_credentials,\n \"avf-phone-uuid-\"\n )\n log.info(\"Initialised the Firestore UUID table\")\n\n log.info(f\"Loading csv from '{csv_input_path}'...\")\n with open(csv_input_path, \"r\", encoding='utf-8-sig') as f:\n raw_data = list(csv.DictReader(f))\n log.info(f\"Loaded {len(raw_data)} rows\")\n\n log.info(f\"Normalising phone numbers in column '{column_to_de_identify}'...\")\n for row in raw_data:\n row[column_to_de_identify] = PhoneCleaner.normalise_phone(row[column_to_de_identify])\n\n log.info(f\"De-identifying column '{column_to_de_identify}'...\")\n phone_numbers = [row[column_to_de_identify] for row in raw_data]\n phone_to_uuid_lut = phone_number_uuid_table.data_to_uuid_batch(phone_numbers)\n for row in raw_data:\n row[column_to_de_identify] = phone_to_uuid_lut[row[column_to_de_identify]]\n\n log.info(f\"Exporting {len(raw_data)} de-identified rows to {de_identified_csv_output_path}...\")\n with open(de_identified_csv_output_path, \"w\") as f:\n writer = csv.DictWriter(f, fieldnames=raw_data[0].keys())\n writer.writeheader()\n\n for row in raw_data:\n writer.writerow(row)\n log.info(f\"Exported de-identified csv\")\n","sub_path":"de_identify_csv.py","file_name":"de_identify_csv.py","file_ext":"py","file_size_in_byte":4017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"111660432","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 28 08:03:00 2021\n\n@author: maurop\n\"\"\"\n\nimport math\n\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\n\nimport Blocks\n\n\nblocks = Blocks.load_blocks()\n\ndef draw_rectangle(color, ax = None):\n if ax == None:\n fig, ax = plt.subplots()\n\n ax.add_patch(patches.Rectangle((0,0), 1, 1, facecolor=color))\n \n plt.show()\n\n\ndef distance(p1, p2):\n \n sq = 0\n \n for i in range(3):\n sq += (p2[i] - p1[i])**2\n \n return math.sqrt(sq)\n\ndef wdistance(c1, c2):\n \n c1 = [x * 256 for x in c1]\n c2 = [x * 256 for x in c2]\n \n R1 = c1[0]\n G1 = c1[1]\n B1 = c1[2]\n \n R2 = c2[0]\n G2 = c2[1]\n B2 = c2[2]\n \n \n r = (R1 + R2) / 2\n \n DR = R1 - R2\n DG = G1 - G2\n DB = B1 - B2\n \n\n dc = math.sqrt((2 + r /256) * DR ** 2 + 4 * DG ** 2 + (2 + (255 - r)/256) * DB ** 2)\n \n return dc\n\n\n\ndef best_block(color):\n \n mind = None\n best_block = None\n \n for block in blocks:\n \n dblock = wdistance(color, block.average_color())\n \n if mind == None:\n mind = dblock\n best_block = block\n \n \n elif dblock < mind:\n \n mind = dblock\n best_block = block\n \n return best_block\n\n\n\ndef best_block_image(image):\n \n dim = image.size\n \n colors_analyzed = {}\n \n px_matrix = image.load()\n \n block_matrix = []\n \n for i in range(dim[0]):\n \n row = []\n block_matrix.append(row)\n\n for j in range(dim[1]):\n \n px = px_matrix[i, j]\n \n color = tuple([x / 256 for x in px])\n \n if color in colors_analyzed:\n row.append(colors_analyzed[color])\n else:\n bblock = best_block(color)\n \n colors_analyzed[color] = bblock\n \n row.append(bblock)\n \n return block_matrix\n \n \nclass Stack:\n \n def __init__(self):\n \n self.stack_size = 20\n \n self.stack = []\n \n self.refused_blocks = []\n \n \n def add(self, block, distance):\n \n for b, _ in self.stack:\n if block == b:\n print(\"block already in stack\")\n return\n \n for b, _ in self.refused_blocks:\n if block == b:\n print(\"block lready refused\")\n \n \n \n \n if len(self.stack) < self.stack_size:\n self.stack.append((block, distance))\n \n else:\n # append\n \n self.stack.append((block, distance))\n \n # sort\n \n self.stack.sort(key=lambda i : i[1])\n \n # pop\n \n refused = self.stack.pop()\n \n self.refused_blocks.append(refused)\n \n def print_block_names(self):\n for block, distance in self.stack:\n print(block.name, f\"{distance:.2f}\", [f\"{x:.2f}\" for x in block.average_color()])\n \n def show_images(self):\n \n for block, _ in self.stack:\n \n fig, axs = plt.subplots(nrows=1, ncols=2)\n \n axs[0].imshow(block.image)\n \n draw_rectangle(block.average_color(), axs[1])\n \n\ndef top_matching_blocks(color):\n stack = Stack()\n\n\n for block in blocks:\n \n dblock = wdistance(color, block.average_color())\n \n stack.add(block, dblock) \n \n return stack\n","sub_path":"FindBestBlock.py","file_name":"FindBestBlock.py","file_ext":"py","file_size_in_byte":3641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"375908696","text":"import sys\n\ndef is_sdn(n_str):\n for x in enumerate(n_str):\n if n_str.count(str(x[0])) != int(x[1]):\n return 0\n return 1\n\nwith open(sys.argv[1], \"r\") as fh:\n for td in fh.read().split(\"\\n\"):\n print(str(is_sdn(td)))\n","sub_path":"Easy/self_describing_numbers.py","file_name":"self_describing_numbers.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"202091993","text":"\"\"\"\nCrie um pograma onde 4 jogadores joguem dados e tenham\nresultados aleatórios. Guarde esses resultados em um dicionário\nNo final, coloque esse dicionário em ordem, sabendo que o\nvencedor tirou o maior número do dado.\n\"\"\"\nfrom random import randint\nfrom time import sleep\nfrom operator import itemgetter\njogo = {'jogador1': randint(1,6),\n 'jogador2': randint(1,6),\n 'jogador3': randint(1,6),\n 'jogador4': randint(1,6)}\nranking = []\nprint(f'{\"VALORES SORTEADOS:\":^30}')\nfor k, v in jogo.items():\n print(f'{k} tirou {v} no dado.')\n sleep(1)\nranking = sorted(jogo.items(), key=itemgetter(1), reverse=True) # coloca o dicionário em ordem pela posição indicada.\nprint('='*30)\nprint(f'{\"=== RANKING DOS JOGADORES ===\":^30}')\n\nfor i, v in enumerate(ranking):\n print(f'{i+1}º lugar: {v[0]} tirou {v[1]}')\n sleep(1)\n","sub_path":"exe091.py","file_name":"exe091.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"539446262","text":"# Definition for a undirected graph node\n# class UndirectedGraphNode:\n# def __init__(self, x):\n# self.label = x\n# self.neighbors = []\nclass Solution:\n def cloneGraph(self, node):\n node_copy_map = {None: None}\n\n def dfs(node):\n if node not in node_copy_map:\n node_copy = UndirectedGraphNode(node.label)\n node_copy_map[node] = node_copy\n node_copy.neighbors = [dfs(child) for child in node.neighbors]\n return node_copy_map[node]\n\n return dfs(node)\n\n\nclass Solution:\n # @param node, a undirected graph node\n # @return a undirected graph node\n def cloneGraph(self, node):\n if not node:\n return node\n\n stack = [node]\n root = UndirectedGraphNode(node.label)\n dct = {node.label: root}\n\n while stack:\n top = stack.pop()\n for n in top.neighbors:\n if n.label not in dct:\n stack.append(n)\n dct[n.label] = UndirectedGraphNode(n.label)\n dct[top.label].neighbors.append(dct[n.label])\n\n return root","sub_path":"leetcode/py/133.py","file_name":"133.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"251702451","text":"# Программа для редактирования файлов.\r\n# Буланый Константин\r\n# ИУ7-16Б\r\n\r\n\r\ndef input_natural(natural_message, error_message): # Проверка на натуральное число.\r\n while True:\r\n try:\r\n line = input(natural_message)\r\n if \"e\" in line or float(line) != int(line) or int(line) <= 0:\r\n print(error_message)\r\n continue\r\n return int(line)\r\n except ValueError:\r\n print(error_message)\r\n continue\r\n\r\n\r\ndef choose_read(): # Выбор файла на чтение.\r\n global file\r\n try: # Если какой-то файл открыт, то он будет закрыт.\r\n file.close()\r\n except AttributeError:\r\n pass\r\n try:\r\n name = input('\\nВведите имя файла: ')\r\n file = open(name, 'r', encoding='UTF8')\r\n print('Вы выбрали файл: ', name)\r\n except:\r\n print('Файл не найден.')\r\n\r\n\r\ndef create(): # Создание файла.\r\n global file\r\n try: # Если какой-то файл открыт, то он будет закрыт.\r\n file.close()\r\n except AttributeError:\r\n pass\r\n try:\r\n name = input('\\nВведите имя файла: ')\r\n file = open(name, 'w', encoding='UTF8')\r\n file.close()\r\n print('Вы создали файл: ', name)\r\n print('Файл закрыт.')\r\n\r\n except:\r\n print('Неправильно указано имя.')\r\n\r\n\r\ndef all_records(): # Вывод всех записей.\r\n global file\r\n if type(file) == bool: # Если file - bool переменная, то файл не был выбран.\r\n print('Вы не выбрали файл.')\r\n else:\r\n heading = True # Если True, то выведется заголовок.\r\n file.seek(0, 0)\r\n for line in file:\r\n if heading:\r\n print('| Автор | Книга | Год |')\r\n heading = False\r\n print('|{:^20}|{:^20}|{:^20}|'.format(line.split('|')[1], line.split('|')[2], line.split('|')[3]))\r\n\r\n\r\ndef one_field(): # Поиск по автору.\r\n global file\r\n if type(file) == bool: # Если file - bool переменная, то файл не был выбран.\r\n print('Вы не выбрали файл.')\r\n else:\r\n author = input('Введите автора: ')\r\n found = True # Если True, то выведется сообщение, что не найдено совпадений.\r\n heading = True # Если True, то выведется заголовок.\r\n file.seek(0, 0)\r\n for line in file:\r\n if line.split('|')[1].lower() == author.lower():\r\n if heading:\r\n print('| Автор | Книга | Год |')\r\n heading = False\r\n print('|{:^20}|{:^20}|{:^20}|'.format(line.split('|')[1], line.split('|')[2], line.split('|')[3]))\r\n found = False\r\n if found:\r\n print('Совпадений не найдено.')\r\n\r\n\r\ndef two_field(): # Поиск по автору и году публикации.\r\n global file\r\n if type(file) == bool: # Если file - bool переменная, то файл не был выбран.\r\n print('Вы не выбрали файл.')\r\n else:\r\n author = input('Введите автора: ')\r\n year = input_natural('Введите год публикации: ', 'Год публикации должен быть натуральным числом.')\r\n found = True # Если True, то выведется сообщение, что не найдено совпадений.\r\n heading = True # Если True, то выведется заголовок.\r\n file.seek(0, 0)\r\n for line in file:\r\n if line.split('|')[1].lower() == author.lower() and int(line.split('|')[3]) == year:\r\n if heading:\r\n print('| Автор | Книга | Год |')\r\n heading = False\r\n print('|{:^20}|{:^20}|{:^20}|'.format(line.split('|')[1], line.split('|')[2], line.split('|')[3]))\r\n found = False\r\n if found:\r\n print('Совпадений не найдено.')\r\n\r\n\r\ndef add_record(): # Добавление записей.\r\n global file\r\n try: # Если какой-то файл открыт, то он будет закрыт.\r\n file.close()\r\n except AttributeError:\r\n pass\r\n\r\n name = input('\\nВведите имя файла, в который хотите добавить запись: ')\r\n file = open(name, 'a', encoding='UTF8')\r\n print('Вы выбрали файл: ', name)\r\n\r\n while True:\r\n author = input('Введите имя автора: ')\r\n while len(author) > 19 or '|' in author:\r\n print('Неправильный ввод.')\r\n author = input('Введите имя автора: ')\r\n book = input('Введите название книги: ')\r\n while len(book) > 19 or '|' in author:\r\n print('Неправильный ввод.')\r\n book = input('Введите название книги: ')\r\n year = input('Введите год публикации: ')\r\n while len(year) > 19 or '|' in author:\r\n print('Неправильный ввод.')\r\n year = input_natural('Введите год публикации: ', 'Год публикации должен быть натуральным числом.')\r\n file.write('|' + author + '|' + book + '|' + year + '|\\n')\r\n\r\n if input('Если хотите продолжнить запись, введите любую строку, иначе нажмите Enter: ') == '':\r\n print('Информация успешно записана, файл закрыт.')\r\n file.close()\r\n file = False\r\n break\r\n\r\n\r\ndef exit_prgm(): # Выход из программы.\r\n global ext, file\r\n ext = True\r\n try:\r\n file.close()\r\n print('Программа завершена успешно.')\r\n except AttributeError:\r\n print('Программа завершена успешно.')\r\n pass\r\n\r\n\r\next = False # Переменная, показывающая был ли инициализирован выход из программы.\r\nfile = False\r\nwhile True:\r\n print('\\nВведите номер операции, которую хотите выполнить:\\n',\r\n '0. Открыть файл.\\n',\r\n '1. Создать файл.\\n',\r\n '2. Вывести все записи.\\n',\r\n '3. Поиск по автору.\\n',\r\n '4. Поиск по автору и году публикации.\\n',\r\n '5. Добавить запись.\\n',\r\n '6. Завершение программы.\\n',\r\n 'Ввод: ', sep='', end='')\r\n\r\n try:\r\n operation = int(input())\r\n if operation not in [0, 1, 2, 3, 4, 5, 6]:\r\n print('Некорректный ввод номера операции. Попробуйте снова.', end='')\r\n else:\r\n {0: choose_read, 1: create, 2: all_records,\r\n 3: one_field, 4: two_field, 5: add_record, 6: exit_prgm}[operation]()\r\n except ValueError:\r\n print('Некорректный ввод номера операции. Попробуйте снова.', end='')\r\n\r\n if ext:\r\n break\r\n","sub_path":"term_01/labs/23. Лаба 10 Файлы текст.py","file_name":"23. Лаба 10 Файлы текст.py","file_ext":"py","file_size_in_byte":7887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"578362602","text":"from django import template\nregister = template.Library()\n\n\n@register.inclusion_tag('family/blood.html')\ndef blood_graph(takes_context=True):\n groups = [(36, 'O+'), (30, 'B+'), (21, 'A+'), (8, 'AB+'), (4, 'O-'), (3, 'B-'), (2, 'A-'), (1, 'AB-')]\n blood = '
General Availability
'\n for g in groups:\n blood += ''+ ' ' * g[0] + ' ' + g[1] + '
'\n blood += '
Approximate Graph
'\n return {'blood': blood}\n\n","sub_path":"family/templatetags/gopala_tags.py","file_name":"gopala_tags.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"414128196","text":"from time import sleep, clock\nfrom threading import Thread, Timer\nimport random\n\nclass Election_Timer:\n\n def __init__(self, duration: float, target):\n self.target = target\n self.duration = duration\n self.running = True\n self.restart = False\n self.stop = False\n\n t = Thread( \n\t\t\ttarget=self.run, \n\t\t\tname='Election Timer Thread'\n\t\t\t)\n t.start()\n\n def kill_thread(self):\n self.running = False\n\n def stop_timer(self):\n self.stop = True\n\n def restart_timer(self):\n self.restart = True\n self.stop = False\n\n def new_timeout(self) -> float:\n return (self.duration + 2*self.duration * random.random())\n\n def run(self):\n # randomize timeouts to avoid conflicting elections\n timeout = self.new_timeout()\n #start the timer\n start = clock()\n count = 0\n while self.running:\n while not self.stop:\n count += 1\n if self.restart:\n timeout = self.new_timeout()\n start = clock()\n self.restart = False\n\n elapsed_time = clock() - start\n if elapsed_time > timeout:\n print('\\nCountodwn elapsed ', timeout, ',', self.target.id, ' Starting Election \\n')\n self.target.start_election()\n self.restart_timer()\n break\n else:\n if count > 20000: \n print('Election Timer: ', timeout-elapsed_time) \n count =0\n","sub_path":"code/ElectionTimer.py","file_name":"ElectionTimer.py","file_ext":"py","file_size_in_byte":1610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"552807507","text":"#!/bin/python3\n#Utilities for downloading and parsing Final Fantasy 14 Loadstone content\n#Copyright Arthur Moore 2016 BSD 3 clause license\n#Updated and revised by Akurosia Kamo in 2018\n\nimport requests\nfrom bs4 import BeautifulSoup\nimport re\n\n#Get a page from the Loadstone\n# returns a BeautifulSoup object\ndef get_loadstone_page(url,session_id):\n #Time format used for cookies\n #import time\n #time.strftime('%a, %d-%b-%Y %H:%M:%S %Z')\n #ldst_is_support_browser=1, ldst_touchstone=1, ldst_bypass_browser=1\", expires=session_expiration\n cookies = dict(ldst_sess=session_id,domain='finalfantasyxiv.com', path='/')\n raw_page = requests.get(url, cookies=cookies)\n\n if(raw_page.status_code != 200):\n raise Exception(\"Unable to download web page!\")\n\n return BeautifulSoup(raw_page.text,'html.parser')\n\n# Return charachter id derived from \"My charachter\" button on lodestone\ndef get_character_id(session_id):\n char_id = []\n url = 'http://de.finalfantasyxiv.com/lodestone/'\n soup_page = get_loadstone_page(url,session_id)\n my_char_button = soup_page.find(\"ul\", attrs={\"class\": 'my-menu__colmun'})\n my_char_link = my_char_button.find_all(\"a\")[1].get('href')\n char_id.append(my_char_link.split(\"/\")[3].encode(\"utf-8\"))\n return char_id\n\n# Return fc id derived from the character page, default tab\ndef get_fc_id(char_id, session_id):\n fc_id = []\n url = 'http://de.finalfantasyxiv.com/lodestone/character/'+ str(char_id) + '/'\n soup_page = get_loadstone_page(url,session_id)\n fc_button = soup_page.find(\"div\", attrs={\"class\": 'character__freecompany__name'})\n fc_link = fc_button.find(\"a\").get('href')\n fc_id.append(fc_link.split(\"/\")[3].encode(\"utf-8\"))\n return fc_id\n\n# Return retainer ids from character page, retainer tab\ndef get_retainer_ids(char_id, session_id):\n url = 'http://de.finalfantasyxiv.com/lodestone/character/'+ str(char_id) + '/retainer/'\n soup_page = get_loadstone_page(url,session_id)\n retainer_button = soup_page.find(\"ul\", attrs={\"class\": 'parts__switch js__toggle_item'})\n retainer_links = retainer_button.find_all(\"a\")\n links = []\n for link in retainer_links:\n links.append(link.get('href').split(\"/\")[5].encode(\"utf-8\"))\n return links\n\n# Get all items in the Free company chest (does not get number of crystals yet)\ndef get_fc_items(fc_id,session_id):\n url = 'http://de.finalfantasyxiv.com/lodestone/freecompany/'+str(fc_id)+'/chest/'\n soup_page = get_loadstone_page(url,session_id)\n #Get all items\n raw_items=soup_page.find_all(\"li\", attrs={\"class\": \"item-list__list\"})\n #Parse the items\n items=[]\n items.append(get_fc_gil(soup_page))\n items += get_crystal(soup_page, 'Company Chest')\n for item in raw_items:\n tmp = {}\n tmp['name'] = item.find(\"h2\", attrs={\"class\": 'db-tooltip__item__name'}).text.strip().encode(\"utf-8\")\n tmp['quantity'] = int(item['data-stack'])\n tmp['quality'] = \"\\\"HQ\\\"\" if item.find(\"h2\").find(\"img\") != None else \"\"\n tmp['image'] = \"\"\n tmp['location'] = 'Company Chest'\n tmp['sub_location'] = item.find_parent('ul')['id']\n items.append(tmp)\n return items\n\n#get Gil from FC chest (may produce an issue when user cannot see fc chest)\ndef get_fc_gil(soup_page):\n tmp = {}\n tmp['name'] = \"Gil\"\n tmp['quantity'] = soup_page.find(\"div\", attrs={\"class\": 'freecompany__chest__header--gil'}).p.text.strip().encode(\"utf-8\")\n tmp['quality'] = \"\"\n tmp['image'] = \"\"\n tmp['location'] = 'Company Chest'\n tmp['sub_location'] = \"Money\"\n return tmp\n\n#Get all items in a retainers inventory (does not get number of crystals)\ndef get_retainer_items(char_id,retainer_id,session_id):\n url = 'http://de.finalfantasyxiv.com/lodestone/character/'+str(char_id)+'/retainer/'+retainer_id+'/baggage/'\n soup_page = get_loadstone_page(url,session_id)\n #Get retainers name\n retainer_name = soup_page.find(\"h3\", attrs={\"class\": 'retainer__data--name'}).text.strip().encode(\"utf-8\")\n #Get all items\n raw_items=soup_page.find_all(\"li\", attrs={\"class\": \"item-list__list sys_item_row\"})\n #Parse the items\n items=[]\n items.append(get_retainer_gil(soup_page, retainer_name))\n items += get_crystal(soup_page, 'Retainer: ' + retainer_name)\n for item in raw_items:\n tmp = {}\n tmp['name'] = item.find(\"h2\", attrs={\"class\": 'db-tooltip__item__name'}).text.strip().encode(\"utf-8\")\n tmp['quantity'] = int(item['data-stack'])\n tmp['quality'] = \"\\\"HQ\\\"\" if item.find(\"h2\").find(\"img\") != None else \"\"\n tmp['image'] = \"\"\n tmp['location'] = 'Retainer: ' + retainer_name\n tmp['sub_location'] = 'Inventory'\n items.append(tmp)\n return items\n\n# Get gil from Retainer\ndef get_retainer_gil(soup_page, retainer_name):\n tmp = {}\n tmp['name'] = \"Gil\"\n tmp['quantity'] = soup_page.find(\"div\", attrs={\"class\": 'heading__toggle'}).p.text.strip().encode(\"utf-8\")\n tmp['quality'] = \"\"\n tmp['image'] = \"\"\n tmp['location'] = 'Retainer: ' + str(retainer_name)\n tmp['sub_location'] = \"Money\"\n return tmp\n\n# Get all retainer crystals\ndef get_crystal(soup_page, location):\n table = soup_page.find(\"div\", attrs={\"class\": 'table__crystal'})\n crystal_types = table.find(\"thead\").find_all(\"span\")\n crystal_body = table.find(\"tbody\")\n crsytal_lines = crystal_body.find_all(\"tr\")\n items = []\n for crsytal_line in crsytal_lines:\n element = crsytal_line.find(\"span\")['data-tooltip']\n for i in range(3):\n type = crystal_types[i]['data-tooltip']\n name = (element + \" \" + type).strip().encode(\"utf-8\")\n qty = crsytal_line.find_all(\"a\")[i].text.encode(\"utf-8\")\n image = name.lower().replace(\" \", \"\")\n items.append(create_cristal_item(name,qty,image,location))\n return items\n\n# Gather crystal information and create a \"crystal\" item\ndef create_cristal_item(name, quantity, image, location):\n tmp = {}\n tmp['name'] = name\n tmp['quantity'] = quantity\n tmp['quality'] = \"\"\n tmp['image'] = \"
\"\n tmp['location'] = location\n tmp['sub_location'] = 'Crystal Inventory'\n return tmp\n\n# Get all items a retainer is selling (does not get number of crystals)\ndef get_retainer_selling(char_id,retainer_id,session_id):\n url = 'http://de.finalfantasyxiv.com/lodestone/character/'+str(char_id)+'/retainer/'+retainer_id\n soup_page = get_loadstone_page(url,session_id)\n #Get retainers name\n retainer_name = soup_page.find(\"h3\", attrs={\"class\": 'retainer__data--name'}).text.strip().encode(\"utf-8\")\n #Get all items\n sale_inventory=soup_page.find(\"div\", attrs={\"class\": 'retainer__content sys_retainer-content'})\n #If no items, just return an empty set\n if not sale_inventory:\n return []\n raw_items=sale_inventory.find_all(\"li\", attrs={\"class\": 'item-list__list'})\n #Parse the items\n items=[]\n for item in raw_items:\n tmp = {}\n tmp['name'] = item.find(\"h2\", attrs={\"class\": 'db-tooltip__item__name'}).text.strip().encode(\"utf-8\")\n tmp['quantity'] = int(item.find_all(\"div\", attrs={\"class\": 'item-list__item item-list__cell--sm'})[1].text.strip())\n tmp['image'] = \"\"\n tmp['location'] = 'Retainer: ' + retainer_name\n tmp['sub_location'] = 'Selling'\n tmp['quality'] = \"\\\"HQ\\\"\" if item.find(\"h2\").find(\"img\") != None else \"\"\n items.append(tmp)\n return items\n\n# Use this to convert the provided items into something useful\ndef list_items_table(items):\n item_row_format='{name} {quality}{quantity}{image}{location}{sub_location}'\n item_buffer = ''\n checkf = '{quantity}'\n for i in items:\n check = str(checkf.format(**i))\n if (int(check.replace(\".\",\"\"))>0):\n item_buffer += item_row_format.format(**i)\n item_buffer += '
Item NameQuantityImageLocationSub-LocationLock
'\n return item_buffer\n\n# Converts the item table to full html content page\ndef items2html(table):\n yourdomain = \"https://example.com\"\n meta = \"\"\n css = \"\"\n js = \"\"\n js += \"\"\n inputfield = \"
\"\n inputfield += \"
\"\n searchfield = \"
\"\n searchfield += \"
\"\n searchfield += \"\"\n head = \"\" + meta + css + js + \"\"\n body = \"\" + inputfield + \"
\" + table + searchfield + \"
\" + \"\"\n html = \"\" + head + body + \"\"\n return BeautifulSoup(html, \"html.parser\").prettify().encode(\"utf-8\")\n\n#Debug function to write some data to '.html'\ndef write_data(char_id, data):\n out_file=open(str(char_id)+'.html','w')\n out_file.write(data)\n out_file.close()","sub_path":"parse_loadstone.py","file_name":"parse_loadstone.py","file_ext":"py","file_size_in_byte":10595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"583380317","text":"# -*- coding: utf-8 -*-\n#\n# WowBand\n# Matthew Kwon\n#\n\n\nfrom dp_tornado.engine.model import Model as dpModel\n\n\nclass BruteForceModel(dpModel):\n def cache_key(self, identifier):\n return 'temporary:common:brute:force:attack:%s' % identifier\n\n def validate(self, identifier, max_attempt=5):\n if isinstance(identifier, (tuple, list)):\n for e in identifier:\n if not self.validate(e, max_attempt):\n return False\n\n return True\n\n count = self.cache.get\n\n return False if count and int(count) >= max_attempt else True\n\n def failed(self, identifier, duration=60*60):\n if isinstance(identifier, (tuple, list)):\n for e in identifier:\n self.failed(e, duration)\n\n return\n\n return self.cache.increase(self.cache_key(identifier), 1, 'kg.db/temporary', expire_in=duration)\n\n def success(self, identifier):\n if isinstance(identifier, (tuple, list)):\n for e in identifier:\n self.success(e)\n\n return\n\n return self.cache.delete(self.cache_key(identifier), 'kg.db/temporary')\n","sub_path":"model/bjs/common/brute_force.py","file_name":"brute_force.py","file_ext":"py","file_size_in_byte":1155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"455459007","text":"import json\nimport unittest\nfrom mock import Mock\nfrom werkzeug.test import Client\nfrom wsgiservice import get_app\nimport guess_language\nfrom controllers import LanguageDetector\n\n\nclass LanguageDetectorTestCase(unittest.TestCase):\n\n def setUp(self):\n self.app = get_app(globals())\n self.client = Client(self.app)\n guess_language.guessLanguage = Mock(return_value='en')\n\n def test_post_request_with_valid_data(self):\n data = {'text': 'Hello world. Has the sun risen on you today.'}\n response, status, headers = self.client.post(data=data)\n\n self.assertEqual('200 OK', status)\n self.assertEqual({'language': 'en'}, json.loads(response[0]))\n self.assertIn('application/json', headers.get('Content-type'))\n\n def test_post_request_without_text(self):\n data = {}\n response, status, headers = self.client.post(data=data)\n\n self.assertEqual('200 OK', status)\n self.assertEqual({}, json.loads(response[0]))\n self.assertIn('application/json', headers.get('Content-type'))\n\n def test_get_request(self):\n response, status, headers = self.client.get()\n\n self.assertEqual('501 Not Implemented', status)\n\n def test_put_request(self):\n response, status, headers = self.client.put()\n\n self.assertEqual('501 Not Implemented', status)\n\n def test_delete_request(self):\n response, status, headers = self.client.delete()\n\n self.assertEqual('501 Not Implemented', status)\n\n\ndef run_tests():\n test_suite = unittest.TestSuite()\n test_suite.addTest(unittest.makeSuite(LanguageDetectorTestCase))\n runner = unittest.TextTestRunner()\n runner.run(test_suite)","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"569681910","text":"class Solution:\n \n used = [False] * 9\n \n def numberOfPatterns(self, m, n):\n \"\"\"\n :type m: int\n :type n: int\n :rtype: int\n \"\"\"\n count = 0\n for i in range(m, n+1):\n count += self.search(-1, i) \n self.used = [False] * 9\n return count\n \n def search(self, last, length):\n if length == 0: return 1\n count = 0\n for i in range(9):\n if self.isValid(last, i):\n self.used[i] = True\n count += self.search(i, length-1)\n self.used[i] = False\n return count\n \n def isValid(self, curr, nxt):\n if curr == -1: return True\n if self.used[nxt]: return False\n if (curr + nxt) % 2: return True\n mid = (curr + nxt) // 2 \n if mid == 4: return self.used[mid]\n if curr % 3 != nxt % 3 and curr // 3 != nxt // 3:\n return True\n return self.used[mid]","sub_path":"leetcode/python/ex_351.py","file_name":"ex_351.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"327721383","text":"# Copyright 2020 The dm_control Authors.\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\"\"\"Tests for the Rodent.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\nfrom dm_control import composer\nfrom dm_control import mjcf\nfrom dm_control.composer.observation.observable import base as observable_base\nfrom dm_control.locomotion.arenas import corridors as corr_arenas\nfrom dm_control.locomotion.tasks import corridors as corr_tasks\nfrom dm_control.locomotion.walkers import rodent\n\nimport numpy as np\nfrom six.moves import range\n\n_CONTROL_TIMESTEP = .02\n_PHYSICS_TIMESTEP = 0.001\n\n\ndef _get_rat_corridor_physics():\n walker = rodent.Rat()\n arena = corr_arenas.EmptyCorridor()\n task = corr_tasks.RunThroughCorridor(\n walker=walker,\n arena=arena,\n walker_spawn_position=(5, 0, 0),\n walker_spawn_rotation=0,\n physics_timestep=_PHYSICS_TIMESTEP,\n control_timestep=_CONTROL_TIMESTEP)\n\n env = composer.Environment(\n time_limit=30,\n task=task,\n strip_singleton_obs_buffer_dim=True)\n\n return walker, env\n\n\nclass RatTest(parameterized.TestCase):\n\n def test_can_compile_and_step_simulation(self):\n _, env = _get_rat_corridor_physics()\n physics = env.physics\n for _ in range(100):\n physics.step()\n\n @parameterized.parameters([\n 'egocentric_camera',\n 'head',\n 'left_arm_root',\n 'right_arm_root',\n 'root_body',\n 'pelvis_body',\n ])\n def test_get_element_property(self, name):\n attribute_value = getattr(rodent.Rat(), name)\n self.assertIsInstance(attribute_value, mjcf.Element)\n\n @parameterized.parameters([\n 'actuators',\n 'bodies',\n 'mocap_bodies',\n 'end_effectors',\n 'mocap_joints',\n 'observable_joints',\n ])\n def test_get_element_tuple_property(self, name):\n attribute_value = getattr(rodent.Rat(), name)\n self.assertNotEmpty(attribute_value)\n for item in attribute_value:\n self.assertIsInstance(item, mjcf.Element)\n\n def test_set_name(self):\n name = 'fred'\n walker = rodent.Rat(name=name)\n self.assertEqual(walker.mjcf_model.model, name)\n\n @parameterized.parameters(\n 'tendons_pos',\n 'tendons_vel',\n 'actuator_activation',\n 'appendages_pos',\n 'head_height',\n 'sensors_torque',\n )\n def test_evaluate_observable(self, name):\n walker, env = _get_rat_corridor_physics()\n physics = env.physics\n observable = getattr(walker.observables, name)\n observation = observable(physics)\n self.assertIsInstance(observation, (float, np.ndarray))\n\n def test_proprioception(self):\n walker = rodent.Rat()\n for item in walker.observables.proprioception:\n self.assertIsInstance(item, observable_base.Observable)\n\nif __name__ == '__main__':\n absltest.main()\n","sub_path":"src/env/dm_control/dm_control/locomotion/walkers/rodent_test.py","file_name":"rodent_test.py","file_ext":"py","file_size_in_byte":3460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"611143997","text":"# Based on https://github.com/CoffeaTeam/coffea/blob/7dd4f863837a6319579f078c9e445c61d9106943/coffea/nanoevents/schemas/nanoaod.py\nfrom coffea.nanoevents.schemas.base import BaseSchema, zip_forms\n\nclass MultiClassifierSchema(BaseSchema):\n \"\"\"Basic multiclassifier friend tree schema\"\"\"\n def __init__(self, base_form, name=''):\n super().__init__(base_form)\n self.mixins = {}\n self._form[\"contents\"] = self._build_collections(self._form[\"contents\"])\n\n def _build_collections(self, branch_forms):\n for k in branch_forms:\n if k.startswith('SvB_MA'):\n name = 'SvB_MA'\n break\n if k.startswith('SvB'):\n name = 'SvB'\n break\n if k.startswith('FvT'):\n name = 'FvT'\n break\n\n mixin = self.mixins.get(name, \"NanoCollection\")\n\n # simple collection\n output = {}\n output[name] = zip_forms(\n {\n k[len(name) + 1 :]: branch_forms[k]\n for k in branch_forms\n if k.startswith(name + \"_\")\n },\n name,\n record_name=mixin,\n )\n output[name].setdefault(\"parameters\", {})\n output[name][\"parameters\"].update({\"collection_name\": name})\n\n return output \n\n @property\n def behavior(self):\n \"\"\"Behaviors necessary to implement this schema\"\"\"\n from coffea.nanoevents.methods import nanoaod\n\n return nanoaod.behavior\n","sub_path":"nTupleAnalysis/scripts/MultiClassifierSchema.py","file_name":"MultiClassifierSchema.py","file_ext":"py","file_size_in_byte":1523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"597803123","text":"import sys\nfrom flask import Flask\nfrom pymongo import MongoClient\n\napp = Flask(__name__)\nWTF_CSRF_ENABLED = True\nSECRET_KEY = 'you-will-never-guess'\n\nreload(sys)\nsys.setdefaultencoding('utf8')\n\nclient = MongoClient(\"localhost\", 27017)\ndb = client['test']\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"464046696","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\ndef f(x):\r\n if x>-0.5*np.pi and x<0.5*np.pi:\r\n y = np.cos(x)**2\r\n else:\r\n y = 0\r\n return y\r\n\r\ndef p(x):\r\n y = np.exp(-x**2/(2*sigma**2))/(np.sqrt(2*np.pi)*sigma)\r\n return y\r\n\r\n# num = 100000\r\n# sigma = 0.7\r\n# n1 = np.pi*np.random.random(num)-0.5*np.pi\r\n\r\n# r1 = np.random.random(num)\r\n# r2 = np.random.random(num)\r\n# n2 = np.sqrt(-2*np.log(r1))*np.cos(2*np.pi*r2)*sigma\r\n\r\n# x = np.arange(num)\r\n# y1 = [f(n1[0])]\r\n# y2 = [f(n2[0])/p(n2[0])]\r\n\r\nfor i in range(1, num):\r\n m1 = y1[-1]*i + f(n1[i])\r\n m2 = y2[-1]*i + f(n2[i])/p(n2[i])\r\n y1.append(m1/(i+1))\r\n y2.append(m2/(i+1))\r\n\r\n# font1 = {'family': 'Times New Roman','size': 20}\r\n# plt.semilogx(x, np.array(y1)*np.pi, label='πn')\r\n# plt.semilogx(x, y2, color='red', label='n')\r\n# plt.semilogx(x, [0.5*np.pi]*num, '--', color='black', label='π/2')\r\n# plt.legend(prop=font1)\r\n# plt.xlabel('n', font1)\r\n# plt.ylabel('πn n', font1)\r\n# plt.show()\r\n\r\n# x = np.arange(-3, 3, 0.01)\r\n# sigma = 0.7\r\n# y1 = []\r\n# y2 = []\r\n# y3 = []\r\n\r\n# for i in range(len(x)):\r\n# m1 = p(x[i])\r\n# y1.append(m1)\r\n\r\n# for i in range(len(x)):\r\n# m2 = f(x[i])\r\n# y2.append(m2)\r\n\r\n# for i in range(len(x)):\r\n# m3 = f(x[i])/p(x[i])\r\n# y3.append(m3)\r\n\r\n# plt.plot(x, y1)\r\n# plt.plot(x, y2)\r\n# plt.plot(x, y3)\r\n# plt.show()","sub_path":"sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"559144926","text":"import subprocess\nimport os\nimport glob\n\n\nfrom subprocess import Popen, PIPE\n#print(\"Root-Verzeichnis ist zum Beispiel P:\\\\\")\nprint(\"Examples for the Root-Folder: C:\\ or a mapped network share Z:\\\\\")\nprint(\"\")\n#path = input(\"Root-Verzeichnis für Matrix:\")\npath = input(\"Root-Folder for the Matrix:\")\npath = path+\"\\\\\"\n#maxDepth = input(\"Maximale Ordner-Tiefe:\")\nmaxDepth = input(\"Maximum recursiveness:\")\n\n#print(\"Suche in \"+path)\nprint(\"Searching ... \"+path)\n\n\ngroupsArray = [\"administrator\",\"Jeder\",\"otherADGroups\",\"Sales\",\"CEO\",\"...\"]\n\nfile = open(\"accessMatrix-Ausgabe.txt\",\"w\")\n\ndef getPermissions(path):\n with subprocess.Popen([\"powershell.exe\",\n \"Get-Acl '\"+path+\"' | Select-Object -Expand Access | Select-Object AccessControlType,IdentityReference | format-list\"],\n stdout=subprocess.PIPE, stdin=subprocess.PIPE) as p:\n output, errors = p.communicate()\n\n lines = output.decode('iso-8859-15').splitlines()\n lines = list(filter(None, lines))\n\n\n accessControll = []\n\n\n for x in lines:\n x = x.replace(\"AccessControlType : \",\"\")\n x = x.replace(\"IdentityReference : \",\"\")\n accessControll.append(x)\n\n\n users =[]\n rights =[]\n\n foo = {}\n\n for i,k in zip(accessControll[0::2], accessControll[1::2]):\n k = str(k.split(\"\\\\\")[-1])\n i = str(i)\n foo[k] = i\n\n currentFolderRights = []\n for group in groupsArray:\n try:\n currentFolderRights.append(foo[group]+\";\")\n except KeyError:\n currentFolderRights.append(\"-\"+\";\")\n\n\n currentFolderRightsString = ''.join(currentFolderRights)\n print(path + \";\" + currentFolderRightsString)\n file.write(path + \";\" + currentFolderRightsString+\"\\n\")\n p.kill()\n\n#print(foo)\n\n\n\ndef glob_list(start, max_depth=0, min_depth=0):\n # start out at least `min_depth` levels deep\n current_dir = os.path.join(start, *\"*\" * min_depth)\n for depth in range(min_depth, max_depth+1):\n # go one level deeper\n current_dir = os.path.join(current_dir, \"*\")\n # print(current_dir)\n yield from filter(os.path.isdir, glob.iglob(current_dir))\n\nprint(\"Folder\" + \";\" + ';'.join(groupsArray))\nfile.write(\"Folder\" + \";\" + ';'.join(groupsArray)+\"\\n\")\n\n\nif __name__ == \"__main__\":\n for folder in glob_list(path, max_depth=int(maxDepth), min_depth=1):\n if not folder.startswith('.'):\n if not folder.endswith('.lnk'):\n if not folder.endswith('.bat'):\n getPermissions(folder)\n\nfile.close()","sub_path":"AccessMatrix.py","file_name":"AccessMatrix.py","file_ext":"py","file_size_in_byte":2525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"418458284","text":"import mysql.connector\nfrom databse_connect_pgm.DB_CONNECTION2 import *\n# db=sql_injection_with_python()\n# cursor=db.cursor()\nn = 115\nfor m in range(1,1000000):\n db = sql_injection_with_python()\n cursor = db.cursor()\n id = n\n name=input(\"Enter the company name\")\n model=input(\"Enter the model name\")\n# sql2=\"\"\"insert into bikes (id,name,company) values (%s,%s,%s)\"\"\",(id,model,name)\n try:\n cursor.execute(\"\"\"insert into bikes (id,name,company) values (%s,%s,%s)\"\"\",(id,model,name))\n # cursor.execute(sql2)\n db.commit()\n print(\"succesfully inserted\")\n\n except Exception as e:\n print(e.args)\n finally:\n n=n+1\n num=input(\"Press 'x' to close, Press anykey to continue\")\n if(num!='x'):\n db.close()\n else:\n break","sub_path":"databse_connect_pgm/data_insertion_from_user.py","file_name":"data_insertion_from_user.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"164536955","text":"from io import StringIO\r\nimport numpy as np\r\nfrom tensorflow.keras.models import model_from_json\r\nimport operator\r\nimport cv2\r\nimport sys, os\r\n\r\n# Loading the model\r\njson_file = open(\"model-bw.json\", \"r\")\r\nmodel_json = json_file.read()\r\njson_file.close()\r\nloaded_model = model_from_json(model_json)\r\n# load weights into new model\r\nloaded_model.load_weights(\"model-bw.h5\")\r\nprint(\"Loaded model from disk\")\r\n\r\ncap = cv2.VideoCapture(0)\r\n\r\n# Category dictionary\r\nmap_to_labels = {0: 'rock', 1: 'paper', 2: 'scissor'}\r\nprediction=[]\r\n\r\nwhile True:\r\n _, frame = cap.read()\r\n # Simulating mirror image\r\n frame = cv2.flip(frame, 1)\r\n \r\n # Got this from collect-data.py\r\n # Coordinates of the ROI\r\n x1 = int(0.5*frame.shape[1])\r\n y1 = 10\r\n x2 = frame.shape[1]-10\r\n y2 = int(0.5*frame.shape[1])\r\n # Drawing the ROI\r\n # The increment/decrement by 1 is to compensate for the bounding box\r\n cv2.rectangle(frame, (x1-1, y1-1), (x2+1, y2+1), (255,0,0) ,1)\r\n # Extracting the ROI\r\n roi = frame[y1:y2, x1:x2]\r\n \r\n # Resizing the ROI so it can be fed to the model for prediction\r\n roi = cv2.resize(roi, (64, 64)) \r\n roi = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)\r\n _, test_image = cv2.threshold(roi, 120, 255, cv2.THRESH_BINARY)\r\n cv2.imshow(\"test\", test_image)\r\n # Batch of 1\r\n result = loaded_model.predict(test_image.reshape(1, 64, 64, 1))\r\n prediction = {'paper': result[0][0], #prs not rps becoz model is trained in such way\r\n 'rock': result[0][1], \r\n 'scissor': result[0][2],\r\n }\r\n # Sorting based on top prediction\r\n prediction = sorted(prediction.items(), key=operator.itemgetter(1), reverse=True)\r\n \r\n # Displaying the predictions\r\n cv2.putText(frame, prediction[0][0], (10, 120), cv2.FONT_HERSHEY_PLAIN, 1, (0,255,255), 1) \r\n cv2.putText(frame, \"your move is : \"+prediction[0][0], (10, 140), cv2.FONT_HERSHEY_PLAIN, 1, (0,255,255), 1) \r\n x=np.random.choice([0,1,2])\r\n cv2.putText(frame, \"Bot move is : \"+str(x), (10, 160), cv2.FONT_HERSHEY_PLAIN, 1, (0,255,255), 1)\r\n res=\"\"\r\n if prediction[0][0]=='rock':\r\n if x==1: \r\n res=\"YOU LOOSE \"\r\n elif x==0:\r\n res=\"Draw\"\r\n else :\r\n res=\"YOU WON\"\r\n elif prediction[0][0]==\"paper\":\r\n if x==2:\r\n res=\"YOU LOOSE\"\r\n elif x==1:\r\n res=\"Draw\"\r\n else :\r\n res=\"YOU WON\"\r\n else :\r\n if x==0:\r\n res=\"YOU LOOSE\"\r\n elif x==2:\r\n res=\"Draw\"\r\n else :\r\n res=\"YOU WON\"\r\n \r\n cv2.putText(frame, res , (10, 180), cv2.FONT_HERSHEY_PLAIN, 1, (255,255,0), 2)\r\n cv2.imshow(\"Frame\", frame)\r\n \r\n interrupt = cv2.waitKey(10)\r\n if interrupt & 0xFF == 27: # esc key\r\n break\r\n \r\n \r\ncap.release()\r\ncv2.destroyAllWindows()","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":2875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"63730174","text":"from django.db import models\n\nclass PythonTopic(models.Model):\n num = models.IntegerField() # 題號\n title = models.CharField(max_length=128) # 題目名稱\n topic = models.TextField() # 題目\n example = models.TextField() # 輸出範例\n answer = models.TextField(null=True, blank=True) # 答案\n difficult = models.IntegerField(null=True, blank=True) # 難度; 1:容易(S) 2:中等(M)\n isActive = models.BooleanField(default=True) # 啟用停用\n \n \n def __str__(self):\n return self.title\n \n class Meta:\n ordering = ['num']\n","sub_path":"ailan/tutorial/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"95275041","text":"\nimport random\nrandom.seed(0)\n\nfrom collections import defaultdict\n\nfrom sklearn.preprocessing import MinMaxScaler\n\nfrom matplotlib.collections import LineCollection\nfrom scipy.interpolate import make_interp_spline, BSpline\n\nfrom scipy.interpolate import interp1d\n\nimport matplotlib.patches as mpatches\nfrom pathlib import Path\nimport pandas as pd\n\nfrom IPython import embed\nimport html\n\nimport numpy as np\n\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction import stop_words\n\nfrom scipy.sparse import csr_matrix\n\nfrom collections import Counter\nfrom copy import deepcopy\n\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\n\nimport seaborn as sns\n\n\nclass Dataset:\n\n def __init__(self):\n\n # earliest and latest year in dataset\n self.start_year = min(self.df.year)\n self.end_year = max(self.df.year)\n # male and female authors\n self.author_gender = 'both'\n # no term filter active. When term filter is active, only documents mentioning the term\n # in the abstract are retained.\n self.term_filter = None\n self.institution_filter = None\n self.advisor_gender_filter = None\n self.descendants_filter = None\n self.topic_percentile_score_filters = []\n self.vocabulary_set = None\n\n\n def __len__(self):\n return len(self.df)\n\n def __repr__(self):\n return f'Dissertation Dataset, {self.name_full}'\n\n @property\n def name(self):\n return f'{self.start_year}-{self.end_year}, {self.author_gender}'\n\n @property\n def name_full(self):\n n = self.name\n if self.institution_filter:\n n += f' {self.institution_filter}'\n if self.advisor_gender_filter:\n n += f' {self.advisor_gender_filter}'\n if self.topic_percentile_score_filters:\n for f in self.topic_percentile_score_filters:\n topic_id = int(f['topic'][6:])\n n += f' percentile score between {f[\"min_percentile_score\"]}th and ' \\\n f'{f[\"max_percentile_score\"]}th for {self.topics[topic_id][\"name\"]}'\n return n\n\n @property\n def vocabulary(self):\n \"\"\"\n Lazy-loaded vocabulary set to check if a word appears in the dataset\n :return: set\n\n >>> d = Dataset()\n >>> 'family' in d.vocabulary\n True\n\n >>> 'familoeu' in d.vocabulary\n False\n\n \"\"\"\n if not self.vocabulary_set:\n self.vocabulary_set = self.get_vocabulary(exclude_stopwords=False)\n return self.vocabulary_set\n\n def copy(self):\n\n return deepcopy(self)\n\n def load_topic_data(self, file_path):\n \"\"\"\n\n :param file_path: Path\n :return:\n \"\"\"\n topics = {}\n df = pd.read_csv(file_path, encoding='cp1252')\n\n for _, row in df.iterrows():\n\n gen_approach = row['General Approach Standardized']\n spec_approach = row['Specialized Approach Standardized']\n gen_area = row['Gen Geogr']\n spec_area = row['Spec Geogr']\n\n name = f'{gen_approach} ({spec_approach}). {gen_area}({spec_area})'\n\n topic_id = int(row['name'])\n terms_prob = row['prob'].split(\", \")\n terms_frex = row['frex'].split(\", \")\n topics[topic_id] = {\n 'name': name,\n 'gen_approach': gen_approach,\n 'spec_approach': spec_approach,\n 'gen_area': gen_area,\n 'spec_area': spec_area,\n 'terms_prob': terms_prob,\n 'terms_frex': terms_frex,\n 'terms_both': terms_prob + terms_frex\n }\n return topics\n\n def store_aggregate_approach_and_geographical_info_in_df(self):\n \"\"\"\n To aggregate, e.g. the multiple political history general approach topics,\n we calculate the average for each article.\n e.g. if topics 30 and 55 are the political history topics, we set\n df['gen_approach_Political History'] to the average of the columns X30 and X55.\n\n TODO: expand for specific approaches and geographical areas\n\n :return:\n \"\"\"\n\n gen_approaches_to_id = defaultdict(set)\n for topic_id, topic in self.topics.items():\n if topic['gen_approach'] == '' or not isinstance(topic['gen_approach'], str):\n continue\n gen_approaches_to_id[topic['gen_approach']].add(topic_id)\n\n sum_of_means = 0\n for gen_approach in gen_approaches_to_id:\n #e.g. ['X10', 'X30]\n selectors = [f'X{i}' for i in gen_approaches_to_id[gen_approach]]\n self.df[f'gen_approach_{gen_approach}'] = self.df[selectors].sum(axis=1)\n m = self.df[f'gen_approach_{gen_approach}'].mean()\n sum_of_means += m\n print(gen_approach, gen_approaches_to_id[gen_approach], m)\n print(\"means\", sum_of_means)\n\n\n\n def topic_percentile_score_filter(self, topic, min_percentile_score=0, max_percentile_score=100):\n \"\"\"\n Filter the dataset such that it only contains documents that score between\n min_percentile_score and max_percentile_score for a topic\n\n :param topic: topic id (int) or str ('topic.XX')\n :param min_percentile_score: 0 to 100\n :param max_percentile_score: 0 to 100\n :return:\n\n >>> d = Dataset()\n >>> len(d)\n 21634\n\n # select dissertations that score in the top decile (strongest) for the gender topic (28)\n >>> d.topic_percentile_score_filter(topic=28, min_percentile_score=90)\n >>> print(len(d), min(d.df['percentile_score_topic.28']))\n 2164 90.0\n\n # select 50th-70th decile\n >>> d2 = Dataset()\n >>> d2.topic_percentile_score_filter('topic.28', min_percentile_score=50, max_percentile_score=70)\n >>> len(d2)\n 6491\n\n # filters can be combined\n >>> d3 = Dataset()\n >>> d3.topic_percentile_score_filter(14, min_percentile_score=80)\n >>> d3.topic_percentile_score_filter(28, min_percentile_score=80)\n >>> len(d3)\n 866\n\n\n \"\"\"\n if not isinstance(topic, str):\n topic = f'topic.{topic}'\n\n if not f'percentile_score_{topic}' in self.df.columns:\n # add all of the topics at once because if we filter topics twice, the ranks would be\n # influenced by the first selection\n for i in range(1, 71):\n t = f'topic.{i}'\n self.df[f'percentile_score_{t}'] = self.df[t].rank(pct=True) * 100 // 10 * 10\n self.df = self.df[self.df[f'percentile_score_{topic}'] >= min_percentile_score]\n self.df = self.df[self.df[f'percentile_score_{topic}'] <= max_percentile_score]\n self.df = self.df.reset_index()\n self.topic_percentile_score_filters.append({\n 'topic': topic,\n 'min_percentile_score': min_percentile_score,\n 'max_percentile_score': max_percentile_score\n })\n\n\n def filter(self, start_year=None, end_year=None, author_gender=None,\n term_filter=None, institution_filter=None, advisor_gender=None,\n has_descendants=None):\n \"\"\"\n\n :param start_year: (int between 1976 and 2015) earliest year to include\n :param end_year: (int between 1976 and 2015) last year to include\n :param author_gender: (male or female) only include male or female authors\n :param term_filter: string or raw string only include documents mentioning term\n :return:\n\n >>> d = Dataset()\n >>> len(d)\n 21634\n\n # filter for years (inclusive) between 1985 and 1995\n >>> d.filter(start_year=1985, end_year=1995)\n >>> len(d)\n 6532\n\n # filter by author gender\n >>> d.filter(author_gender='male')\n >>> len(d)\n 4055\n\n # filter by advisor gender\n >>> d.filter(advisor_gender='female')\n >>> len(d)\n 220\n\n\n # filter by term or regex\n # regex example: r'\\bgender\\b'\n >>> d.filter(term_filter='gender')\n >>> len(d)\n 13\n\n # filter by institution\n >>> d = Dataset()\n >>> d.filter(institution_filter='harvard')\n >>> len(d)\n 778\n\n >>> d = Dataset()\n >>> d.filter(institution_filter='not_harvard')\n >>> len(d)\n 20856\n\n >>> d = Dataset()\n >>> d.filter(has_descendants=True)\n >>> len(d)\n 1583\n\n \"\"\"\n\n df = self.df\n\n if start_year:\n df = df[df.year >= start_year]\n self.start_year = start_year\n if end_year:\n df = df[df.year <= end_year]\n self.end_year = end_year\n if author_gender:\n if not author_gender in ['male', 'female']:\n raise ValueError(f'Author gender needs to be male or female but not {author_gender}')\n df = df[df.author_genders == author_gender]\n self.author_gender = author_gender\n\n if advisor_gender:\n if not advisor_gender in ['male', 'female', 'unknown']:\n raise ValueError(f'Author gender needs to be male or female but not {advisor_gender}')\n df = df[df.AdvisorGender == advisor_gender]\n self.advisor_gender = advisor_gender\n\n\n if term_filter:\n if term_filter.startswith('not_'):\n term_filter = term_filter[4:]\n df = df[df['text'].str.contains(pat=term_filter, regex=True) == False]\n else:\n df = df[df['text'].str.contains(pat=term_filter, regex=True) == True]\n self.term_filter = term_filter\n\n if institution_filter:\n if institution_filter.startswith('not_'):\n institution_filter = institution_filter[4:]\n df = df[df['ThesisInstitution'].str.contains(institution_filter, case=False) == False]\n else:\n df = df[df['ThesisInstitution'].str.contains(institution_filter, case=False) == True]\n self.institution_filter = institution_filter\n\n if has_descendants == True:\n df = df[df.AnyDescendants == 1]\n self.descendants_filter = True\n\n if has_descendants == False:\n df = df[df.AnyDescendants == 0]\n self.descendants_filter = False\n\n self.df = df.reset_index()\n return self\n\n\n def get_vocabulary(self, exclude_stopwords=True, max_terms=None, min_appearances=None,\n include_2grams=False):\n \"\"\"\n Returns a list of all terms that appear in the text column\n\n :return: list\n\n # stop words are excluded by default\n >>> d = Dataset()\n >>> len(d.get_vocabulary(exclude_stopwords=True))\n 176458\n >>> d.get_vocabulary().count('are')\n 0\n\n # you can also limit the number of terms and require a minimum number of appearances\n >>> voc = d.get_vocabulary(max_terms=1000, min_appearances=2)\n >>> len(voc)\n 1000\n\n \"\"\"\n\n if not max_terms:\n max_terms = 1000000\n\n vocabulary = Counter()\n for abstract in self.df['text']:\n a = abstract.split()\n for idx, word in enumerate(a):\n vocabulary[word] += 1\n if include_2grams:\n try:\n gram = '{} {}'.format(word, a[idx+1])\n vocabulary[gram] += 1\n except IndexError:\n pass\n\n\n\n if exclude_stopwords:\n clean_vocabulary = Counter()\n stopwords = stop_words.ENGLISH_STOP_WORDS.union({'wa', 'ha',\n 'óé', 'dotbelow', 'cyrillic'})\n\n for ngram in vocabulary:\n valid = True\n for term in ngram.split():\n if term in stopwords:\n valid = False\n if valid:\n clean_vocabulary[ngram] = vocabulary[ngram]\n vocabulary = clean_vocabulary\n\n\n vocab_list = []\n for word, count in vocabulary.most_common(max_terms):\n if min_appearances and count < min_appearances:\n continue\n else:\n vocab_list.append(word)\n\n return sorted(vocab_list)\n\n\n def get_document_topic_matrix(self, vocabulary):\n \"\"\"\n Returns a document-topic sparse matrix. each row represents a document and each column a\n topic\n Note: all topics are one-off because there is no topic.0, i.e. topic.1 is stored in the\n 0th column.\n\n Vocabulary are the columns to select\n\n >>> d = Dataset()\n >>> vocabulary = [f'X{i}' for i in range(1, 101)]\n >>> dtm = d.get_document_topic_matrix()\n >>> dtm.shape\n (23246, 70)\n\n :return: csr_matrix\n \"\"\"\n\n dtm = csr_matrix(self.df[vocabulary].to_numpy())\n return dtm\n\n\n def get_document_term_matrix(self, vocabulary, store_in_df=False):\n \"\"\"\n\n Returns a document-term sparse matrix. each row represents a document and each column a\n topic\n\n If store_in_df is selected, the dtm will be stored in the dataframe, i.e. every term\n is stored as a row in the dataframe (useful for quick term selection)\n\n :param vocabulary: list\n :param store_in_df: bool\n :return:\n\n >>> d = Dataset()\n >>> vocabulary = d.get_vocabulary(max_terms=10000)\n >>> dtm = d.get_document_term_matrix(vocabulary)\n >>> dtm.shape\n (23246, 10000)\n\n \"\"\"\n\n vectorizer = CountVectorizer(vocabulary=vocabulary)\n dtm = vectorizer.fit_transform(self.df['text'].to_list())\n\n if store_in_df:\n dtm_df = pd.DataFrame(dtm.toarray(), columns=vocabulary)\n self.df = pd.concat([self.df, dtm_df], axis=1)\n else:\n return dtm\n\n def print_dissertations_mentioning_terms_or_topics(self, terms, no_dissertations=5):\n \"\"\"\n print dissertations that mention specific terms or topics,\n can be weighted or unweighted\n\n :param terms: list or dict\n :param no_dissertations: number of dissertations to print, default: 5\n\n >>> d = Dataset()\n >>> terms = ['woman', 'female', 'women', 'feminist', 'gender']\n >>> d.print_dissertations_mentioning_terms_or_topics(terms=terms, no_dissertations=2)\n 2014 Author: female Advisor: female Authors, Activists, Apostles: Women's Leadership in the New Christian Right\n 2006 Author: female Advisor: male Women on the march: Gender and anti-fascism in American communism, 1935--1939\n\n # by default, each term has weight=1. However, terms can also be a dict of term weights\n >>> terms = {'nurse': 1, 'drugs': 10}\n >>> d.print_dissertations_mentioning_terms_or_topics(terms=terms, no_dissertations=2)\n 1997 Author: female Advisor: male Regulating beauty: Cosmetics in American culture from the 1906 Pure Food and Drugs Act to the 1938 Food, Drug and Cosmetic Act\n 1994 Author: female Advisor: female G.I. nurses at war: Gender and professionalization in the Army Nurse Corps during World War II\n\n # topics also work:\n >>> terms = ['topic.28']\n >>> d.print_dissertations_mentioning_terms_or_topics(terms=terms, no_dissertations=2)\n 1989 Author: female Advisor: unknown Day nurseries and wage-earning mothers in the United States, 1890-1930\n 1988 Author: female Advisor: female \"Women adrift\" and \"urban pioneers\": Self-supporting working women in America, 1880-1930\n\n >>> terms = ['gay', 'homosexual', 'homosexuality', 'masculinity']\n >>> d.print_dissertations_mentioning_terms_or_topics(terms=terms, no_dissertations=20)\n\n \"\"\"\n\n # if input is a list, give each term weight 1\n if isinstance(terms, list):\n terms = {t: 1 for t in terms}\n\n out = ''\n\n if list(terms.keys())[0].startswith('topic.'):\n self.df['dissertation_weights'] = 0\n for topic, weight in terms.items():\n self.df['dissertation_weights'] += weight * self.df[topic]\n for _, row in self.df.sort_values(by='dissertation_weights', ascending=False)[:no_dissertations].iterrows():\n out += ('\\n{} Author: {:7s} Advisor: {:7s} {}'.format(\n row['Year'], row['author_genders'],\n row['AdvisorGender'], row['ThesisTitle']\n ))\n\n elif list(terms.keys())[0].startswith('X'):\n topic = list(terms.keys())[0]\n self.df['article_weights'] = 0\n for _, row in self.df.sort_values(by=topic, ascending=False)[:no_dissertations].iterrows():\n out += ('\\n{} {:7s}. Title: {}. Authors: {}.'.format(row.year, row.author_genders,\n row.title, row.authors))\n\n\n\n else:\n dtm = self.get_document_term_matrix(vocabulary=terms.keys())\n weights = np.array(list(terms.values()))\n scores = dtm * weights\n\n for i in scores.argsort()[::-1][:no_dissertations]:\n\n\n out +=('{} Author: {:7s} Advisor: {:7s} {}'.format(\n self.df['Year'][i], self.df['author_genders'][i],\n self.df['AdvisorGender'][i], self.df['ThesisTitle'][i]\n ))\n return out\n\n\n def print_topics_and_text_samples(self, file_path):\n \"\"\"\n prints ids, names, terms, sample docs for each topic\n\n :param file_path:\n :return:\n \"\"\"\n print(\"here\")\n out = ''\n for i in range(1, 101):\n topic = self.topics[i]\n out += '\\n\\nTopic ID: {:3s}. Topic Name: {}'.format(str(i), topic['name'])\n out += f'\\nterms, prob: {topic[\"terms_prob\"][:10]}'\n out += f'\\nterms, frex: {topic[\"terms_frex\"][:10]}\\nExamples:'\n\n out += self.print_dissertations_mentioning_terms_or_topics([f'X{i}'], no_dissertations=10)\n\n print(out)\n with open('tset.txt', 'w') as outf: outf.write(out)\n\n\n\n\n def print_examples_of_term_in_context(self, term, no_examples=10):\n \"\"\"\n Finds examples of a term in the abstracts and prints them\n\n >>> d = Dataset()\n >>> d.print_examples_of_term_in_context('hegel', 2)\n 1987 PHILIP SCHAFF (1819-1893): PORTRAIT OF AN IMMIGRANT THEOLOGIAN heology that accommodated such figure a hegel and schleiermacher tolerated liberal position yet rema\n 1995 State, society, and the market: Karl Sigmund Altenstein and the langua n idealism first by fichte and later by hegel thus the importance of his relationship to fichte and\n\n :param term:\n :return:\n \"\"\"\n\n df = self.df[self.df['text'].str.contains(pat=r'\\b{}\\b'.format(term))]\n if len(df) == 0:\n print(f'No texts mention {term}.')\n return\n\n while True:\n try:\n samples = df.sample(no_examples)\n break\n except ValueError:\n no_examples -= 1\n\n print(f'\\n Found {len(df)} examples of {term}.')\n for _, row in samples.iterrows():\n\n pos = row['text'].find(term)\n if pos > -1:\n text = row['text'][max(0, pos-40):pos+60]\n print('{} {:7s} {:70s} {}'.format(\n row['year'], row['author_genders'], row['title'][:70], text,\n ))\n\n\n def normalize_dataset_by_5year_interval(self, no_docs_per_5year_interval=5000):\n\n# dfs = {}\n\n docs = []\n\n for years_range in [(1976, 1984), (1985, 1989), (1990, 1994), (1995, 1999), (2000, 2004),\n (2005, 2009), (2010, 2015)]:\n y1, y2 = years_range\n if self.start_year >= y2 or self.end_year < y2:\n continue\n# dfs[years_range] = self.df[(self.df['Year'] >= y1) & (self.df['Year'] <= y2)]\n df = self.df[(self.df['year'] >= y1) & (self.df['year'] <= y2)]\n df = df.to_dict('records')\n\n if len(df) == 0:\n raise IndexError(f'Cannot generate dataset of {no_docs_per_5year_interval} docs for {y1}-{y2} for'\n f' {self.name_full} with 0 docs.')\n if len(df) < 50:\n print(f'WARNING. Generating dataset of {no_docs_per_5year_interval} docs for {y1}-{y2} for'\n f' {self.name} with only {len(df)} docs.')\n\n for i in range(no_docs_per_5year_interval):\n docs.append(random.sample(df, 1)[0])\n self.df = pd.DataFrame(docs)\n\n\n def grid_plot_topics(self, sorted_topic_ids, hue,\n y_max=None, df=None, show_plot=True, store_as_filename=None):\n \"\"\"\n Can be used to plot a 10x7 grid of all topics\n\n :param df:\n :param sorted_topic_ids: list(int)\n :param hue:\n :param y_max:\n :return:\n\n # show topic distribution from most female to most male\n >>> d = Dataset()\n >>> male = d.copy().filter(author_gender='male')\n >>> female = d.copy().filter(author_gender='female')\n >>> difs = {}\n >>> for topic_id in range(1, 71):\n ... dif = np.mean(female.df[f'topic.{topic_id}']) - np.mean(male.df[f'topic.{topic_id}'])\n ... difs[topic_id] = dif\n >>> sorted_topic_ids = [t[0] for t in sorted(difs.items(), key = lambda x: x[1], reverse=True)]\n >>> d.grid_plot_topics(sorted_topic_ids, hue='author_genders')\n\n \"\"\"\n\n print(\"Creating topic gridplot\")\n\n if not df:\n df = self.df\n\n fig = plt.figure(figsize=(50, 50))\n gs = gridspec.GridSpec(nrows=10, ncols=10, figure=fig)\n\n for ax_id, topic_id in enumerate(sorted_topic_ids):\n\n print(ax_id, topic_id)\n row = ax_id // 10\n col = ax_id % 10\n ax = fig.add_subplot(gs[row, col])\n ax = sns.lineplot(x='year', y=f'X{topic_id}', hue=hue,\n data=df, ax=ax)\n ax.set_title(f'{topic_id}: {self.topics[topic_id][\"name\"]}')\n ax.set_xlim(self.start_year, self.end_year)\n if y_max:\n ax.set_ylim(0, y_max)\n\n if show_plot:\n plt.show()\n if store_as_filename:\n fig.savefig(Path('data', 'plots', store_as_filename))\n\n def get_data(self, data_type, token_list, smoothing):\n\n # load text info and turn it into term frequencies\n if data_type == 'terms':\n self.get_document_term_matrix(vocabulary=token_list, store_in_df=True)\n for idx, row in self.df.iterrows():\n text_len = len(row.text.split())\n self.df.at[idx, 'text_len'] = text_len\n for t in token_list:\n self.df[t] = self.df[t] / self.df['text_len']\n\n data = {}\n for t in token_list:\n data[t] = defaultdict(list)\n\n df = self.df\n\n for idx, year in enumerate(range(self.start_year, self.end_year)):\n time_slice = df[(df.year >= year - smoothing) & (df.year <= year + smoothing)]\n time_slice_female = time_slice[time_slice.author_genders == 'female']\n time_slice_male = time_slice[time_slice.author_genders == 'male']\n\n for t in token_list:\n freq_both = time_slice[t].mean()\n freq_female = time_slice_female[t].mean()\n freq_male = time_slice_male[t].mean()\n\n\n # if a term doesn't appear, it is neutral\n if (freq_male + freq_female) == 0:\n freq_score = 0.5\n else:\n freq_score = freq_female / (freq_female + freq_male)\n\n data[t]['year'].append(year)\n data[t]['freq_score'].append(freq_score)\n data[t]['freq_both'].append(freq_both)\n\n for t in token_list:\n data[t]['mean_freq_score'] = np.mean(data[t]['freq_score'])\n data[t]['mean_freq_both'] = np.mean(data[t]['freq_both'])\n data[t]['freq_score_range'] = max(data[t]['freq_score']) - min(data[t]['freq_score'])\n\n return data\n\n\n\n\n\n def plot_topic_grid(self, smoothing=5):\n\n from divergence_analysis import divergence_analysis\n c1 = self.copy().filter(author_gender='male')\n c2 = self.copy().filter(author_gender='female')\n topic_df = divergence_analysis(self, c1, c2, topics_or_terms='topics',\n c1_name='male', c2_name='female', sort_by='dunning',\n number_of_terms_to_print=50)\n\n topic_ids_sorted = [r['index'] + 1 for _, r in topic_df.iterrows()]\n topic_names_sorted = [f'X{tid}' for tid in topic_ids_sorted]\n\n data = self.get_data(data_type='topics', token_list=topic_names_sorted,\n smoothing=smoothing)\n\n fig = plt.figure(figsize=(50, 50))\n gs = gridspec.GridSpec(nrows=10, ncols=10, figure=fig)\n\n for ax_id, topic_id in enumerate(topic_ids_sorted):\n print(ax_id, topic_id)\n row = ax_id // 10\n col = ax_id % 10\n ax = fig.add_subplot(gs[row, col])\n\n t = f'X{topic_id}'\n x = data[t]['year']\n y = data[t]['freq_both']\n freq_scores = data[t]['freq_score']\n x_lin = np.linspace(min(data[t]['year']), max(data[t]['year']), 1000)\n spl = make_interp_spline(x, y, k=2)\n y_lin = spl(x_lin)\n spl_freq_score = make_interp_spline(x, freq_scores, k=1)\n freq_score_lin = spl_freq_score(x_lin)\n\n points = np.array([x_lin, y_lin]).T.reshape(-1, 1, 2)\n segments = np.concatenate([points[:-1], points[1:]], axis=1)\n norm = plt.Normalize(0.2, 0.8)\n\n lc = LineCollection(segments, cmap='coolwarm', norm=norm)\n # Set the values used for colormapping\n lc.set_array(freq_score_lin)\n lc.set_linewidth(2)\n line = ax.add_collection(lc)\n ax.set_xlim(x_lin.min(), x_lin.max())\n ax.set_ylim(0, y_lin.max() * 1.1)\n\n ax.set_title(topic_df.at[ax_id, 'term'])\n\n plt.savefig(Path('data', 'plots', f'topic_plots.png'))\n plt.show()\n\n\n\n def plot_topic_grid_of_selected_topics(self, smoothing=5):\n\n # topic_ids_sorted = [r['index'] + 1 for _, r in topic_df.iterrows()]\n\n topic_names_sorted = [x for x in self.df.columns if x.startswith('gen_approach_')]\n\n data = self.get_data(data_type='topics', token_list=topic_names_sorted,\n smoothing=smoothing)\n\n n_rows = 6\n n_cols = 6\n fig = plt.figure(figsize=(50, 50))\n gs = gridspec.GridSpec(nrows=n_rows, ncols=n_cols, figure=fig)\n\n for ax_id, name in enumerate(topic_names_sorted):\n print(ax_id, name)\n row = ax_id // n_cols\n col = ax_id % n_cols\n ax = fig.add_subplot(gs[row, col])\n\n t = name\n x = data[t]['year']\n y = data[t]['freq_both']\n freq_scores = data[t]['freq_score']\n x_lin = np.linspace(min(data[t]['year']), max(data[t]['year']), 1000)\n spl = make_interp_spline(x, y, k=2)\n y_lin = spl(x_lin)\n spl_freq_score = make_interp_spline(x, freq_scores, k=1)\n freq_score_lin = spl_freq_score(x_lin)\n\n points = np.array([x_lin, y_lin]).T.reshape(-1, 1, 2)\n segments = np.concatenate([points[:-1], points[1:]], axis=1)\n norm = plt.Normalize(0.2, 0.8)\n\n lc = LineCollection(segments, cmap='coolwarm', norm=norm)\n # Set the values used for colormapping\n lc.set_array(freq_score_lin)\n lc.set_linewidth(2)\n line = ax.add_collection(lc)\n ax.set_xlim(x_lin.min(), x_lin.max())\n ax.set_ylim(0, max(y_lin) * 1.1)\n\n ax.set_title(name)\n # ax.set_title(f'({topic_id}) {self.topics[topic_id][\"name\"]}')\n\n plt.savefig(Path('data', 'plots', f'general_approaches.png'))\n plt.show()\n\n\n\n\n def plot_londa(self,\n data_type,\n term_or_topic_list,\n smoothing=3):\n\n data = self.get_data(data_type=data_type, token_list=term_or_topic_list,\n smoothing=smoothing)\n\n # 2: Set up plot\n fig = plt.figure(figsize=(12, 12))\n gs = gridspec.GridSpec(nrows=1,\n ncols=1,\n figure=fig,\n width_ratios=[1],\n height_ratios=[1],\n wspace=0.2, hspace=0.05\n )\n\n ax = fig.add_subplot(gs[0, 0])\n ax.set_ylim(0, 1)\n ax.set_xlim(self.start_year + 2, self.end_year - 2)\n ax.set_axisbelow(True)\n ax.grid(which='major', axis='both')\n\n for t in term_or_topic_list:\n x = data[t]['year']\n y = data[t]['freq_both']\n freq_scores = data[t]['freq_score']\n x_lin = np.linspace(min(data[t]['year']), max(data[t]['year']), 1000)\n spl = make_interp_spline(x, y, k=2)\n y_lin = spl(x_lin)\n spl_freq_score = make_interp_spline(x, freq_scores, k=1)\n freq_score_lin = spl_freq_score(x_lin)\n\n # points[0] = (x[0], y[0]\n points = np.array([x_lin, y_lin]).T.reshape(-1, 1, 2)\n # segments[0] = 2x2 matrix. segments[0][0] = points[0]; segments[0][1] = points[1]\n segments = np.concatenate([points[:-1], points[1:]], axis=1)\n norm = plt.Normalize(0.2, 0.8)\n\n lc = LineCollection(segments, cmap='coolwarm', norm=norm)\n # Set the values used for colormapping\n lc.set_array(freq_score_lin)\n lc.set_linewidth(4)\n line = ax.add_collection(lc)\n\n\n fig.colorbar(line, ax=ax)\n\n ax.set_xlim(x_lin.min(), x_lin.max())\n # ax.set_ylim(0, y_lin.max() * 1.1)\n ax.set_ylim(0, 0.4)\n\n plt.savefig(Path('data', 'plots', f'plot_londa.png'))\n plt.show()\n\n\n\n def plot_gender_development_over_time(self,\n no_terms_or_topics_to_show=8,\n data='topics',\n display_selector='most_frequent',\n selected_terms_or_topics=None,\n show_plot=True,\n store_to_filename=None,\n title=None,\n smoothing=3\n\n ):\n\n \"\"\"\n\n :param no_terms_or_topics_to_show: int\n :param data: 'topics', 'terms', 'terms_of_topics'\n :param display_selector: 'most_frequent', 'most_divergent', 'most_variable'\n :param selected_terms_or_topics: topic_id or list of terms\n :param show_plot: bool\n :param store_to_filename: bool or str\n :return:\n \"\"\"\n\n if data == 'terms_of_topic':\n if not isinstance(selected_terms_or_topics, int):\n raise ValueError(\"When displaying 'terms_of_topic', please pass a topic_id for param\"\n \"selected_terms_or_topics\")\n\n # 0: find terms or topics to display\n if data == 'topics':\n selected_terms_or_topics = [f'topic.{id}' for id in range(1, 71)]\n title_name = 'topics'\n elif data == 'terms':\n vocab = []\n for t in selected_terms_or_topics:\n vocab.append(t)\n self.get_document_term_matrix(vocabulary=vocab, store_in_df=True)\n title_name = 'terms'\n elif data == 'terms_of_topic':\n vocab = []\n topic_id = selected_terms_or_topics\n for term in self.topics[topic_id]['terms_prob']:\n if term in self.vocabulary:\n vocab.append(term)\n selected_terms_or_topics = vocab\n self.get_document_term_matrix(vocabulary=vocab, store_in_df=True)\n title_name = f'terms of topic {topic_id}'\n else:\n raise ValueError('\"data\" has to be \"terms\" \"topics\" or \"terms_of_topic\"')\n\n if not title:\n if display_selector == 'most_frequent':\n title = f'Most frequent {title_name} for female (top) and male authors (bottom)'\n elif display_selector == 'most_divergent':\n title = f'Most divergent {title_name} for female (top) and male authors (bottom)'\n else:\n title = f'Most variable {title_name} for female (top) and male authors (bottom)'\n\n df = self.df\n\n # 1: Load data\n data = {}\n for t in selected_terms_or_topics:\n data[t] = defaultdict(list)\n min_freq_total = 1\n max_freq_total = 0\n\n for idx, year in enumerate(range(self.start_year, self.end_year)):\n\n time_slice = df[(df.year >= year - smoothing) & (df.year <= year + smoothing)]\n time_slice_female = time_slice[time_slice.author_genders == 'female']\n time_slice_male = time_slice[time_slice.author_genders == 'male']\n\n for t in selected_terms_or_topics:\n freq_total = time_slice[t].mean()\n freq_female = time_slice_female[t].mean()\n freq_male = time_slice_male[t].mean()\n\n # if a term doesn't appear, it is neutral\n if (freq_male + freq_female) == 0:\n freq_score = 0.5\n else:\n freq_score = freq_female / (freq_female + freq_male)\n\n data[t]['year'].append(year)\n data[t]['freq_score'].append(freq_score)\n data[t]['freq_total'].append(freq_total)\n\n if freq_total < min_freq_total:\n min_freq_total = freq_total\n if freq_total > max_freq_total:\n max_freq_total = freq_total\n\n for t in terms:\n data[t]['mean_freq_score'] = np.mean(data[t]['freq_score'])\n data[t]['mean_freq_total'] = np.mean(data[t]['freq_total'])\n data[t]['freq_score_range'] = max(data[t]['freq_score']) - min(data[t]['freq_score'])\n\n # 2: Set up plot\n fig = plt.figure(figsize=(12, 12))\n gs = gridspec.GridSpec(nrows=1,\n ncols=1,\n figure=fig,\n width_ratios=[1],\n height_ratios=[1],\n wspace=0.2, hspace=0.05\n )\n\n ax = fig.add_subplot(gs[0, 0])\n ax.set_ylim(0, 1)\n ax.set_xlim(self.start_year + 2, self.end_year -2)\n ax.set_axisbelow(True)\n ax.grid(which='major', axis='both')\n\n dot_scaler = MinMaxScaler((0.0, 50.0))\n dot_scaler.fit(np.array([min_freq_total, max_freq_total]).reshape(-1, 1))\n legends = []\n\n def draw_line(t, t_data, df):\n \"\"\"\n Draws one line depending on t (term or topic string) and t_data (dict of data belonging\n to t)\n\n :param t: str\n :param t_data: dict\n :return:\n \"\"\"\n y = t_data['freq_score']\n x = t_data['year']\n frequencies = t_data['freq_total']\n if t.startswith('topic.'):\n legend = self.topics[int(t[6:])]['name']\n else:\n legend = '{:10s} ({})'.format(t, df[t].sum())\n\n x_spline = np.linspace(min(x), max(x), ((self.end_year - 2) - (self.start_year + 2)) * 1000)\n spl = make_interp_spline(x, y, k=1) # BSpline object\n y_spline = spl(x_spline)\n\n line_interpolater = interp1d(x, frequencies)\n line_widths = line_interpolater(x_spline)\n line_widths = dot_scaler.transform(line_widths.reshape(-1, 1)).flatten()\n\n try:\n color = sns.color_palette()[len(legends)]\n except IndexError:\n color = sns.cubehelix_palette(100, start=2, rot=0, dark=0, light=.95)[len(legends)]\n\n ax.scatter(x_spline, y_spline, s=line_widths, antialiased=True,\n color=color)\n legends.append(mpatches.Patch(color=color, label=legend))\n\n # 3: Plot\n if display_selector == 'most_frequent':\n ax.set_title(title, weight='bold', fontsize=18)\n sorted_items = sorted(data.items(), key=lambda k_v: k_v[1]['mean_freq_total'], reverse=True)\n for t, t_data in sorted_items[:no_terms_or_topics_to_show]:\n draw_line(t, t_data, df)\n elif display_selector == 'most_divergent':\n ax.set_title(title, weight='bold', fontsize=18)\n sorted_items = sorted(data.items(), key=lambda k_v: k_v[1]['mean_freq_score'], reverse=True)\n no_disp = no_terms_or_topics_to_show // 2\n for t, t_data in sorted_items[:no_disp] + sorted_items[::-1][:no_disp]:\n draw_line(t, t_data, df)\n elif display_selector == 'most_variable':\n ax.set_title(title, weight='bold', fontsize=18)\n # sort by mean_freq_range second to preserve colors between plots\n sorted_items = sorted(data.items(), key=lambda k_v: k_v[1]['freq_score_range'], reverse=True)\n sorted_items = sorted_items[:no_terms_or_topics_to_show]\n sorted_items = sorted(sorted_items, key=lambda k_v: k_v[1]['mean_freq_score'], reverse=True)\n for t, t_data in sorted_items:\n draw_line(t, t_data, df)\n\n else:\n raise ValueError('display_selector has to be most_frequent, most_variable, or most_divergent')\n\n ax.legend(handles=legends, loc=4)\n\n if show_plot:\n plt.show()\n if store_to_filename:\n fig.savefig(Path('data', store_to_filename))\n\n\ndef plot_adviser_gender():\n\n d = Dataset()\n d.filter(start_year=1980, end_year=2015)\n\n fig = plt.figure(figsize=(50, 50))\n gs = gridspec.GridSpec(nrows=10, ncols=7, figure=fig)\n\n for ax_id, topic_id in enumerate(range(1, 71)):\n print(ax_id)\n\n row = ax_id // 7\n col = ax_id % 7\n ax = fig.add_subplot(gs[row, col])\n\n male = np.zeros(2015-1980+1)\n female = np.zeros(2015 - 1980 + 1)\n unknown = np.zeros(2015 - 1980 + 1)\n\n male_a = np.zeros(2015 - 1980 + 1)\n female_a = np.zeros(2015 - 1980 + 1)\n\n\n top = d.copy()\n top.topic_percentile_score_filter(topic_id, min_percentile_score=80)\n for _, row in top.df.iterrows():\n year = row['Year']\n advisor_gender = row['AdvisorGender']\n advisee_gender = row['author_genders']\n\n if row['AdvisorGender'] == 'female':\n female[row['Year'] - 1980] += 1\n elif row['AdvisorGender'] == 'male':\n male[row['Year'] - 1980] += 1\n else:\n unknown[row['Year'] - 1980] += 1\n\n if advisee_gender == 'female':\n female_a[year - 1980] += 1\n elif advisee_gender == 'male':\n male_a[year - 1980] += 1\n\n # sns.lineplot(x=range(1980, 2016), y=unknown, ax=ax, label='unknown')\n # sns.lineplot(x=range(1980, 2016), y=male, ax=ax, label='male')\n # sns.lineplot(x=range(1980, 2016), y=female, ax=ax, label='female')\n # sns.lineplot(x=range(1980, 2016), y=female_a, ax=ax, label='female_a')\n # sns.lineplot(x=range(1980, 2016), y=male_a, ax=ax, label='male_a')\n sns.lineplot(x=range(1980, 2016), y=female_a / (female_a+male_a), label='Advisee')\n sns.lineplot(x=range(1980, 2016), y=female / (female+male), label='Advisor')\n\n\n ax.legend()\n ax.set_title(f'{topic_id}: {d.topics[topic_id][\"name\"]}')\n\n plt.show()\n\n\n\n\n\n\n\n\n\n\n\n\n\nif __name__ == '__main__':\n\n pass\n\n\n","sub_path":"dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":40061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"24571935","text":"class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n result = 0\n listLength = 1\n while (listLength <= len(arr)):\n for index, item in enumerate(arr):\n subList = arr[index:index + listLength]\n if (len(subList) == listLength): result += sum(subList)\n listLength += 2\n return result","sub_path":"sum-of-all-odd-length-subarrays-92ms-14.1mb.py","file_name":"sum-of-all-odd-length-subarrays-92ms-14.1mb.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"22859591","text":"import numpy as np\nimport os\nimport pdb\nfrom copy import deepcopy as COPY\nfrom matplotlib import pyplot as plt\nfrom scipy.stats import norm\nfrom scipy.stats import pearsonr\nfrom scipy.stats import gaussian_kde as smooth\nfrom scipy.stats import expon\nfrom scipy.stats import norm\n\n#-----------------------------------------------------------------------------\n#-----------------------------------------------------------------------------\n# SECTION 2: Removes spikes from the data.\n#-----------------------------------------------------------------------------\n#-----------------------------------------------------------------------------\n\ndef remove_spikes(x, x_spiked, name, prefix, count, spikes, decreases):\n x_unique, x_counts = np.unique(x, return_counts = True)\n if np.max(x_counts)/np.sum(x_counts) < 0.5 or count == 3:\n return(x, spikes, decreases)\n decreases.append(1 - np.max(x_counts)/np.sum(x_counts))\n new_spike = x_unique[np.argmax(x_counts)]\n spikes.append(new_spike)\n x = x[x != new_spike]\n count += 1\n return(remove_spikes(x, x_spiked, name, prefix, \n count, spikes, decreases))\n\n#-----------------------------------------------------------------------------\n#-----------------------------------------------------------------------------\n# SECTION 2: code that corrects for various continuity violations.\n#-----------------------------------------------------------------------------\n#-----------------------------------------------------------------------------\n\ndef adjust_median_values(x, Q_vec):\n\n dists_sub50, dists_sup50 = x - Q_vec[2], x - Q_vec[2]\n dists_sub50[dists_sub50 >= 0] = -np.inf\n dists_sup50[dists_sup50 <= 0] = np.inf\n x_sub50 = x[np.argmax(dists_sub50)]\n x_sup50 = x[np.argmin(dists_sup50)]\n n_sub50 = np.sum(x == x_sub50)\n n_sup50 = np.sum(x == x_sup50)\n p_sup50 = n_sup50/(n_sup50 + n_sub50)\n\n x2 = COPY(x)\n n_50 = np.sum(x == Q_vec[2])\n choices = [x_sub50, x_sup50]\n p_vec = [1 - p_sup50, p_sup50]\n x2[x == Q_vec[2]] = np.random.choice(choices, n_50, True, p_vec)\n return(x2)\n \ndef get_fitted_quantiles(percentiles, fitted_cdf, range0, \n qstart, qend, good_cdf_tails):\n Q_vec = np.zeros(5)\n if good_cdf_tails == True:\n try:\n Q_vec[0] = range0[np.where(fitted_cdf >= percentiles[0]/100)[0][0]]\n except:\n return(Q_vec)\n else:\n Q_vec[0] = qstart\n Q_vec[1] = range0[np.where(fitted_cdf >= 0.25)[0][0]] \n Q_vec[2] = range0[np.where(fitted_cdf >= 0.5)[0][0]] \n Q_vec[3] = range0[np.where(fitted_cdf >= 0.75)[0][0]] \n if good_cdf_tails == True: \n Q_vec[4] = range0[np.where(fitted_cdf >= percentiles[4]/100)[0][0]]\n else:\n Q_vec[4] = qend \n return(Q_vec)\n\ndef approximate_quantiles(x, percentiles):\n\n \"\"\"\n Purpose\n -------\n to smoothly approximate discrete distributions for\n the purpose of computing quantiles when necessary.\n \n Parameters\n ----------\n x: numeric input numpy array\n percentiles: list of percentiles at which quantiles are computed\n from the x distribution's smooth approximation\n bw_coef: smoothing parameter value that usually works well\n\n Returns\n -------\n Q_vec: list of quantiles that were computed from the \n x distribution's smooth approximation. Extreme\n quantiles are taken from x when possible. \n\n \"\"\"\n q1, q5, q35, q65, q95, q99 = np.percentile(x, [0.5, 5, 35, 65, 95, 99.5])\n qstart = np.percentile(x, percentiles[0])\n spacer = (q99 - q1)/2.75\n qend = np.percentile(x, percentiles[-1])\n range1 = np.linspace(q1 - spacer, q35, 200)\n range2 = np.linspace(q35, q65, 200)\n range3 = np.linspace(q65, q99 + spacer, 200)\n range0 = np.concatenate([range1[:-1], range2[:-1], range3])\n x_bounded = x[np.logical_and(x >= q1, x <= q99)]\n smooth_x = smooth(x_bounded, bw_method = 'silverman')(range0)\n mid_x = (smooth_x[:-1] + smooth_x[1:])/2\n integrand1 = (mid_x*(range0[1:] - range0[:-1]))\n cdf1 = np.cumsum(integrand1)\n good_bounds = np.abs(np.min(cdf1) - 0) + np.abs(np.max(cdf1) - 1) < 0.1\n Q_vec = get_fitted_quantiles(percentiles, cdf1, range0, qstart, qend, True)\n if good_bounds and len(np.unique(Q_vec)) == 5:\n return(Q_vec)\n\n for i in [0.01, 0.05, 0.1, 0.5, 1, 5, 10]:\n smooth_x = smooth(x_bounded, bw_method = i)(range0)\n mid_x = (smooth_x[:-1] + smooth_x[1:])/2\n integrand1 = (mid_x*(range0[1:] - range0[:-1]))\n cdf1 = np.cumsum(integrand1)\n good_bounds = np.abs(np.min(cdf1) - 0) + np.abs(np.max(cdf1) - 1) < 0.1\n Q_vec = get_fitted_quantiles(percentiles, cdf1, range0, qstart, qend, True)\n if good_bounds and len(np.unique(Q_vec)) == 5:\n return(Q_vec)\n\n mu = np.mean(x)\n sig = np.std(x)\n return(norm(mu, sig).ppf(np.array(percentiles)/100))\n \n\n","sub_path":"STAR_outliers_polishing_library.py","file_name":"STAR_outliers_polishing_library.py","file_ext":"py","file_size_in_byte":4935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"411330868","text":"import datetime\nimport itertools\nimport json\nimport logging\nimport momi\nimport numpy as np\nimport os\nimport string\nimport time\nimport tempfile\n\nfrom collections import OrderedDict\n\nimport PTA\nfrom PTA.util import *\nfrom PTA.msfs import *\n\nLOGGER = logging.getLogger(__name__)\n\nclass DemographicModel(object):\n \"\"\"\n The PTA object\n\n :param str name: The name of this PTA simulation. This is used for\n creating output files.\n :param bool quiet: Don't print anything ever.\n :param bool verbose: Print more progress info.\n \"\"\"\n\n def __init__(self, name, quiet=False, verbose=False):\n if not name:\n raise PTAError(REQUIRE_NAME)\n\n ## Do some checking here to make sure the name doesn't have\n ## special characters, spaces, or path delimiters. Allow _ and -.\n ## This will raise an error immediately if there are bad chars in name.\n self._check_name(name)\n self.name = name\n\n self._version = PTA.__version__\n\n ## stores default ipcluster launch info\n self._ipcluster = {\n \"cluster_id\" : \"\",\n \"profile\" : \"default\",\n \"engines\" : \"Local\",\n \"quiet\" : 0,\n \"timeout\" : 120,\n \"cores\" : 0, #detect_cpus(),\n \"threads\" : 2,\n \"pids\": {},\n }\n\n ## the default params dict\n ## If you add a parameter to this dictionary you need\n ## to also add a short description to the PARAMS dict\n ## at the end of this file\n ##\n ## Also be sure to add it to _paramschecker so the type gets set correctly\n self.paramsdict = OrderedDict([\n (\"simulation_name\", name),\n (\"project_dir\", \"./default_PTA\"),\n (\"npops\", 10),\n (\"nsamps\", 4),\n (\"N_e\", 10000),\n (\"tau\", 20000),\n (\"epsilon\", 10),\n (\"zeta\", 0),\n (\"length\", 1000),\n (\"num_replicates\", 100),\n (\"generation_time\", 1),\n (\"recoms_per_gen\", 1e-9),\n (\"muts_per_gen\", 1e-8)\n ])\n\n ## Separator to use for reading/writing files\n self._sep = \" \"\n\n ## A dictionary for storing taxon specific information. This dictionary\n ## is populated when empirical data is loaded. If no per taxon info\n ## is present then we sample from the priors as specified in the params\n ## file.\n self.taxa = {}\n\n ## elite hackers only internal dictionary, normally you shouldn't mess with this\n ## * sorted_sfs: Whether or not to sort the bins of the msfs\n ## * allow_psi>1: Whether to allow multiple co-expansion events per simulation\n ## or to fix it to 1. This is the msbayes vs pipemaster flag.\n ## * proportional_msfs: Scale counts within an sfs bin per population to sum to 1.\n ## * mu_variance: If this parameter is > 0, then mu will be sampled from a zero-\n ## truncated normal distribution with mean `muts_per_gen` and variance\n ## `mu_variance`. If 0, then `muts_per_gen` is a fixed global mutation rate.\n self._hackersonly = dict([\n (\"sorted_sfs\", True),\n (\"allow_psi>1\", False), \n (\"proportional_msfs\", False),\n (\"mu_variance\", 0),\n ])\n\n ## Ne_ave, the expected value of the Ne parameter given a unifrom prior\n ## This will actually be set inside _paramschecker\n self._Ne_ave = self.paramsdict[\"N_e\"]\n\n ## The empirical msfs\n self.empirical_msfs = \"\"\n\n\n #########################\n ## Housekeeping functions\n #########################\n def __str__(self):\n return \"\".format(self.paramsdict[\"simulation_name\"])\n\n\n ## Test assembly name is valid and raise if it contains any special characters\n def _check_name(self, name):\n invalid_chars = string.punctuation.replace(\"_\", \"\")\\\n .replace(\"-\", \"\")+ \" \"\n if any(char in invalid_chars for char in name):\n raise PTAError(BAD_PTA_NAME.format(name))\n\n\n def _get_simulation_outdir(self, prefix=\"\"):\n \"\"\"\n Construct an output directory for a simulation run.\n Make output directory formatted like /-\n This will _mostly_ avoid output directory collisions, right?\n\n :param string prefix: The directory within which to create the\n simulation output directory.\n \"\"\"\n\n dirname = prefix + self.paramsdict[\"simulation_name\"]\n outdir = os.path.join(self.paramsdict[\"project_dir\"],\\\n dirname\\\n + \"-\" + str(time.time()).replace(\".\", \"\")[-7:]\\\n + str(np.random.randint(100)))\n if not os.path.exists(outdir):\n os.mkdir(outdir)\n\n return outdir\n\n\n def _paramschecker(self, param, newvalue, quiet=True):\n \"\"\"\n Check and set parameters. Raises exceptions when params are set to \n values they should not be.\n\n :param string param: The parameter to set.\n :param newvalue: The value of the parameter.\n :param bool quiet: Whether to print info.\n \"\"\"\n ## TODO: This should actually check the values and make sure they make sense\n try:\n ## Cast params to correct types\n if param == \"project_dir\":\n ## If it already exists then just inform the user that we'll be adding\n ## more simulations to the current project directory\n if \" \" in newvalue:\n raise PTAError(\"`project_dir` may not contain spaces. You put:\\n{}\".format(newvalue))\n self.paramsdict[param] = os.path.realpath(os.path.expanduser(newvalue))\n\n if not os.path.exists(self.paramsdict[\"project_dir\"]):\n os.mkdir(self.paramsdict[\"project_dir\"])\n \n elif param in [\"N_e\", \"tau\", \"epsilon\"]:\n dtype = int\n if param == \"epsilon\":\n dtype = float\n tup = tuplecheck(newvalue, dtype=dtype)\n if isinstance(tup, tuple):\n self.paramsdict[param] = tup\n if tup[0] <= 0:\n raise PTAError(\"{} values must be strictly > 0. You put {}\".format(param, tup))\n else:\n self.paramsdict[param] = tup\n if tup <= 0:\n raise PTAError(\"{} values must be strictly > 0. You put {}\".format(param, tup))\n if param == \"N_e\":\n # Calculate Ne_ave, the expected value of the uniform prior on Nes\n self._Ne_ave = np.mean(tup)\n\n elif param in [\"num_replicates\"]:\n ## num_replicates must be a list that is the same length\n ## as the number of populations, and should contain the\n ## numbers of observed loci for each sample in the data.\n ## If you pass in a single integer value then we just use\n ## the same num_replicates for all pops.\n ## islist will properly handle setting with a list in API\n ## mode and will do nothing in CLI mode.\n newvalue = tuplecheck(newvalue, islist=True, dtype=int)\n if isinstance(newvalue, int):\n newvalue = [newvalue] * self.paramsdict[\"npops\"]\n self.paramsdict[param] = newvalue\n if not len(newvalue) == self.paramsdict[\"npops\"]:\n raise PTAError(BAD_NUM_REPLICATES.format(len(newvalue),\\\n self.paramsdict[\"npops\"]))\n\n elif param in [\"npops\", \"nsamsp\", \"length\"]:\n self.paramsdict[param] = int(newvalue)\n\n elif param in [\"generation_time\", \"recoms_per_gen\", \"muts_per_gen\", \"zeta\"]:\n self.paramsdict[param] = float(newvalue)\n\n else:\n self.paramsdict[param] = newvalue\n except Exception as inst:\n ## Do something intelligent here?\n raise\n\n\n ## Getting parameters header and parameters carves off\n ## the simulation name and the project directory\n def _get_params_header(self):\n return list(self.paramsdict.keys())[2:]\n\n\n def _get_params_values(self):\n return list(self.paramsdict.values())[2:]\n\n\n def set_param(self, param, value, quiet=True):\n \"\"\"\n A convenience function for setting parameters in the API mode, which\n turns out to be a little annoying if you don't provide this. With\n the set_param method you can set parameters on the Region, the\n Metacommunity, or the LocalCommunity. Simply pass the parameter\n name and the value, and this method identifies the appropriate target\n parameter.\n\n :param string param: The name of the parameter to set.\n :param value: The value of the parameter to set.\n :param bool quiet: Whether to print info to the console.\n \"\"\"\n try:\n self = set_params(self, param, value, quiet)\n except:\n raise PTAError(\"Bad param/value {}/{}\".format(param, value))\n\n\n def get_params(self):\n \"\"\"\n A convenience function for getting nicely formatted params in API mode.\n\n :return: A string of all the params ready to be printed.\n \"\"\"\n tf = tempfile.NamedTemporaryFile()\n self.write_params(outfile=tf.name, force=True)\n dat = open(tf.name).read()\n return dat\n\n\n def write_params(self, outfile=None, outdir=None, force=False):\n \"\"\"\n Write out the parameters of this model to a file properly formatted as\n input for the PTA CLI. A good and simple way to share/archive \n parameter settings for simulations. This is also the function that's\n used by __main__ to generate default params.txt files for `PTA -n`.\n\n :param string outfile: The name of the params file to generate. If not\n specified this will default to `params-.txt`.\n :param string outdir: The directory to write the params file to. If not\n specified this will default to the project_dir.\n :param bool force: Whether to overwrite if a file already exists.\n \"\"\"\n if outfile is None:\n outfile = \"params-\"+self.paramsdict[\"simulation_name\"]+\".txt\"\n\n ## If outdir is blank then default to writing to the project dir\n if outdir is None:\n outdir = self.paramsdict[\"project_dir\"]\n elif not os.path.exists(outdir):\n raise PTAError(NO_OUTDIR).format(outdir)\n\n outfile = os.path.join(outdir, outfile)\n ## Test if params file already exists?\n ## If not forcing, test for file and bail out if it exists\n if not force:\n if os.path.isfile(outfile):\n raise PTAError(PARAMS_EXISTS.format(outfile))\n\n with open(outfile, 'w') as paramsfile:\n ## Write the header. Format to 80 columns\n header = \"------- PTA params file (v.{})\".format(PTA.__version__)\n header += (\"-\"*(80-len(header)))\n paramsfile.write(header)\n\n ## Whip through the current paramsdict and write out the current\n ## param value, the ordered dict index number. Also,\n ## get the short description from paramsinfo. Make it look pretty,\n ## pad nicely if at all possible.\n for key, val in self.paramsdict.items():\n if isinstance(val, tuple):\n paramvalue = \"-\".join(map(str, val))\n elif isinstance(val, list):\n paramvalue = \",\".join(map(str, val))\n else:\n paramvalue = str(val)\n\n padding = (\" \"*(20-len(paramvalue)))\n paramkey = list(self.paramsdict.keys()).index(key)\n paramindex = \" ## [{}] \".format(paramkey)\n LOGGER.debug(\"{} {} {}\".format(key, val, paramindex))\n name = \"[{}]: \".format(key)\n description = PARAMS[key]\n paramsfile.write(\"\\n\" + paramvalue + padding + \\\n paramindex + name + description)\n\n paramsfile.write(\"\\n\")\n\n\n def save(self):\n _save_json(self)\n\n\n @staticmethod\n def load(json_path, quiet=False):\n \"\"\"\n Load a json serialized object and ensure it matches to the current model format.\n \"\"\"\n # expand HOME in JSON path name\n json_path = json_path.replace(\"~\", os.path.expanduser(\"~\"))\n\n # raise error if JSON not found\n if not os.path.exists(json_path):\n raise PTAError(\"\"\"\n Could not find saved model file (.json) in expected location.\n Checks in: [project_dir]/[assembly_name].json\n Checked: {}\n \"\"\".format(json_path))\n\n # load JSON file\n with open(json_path, 'rb') as infile:\n fullj = json.loads(infile.read(), object_hook=_tup_and_byte)\n\n # get name and project_dir from loaded JSON\n oldname = fullj[\"model\"].pop(\"name\")\n olddir = fullj[\"model\"][\"paramsdict\"][\"project_dir\"]\n oldpath = os.path.join(olddir, os.path.splitext(oldname)[0] + \".json\")\n\n # create a fresh new Assembly\n null = PTA.DemographicModel(oldname, quiet=True)\n\n # print Loading message with shortened path\n if not quiet:\n oldpath = oldpath.replace(os.path.expanduser(\"~\"), \"~\")\n print(\" loading DemographicModel: {}\".format(oldname))\n print(\" from saved path: {}\".format(oldpath))\n\n ## get the taxa. Create empty taxa dict of correct length\n taxa = fullj[\"model\"].pop(\"taxa\")\n null.taxa = taxa\n\n ## Set params\n oldparams = fullj[\"model\"].pop(\"paramsdict\")\n for param, value in oldparams.items():\n null.set_param(param, value)\n\n oldhackersonly = fullj[\"model\"].pop(\"_hackersonly\")\n null._hackersonly = oldhackersonly\n\n null._sep = fullj[\"model\"].pop(\"_sep\")\n null.empirical_msfs = fullj[\"model\"].pop(\"empirical_msfs\")\n\n taxon_names = list(fullj[\"taxa\"].keys())\n\n return null\n\n\n def load_empirical(inpath):\n \"\"\"\n Load in empirical data, either from a stored msfs or from a directory\n of individual momi-style sfs which have been dumped to file.\n \"\"\"\n pass\n\n ########################\n ## Model functions/API\n ########################\n\n ## For sampling from priors, the draw comes from the half open interval\n ## so for tau we add 1 to account for most people not thinking of this.\n def _sample_tau(self, pops_per_tau):\n \"\"\"\n pops_per_tau - A list of number of populations per coexpansion event.\n In the simplest case of one coexpansion it will look\n like this [6, 1, 1, 1], indictating one coexpansion of\n 6 taxa and independent expansions of 3 other taxa (9 total).\n returns a list of expansion times of length npops\n \"\"\"\n tau = self.paramsdict[\"tau\"]\n if isinstance(tau, tuple):\n tau = (tau[0], tau[1]+1)\n else:\n tau = (tau, tau+1)\n taus = [[np.random.randint(tau[0], tau[1], 1)[0]] * x for x in pops_per_tau]\n # Collapse the list of lists to a single list with ts per population\n taus = np.array(list(itertools.chain.from_iterable(taus)))\n\n # Scale years to generations\n taus = taus/self.paramsdict[\"generation_time\"]\n\n return taus\n\n ## Here we can either have all co-expanding taxa with the same epsilon\n ## or we can have one random epsilon per taxon. As it stands it's the first way\n def _sample_epsilon(self, pops_per_tau):\n eps = self.paramsdict[\"epsilon\"]\n if isinstance(eps, tuple):\n eps = [[np.random.uniform(eps[0], eps[1], 1)[0]] * x for x in pops_per_tau]\n eps = np.array(list(itertools.chain.from_iterable(eps)))\n else:\n eps = np.array([eps] * self.paramsdict[\"npops\"])\n return eps\n\n\n def _sample_zeta(self):\n \"\"\"\n If zeta is specified in the params dict, then just use this value. If zeta\n is zero (the default), then sample a random value between [0, 1).\n \"\"\"\n zeta = self.paramsdict[\"zeta\"]\n ## If tau is fixed then zeta is 1 by definition\n if not isinstance(self.paramsdict[\"tau\"], tuple):\n zeta = 1\n ## If zeta is 0 sample uniform [0, 1)\n elif not zeta:\n zeta = np.random.uniform()\n return zeta\n\n\n def _sample_Ne(self, nsamps=1):\n N_e = self.paramsdict[\"N_e\"]\n if isinstance(N_e, tuple):\n N_e = np.random.randint(N_e[0], N_e[1]+1, nsamps)\n else:\n N_e = np.array([N_e] * nsamps)\n return N_e\n\n\n def _check_numreplicates(self):\n \"\"\"\n Ensure num_replicates is the correct length. API mode doesn't\n automatically expand an individual integer to an int list, and\n also, if one chooses to specify the number of loci per pop, but\n this doesn't agree with the number of npops this is a problem.\n \"\"\"\n num_replicates = self.paramsdict[\"num_replicates\"]\n if isinstance(num_replicates, list):\n if not len(num_replicates) == self.paramsdict[\"npops\"]:\n raise PTAError(BAD_NUM_REPLICATES.format(len(num_replicates),\\\n self.paramsdict[\"npops\"]))\n elif isinstance(num_replicates, int):\n num_replicates = [num_replicates] * self.paramsdict[\"npops\"]\n else:\n raise PTAError(\"num_replicates param must be int or list: {}\".format(num_replicates))\n return num_replicates\n\n\n def _sample_mu(self):\n \"\"\"\n Sample mu from a zero-truncated normal distribution, if mu_var is\n specified, otherwise use fixed, global mu. If you set the mu_variance\n too high and you get a very small value, or zero, then the simulation\n will die and it'll raise a PTAError.\n \"\"\"\n mu = self.paramsdict[\"muts_per_gen\"]\n mu_var = self._hackersonly[\"mu_variance\"]\n if mu_var:\n mu = np.random.normal(mu, mu_var)\n if mu < 0:\n mu = 0\n return mu\n\n\n def get_pops_per_tau(self, n_sync):\n \n # There needs to be at least 1 coexpansion event and coexpansion events must\n # include at least 2 taxa\n if n_sync > 1:\n try:\n if self._hackersonly[\"allow_psi>1\"]:\n psi = np.random.randint(1, (n_sync+1)/2)\n else:\n psi = 1\n except ValueError:\n # If n_sync + 1 / 2 = 1 then psi = 1\n psi = 1\n n_async = self.paramsdict[\"npops\"] - n_sync\n \n # Have to allocate all pops to a table in the restaurant\n # Each table has to have at least 2 customers or its not a real table\n pops_per_tau = np.array([2] * psi, dtype=int)\n \n # Allocate any remaining pops to a table with uniform probability\n unallocated_pops = n_sync - np.sum(pops_per_tau)\n unallocated_pops = np.random.multinomial(unallocated_pops, [1/psi]*psi)\n \n pops_per_tau = pops_per_tau + unallocated_pops\n pops_per_tau = np.concatenate([pops_per_tau, [1]*n_async])\n else:\n # If no coexpansion events then everyone gets their own table\n psi = 0\n n_sync = 0\n n_async = self.paramsdict[\"npops\"]\n pops_per_tau = np.array([1] * self.paramsdict[\"npops\"])\n \n return psi, pops_per_tau.astype(int)\n\n \n def parallel_simulate(self, ipyclient, nsims=1, quiet=False, verbose=False):\n npops = self.paramsdict[\"npops\"]\n parallel_jobs = {}\n _ipcluster = {}\n ## store ipyclient engine pids to the Assembly so we can\n ## hard-interrupt them later if assembly is interrupted.\n ## Only stores pids of engines that aren't busy at this moment,\n ## otherwise it would block here while waiting to find their pids.\n _ipcluster[\"pids\"] = {}\n for eid in ipyclient.ids:\n engine = ipyclient[eid]\n if not engine.outstanding:\n pid = engine.apply(os.getpid).get()\n _ipcluster[\"pids\"][eid] = pid\n\n lbview = ipyclient.load_balanced_view()\n for i in range(nsims):\n ## Call do_serial sims args are: nsims, quiet, verbose\n parallel_jobs[i] = lbview.apply(serial_simulate, self, 1, True, False)\n\n ## Wait for all jobs to finish\n start = time.time()\n printstr = \" Performing Simulations | {} |\"\n while 1:\n try:\n fin = [i.ready() for i in parallel_jobs.values()]\n elapsed = datetime.timedelta(seconds=int(time.time()-start))\n if not quiet: progressbar(len(fin), sum(fin), printstr.format(elapsed))\n time.sleep(0.1)\n if len(fin) == sum(fin):\n break\n except KeyboardInterrupt as inst:\n print(\"\\n Cancelling remaining simulations.\")\n break\n if not quiet: progressbar(100, 100, \" Finished {} simulations in {}\\n\".format(i+1, elapsed))\n\n faildict = {}\n param_df = pd.DataFrame()\n msfs_list = []\n ## Gather results\n for result in parallel_jobs:\n try:\n if not parallel_jobs[result].successful():\n faildict[result] = parallel_jobs[result].metadata.error\n else:\n msfs_list.extend(parallel_jobs[result].result())\n except Exception as inst:\n LOGGER.error(\"Caught a failed simulation - {}\".format(inst))\n ## Don't let one bad apple spoin the bunch,\n ## so keep trying through the rest of the asyncs\n LOGGER.debug(faildict)\n\n return msfs_list\n \n \n def serial_simulate(self, nsims=1, quiet=False, verbose=False):\n import pandas as pd\n npops = self.paramsdict[\"npops\"]\n \n msfs_list = []\n\n printstr = \" Performing Simulations | {} |\"\n start = time.time()\n for i in range(nsims):\n try:\n elapsed = datetime.timedelta(seconds=int(time.time()-start))\n if not quiet: progressbar(nsims, i, printstr.format(elapsed))\n\n zeta = self._sample_zeta()\n # Get effective # of coexpanding taxa\n zeta_e = int(np.round(zeta * self.paramsdict[\"npops\"]))\n psi, pops_per_tau = self.get_pops_per_tau(n_sync=zeta_e)\n\n LOGGER.debug(\"sim {} - zeta {} - zeta_e {} - psi {} - pops_per_tau{}\".format(i, zeta, zeta_e, psi, pops_per_tau))\n # All taus, epsilons, and N_es will be the length of npops\n # taus here will be in generations not years\n taus = self._sample_tau(pops_per_tau)\n epsilons = self._sample_epsilon(pops_per_tau)\n N_es = self._sample_Ne(self.paramsdict[\"npops\"])\n num_replicates = self._check_numreplicates()\n sfs_list = []\n idx = 0\n for tidx, tau_pops in enumerate(pops_per_tau):\n for pidx in range(tau_pops):\n name = \"pop{}-{}\".format(tidx, pidx)\n ## FIXME: Here the co-expanding pops all receive the same\n ## epsilon. Probably not the best way to do it.\n sfs_list.append(self._simulate(name,\n N_e=N_es[idx],\n tau=taus[idx],\n epsilon=epsilons[idx],\n num_replicates=num_replicates[idx]))\n idx += 1\n msfs = multiSFS(sfs_list,\\\n sort=self._hackersonly[\"sorted_sfs\"],\\\n proportions=self._hackersonly[\"proportional_msfs\"])\n\n ## Scale time to coalsecent units\n ## Here taus in generations already, so scale to coalescent units\n ## assuming diploid so 2 * 2Ne\n taus = taus/(4*self._Ne_ave)\n\n ## In the pipe_master model the first tau in the list is the co-expansion time\n ## If/when you get around to doing the msbayes model of multiple coexpansion\n ## pulses, then this will have to change \n msfs.set_params(pd.Series([zeta, zeta_e, psi, taus[0], pops_per_tau, taus, epsilons, N_es],\\\n index=[\"zeta\", \"zeta_e\", \"psi\", \"t_s\", \"pops_per_tau\", \"taus\", \"epsilons\", \"N_es\"]))\n msfs_list.append(msfs)\n\n except KeyboardInterrupt as inst:\n print(\"\\n Cancelling remaining simulations\")\n break\n except Exception as inst:\n LOGGER.debug(\"Simulation failed: {}\".format(inst))\n raise PTAError(\"Failed inside serial_simulate: {}\".format(inst))\n\n if not quiet: progressbar(100, 100, \" Finished {} simulations in {}\\n\".format(i+1, elapsed))\n\n return msfs_list\n\n\n def _simulate(self,\n name,\n N_e=1e6,\n tau=20000,\n epsilon=10,\n num_replicates=100,\n verbose=False):\n\n model = momi.DemographicModel(N_e=N_e)\n model.add_leaf(name)\n ## epsilon > 1 is bottleneck backwards in time\n ## epsilon < 1 is expansion\n ## epsilon == 1 is constant size\n model.set_size(name, t=tau, N=N_e*epsilon)\n\n sampled_n_dict={name:self.paramsdict[\"nsamps\"]}\n if verbose: print(sampled_n_dict)\n ac = model.simulate_data(length=self.paramsdict[\"length\"],\n num_replicates=num_replicates,\n recoms_per_gen=self.paramsdict[\"recoms_per_gen\"],\n muts_per_gen=self._sample_mu(),\n sampled_n_dict=sampled_n_dict)\n try:\n sfs = ac.extract_sfs(n_blocks=1)\n ## TODO: Issue #12 <- Allow unfolded SFS.\n sfs = sfs.fold()\n except ValueError:\n ## If _sample_mu() returns zero, or a very small value with respect to\n ## sequence length, Ne, and tau, then you can get a case where there\n ## are no snps in the data, and constructing the sfs freaks.\n raise PTAError(\"Can't extract SFS from a simulation with no variation. Check that muts_per_gen looks reasonable.\")\n\n return sfs\n\n \n def simulate(self, nsims=1, ipyclient=None, quiet=False, verbose=False, force=False):\n \"\"\"\n Do the heavy lifting here. \n\n :param int nsims: The number of PTA codemographic simulations to\n perform.\n :param ipyparallel.Client ipyclient: If specified use this ipyparallel\n client to parallelize simulation runs. If not specified simulations\n will be run serially.\n :para bool quiet: Whether to display progress of these simulations.\n :para bool verbose: Display a bit more progress information.\n :param bool force: Whether to append to or overwrite results from\n previous simulations. Setting `force` to ``True`` will overwrite\n any previously generated simulation in the `project_dir/{name}-SIMOUT.txt`\n file.\n \"\"\"\n param_df = pd.DataFrame([], columns=[\"zeta\", \"psi\", \"pops_per_tau\", \"taus\", \"epsilons\"])\n\n if not quiet: print(\" Generating {} simulation(s).\".format(nsims))\n\n if not os.path.exists(self.paramsdict[\"project_dir\"]):\n os.mkdir(self.paramsdict[\"project_dir\"])\n\n if ipyclient:\n msfs_list = self.parallel_simulate(ipyclient, nsims=nsims, quiet=quiet, verbose=verbose)\n else:\n # Run simulations serially\n msfs_list = self.serial_simulate(nsims=nsims, quiet=quiet, verbose=verbose)\n\n self._write_df(msfs_list, force=force)\n\n\n ## Save the results to the output DataFrame\n def _write_df(self, msfs_list, force=False):\n\n simfile = os.path.join(self.paramsdict[\"project_dir\"], \"{}-SIMOUT.csv\".format(self.name))\n ## Open output file. If force then overwrite existing, otherwise just append.\n if force:\n ## Prevent from shooting yourself in the foot with -f\n try:\n os.rename(simfile, simfile+\".bak\")\n except FileNotFoundError:\n ## If the simfile doesn't exist catch the error and move on\n pass\n try:\n dat = pd.read_csv(simfile, sep=self._sep)\n except FileNotFoundError:\n dat = pd.DataFrame()\n\n ## sort=False suppresses a warning about non-concatenation index if\n ## SIMOUT is empty\n msfs_df = pd.DataFrame(pd.concat([x.to_dataframe() for x in msfs_list], sort=False)).fillna(0)\n dat = pd.concat([dat, msfs_df], sort=False)\n dat.to_csv(simfile, header=True, index=False, sep=self._sep, float_format='%.3f')\n\n\n def _write_simout(self, msfs_list, force=False):\n \"\"\"\n This is the somewhat old-fashioned way of doing it where you just open\n the file and start writing out the simulations. This will _bite_ you if\n the msfs are sparse because then the lengths of lines will be different.\n I'm keeping it for now because I wrote it and it works and I'm precious\n about it. You can probably just remove, as the _write_df call generates\n essentially the exact same output, but is more reliable.\n \"\"\"\n simfile = os.path.join(self.paramsdict[\"project_dir\"], \"{}-SIMOUT.txt\".format(self.name))\n ## Open output file. If force then overwrite existing, otherwise just append.\n io_mode = 'a'\n if force:\n io_mode = 'w'\n ## Prevent from shooting yourself in the foot with -f\n try:\n os.rename(simfile, simfile+\".bak\")\n except FileNotFoundError:\n ## If the simfile doesn't exist catch the error and move on\n pass\n\n ## Decide whether to print the header, if stuff is already in there then\n ## don't print the header, unless you're doing force because this opens\n ## in overwrite mode.\n header = msfs_list[0]._header(sep=self._sep) + \"\\n\"\n if os.path.exists(simfile) and not force:\n header = \"\"\n\n with open(simfile, io_mode) as outfile:\n outfile.write(header)\n\n for msfs in msfs_list:\n try:\n outfile.write(msfs.to_string(sep=self._sep) + \"\\n\")\n except Exception as inst:\n print(\"Writing output failed. See pta_log.txt.\")\n LOGGER.error(\"Malformed msfs: {}\\n{}\\n{}\".format(inst, msfs.to_string(self._sep)))\n\n\ndef serial_simulate(model, nsims=1, quiet=False, verbose=False):\n import os\n LOGGER.debug(\"Entering sim - {} on pid {}\\n{}\".format(model, os.getpid(), model.paramsdict))\n res = model.serial_simulate(nsims, quiet=quiet, verbose=verbose)\n LOGGER.debug(\"Leaving sim - {} on pid {}\".format(model, os.getpid()))\n return res\n\n\n##########################################\n## Saving functions to dump model to json\n## This is all ripped directly from ipyrad\n## with minor modifications.\n##########################################\n\nclass _Encoder(json.JSONEncoder):\n \"\"\"\n Save JSON string with tuples embedded as described in stackoverflow\n thread. Modified here to include dictionary values as tuples.\n link: http://stackoverflow.com/questions/15721363/\n\n This Encoder Class is used as the 'cls' argument to json.dumps()\n \"\"\"\n def encode(self, obj):\n \"\"\" function to encode json string\"\"\"\n def hint_tuples(item):\n \"\"\" embeds __tuple__ hinter in json strings \"\"\"\n if isinstance(item, tuple):\n return {'__tuple__': True, 'items': item}\n if isinstance(item, list):\n return [hint_tuples(e) for e in item]\n if isinstance(item, dict):\n return {\n key: hint_tuples(val) for key, val in item.items()\n }\n else:\n return item\n return super(_Encoder, self).encode(hint_tuples(obj))\n\n\ndef _default(o):\n print(o)\n # https://stackoverflow.com/questions/11942364/\n # typeerror-integer-is-not-json-serializable-when-\n # serializing-json-in-python?utm_medium=organic&utm_\n # source=google_rich_qa&utm_campaign=google_rich_qa\n if isinstance(o, np.int64):\n return int(o)\n raise TypeError\n\n\ndef _tup_and_byte(obj):\n \"\"\" this is used in loading \"\"\"\n\n # convert all strings to bytes\n if isinstance(obj, (bytes)):\n return obj.decode() # encode('utf-8')\n #return obj.encode('utf-8')\n\n # if this is a list of values, return list of byteified values\n if isinstance(obj, list):\n return [_tup_and_byte(item) for item in obj]\n\n # if this is a dictionary, return dictionary of byteified keys and values\n # but only if we haven't already byteified it\n if isinstance(obj, dict):\n if \"__tuple__\" in obj:\n return tuple(_tup_and_byte(item) for item in obj[\"items\"])\n else:\n return {\n _tup_and_byte(key): _tup_and_byte(val) for\n key, val in obj.items()\n }\n\n # if it's anything else, return it in its original form\n return obj\n\n\ndef _save_json(data, quiet=False):\n \"\"\"\n Save assembly and samples as json\n ## data as dict\n #### samples save only keys\n \"\"\"\n # store params without the reference to Assembly object in params\n paramsdict = {i: j for (i, j) in data.paramsdict.items() if i != \"_data\"}\n\n # store all other dicts\n datadict = OrderedDict([\\\n (\"name\", data.name),\\\n (\"__version__\", data._version),\\\n (\"_sep\", data._sep),\\\n (\"paramsdict\", paramsdict),\\\n (\"taxa\", list(data.taxa.keys())),\\\n (\"_hackersonly\", data._hackersonly),\\\n (\"empirical_msfs\", data.empirical_msfs)\\\n ])\n\n ## save taxat\n taxadict = OrderedDict([])\n for key, taxon in data.taxa.items():\n taxadict[key] = taxon._to_fulldict()\n\n ## json format it using cumstom Encoder class\n fulldumps = json.dumps({\n \"model\": datadict,\n \"taxa\": taxadict\n },\n cls=_Encoder,\n sort_keys=False, indent=4, separators=(\",\", \":\"),\n default=_default,\n )\n\n ## save to file\n modelpath = os.path.join(data.paramsdict[\"project_dir\"],\\\n data.name + \".json\")\n if not os.path.exists(data.paramsdict[\"project_dir\"]):\n os.mkdir(data.paramsdict[\"project_dir\"])\n\n ## protect save from interruption\n done = 0\n if not quiet: print(\" Saving DemographicModel to {}\".format(modelpath))\n while not done:\n try:\n with open(modelpath, 'w') as jout:\n jout.write(fulldumps)\n done = 1\n except (KeyboardInterrupt, SystemExit):\n print('.')\n continue\n\n\n#############################\n## Model Parameter Info Dicts\n#############################\nPARAMS = {\n \"simulation_name\" : \"The name of this simulation scenario\",\\\n \"project_dir\" : \"Where to save files\",\\\n \"npops\" : \"Number of populations undergoing co-demographic processes\",\\\n \"nsamps\" : \"Numbers of samples for each populations\",\\\n \"N_e\" : \"Effective population size of the contemporary population\",\\\n \"tau\" : \"Time of demographic change\",\\\n \"epsilon\" : \"Magnitude of demographic change\",\\\n \"zeta\" : \"Proportion of coexpanding taxa. Default will sample U~(0, 1)\",\\\n \"length\" : \"Length in bp of each independent genomic region to simulate\",\\\n \"num_replicates\" : \"Number of genomic regions to simulate\",\\\n \"generation_time\" : \"Generation time in years\",\\\n \"recoms_per_gen\" : \"Recombination rate within independent regions scaled per base per generation\",\\\n \"muts_per_gen\" : \"Mutation rate scaled per base per generation\",\\\n}\n\n\n#############################\n## Global error messages\n#############################\nBAD_PTA_NAME = \"\"\"\\\n No spaces or special characters of any kind are allowed in the simulation\n name. Special characters include all punctuation except dash '-' and\n underscore '_'. A good practice is to replace spaces with underscores '_'.\n An example of a good simulation name is: hawaiian_arthropods\n\n Here's what you put:\n {}\n \"\"\"\n\nBAD_NUM_REPLICATES = \"\"\"\n `num_replicates` parameter must be either a single integer value, which\n will be interpreted as all populations having this number of loci, or it\n must be a list of integer values that is of length `npops`.\n\n len(num_replicates) = {}\n npops = {}\n \"\"\"\n\nPARAMS_EXISTS = \"\"\"\n Error: Params file already exists: {}\n Use force argument to overwrite.\n \"\"\"\n\nNO_OUTDIR = \"\"\"\n Error: Attempting to write params to a directory that doesn't exist - {}\n \"\"\"\n\nREQUIRE_NAME = \"\"\"\\\n Simulation scenario name _must_ be set. This is the first parameter in the\n params.txt file, and will be used as a prefix for output files. It should be a\n short string with no special characters, i.e., not a path (no \\\"/\\\" characters).\n If you need a suggestion, name it after the location you're working on.\n \"\"\"\n\nif __name__ == \"__main__\":\n pass\n","sub_path":"PTA/demography.py","file_name":"demography.py","file_ext":"py","file_size_in_byte":38262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"538758586","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\n\nfrom evernote.api.client import EvernoteClient\nimport evernote.edam.notestore.ttypes as NoteStoreTypes\n\nfrom endevauth import en_dev_token_production\n\ndef get_note_store():\n\tclient = EvernoteClient(token=en_dev_token_production, sandbox=False)\n\treturn client.get_note_store()\n\ndef index(request):\n note_store = get_note_store()\n result_spec = NoteStoreTypes.NotesMetadataResultSpec()\n result_spec.includeTitle = True\n note_filter = NoteStoreTypes.NoteFilter()\n note_filter.order = 2\n note_filter.words = \"todo:*\"\n metadata_list = note_store.findNotesMetadata(en_dev_token_production, note_filter, 0, 25, result_spec)\n context = {'todo_notes_list': metadata_list.notes}\n return render(request, 'agenda/index.html', context)","sub_path":"django_tensor/agenda/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"43669883","text":"\"\"\"\nPrepare resnet model to deploy on Raspberry Pi. TVM compiles net on Mac and deploys\non Raspberry Pi at runtime. Uses RPC server.\nhttps://docs.tvm.ai/tutorials/frontend/deploy_model_on_rasp.html\n\n\"\"\"\n\nimport tvm\nimport tvm.relay as relay\nfrom tvm import rpc\nfrom tvm.contrib import util, graph_runtime as runtime\nfrom tvm.contrib.download import download_testdata\n\nfrom mxnet.gluon.model_zoo.vision import get_model\nfrom PIL import Image\nimport numpy as np\n\ndef transform_image(image):\n image = np.array(image) - np.array([123., 117., 104.])\n image /= np.array([58.395, 57.12, 57.375])\n image = image.transpose((2, 0, 1))\n image = image[np.newaxis, :]\n return image\n\ndef main():\n # one line to get the model\n block = get_model('resnet18_v1', pretrained=True)\n # test model\n img_url = 'https://github.com/dmlc/mxnet.js/blob/master/data/cat.png?raw=true'\n img_name = 'cat.png'\n img_path = download_testdata(img_url, img_name, module='data')\n image = Image.open(img_path).resize((224, 224))\n # tvm specific data path\n # print(img_path)\n\n x = transform_image(image)\n\n # label number to word dict prepped with synset\n synset_url = ''.join(['https://gist.githubusercontent.com/zhreshold/',\n '4d0b62f3d01426887599d4f7ede23ee5/raw/',\n '596b27d23537e5a1b5751d2b0481ef172f58b539/',\n 'imagenet1000_clsid_to_human.txt'])\n synset_name = 'imagenet1000_clsid_to_human.txt'\n synset_path = download_testdata(synset_url, synset_name, module='data')\n with open(synset_path) as f:\n synset = eval(f.read())\n # print(synset)\n\n # Port GLuon model to portable computational graph\n batch_size = 1\n num_classes = 1000\n image_shape = (3, 224, 224)\n data_shape = (batch_size,) + image_shape\n\n shape_dict = {'data': x.shape}\n mod, params = relay.frontend.from_mxnet(block, shape_dict)\n # we want a probability so add a softmax operator\n func = mod[\"main\"]\n func = relay.Function(func.params, relay.nn.softmax(func.body), None, func.type_params, func.attrs)\n\n # compile the graph to run on RaspPi modelB\n local_demo = False\n\n if local_demo:\n target = tvm.target.create('llvm')\n else:\n target = tvm.target.arm_cpu('rasp3b')\n\n with relay.build_config(opt_level=3):\n graph, lib, params = relay.build(func, target, params=params)\n\n # Save the library at local temporary directory.\n tmp = util.tempdir()\n lib_fname = tmp.relpath('net.tar')\n lib.export_library(lib_fname)\n\n # RPC server is running on the Rasp Pi.\n # Get the IP address of the Rasp Pi and connect to the machine to run the net compiled here with Relay.\n\n # obtain an RPC session from remote device.\n if local_demo:\n remote = rpc.LocalSession()\n else:\n # The following is my environment, change this to the IP address of your target device\n host = '192.168.0.10'\n port = 9090\n remote = rpc.connect(host, port)\n\n # upload the library to remote device and load it\n remote.upload(lib_fname)\n rlib = remote.load_module('net.tar')\n\n # create the remote runtime module\n ctx = remote.cpu(0)\n module = runtime.create(graph, rlib, ctx)\n # set parameter (upload params to the remote device. This may take a while)\n module.set_input(**params)\n # set input data\n module.set_input('data', tvm.nd.array(x.astype('float32')))\n # run\n module.run()\n # get output\n out = module.get_output(0)\n # get top1 result\n top1 = np.argmax(out.asnumpy())\n print('TVM prediction top-1: {}'.format(synset[top1]))\n # ran on Raspberry Pi, messages in terminal on Raspberry PI:\n # INFO:RPCServer: connection from (machost, port)\n # INFO:RPCServer: load_module /tmp/tmp5sdcfiaw/net.tar\n # INFO: RPCServer:Finish serving (machost, port)\n\nif __name__ == \"__main__\":\n main()","sub_path":"tvm_mxnet_resnet.py","file_name":"tvm_mxnet_resnet.py","file_ext":"py","file_size_in_byte":3907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"617647088","text":"import datetime\nimport json\nimport os\nimport subprocess\nimport tempfile\nimport time\nimport boto3\nimport sys\nimport re\nimport shlex\n\nCONCAT_SNS_TOPIC_ARN = os.environ['CONCAT_SNS_TOPIC_ARN']\nREFERENCE_GENOME = os.environ['REFERENCE_GENOME']\nSVEP_REGIONS = os.environ['SVEP_REGIONS']\nos.environ['PATH'] += ':' + os.environ['LAMBDA_TASK_ROOT']\nsns = boto3.client('sns')\n\n\ndef queryUpdownstream(chrom, pos, alt, transcripts):\n up = int(pos)-5000\n down = int(pos)+5000\n results = []\n loc = str(chrom)+\":\"+str(up)+\"-\"+str(down)\n #print(loc)\n #print(\"position is \", pos)\n args = [\n 'tabix',\n REFERENCE_GENOME,loc]\n query_process = subprocess.Popen(args, stdout=subprocess.PIPE,stderr=subprocess.PIPE, cwd='/tmp',encoding='ascii')\n mainData = query_process.stdout.read().rstrip('\\n').split('\\n')\n line=\"\"\n for data in mainData:\n #print(data)\n if(re.search('transcript_id\\s\\\\\\\"(\\w+)\\\\\\\"\\;', data, re.IGNORECASE).group(1) in transcripts):\n continue\n metadata = data.split('\\t')\n info = dict(shlex.split(item) for item in metadata[8].split(\"; \"))\n #print(info)\n if(metadata[6] == \"+\" and pos < metadata[3] and pos < metadata[4]):\n if('transcript_support_level' in info):\n line= \"24\"+\"\\t\"+\".\"+\"\\t\"+chrom+\":\"+str(pos)+\"-\"+str(pos)+\"\\t\"+alt+\"\\t\"+\"upstream_gene_variant\"+\"\\t\"+info[\"gene_name\"].strip('\"')+\"\\t\"+info[\"gene_id\"].strip('\"')+\"\\t\"+metadata[2]+\"\\t\"+info[\"transcript_id\"].strip('\"')+\".\"+info[\"transcript_version\"].strip('\"')+\"\\t\"+info[\"transcript_biotype\"].strip('\"')+\"\\t\"+'-'+\"\\t\"+\"-\"+\"\\t\"+\"-\"+\"\\t\"+metadata[6]+\"\\t\"+info[\"transcript_support_level\"].rstrip(';').strip('\"')\n else:\n line= \"24\"+\"\\t\"+\".\"+\"\\t\"+chrom+\":\"+str(pos)+\"-\"+str(pos)+\"\\t\"+alt+\"\\t\"+\"upstream_gene_variant\"+\"\\t\"+info[\"gene_name\"].strip('\"')+\"\\t\"+info[\"gene_id\"].strip('\"')+\"\\t\"+metadata[2]+\"\\t\"+info[\"transcript_id\"].strip('\"')+\".\"+info[\"transcript_version\"].strip('\"')+\"\\t\"+info[\"transcript_biotype\"].rstrip(';').strip('\"')+\"\\t\"+'-'+\"\\t\"+\"-\"+\"\\t\"+\"-\"+\"\\t\"+metadata[6]\n elif(metadata[6] == \"+\" and pos > metadata[3] and pos > metadata[4]):\n if('transcript_support_level' in info):\n line= \"24\"+\"\\t\"+\".\"+\"\\t\"+chrom+\":\"+str(pos)+\"-\"+str(pos)+\"\\t\"+alt+\"\\t\"+\"downstream_gene_variant\"+\"\\t\"+info[\"gene_name\"].strip('\"')+\"\\t\"+info[\"gene_id\"].strip('\"')+\"\\t\"+metadata[2]+\"\\t\"+info[\"transcript_id\"].strip('\"')+\".\"+info[\"transcript_version\"].strip('\"')+\"\\t\"+info[\"transcript_biotype\"].strip('\"')+\"\\t\"+'-'+\"\\t\"+\"-\"+\"\\t\"+\"-\"+\"\\t\"+metadata[6]+\"\\t\"+info[\"transcript_support_level\"].rstrip(';').strip('\"')\n else:\n line= \"24\"+\"\\t\"+\".\"+\"\\t\"+chrom+\":\"+str(pos)+\"-\"+str(pos)+\"\\t\"+alt+\"\\t\"+\"downstream_gene_variant\"+\"\\t\"+info[\"gene_name\"].strip('\"')+\"\\t\"+info[\"gene_id\"].strip('\"')+\"\\t\"+metadata[2]+\"\\t\"+info[\"transcript_id\"].strip('\"')+\".\"+info[\"transcript_version\"].strip('\"')+\"\\t\"+info[\"transcript_biotype\"].rstrip(';').strip('\"')+\"\\t\"+'-'+\"\\t\"+\"-\"+\"\\t\"+\"-\"+\"\\t\"+metadata[6]\n elif(metadata[6] == \"-\" and pos < metadata[3] and pos < metadata[4]):\n if('transcript_support_level' in info):\n line= \"24\"+\"\\t\"+\".\"+\"\\t\"+chrom+\":\"+str(pos)+\"-\"+str(pos)+\"\\t\"+alt+\"\\t\"+\"downstream_gene_variant\"+\"\\t\"+info[\"gene_name\"].strip('\"')+\"\\t\"+info[\"gene_id\"].strip('\"')+\"\\t\"+metadata[2]+\"\\t\"+info[\"transcript_id\"].strip('\"')+\".\"+info[\"transcript_version\"].strip('\"')+\"\\t\"+info[\"transcript_biotype\"].strip('\"')+\"\\t\"+'-'+\"\\t\"+\"-\"+\"\\t\"+\"-\"+\"\\t\"+metadata[6]+\"\\t\"+info[\"transcript_support_level\"].rstrip(';').strip('\"')\n else:\n line= \"24\"+\"\\t\"+\".\"+\"\\t\"+chrom+\":\"+str(pos)+\"-\"+str(pos)+\"\\t\"+alt+\"\\t\"+\"downstream_gene_variant\"+\"\\t\"+info[\"gene_name\"].strip('\"')+\"\\t\"+info[\"gene_id\"].strip('\"')+\"\\t\"+metadata[2]+\"\\t\"+info[\"transcript_id\"].strip('\"')+\".\"+info[\"transcript_version\"].strip('\"')+\"\\t\"+info[\"transcript_biotype\"].rstrip(';').strip('\"')+\"\\t\"+'-'+\"\\t\"+\"-\"+\"\\t\"+\"-\"+\"\\t\"+metadata[6]\n elif(metadata[6] == \"-\" and pos > metadata[3] and pos > metadata[4]):\n if('transcript_support_level' in info):\n line= \"24\"+\"\\t\"+\".\"+\"\\t\"+chrom+\":\"+str(pos)+\"-\"+str(pos)+\"\\t\"+alt+\"\\t\"+\"upstream_gene_variant\"+\"\\t\"+info[\"gene_name\"].strip('\"')+\"\\t\"+info[\"gene_id\"].strip('\"')+\"\\t\"+metadata[2]+\"\\t\"+info[\"transcript_id\"].strip('\"')+\".\"+info[\"transcript_version\"].strip('\"')+\"\\t\"+info[\"transcript_biotype\"].strip('\"')+\"\\t\"+'-'+\"\\t\"+\"-\"+\"\\t\"+\"-\"+\"\\t\"+metadata[6]+\"\\t\"+info[\"transcript_support_level\"].rstrip(';').strip('\"')\n else:\n line= \"24\"+\"\\t\"+\".\"+\"\\t\"+chrom+\":\"+str(pos)+\"-\"+str(pos)+\"\\t\"+alt+\"\\t\"+\"upstream_gene_variant\"+\"\\t\"+info[\"gene_name\"].strip('\"')+\"\\t\"+info[\"gene_id\"].strip('\"')+\"\\t\"+metadata[2]+\"\\t\"+info[\"transcript_id\"].strip('\"')+\".\"+info[\"transcript_version\"].strip('\"')+\"\\t\"+info[\"transcript_biotype\"].rstrip(';').strip('\"')+\"\\t\"+'-'+\"\\t\"+\"-\"+\"\\t\"+\"-\"+\"\\t\"+metadata[6]\n else:\n line= \"Couldn't classify - need to check -\" + info[\"transcript_id\"].strip('\"')\n\n results.append(line)\n #print(results)\n return(\"\\n\".join(results))\n\n\n\n\ndef lambda_handler(event, context):\n print('Event Received: {}'.format(json.dumps(event)))\n ################test#################\n #message = json.loads(event['Message'])\n #id = \"ksndfkjsndkfnsf\"\n #######################################\n message = json.loads(event['Records'][0]['Sns']['Message'])\n snsData = message['snsData']\n APIid = message['APIid']\n batchID = message['batchID']\n lastBatchID = message['lastBatchID']\n writeData = []\n for row in snsData:\n chrom = row['chrom']\n pos = row['pos']\n data = row['data']\n alt = row['alt']\n transcripts = []\n results = []\n for dat in data:\n if(len(dat) == 0):\n writeData.append(\"-\"+\"\\t\"+\".\"+\"\\t\"+chrom+\":\"+str(pos)+\"-\"+str(pos)+\"\\t\"+alt+\"\\t\"+\"intergenic_gene_variant\")\n transcripts = []\n continue\n transcripts.append(re.search('transcript_id\\s\\\\\\\"(\\w+)\\\\\\\"\\;', dat, re.IGNORECASE).group(1))\n if(len(transcripts) != 0):\n results = queryUpdownstream(chrom,pos,alt,list(set(transcripts)))\n if (len(results) != 0):\n writeData.append(results)\n filename = \"/tmp/\"+ APIid+\"_upstream.tsv\"\n print(batchID)\n with open(filename, 'w') as tsvfile:\n tsvfile.write(\"\\n\".join(writeData))\n s3 = boto3.resource('s3')\n s3.Bucket(SVEP_REGIONS).upload_file(filename, APIid+\"_\"+batchID+\"_updownstream.tsv\")\n print(\"uploaded\")\n if(lastBatchID == 1):\n print(\"sending for concat\")\n kwargs = {\n 'TopicArn': CONCAT_SNS_TOPIC_ARN,\n }\n kwargs['Message'] = json.dumps({'APIid' : APIid,'lastBatchID' : batchID})\n print('Publishing to SNS: {}'.format(json.dumps(kwargs)))\n response = sns.publish(**kwargs)\n print('Received Response: {}'.format(json.dumps(response)))\n","sub_path":"lambda/pluginUpdownstream/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":7145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"453064623","text":"#made by mohammed\r\namount = int(input())\r\nplayer1 = 100\r\nplayer2 = 100\r\n\r\nfor i in range(amount):\r\n roll = input()\r\n roll1 = roll.split()\r\n roll1 = [int(i) for i in roll1] \r\n if roll1[0] > roll1[1]:\r\n player1 = player1 - roll1[0]\r\n if roll1[0] < roll1[1]:\r\n player2 = player2 - roll1[1]\r\n\r\nprint(player2)\r\nprint(player1)\r\n","sub_path":"2014-j3.py","file_name":"2014-j3.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"101473444","text":"import requests\nimport os\nimport sys\nimport base64\nimport json\nimport time\nimport threading\nimport subprocess\nimport random\nimport math\nimport re\nimport signal\nimport string\n\nclass ExoSolution(object):\n\n def __init__(self):\n try:\n self.EMAIL = \"testing@exosite.com\"\n self.PASSWORD = \"1234eszxcv++\"\n self.SOLUTION_HOST = \"apps.exosite-staging.io\"\n self.HOST = \"https://{}/api:1\".format(\n \"bizapi-staging.hosted.exosite.io\")\n except:\n print('import BuiltIn failed')\n\n self.SESSION = requests.Session()\n self.TOKEN = None\n\n def __request(self, method, append='', **kwargs):\n resp = self.SESSION.request(method, self.HOST + append, **kwargs)\n if resp.text == \"\":\n return resp.status_code\n else:\n try:\n return resp.json()\n except ValueError as e:\n return resp.text\n\n def __headers(self, token=None):\n if self.TOKEN is None:\n if token is None:\n self.TOKEN = self.get_user_token()\n else:\n self.TOKEN = token\n self.SESSION.headers.update({\n \"content-type\": \"application/json\",\n 'accept': 'application/json',\n 'authorization': 'token %s' % self.TOKEN\n })\n\n def __businessId(self, businessId):\n if businessId is None:\n businessId = self.BuiltIn.run_keyword(\n 'ExoYeti.get_business_id', self.TOKEN)\n return businessId\n\n def get_user_token(self, email=None, password=None):\n if email is None:\n email = self.EMAIL\n if password is None:\n password = self.PASSWORD\n\n data = {\"email\": \"%s\" % email, \"password\": \"%s\" % password}\n resp = self.__request('post', \"/token/\", json=data)\n return resp['token']\n\n def create_eventhandler_via_api(self, solutionId, service, event, script=\"\", token=None):\n self.__headers(token)\n data = {\"solution_id\": solutionId, \"service\": service,\n \"event\": event, \"script\": script}\n resp = self.__request(\n 'post', \"/solution/%s/eventhandler\" % solutionId, json=data)\n time.sleep(1)\n if \"errors\" in resp:\n raise AssertionError(resp[\"errors\"])\n return resp\n\n # Comment For Create Module Via API\n # If the user is different with setting.py\n # Please input Authorization Token\n def create_module_via_api(self, solutionId, moduleName, script=\"\", token=None):\n self.__headers(token)\n data = {\"name\": \"%s\" % moduleName, \"solution_id\": \"%s\" %\n solutionId, \"script\": \"%s\" % script}\n resp = self.__request('post', \"/solution/%s/library\" %\n solutionId, json=data)\n if 'id' not in resp:\n raise AssertionError(\n \"Module '%s' did not be created --> %s\" % (moduleName, resp))\n return resp['id']\n\n # Comment For Create Role Via API\n # If the user is different with setting.py\n # Please input Authorization Token\n def create_role_via_api(self, solutionId, roleId, parameter=None, token=None):\n self.__headers(token)\n data = {\"role_id\": roleId}\n if parameter is not None:\n data.update({\"parameter\": parameter})\n resp = self.__request('post', \"/solution/%s/role\" %\n solutionId, json=data)\n if resp is 400:\n raise AssertionError(\n \"Role '%s' did not be created --> %s\" % (roleId, resp))\n return resp\n\n # Comment For Create User Via API\n # If the user is different with setting.py\n # Please input Authorization Token\n def create_user_via_api(self, solutionId, userName, userEmail, userPassword, token=None):\n self.__headers(token)\n data = {\"name\": userName, \"email\": userEmail, \"password\": userPassword}\n resp = self.__request('post', \"/solution/%s/user\" %\n solutionId, json=data)\n return resp\n\n # Comment For Create User And Activate Via API\n # If the user is different with setting.py\n # Please input Authorization Token\n def create_activation_user_via_api(self, solutionId, userName, userEmail, userPassword, token=None):\n self.__headers(token)\n verifycode = self.create_user_via_api(\n solutionId, userName, userEmail, userPassword, token)\n resp = self.__request(\n 'get', '/solution/%s/user/verify?code=%s' % (solutionId, verifycode))\n if resp != 'OK':\n raise AssertionError(\n \"User '%s' did not be activated --> %s\" % (userName, resp))\n return resp\n\n def delete_eventhandler_via_api(self, solutionId, service, event, token=None):\n self.__headers(token)\n eventhandlerId = self.get_eventhandler_id_via_api(\n solutionId, service, event, token)\n resp = self.__request(\n 'delete', \"/solution/%s/eventhandler/%s\" % (solutionId, eventhandlerId))\n return resp\n\n # Comment For Delete Module Via API\n # If the user is different with setting.py\n # Please input Authorization Token\n def delete_module_via_api(self, solutionId, moduleName, token=None):\n self.__headers(token)\n moduleId = self.get_module_id(solutionId, moduleName)\n resp = self.__request(\n 'delete', \"/solution/%s/library/%s\" % (solutionId, moduleId))\n if resp != 204:\n raise AssertionError(\n \"Endpoint '%s' did not be deleted --> %s\" % (solutionName, resp))\n return resp\n\n # Comment For Delete Role Via API\n # If the user is different with setting.py\n # Please input Authorization Token\n def delete_role_via_api(self, solutionId, roleId, token=None):\n self.__headers(token)\n resp = self.__request(\n 'delete', \"/solution/%s/role/%s\" % (solutionId, roleId))\n if resp != 204:\n raise AssertionError(\n \"Role '%s' did not be deleted --> %s \" % (roleId, resp))\n return resp\n\n # Comment For Delete Roles By List Via API\n # If the user is different with setting.py\n # Please input Authorization Token\n def delete_roles_by_list_via_api(self, solutionId, token=None):\n roles = self.get_role_lists(solutionId, token)\n if not roles:\n return\n roleIds = map(lambda x: x['role_id'], roles)\n for roleId in roleIds:\n self.delete_role_via_api(solutionId, roleId)\n return\n\n def delete_service_scriptkey_via_api(self, solutionId, alias, token=None):\n \"\"\" Delete service scriptkey \"\"\"\n self.__headers(token)\n resp = self.__request(\n 'delete', \"/solution/%s/serviceconfig/%s\" % (solutionId, alias))\n if resp != 204:\n raise AssertionError(\n \"Service '%s' did not be deleted --> %s \" % (solutionId, resp))\n return resp\n\n # Comment For Delete Solution Via API\n # If the user is different with setting.py\n # Please input Business ID and Authorization Token\n def delete_solution_via_api(self, solutionName, token=None, businessId=None):\n self.__headers(token)\n businessId = self.__businessId(businessId)\n solutionSid = self.get_solution_sid(solutionName, token, businessId)\n resp = self.__request(\n 'delete', \"/business/%s/solution/%s\" % (businessId, solutionSid))\n if resp != 204:\n raise AssertionError(\n \"Solution '%s' did not be deleted --> %s\" % (solutionName, resp))\n return resp\n\n # Comment For Delete User Via API\n # If the user is different with setting.py\n # Please input Authorization Token\n def delete_user_via_api(self, solutionId, userId, token=None):\n self.__headers(token)\n resp = self.__request(\n 'delete', \"/solution/%s/user/%s\" % (solutionId, userId))\n if resp != 204:\n raise AssertionError(\n \"User '%s' did not be deleted --> %s \" % (userId, resp))\n return resp\n\n # Comment For Delete Users By List Via API\n # If the user is different with setting.py\n # Please input Authorization Token\n def delete_users_by_list_via_api(self, solutionId, token=None):\n users = self.get_user_lists(solutionId, token)\n if not users:\n return\n userIds = map(lambda x: x['id'], users)\n for userId in userIds:\n self.delete_user_via_api(solutionId, userId)\n return\n\n def get_user_list_via_api(self, solutionId, token=None):\n \"\"\" get user list from specific solution.\n\n Args:\n solutionId (str): Solution id.\n token (str): Authorization token.\n\n Returns:\n list: The user list.\n \"\"\"\n self.__headers(token)\n return self.__request('get', \"/solution/%s/user/\" % (solutionId))\n\n def update_user_via_api(self, solutionId, userId, userName, userPassword, originalPassword, token=None):\n \"\"\" Update specific user with given data.\n\n Args:\n solutionId (str): Solution id.\n userId (int): User id.\n userName (str): What user name you want to update.\n userPassword (str): What password you want to update.\n originalPassword (str): The password of user.\n token (str): Authorization token.\n\n Returns:\n bool: The response of update user.\n \"\"\"\n self.__headers(token)\n payload = {\"name\": userName, \"password\": userPassword,\n \"original_password\": originalPassword}\n path = \"/solution/%s/user/%s\" % (solutionId, userId)\n\n return self.__request('put', path, json=payload)\n\n def subscribe_product_service(self, solutionId, productId, serviceKey, token=None):\n \"\"\" Comment For Update Service Product\n If the user is different with setting.py\n Please input Authorization Token\n \"\"\"\n self.__headers(token)\n data = {\n \"solution_id\": solutionId,\n \"service\": productId,\n \"script_key\": serviceKey\n }\n resp = self.__request(\n 'post', \"/solution/%s/serviceconfig/\" % (solutionId), json=data)\n if 'statusCode' in resp:\n raise AssertionError(\"Update failed --> %s\" % resp)\n return resp\n\n def update_eventhandler_via_api(self, solutionId, service, event, script=\"\", token=None):\n self.__headers(token)\n eventhandlerId = self.get_eventhandler_id_via_api(\n solutionId, service, event, token)\n data = {\"script\": script}\n resp = self.__request('put', \"/solution/%s/eventhandler/%s\" %\n (solutionId, eventhandlerId), json=data)\n if resp != 204:\n raise AssertionError(\"Update failed --> %s\" % resp)\n time.sleep(1)\n return resp\n\n # Comment For Update Module\n # If the user is different with setting.py\n # Please input Authorization Token\n def update_module(self, solutionId, moduleId, script, name=None, token=None):\n self.__headers(token)\n if name is None:\n name = self.get_module_name(solutionId, moduleId)\n data = {\"name\": \"%s\" % name, \"script\": \"%s\" % script}\n resp = self.__request('put', \"/solution/%s/library/%s\" %\n (solutionId, moduleId), json=data)\n if resp != 204:\n raise AssertionError(\"Update failed --> %s\" % resp)\n return resp\n\n # Comment For Update Service Product\n # If the user is different with setting.py\n # Please input Authorization Token\n def update_service_product(self, solutionId, script, event=\"datapoint\", service=\"device\", token=None):\n self.__headers(token)\n data = {\"script\": \"%s\" % script, \"event\": \"%s\" %\n event, \"service\": \"%s\" % service}\n resp = self.__request(\n 'put', \"/solution/%s/eventhandler/%s_device_datapoint\" % (solutionId, solutionId), json=data)\n if resp != 204:\n raise AssertionError(\"Update failed --> %s\" % resp)\n return resp\n\n # Comment For Update Service Timer\n # If the user is different with setting.py\n # Please input Authorization Token\n def update_service_timer(self, solutionId, script, event=\"timer\", service=\"timer\", token=None):\n self.__headers(token)\n data = {\"script\": \"%s\" % script, \"event\": \"%s\" %\n event, \"service\": \"%s\" % service}\n resp = self.__request(\n 'put', \"/solution/%s/eventhandler/%s_timer_timer\" % (solutionId, solutionId), json=data)\n if resp != 204:\n raise AssertionError(\"Update failed --> %s\" % resp)\n return resp\n\n # Comment For Update Solution Product Service\n # If the user is different with setting.py\n # Please input Business ID and Authorization Token\n def update_solution_products(self, solutionId, productIds, token=None, businessId=None):\n if isinstance(productIds, list) is not True:\n raise AssertionError(\n \"ProductIds is not a array, it should be an array.\")\n self.__headers(token)\n businessId = self.__businessId(businessId)\n service = self.get_solution_service(solutionId, token)\n item = filter(lambda i: i[\"service\"] == \"device\", service[\"items\"])\n if not item:\n raise AssertionError(\n \"Service is None, please check solution id is correctly.\")\n service = self.__request(\n 'get', \"/solution/%s/serviceconfig/%s\" % (solutionId, item[0][\"id\"]))\n service[\"triggers\"] = {\"pid\": productIds, \"vendor\": productIds}\n service[\"parameters\"][\"pid\"] = productIds\n resp = self.__request('put', \"/solution/%s/serviceconfig/%s\" %\n (solutionId, service[\"id\"]), json=service)\n if resp != 204:\n raise AssertionError(\"Update failed --> %s\" % resp)\n time.sleep(1.5)\n return resp\n\n def get_eventhandler_via_api(self, solutionId, token=None):\n self.__headers(token)\n resp = self.__request('get', \"/solution/%s/eventhandler\" % solutionId)\n try:\n return resp[\"items\"]\n except:\n raise AssertionError(resp)\n\n def get_eventhandler_detail_via_api(self, solutionId, service, event, token=None):\n self.__headers(token)\n eventHandlerId = self.get_eventhandler_id_via_api(\n solutionId, service, event, token)\n resp = self.__request(\n 'get', \"/solution/%s/eventhandler/%s\" % (solutionId, eventHandlerId))\n try:\n return resp\n except:\n raise AssertionError(resp)\n\n def get_eventhandler_id_via_api(self, solutionId, service, event, token=None):\n self.__headers(token)\n resp = self.get_eventhandler_via_api(solutionId, token)\n eventHandlerId = filter(\n lambda i: i[\"service\"] == service and i[\"event\"] == event, resp)\n return eventHandlerId[0]['id']\n\n # Comment For Get Module id\n # If the user is different with setting.py\n # Please input Authorization Token\n def get_module_id(self, solutionId, name, token=None):\n items, _ = self.get_module_list(solutionId, token)\n moduleId = filter(lambda i: i['name'] == '%s' % name, items)\n if not moduleId:\n raise AssertionError(\"Module name :'%s' was not existing\" % (name))\n return moduleId[0]['id']\n\n # Comment For Get Module name\n # If the user is different with setting.py\n # Please input Authorization Token\n def get_module_name(self, solutionId, moduleId, token=None):\n items, _ = self.get_module_list(solutionId, token)\n moduleName = filter(lambda i: i['id'] == '%s' % moduleId, items)\n if not moduleName:\n raise AssertionError(\n \"Module ID :'%s' was not existing\" % (moduleId))\n return moduleName[0]['name']\n\n # Comment For Get Module list\n # If the user is different with setting.py\n # Please input Authorization Token\n def get_module_list(self, solutionId, token=None):\n self.__headers(token)\n resp = self.__request('get', \"/solution/%s/library\" % solutionId)\n return resp['items'], resp['total']\n\n def get_serviceconfig_via_api(self, solutionId, token=None):\n self.__headers(token)\n resp = self.__request('get', \"/solution/%s/serviceconfig\" % solutionId)\n try:\n return resp[\"items\"]\n except:\n raise AssertionError(resp)\n\n def update_serviceconfig_via_api(self, solutionId, serviceconfigID, data, token=None):\n \"\"\"Comment For Update Serviceconfig Via API\n If the user is different with setting.py\n Please input Authorization Token\n \"\"\"\n self.__headers(token)\n resp = self.__request(\n 'put', \"/solution/{}/serviceconfig/{}\".format(solutionId, serviceconfigID), data=data)\n try:\n return resp\n except:\n raise AssertionError(resp)\n\n def get_solution_service_via_api(self, solutionId, serviceconfigID, token=None):\n \"\"\"Comment For Get Solution Service Via API\n If the user is different with setting.py\n Please input Authorization Token\n \"\"\"\n self.__headers(token)\n resp = self.__request(\n 'get', \"/solution/{}/serviceconfig/{}\".format(solutionId, serviceconfigID))\n try:\n return resp\n except:\n raise AssertionError(resp)\n\n # Comment For Update Solution Twilio Service\n # If the user is different with setting.py\n # Please input Business ID and Authorization Token\n def update_solution_twilio(self, solutionId, AuthToken=None, AccountSid=None, token=None):\n self.__headers(token)\n service = self.get_solution_service(solutionId, token)\n item = filter(lambda i: i[\"service\"] == \"twilio\", service[\"items\"])\n if not item:\n raise AssertionError(\n \"Service is None, please check solution id is correctly.\")\n service = self.__request(\n 'get', \"/solution/%s/serviceconfig/%s\" % (solutionId, item[0][\"id\"]))\n\n if AuthToken is not None and AccountSid is not None:\n service[\"parameters\"] = {\"AuthToken\": \"%s\" %\n AuthToken, \"AccountSid\": \"%s\" % AccountSid}\n else:\n service[\"parameters\"] = {}\n\n resp = self.__request('put', \"/solution/%s/serviceconfig/%s\" %\n (solutionId, service[\"id\"]), json=service)\n time.sleep(1)\n return resp\n\n # Comment For Get Role List\n # If the user is different with setting.py\n # Please input and Authorization Token\n def get_role_lists(self, solutionId, token=None):\n self.__headers(token)\n roles = self.__request('get', \"/solution/%s/role\" % solutionId)\n if not roles:\n return False\n return roles\n\n # Comment For Get Solution Info\n # If the user is different with setting.py\n # Please input Business ID and Authorization Token\n def get_solution_info_via_api(self, solutionName, token=None, businessId=None):\n resp = self.get_solutions_list(token, businessId)\n solutionDomain = '{0}.{1}'.format(solutionName, self.SOLUTION_HOST)\n for solution in resp:\n if solution['domain'] == solutionDomain or solution.get('name') == solutionName:\n return solution\n raise AssertionError(\"Solution '%s' was not existing\" % solutionName)\n\n # Comment For Get Solution Sid\n # If the user is different with setting.py\n # Please input Business ID and Authorization Token\n def get_solution_sid(self, solutionName, token=None, businessId=None):\n solution = self.get_solution_info_via_api(\n solutionName, token, businessId)\n return solution['sid']\n\n def get_solution_logs(self, solutionId, token=None):\n self.__headers(token)\n resp = self.__request('get', \"/solution/{0}/logs\".format(solutionId))\n try:\n return resp\n except:\n raise AssertionError(\"Get solution logs fail -> %s\", resp)\n\n # Comment For Get Solution API ID\n # If the user is different with setting.py\n # Please input Business ID and Authorization Token\n def get_solution_id_via_api(self, solutionName, token=None, businessId=None):\n solution = self.get_solution_info_via_api(\n solutionName, token, businessId)\n return solution['apiId']\n\n # Comment For Get Solution Info From Yeti Database\n # If the user is different with setting.py\n # Please input Business ID and Authorization Token\n def get_solution_info_by_id(self, solutionId, token=None, businessId=None):\n self.__headers(token)\n businessId = self.__businessId(businessId)\n resp = self.__request('get', \"/business/%s/solution/%s\" %\n (businessId, solutionId))\n return resp\n\n # Comment For Get Solutions List\n # If the user is different with setting.py\n # Please input Business ID and Authorization Token\n def get_solutions_list(self, token=None, businessId=None):\n self.__headers(token)\n businessId = self.__businessId(businessId)\n return self.__request('get', \"/business/%s/solution/\" % businessId)\n\n # Comment For Get Solution Service Config\n # If the user is different with setting.py\n # Please input Business ID and Authorization Token\n def get_solution_service(self, solutionId, token=None):\n self.__headers(token)\n return self.__request('get', \"/solution/%s/serviceconfig\" % solutionId)\n\n # Comment For Get User ID\n # If the user is different with setting.py\n # Please input and Authorization Token\n def get_user_id(self, solutionId, email, token=None):\n resp = self.get_user_lists(solutionId, token)\n user = filter(lambda i: i['email'] == email, resp)\n if not user:\n raise AssertionError(\"User '%s' was not existing\" % email)\n return user[0]['id']\n\n # Comment For Get User List\n # If the user is different with setting.py\n # Please input and Authorization Token\n def get_user_lists(self, solutionId, token=None):\n self.__headers(token)\n resp = self.__request('get', \"/solution/%s/user\" % solutionId)\n return resp\n\n def verify_solution_tsdb_status(self, solutionId, token=None):\n \"\"\"Verify Create Solutions status, tsdb status should be ready.\n If will drop error when the status is not ready, and remind user solution not be created yet.\n - It will return message from pegasus host.\n \"\"\"\n self.__headers(token)\n resp = self.__request(\n 'get', \"/solution/%s/serviceconfig/%s_tsdb\" % (solutionId, solutionId))\n if 'ready' not in resp['status']:\n raise AssertionError(\n \"Solution '%s' tsdb did not be created successfully\" % solutionId)\n return resp['status']\n","sub_path":"service/user/ExoSolution.py","file_name":"ExoSolution.py","file_ext":"py","file_size_in_byte":23335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"105893292","text":"dicts = {\n \"hc\" : \"Học, học hỏi, học tập\",\n \"ng\" : \"Người\",\n \"pt\" : \"Phát triển, Phú Thọ\",\n \"eny\": \"Em người yêu\",\n \"any\": \"Anh người yêu\",\n \"ns\" : \"Nói, nói chuyện\",\n \"ngta\": \"Người ta\",\n \"lm\" : \"Làm, lắm\",\n \"rk\" : \"Rồi\",\n \"stt\" : \"status\" \n}\nloop = True\nwhile loop:\n for key in dicts.keys():\n print(key, end = \"\\t\")\n print()\n\n input_dict = input(\" ===> Your code ? \")\n if input_dict in dicts:\n print(\"* \"*20)\n print(\"Code: \", input_dict)\n print(\"Translation: \", dicts[input_dict])\n print(\"* \"*20)\n else:\n print(\"No found! \")\n choose = input(\" Do you want to contribute this word (Y/N): \").lower()\n if choose == \"y\":\n # new_key = input(\" Bạn nhập key ? \")\n new_value = input(\" Your translation: \")\n dicts[input_dict] = new_value\n print(\"Updated\") \n if choose == \"N\" or choose == \"n\":\n print(\"Tạm Biệt !! \")\n loop = False\n ","sub_path":"Session05/teencode.py","file_name":"teencode.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"3478304","text":"from rest_framework import serializers\n\n\n#Models Import\nfrom Base.models import *\nfrom Calendar.models import *\n\n#--------------- Serialiazers ------------------------------------------ \n#--------------- Schedule\nclass ScheduleSerializer(serializers.ModelSerializer):\n url = serializers.HyperlinkedIdentityField(view_name = 'schedule_detail_api')\n Schedule_Detail = serializers.StringRelatedField(many = True, read_only = True)\n class Meta:\n model = CatSchedule\n fields = [\n 'url',\n 'IdSchedule',\n 'Date',\n 'IdScheduleDetail',\n 'create',\n 'update',\n 'Schedule_Detail'\n ]\n\n#--------------- ScheduleDetail\nclass ScheduleDetailSerializer(serializers.ModelSerializer):\n url = serializers.HyperlinkedIdentityField(view_name = 'scheduledetail_detail_api') \n class Meta:\n model = CatScheduleDetail\n fields = [\n 'url',\n 'IdScheduleDetail',\n 'IdSchedule',\n 'IdLanguage',\n 'Name',\n 'About',\n 'create',\n 'update'\n ]\n\n#--------------- ScheduleParent\nclass ScheduleParentSerializer(serializers.ModelSerializer):\n url = serializers.HyperlinkedIdentityField(view_name = 'scheduleparent_detail_api')\n ScheduleParent_Detail = serializers.StringRelatedField(many = True, read_only = True)\n class Meta:\n model = CatScheduleParent\n fields = [\n 'url',\n 'IdScheduleParent',\n 'IdSchedule',\n 'BeginHour',\n 'EndHour',\n 'create',\n 'update',\n 'ScheduleParent_Detail'\n ]\n\n#--------------- ScheduleParentDetail\nclass ScheduleParentDetailSerializer(serializers.ModelSerializer):\n url = serializers.HyperlinkedIdentityField(view_name = 'scheduleparentdetail_detail_api')\n class Meta:\n model = CatScheduleParentDetail\n fields = [\n 'url',\n 'IdScheduleParentDetail',\n 'IdScheduleParent',\n 'IdLanguange',\n 'Location',\n 'Name',\n 'Description',\n 'create',\n 'update'\n ]\n\n#--------------- ScheduleManage\nclass ScheduleManageSerializer(serializers.ModelSerializer):\n url = serializers.HyperlinkedIdentityField(view_name = 'schedulemanage_detail_api')\n class Meta:\n model = TblScheduleManage\n fields = [\n 'url',\n 'IdScheduleManage',\n 'IdSchedule',\n 'IdBasicData',\n 'Role',\n 'Name',\n 'Surname',\n 'create',\n 'update'\n ]\n\n#--------------- HousingSchedule\nclass HousingScheduleSerializer(serializers.ModelSerializer):\n url = serializers.HyperlinkedIdentityField(view_name = 'housingschedule_detail_api')\n class Meta:\n model = TblHousingSchedule\n fields = [\n 'url',\n 'IdHousingSchedule',\n 'IdScheduleParent',\n 'IdHousing_Service',\n 'IdHousingRoom',\n 'create',\n 'update'\n ]\n\n#--------------- InstitutionSchedule\nclass InstitutionScheduleSerializer(serializers.ModelSerializer):\n url = serializers.HyperlinkedIdentityField(view_name = 'institutionschedule_detail_api')\n class Meta:\n model = TblInstitutionSchedule\n fields = [\n 'url',\n 'IdInstitutionSchedule',\n 'IdScheduleParent',\n 'IdInstitution',\n 'create',\n 'update'\n ]\n\n#--------------- EntertainmentSchedule\nclass EntertainmentScheduleSerializer(serializers.ModelSerializer):\n url = serializers.HyperlinkedIdentityField(view_name = 'entertainmentschedule_detail_api')\n class Meta:\n model = TblEntertainmentSchedule\n fields = [\n 'url',\n 'IdEntertainmentSchedule',\n 'IdScheduleParent',\n 'IdSpaceArea',\n 'create',\n 'update'\n ]\n\n#--------------- FADSchedule\nclass FADScheduleSerializer(serializers.ModelSerializer):\n url = serializers.HyperlinkedIdentityField(view_name = 'fadschedule_detail_api')\n class Meta:\n model = TblFADSchedule\n fields = [\n 'url',\n 'IdFADSchedule',\n 'IdScheduleParent',\n 'IdFADZone',\n 'create',\n 'update'\n ]\n\n#--------------- StoreSchedule\nclass StoreScheduleSerializer(serializers.ModelSerializer):\n url = serializers.HyperlinkedIdentityField(view_name = 'storeschedule_detail_api')\n class Meta:\n model = TblStoreSchedule\n fields = [\n 'url',\n 'IdStoreSchedule',\n 'IdScheduleParent',\n 'IdStore',\n 'create',\n 'update'\n ]\n\n\n\n","sub_path":"Calendar/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":4899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"408963318","text":"import csv\nimport os\nimport sys\nimport re\n\ndef read_file(file_name):\n with open(file_name, 'rb') as csvfile:\n reader = csv.DictReader(csvfile)\n sum = 0\n line = 0\n lines_used = 0\n name = ''\n key_re = re.search('-(\\d+)range', file_name)\n key_range = key_re.group(1)\n for row in reader:\n name = row['name']\n if line >= 5:\n sum += (int)(row['throughput'])\n lines_used += 1\n line += 1\n average = sum/lines_used\n return [name, key_range, average]\n\n\ndef parse_dir(output_file, dir):\n results = {}\n for filename in os.listdir(dir):\n if filename.endswith(\".csv\") and not filename == 'results.csv':\n [name, key_range, avg] = read_file(dir+ '/' + str(filename))\n if key_range not in results:\n results[key_range] = dict()\n results[key_range][name] = avg\n with open(output_file, 'w') as csvfile:\n fieldnames = ['range', 'BLTree', 'BST', 'AVL', 'Snap', 'SkipList', 'SyncTMAP']\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n writer.writeheader()\n for name in results:\n results[name]['range'] = name\n writer.writerow(results[name])\n\n\nparse_dir(sys.argv[1] + '/results.csv', sys.argv[1])\n","sub_path":"results/new_ver/range_csv_parser.py","file_name":"range_csv_parser.py","file_ext":"py","file_size_in_byte":1332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"23545591","text":"from time import sleep\r\nimport random\r\n\r\nsexualities = ['Gay', 'Lésbica', 'Panssexual', 'Bissexual', 'Hetero', 'Demisseuxal', 'Assexual']\r\ngender_identy = ['Homem cis', 'Mulher cis', 'Não-Binário', 'Homem transsexual', 'Homem trans', 'Mulher transsexual', 'Mulher trans', 'Genero fluido']\r\npronouns = ['Ele/Dele', 'Ela/Dela', 'Elu/Delu', 'Elx/Delx']\r\n\r\nwhile True:\r\n opt = int(input('Quer continuar? 0 - N, 1 - S'\r\n '\\n>>> '))\r\n if opt == 0:\r\n break\r\n elif opt == 1:\r\n pass\r\n else:\r\n opt = 1\r\n age = random.randint(12, 30)\r\n sleep(0.5)\r\n biol1 = f\"{age}y\"\r\n biol2 = sexualities[random.randint(0, 6)]\r\n biol3 = gender_identy[random.randint(0, 7)]\r\n if biol2 == 'Lésbica':\r\n gid = random.randint(0, 3)\r\n if gid == 1:\r\n biol3 = 'Mulher trans'\r\n elif gid == 0:\r\n biol3 = 'Mulher cis'\r\n elif gid == 2:\r\n biol3 = 'Não-Binário'\r\n elif gid == 3:\r\n biol3 = 'Genêro fluido'\r\n elif biol2 == 'Gay':\r\n gid = random.randint(0, 3)\r\n if gid == 0:\r\n biol3 = 'Homem cis'\r\n elif gid == 1:\r\n biol3 = 'Homem trans'\r\n elif gid == 2:\r\n biol3 = 'Não-Binário'\r\n elif gid == 3:\r\n biol3 = 'Genêro fluido'\r\n biol4 = pronouns[random.randint(0, 3)]\r\n if biol3 == 'Homem cis':\r\n biol4 = 'Ele/Dele'\r\n elif biol3 == 'Mulher cis':\r\n biol4 = 'Ela/Dela'\r\n for l in range(0, 2):\r\n biography = open('bio.txt', 'w+')\r\n write_bio = biography.write(f\"\"\"\r\n{biol1}\r\n{biol2}\r\n{biol3}\r\n{biol4}\r\n\"\"\")\r\n print('Saved at bio.txt')\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"367489275","text":"# -*- coding: utf-8 -*-\n\n##\n#@author Victor Cominotti\n#@brief publish in a queue\n\nimport pika\nimport os\nfrom S4_queues_tools import *\n\n#how many messages publish\nn_message = 1000\n\n## publish data with amqp protocol\n#@param args : arguments wanted, see S4_queues_tools for the list\n#@param value : value of arguments, see S4_queues_tools for the list\ndef publish_data(args, value) :\n \n queue_name = set_queueName(args, value)\n user_name = raw_input(\"please enter your name : \")\n \n url = settings[\"url\"]\n params = pika.URLParameters(url)\n params.socket_timeout = 5\n\n basic_properties = pika.BasicProperties(delivery_mode = 1)\n if args & arg_concurrency:\n basic_properties.delivery_mode = 2\n\n connection = pika.BlockingConnection(params)\n channel = connection.channel()\n channel.queue_declare(queue=queue_name)\n\n for i in range(n_message) :\n \n channel.basic_publish(exchange=\"\",\n routing_key=queue_name,\n body=user_name,\n properties=basic_properties)\n\n print(\"[X] Sent '{0}' to the queue '{1}'\".format(user_name, queue_name))\n \n connection.close()\n\n\nif __name__ == \"__main__\" :\n args, value = check_argument()\n\n publish_data(args, value)\n","sub_path":"assignments/Session4/simple_queue_publish.py","file_name":"simple_queue_publish.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"529652314","text":"\"\"\"Helpers for testing models.\"\"\"\n\nfrom models import project\nfrom models import user\n\n\ndef create_project(\n title='title', description='description', lead='lead',\n tech_objectives='tech_objectives',\n github='github', tags='', owner_key=None):\n \"\"\"Returns a new datastore-backed project.\"\"\"\n if owner_key is None:\n # The current user is the project owner.\n owner_key = user.get_current_user_key()\n # If the user is not logged in, an arbitrary user is the owner.\n if owner_key is None:\n owner_key = user.User(email='arbitrary@codethechange.org').put()\n # pylint: disable=W0212\n tag_keys = project._create_tags(tags)\n new_project = project.Project(\n title=title, description=description, lead=lead,\n tech_objectives=tech_objectives, github=github,\n owner_key=owner_key, tag_keys=tag_keys)\n new_project.put()\n return new_project\n","sub_path":"testing/model_helpers.py","file_name":"model_helpers.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"435152800","text":"from enum import auto, Enum\n\nfrom pysketcher._arrow import DoubleArrow\nfrom pysketcher._arrow_with_text import Text\nfrom pysketcher._point import Point\nfrom pysketcher.composition import ShapeWithText\n\n\nclass DistanceWithText(ShapeWithText):\n \"\"\"Arrow <-> with text (usually a symbol) at the midpoint.\n\n Used for identifying a some distance in a figure. The text is placed\n slightly to the right of vertical-like arrows, with text displaced\n `text_spacing` times to total distance in x direction of the plot\n area. The text is by default aligned 'left' in this case. For\n horizontal-like arrows, the text is placed the same distance\n above, but aligned 'center' by default (when `alignment` is None).\n\n Args:\n text: The text which will be displayed.\n start: The start of the arrow.\n end: The end of the arrow.\n spacing: The spacing of the text from the arrow position.\n text_position: The position of the text.\n\n Raises:\n ValueError: when invalid `text_position` is passed.\n\n Examples:\n >>> distance_with_text = ps.DistanceWithText(\n ... \"$a$\", ps.Point(1.0, 1.0), ps.Point(3.0, 1.0)\n ... )\n >>> fig = ps.Figure(0.0, 4.0, 0.0, 2.0, backend=MatplotlibBackend)\n >>> fig.add(distance_with_text)\n >>> fig.save(\"pysketcher/images/distance_with_text.png\")\n\n .. figure:: images/distance_with_text.png\n :alt: An example of DistanceWithText.\n :figclass: align-center\n\n An example of ``DistanceWithText``.\n \"\"\"\n\n class TextPosition(Enum):\n \"\"\"Used to show that text should be at the start, end, or middle of an arrow.\"\"\"\n\n START = auto()\n MIDDLE = auto()\n END = auto()\n\n def swap(self) -> \"DistanceWithText.TextPosition\":\n \"\"\"Swaps the relative position of text.\"\"\"\n swap_dict = {\n self.START: self.END,\n self.END: self.START,\n self.MIDDLE: self.MIDDLE,\n }\n return swap_dict[self]\n\n def __init__(\n self,\n text: str,\n start: Point,\n end: Point,\n spacing: float = 1 / 6.0,\n text_position: TextPosition = TextPosition.MIDDLE,\n ):\n self._start = start\n self._end = end\n\n # Decide first if we have a vertical or horizontal arrow\n vertical = abs(end.x - start.x) < 2 * abs(end.y - start.y)\n\n if vertical:\n # Force end above start\n if end.y < start.y:\n start, end = end, start\n text_position = text_position.swap()\n else: # horizontal arrow\n # Force start to the right of end\n if start.x < end.x:\n start, end = end, start\n text_position = text_position.swap()\n\n normal = (end - start).normal()\n\n if text_position == self.TextPosition.MIDDLE:\n # if the text is in the middle of the line, then place it\n # at a point spacing away normal to the midpoint\n mid = (start + end) * 0.5 # midpoint of start-end line\n text_point = mid - normal * spacing\n elif text_position == self.TextPosition.START:\n # if the text is at the start of the line, then place it\n # at a point spacing away normal to the start\n text_point = start - normal * spacing\n elif text_position == self.TextPosition.END:\n # if the text is at the start of the line, then place it\n # at a point spacing away normal to the end\n text_point = end - normal * spacing\n else:\n raise ValueError(\n \"The value of `text_position`: %s is not valid\", text_position\n )\n\n text = Text(text, text_point)\n\n arrow = DoubleArrow(start, end)\n arrow.line_color = \"black\"\n arrow.line_width = 1\n super().__init__(arrow, text)\n","sub_path":"pysketcher/_distance_with_text.py","file_name":"_distance_with_text.py","file_ext":"py","file_size_in_byte":3947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"136138718","text":"# Import requests\nimport requests\n# Import pandas\nimport pandas as pd\n# Import matplotlib\nimport matplotlib.pyplot as plt\n# Import seaborn\nimport seaborn as sns\nsns.set()\n\n# Build base URL\nHOST = \"https://api.census.gov/data\"\nyear = \"2010\"\ndataset = \"dec/sf1\"\nbase_url = \"/\".join([HOST, year, dataset])\n\n# Specify variables and execute API request\nget_vars = [\"NAME\", \"PCT021005\", \"PCT021015\"]\npredicates = {}\npredicates[\"get\"] = \",\".join(get_vars)\npredicates[\"for\"] = \"state:*\"\nr = requests.get(base_url, params=predicates)\n\n# Construct data frame\ncol_names = [\"name\", \"in_adult\", \"in_juvenile\", \"state\"]\nstates = pd.DataFrame(columns=col_names, data=r.json()[1:])\nstates[[\"in_adult\", \"in_juvenile\"]] = states[[\"in_adult\", \"in_juvenile\"]].astype(int)\n\n# Calculate percentage of incarcerated male minors in adult facilities\nstates[\"pct_in_adult\"] = ((100*states[\"in_adult\"])/(states[\"in_adult\"]+states[\"in_juvenile\"]))\nstates.sort_values(by = \"pct_in_adult\", ascending = False, inplace = True)\nsns.stripplot(x = \"pct_in_adult\", y = \"name\", data = states)\nplt.show()\n","sub_path":"42. API_visualization_group_quarters/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"372281614","text":"from django.utils import timezone\n\nfrom datetime import datetime\n\nfrom ..managerfuncs import testmanager\nfrom .testmanager import random_select\nfrom alcpt.models import User, Exam, Question, TestPaper, AnswerSheet\nfrom alcpt.definitions import QuestionType, ExamType, QuestionTypeCounts\nfrom alcpt.exceptions import IllegalArgumentError\n\n\n# practicemanager create a practice\ndef create_practice(*, user: User, practice_type: ExamType, question_types: list, question_num: int, integration: bool = False):\n now = datetime.now()\n\n practice_name = \"{}-practice-{}-{}\".format(practice_type.value[1], user.reg_id, now)\n\n question_type_counts = QuestionTypeCounts.Exam.value[0] if integration else []\n\n if not integration:\n # how many questions will be selected in any question_type\n for question_type in QuestionType.__members__.values():\n if str(question_type.value[0]) in question_types:\n question_type_counts.append(int(question_num / len(question_types)))\n else:\n question_type_counts.append(0)\n\n if sum(question_type_counts) != question_num:\n q_ts = []\n for q_t in QuestionType:\n q_ts.append(q_t.value[0])\n i = q_ts.index(int(question_types[len(question_types) - 1]))\n question_type_counts[i] += question_num - sum(question_type_counts)\n\n # use testmanager.random_select to shuffle question\n selected_questions = testmanager.random_select(question_type_counts)\n\n practice_testpaper = testmanager.create_testpaper(name=practice_name, created_by=user, is_testpaper=0)\n\n # add the questions into practice_testpaper\n for question in selected_questions:\n practice_testpaper.question_set.add(question)\n\n practice_exam = Exam.objects.create(name=practice_name, exam_type=practice_type.value[0], testpaper=practice_testpaper,\n duration=0, created_by=user)\n\n return practice_exam\n\n\n# practicemanager calculate score of practice, not for exam\ndef calculate_score(exam_id: int, answer_sheet: AnswerSheet):\n answers = answer_sheet.answer_set.all()\n\n score = 0\n for answer in answers:\n tmp = []\n for choice in answer.question.choice_set.all():\n tmp.append(choice)\n\n if tmp[answer.selected-1].is_answer:\n score += 1\n else:\n pass\n\n # calculate average score of practice\n answer_sheet.score = int(score / len(answers)*100)\n answer_sheet.save()\n exam = Exam.objects.get(id=exam_id)\n exam.average_score = answer_sheet.score\n exam.save()\n\n return answer_sheet.score\n","sub_path":"alcpt/managerfuncs/practicemanager.py","file_name":"practicemanager.py","file_ext":"py","file_size_in_byte":2648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"15254097","text":"import sys\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.patches import Rectangle\r\nsys.path.append('.')\r\nimport numpy as np\r\nimport os\r\nimport time\r\nimport pickle\r\n\r\n\r\ncmap = plt.cm.get_cmap('Blues_r')\r\nFactor=1.2\r\nColorS='k'\r\nColorB='tab:red'\r\nColorP=cmap(0.5)\r\nColorT=cmap(0.8)\r\nMaxAP=10*10*5\r\n\r\nfig,ax=plt.subplots(num=0)\r\n\r\nf2 = 2000 # Hz, stimulus frequency\r\nF=5\r\nf1 = f2+F # Hz, stimulus frequency\r\n\r\n# N0=10\r\nN=10\r\nPhase=1\r\ndelay = 20.0e-3 # s, delay for starting stimulation, allows the neuron simulation to \"settle\"\r\n\r\nCycle=1/(f1-f2)*1000\r\n\r\nZZ=0e-3\r\n\r\nScale=1\r\n\r\n\r\nY=np.arange(-4e-3,4.1e-3,0.1e-3)\r\n\r\nH=0.1\r\nW=0.4\r\ndX=1.5*W\r\nXPT=np.arange(3)*dX-W/2\r\n\r\nFreq=2000\r\nDFreq=0\r\nfor YY in Y:\r\n fname='./APs,{:.2f},{:.2f},{:.0f},{:.6f}.p'.format(Freq,DFreq,10,YY*1000)\r\n with open(fname, 'rb') as fp:\r\n data = pickle.load(fp)\r\n\r\n APTs=[]\r\n MaxAPCount=0\r\n for key in data:\r\n if 'node' in key:\r\n temp=data[key].to_python()\r\n if len(temp)>MaxAPCount:\r\n MaxAPCount=len(temp)\r\n APTs.append(temp)\r\n \r\n Node0=APTs[-1]\r\n Node0 = np.asarray(Node0)\r\n Mask = np.ones(len(Node0), dtype=bool)\r\n Mask[Node0N*Cycle+Cycle/2-Cycle]=False\r\n Node0=Node0[Mask]\r\n\r\n if len(Node0)==0:\r\n \r\n fname='./APs,{:.2f},{:.2f},{:.0f},{:.6f}.p'.format(Freq,DFreq,10,YY*1000)\r\n\r\n with open(fname, 'rb') as fp:\r\n data = pickle.load(fp)\r\n\r\n APTs=[]\r\n MaxAPCount=0\r\n for key in data:\r\n if 'node' in key:\r\n temp=data[key].to_python()\r\n if len(temp)>MaxAPCount:\r\n MaxAPCount=len(temp)\r\n APTs.append(temp)\r\n \r\n Node0=APTs[99]\r\n Node0 = np.asarray(Node0)\r\n Mask = np.ones(len(Node0), dtype=bool)\r\n Mask[Node0<2.5*Cycle]=False\r\n Mask[Node0>3.5*Cycle]=False\r\n Node0=Node0[Mask]\r\n if len(Node0)==0:\r\n #Block\r\n rect = Rectangle((XPT[0],YY*1000-H/2), width=W, height=H,alpha=1.0,fill=True,color=ColorB,linewidth=0)\r\n ax.add_patch(rect)\r\n # rect.set_edgecolor(\"black\")\r\n else:\r\n #Silent\r\n rect = Rectangle((XPT[0],YY*1000-H/2), width=W, height=H,alpha=1.0,fill=True,color=ColorS,linewidth=0)\r\n ax.add_patch(rect)\r\n # rect.set_edgecolor(\"black\")\r\n\r\n\r\n else:\r\n Rate=len(Node0)/2/Factor/MaxAP+1/2/Factor\r\n if Rate>1/Factor:\r\n Rate=1/Factor\r\n\r\n rect = Rectangle((XPT[0],YY*1000-H/2), width=W, height=H,alpha=1.0,fill=True,color=cmap(Rate),linewidth=0)\r\n ax.add_patch(rect)\r\n\r\nrect = Rectangle((XPT[0],-4-H/2), width=W, height=8+H,alpha=1.0,fill=False,linewidth=0.75)\r\nrect.set_edgecolor(\"black\")\r\nax.add_patch(rect)\r\nax.axis('scaled')\r\nax.set_frame_on(False)\r\n\r\nax.xaxis.set_ticks_position('none') \r\nax.set_ylabel('Axon distance from midline [mm]',fontsize=10)\r\nax.tick_params(axis='x', pad=-10)\r\nplt.xticks([])\r\nplt.yticks([-4,-3,-2,-1,0,1,2,3,4])\r\nplt.show()","sub_path":"Scripts/Figure6/Figure6D.py","file_name":"Figure6D.py","file_ext":"py","file_size_in_byte":3075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"649558729","text":"import cv2\nimport numpy as np\nimport os\nfrom cv2 import cvtColor \n#image = cv2. imread((os.path.join(\"/root/Desktop/Anil\",\"image.jpg\"))\nimage = cv2.imread('/root/project/DATA/data/data/training/rose/a.jpg')\nimage= cv2.resize(image,(480,480))\n\n \n \nhsv = cv2.cvtColor(image,cv2.COLOR_BGR2HSV)\n# define range of blue color in HSV\nhsvl = np.array([0,0,0])\nhsvh = np.array([180,255,170])\nmask = cv2.inRange(hsv, hsvl, hsvh)\nmasked = cv2.bitwise_or(image,image, mask= mask)\ncv2.imwrite(os.path.join('/root/Desktop/Anil','gray.jpg'),masked)\ncv2.imshow('masked',masked)\ngray_image = cv2.cvtColor(masked, cv2.COLOR_BGR2GRAY)\n\ncv2.imwrite('gray_image.png',gray_image)\ncv2.imshow('color_image',image)\ncv2.imshow('gray_image',gray_image) \ncv2.waitKey(0) # Waits forever for user to press any key\ncv2.destroyAllWindows() # Closes displayed windows\n \n#End of Code\n","sub_path":"aa.py","file_name":"aa.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"129665651","text":"import sys\nsys.path.append(\"/usr/lib/freecad-daily/lib/\")\n\nimport FreeCAD\nfrom FreeCAD import Base\nimport Part\nimport Draft\nimport numpy as np\nimport math as m\nimport DraftVecUtils\nimport DraftGeomUtils\nfrom scipy import integrate\nfrom scipy import interpolate\n\n# Initialise some global variables\nOrigin = Base.Vector(0,0,0)\nOX = Base.Vector(1,0,0)\nOY = Base.Vector(0,1,0)\nOZ = Base.Vector(0,0,1)\n\nPeriodic = False\nNPoints = 100\n\n# Rotate a FreeCAD vector around a center that is not the origin\ndef rotateVectorAroundPoint(Point,center,angle,axis=Base.Vector(0,0,1)):\n Point = Point.sub(center)\n Point = DraftVecUtils.rotate(Point,angle,axis)\n Point = Point.add(center)\n return Point\n\n# Takes in a 2D numpy array (x,y) and returns the 3D FreeCAD vector list\ndef vector3DFromArray2D(Array):\n vectorList = []\n for Point in Array:\n vectorList.append(Base.Vector(Point[0],Point[1],0))\n return vectorList\n\n# Find the point that lies somewhere on the segment between two points\n# e.g. for a midpoint, the ratio=0.5\ndef pointAlongLine(Point1,Point2,ratio=0.5):\n Point1 = DraftVecUtils.scale(Point1,ratio)\n Point2 = DraftVecUtils.scale(Point2,1-ratio)\n Point = Point1.add(Point2)\n return Point\n\n# Create an interpolating BSpline curve from a list of points\ndef makeBSplineWire(PointList):\n Edge = Part.BSplineCurve()\n Edge.interpolate(PointList)\n Edge = Edge.toShape()\n Wire = Part.Wire(Edge)\n return Wire\n\ndef makeStraightWire(PointList):\n edgeList = []\n for i in range(len(PointList)-1):\n edgeList.append(Part.LineSegment(PointList[i],PointList[i+1]).toShape())\n Wire = Part.Wire(edgeList)\n return Wire\n\n# Umbrella class for all other classes\nclass Geometry:\n def __init__(self,params):\n # Size and topology\n self.nBlades = 7 # Fixed\n self.r1 = float(18) # Fixed\n self.r2 = float(75) # Fixed\n self.D = float(50)\n self.h = float(1) # Fixed\n\n # # Volute\n self.alphaValues = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]\n self.L = 60.0\n self.rarc = 56.0\n self.delta = 0.5\n self.k = 0.9775\n self.b3 = 2.5\n self.tongueThickness = 6.5\n self.alpha = m.radians(-35.3165)\n self.volTurn = m.radians(42.5)\n\n self.rValues1 = [params.get('rValue1'),params.get('rValue2'),params.get('rValue3'),params.get('rValue4'),params.get('rValue5'),params.get('rValue6'),params.get('rValue7'),params.get('rValue8'),params.get('rValue9')]\n\n def bendedLine(self,P0,P1,angle,radius):\n Edge1 = Part.Edge(Part.LineSegment(P0,P0.add(Base.Vector(10000.0*m.cos(angle),10000.0*m.sin(angle),0))).toShape())\n Edge2 = Part.Edge(Part.LineSegment(P1.add(Base.Vector(-10000.0,0,0)),P1).toShape())\n Ptmp = DraftGeomUtils.findIntersection(Edge1,Edge2)\n\n wire = makeStraightWire([P0,Ptmp[0],P1])\n wire = DraftGeomUtils.filletWire(wire,radius)\n return wire\n\n def makeVolute(self):\n n = 25 # Number of discrete points along spiral\n\n rStart = self.r2+self.b3\n rEnd = self.k*(self.r2+self.b3+self.D+self.tongueThickness)\n rList = [rStart,rEnd]\n\n angleStart = self.alpha\n angleEnd = 2*m.pi+self.alpha\n angleList = [angleStart,angleEnd]\n\n for i in range(len(self.rValues1)):\n rList.insert(-1,rStart+self.rValues1[i]*(rEnd-rStart))\n angleList.insert(-1,self.alpha+self.alphaValues[i]*2*m.pi)\n\n r = interpolate.interp1d(angleList, rList, kind='linear')(np.linspace(self.alpha,2*m.pi+self.alpha,n))\n\n Points = []\n for num,angle in enumerate(np.linspace(self.alpha,2*m.pi+self.alpha,n)):\n P = Base.Vector(r[num]*m.cos(angle),r[num]*m.sin(angle),0)\n Points.append(P)\n\n PTongue = Points[0].add(Base.Vector(self.tongueThickness*m.cos(self.alpha),self.tongueThickness*m.sin(self.alpha),0))\n\n P0 = PTongue.add(Base.Vector(self.L*m.sin(self.volTurn),self.L*m.cos(self.volTurn),0))\n P1 = P0.add(Base.Vector(self.D*m.sin(m.pi/2+self.volTurn),self.D*m.cos(m.pi/2+self.volTurn),0))\n\n wire1 = self.bendedLine(P0,Base.Vector(500.0,0.5*self.D,0),self.volTurn,self.rarc)\n wire2 = self.bendedLine(P1,Base.Vector(500.0,-0.5*self.D,0),self.volTurn,self.rarc-self.D+10.0)\n\n inlet = Part.Wire(Part.makeCircle(self.r2+self.delta))\n Spiral = makeBSplineWire(Points)\n Wall1 = Part.Wire([makeStraightWire([Points[0],PTongue,P0]),wire1])\n Wall2 = Part.Wire([makeStraightWire([Points[-1],P1]),wire2])\n outlet = makeStraightWire([Base.Vector(500.0,-0.5*self.D,0),Base.Vector(500.0,0.5*self.D,0)])\n\n wall = Spiral.fuse([Wall1,Wall2])\n\n wall.exportBrep(\"wall_Vol.brep\")\n inlet.exportBrep(\"MP_Vol.brep\")\n outlet.exportBrep(\"outlet_Vol.brep\")\n\n\ndef ConstructGeom(params):\n x = Geometry(params)\n\n Volute = x.makeVolute()\n\n return Volute\n\nif __name__ == '__main__':\n params = {'rValue1': 0.136352, 'rValue2': 0.222397, 'rValue3': 0.335322, 'rValue4': 0.343330, \\\n 'rValue5': 0.491625, 'rValue6': 0.484354, 'rValue7': 0.626932, 'rValue8': 0.728822, 'rValue9': 0.700473}\n\n # ConstructGeom(params).exportBrep('Volute.brep')\n\n # shape=Part.Shape()\n\n # shape.read('../RefVoluteWire.step')\n\n # Inlet = Part.Wire(shape.Edges[0]).extrude(Base.Vector(0,0,1.0))\n # Outlet = Part.Wire(shape.Edges[1]).extrude(Base.Vector(0,0,1.0))\n # Wall = []\n # for num,edge in enumerate(shape.Edges):\n # if num > 1:\n # Wall.append(Part.Wire(edge))\n # Wall = Part.makeCompound(Wall).extrude(Base.Vector(0,0,1.0))\n # Inlet.exportBrep(\"MP_Vol.brep\")\n # Outlet.exportBrep(\"outlet_Vol.brep\")\n # Wall.exportBrep(\"wall_Vol.brep\")\n\n # for num,edge in enumerate(shape.Edges):\n # edge.exportBrep('wire_'+str(num)+'.brep')\n\n","sub_path":"2D_Geometries/FitGeometry/Volute.py","file_name":"Volute.py","file_ext":"py","file_size_in_byte":5918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"258465952","text":"from airflow import DAG\nfrom airflow.operators.python_operator import PythonOperator\nfrom datetime import datetime, timedelta\nfrom modules import modules\n\n\nsetup = {\n 'owner': 'xadrianzetx',\n 'depends_on_past': False,\n 'start_date': datetime(2019, 12, 30),\n 'retries': 2,\n 'retry_delay': timedelta(minutes=5)\n}\n\ndag = DAG(\n 'daily_doggos',\n description=\"Daily reddit doggos. use r.get('%d.%m.%Y') to get metadata\",\n default_args=setup,\n schedule_interval='00 12 * * *'\n)\n\n\nt1 = PythonOperator(\n task_id='get_reddit_hot',\n provide_context=True,\n python_callable=modules.get_subreddit_top,\n dag=dag\n)\n\nt2 = PythonOperator(\n task_id='send_messages',\n provide_context=True,\n python_callable=modules.push_message,\n dag=dag\n)\n\nt2.set_upstream(t1)\n","sub_path":"dags/dogdag.py","file_name":"dogdag.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"623007476","text":"#coding=utf-8\nimport os\nimport sys\n\ndef bm_make():\n os.getcwd()\n cmd = \"C:\\\\Progra~2\\\\AngelCode\\\\BMFont\\\\bmfont.exe -t text.txt -c bmconfig.bmfc -o font.fnt\"\n os.system(cmd)\n\nif __name__ == '__main__':\n bm_make()\n os.system(\"pause\")","sub_path":"bmfont/bm_make.py","file_name":"bm_make.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"26733280","text":"def merge(A:list, B:list):\r\n \"\"\" merge sort \"\"\"\r\n\r\n C = [0]*(len(A) + len(B))\r\n\r\n a = b = c = 0\r\n while a < len(A) and b < len(B):\r\n if A[a] <= B[b]:\r\n C[c] = A[a]\r\n a += 1\r\n else:\r\n C[c] = B[b]\r\n b += 1\r\n c += 1\r\n\r\n while a < len(A):\r\n C[c] = A[a]\r\n a += 1\r\n c += 1\r\n\r\n while b < len(B):\r\n C[c] = B[b]\r\n b += 1\r\n c += 1\r\n\r\n return C\r\n\r\ndef merge_sort(S):\r\n\r\n if len(S) <= 1:\r\n return\r\n\r\n middle = len(S) // 2\r\n L = S[:middle]\r\n R = S[middle:]\r\n\r\n print(\"Before L: %r. R: %r\" % (L, R))\r\n merge_sort(L)\r\n merge_sort(R)\r\n print(\"After L: %r. R: %r\" % (L, R))\r\n C = merge(L, R)\r\n for i in range(len(S)):\r\n S[i] = C[i]\r\n\r\nX = [5, 2, 1, 7, 0, 3, 2]\r\n\r\nmerge_sort(X)\r\nprint(X)\r\n","sub_path":"merge_sort.py","file_name":"merge_sort.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"535181849","text":"import sys\nsys.setrecursionlimit(1 << 20)\nINF = float('inf')\n\n\ndef read_int_list():\n return list(map(int, input().split()))\n\n\ndef read_ints():\n return map(int, input().split())\n\n\ndef main():\n H, W = read_ints()\n M = []\n visited = []\n sx, sy = None, None\n for i in range(H):\n M.append(list(input()))\n if 's' in M[-1]:\n sy = M[-1].index('s')\n sx = i\n\n visited.append([False] * W)\n # print(sx, sy)\n\n def dfs(r, c):\n visited[r][c] = True\n if M[r][c] == 'g':\n return True\n\n if r > 0 and M[r - 1][c] != '#' and not visited[r - 1][c]:\n if dfs(r - 1, c):\n return True\n if c > 0 and M[r][c - 1] != '#' and not visited[r][c - 1]:\n if dfs(r, c - 1):\n return True\n if r < H - 1 and M[r + 1][c] != '#' and not visited[r + 1][c]:\n if dfs(r + 1, c):\n return True\n if c < W - 1 and M[r][c + 1] != '#' and not visited[r][c + 1]:\n if dfs(r, c + 1):\n return True\n\n if dfs(sx, sy):\n print('Yes')\n else:\n print('No')\n\n\nmain()\n","sub_path":"others/others_atc1a.py","file_name":"others_atc1a.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"163750877","text":"# Copyright Google LLC All Rights Reserved.\n#\n# Use of this source code is governed by an MIT-style license that can be\n# found in the LICENSE file at https://angular.io/license\n\n\"\"\"Rollup with Build Optimizer\n\n This provides a variant of the [rollup_bundle] rule that works better for Angular apps.\n\n It registers `@angular-devkit/build-optimizer` as a rollup plugin, to get\n better optimization. It also uses ESM5 format inputs, as this is what\n build-optimizer is hard-coded to look for and transform.\n\n [rollup_bundle]: https://bazelbuild.github.io/rules_nodejs/rollup/rollup_bundle.html\n\"\"\"\n\nload(\"@build_bazel_rules_nodejs//:index.bzl\", \"npm_package_bin\")\nload(\"@build_bazel_rules_nodejs//:providers.bzl\", \"JSEcmaScriptModuleInfo\", \"NpmPackageInfo\", \"node_modules_aspect\")\nload(\"//packages/bazel/src:esm5.bzl\", \"esm5_outputs_aspect\", \"esm5_root_dir\", \"flatten_esm5\")\nload(\"@npm_bazel_terser//:index.bzl\", \"terser_minified\")\n\n_NG_ROLLUP_BUNDLE_OUTPUTS = {\n \"bundle\": \"%{name}.js\",\n \"sourcemap\": \"%{name}.js.map\",\n}\n\n_NG_ROLLUP_MODULE_MAPPINGS_ATTR = \"ng_rollup_module_mappings\"\n\ndef _ng_rollup_module_mappings_aspect_impl(target, ctx):\n mappings = dict()\n for dep in ctx.rule.attr.deps:\n if hasattr(dep, _NG_ROLLUP_MODULE_MAPPINGS_ATTR):\n for k, v in getattr(dep, _NG_ROLLUP_MODULE_MAPPINGS_ATTR).items():\n if k in mappings and mappings[k] != v:\n fail((\"duplicate module mapping at %s: %s maps to both %s and %s\" %\n (target.label, k, mappings[k], v)), \"deps\")\n mappings[k] = v\n if ((hasattr(ctx.rule.attr, \"module_name\") and ctx.rule.attr.module_name) or\n (hasattr(ctx.rule.attr, \"module_root\") and ctx.rule.attr.module_root)):\n mn = ctx.rule.attr.module_name\n if not mn:\n mn = target.label.name\n mr = target.label.package\n if target.label.workspace_root:\n mr = \"%s/%s\" % (target.label.workspace_root, mr)\n if ctx.rule.attr.module_root and ctx.rule.attr.module_root != \".\":\n if ctx.rule.attr.module_root.endswith(\".ts\"):\n # This is the type-checking module mapping. Strip the trailing .d.ts\n # as it doesn't belong in TypeScript's path mapping.\n mr = \"%s/%s\" % (mr, ctx.rule.attr.module_root.replace(\".d.ts\", \"\"))\n else:\n mr = \"%s/%s\" % (mr, ctx.rule.attr.module_root)\n if mn in mappings and mappings[mn] != mr:\n fail((\"duplicate module mapping at %s: %s maps to both %s and %s\" %\n (target.label, mn, mappings[mn], mr)), \"deps\")\n mappings[mn] = mr\n return struct(ng_rollup_module_mappings = mappings)\n\nng_rollup_module_mappings_aspect = aspect(\n _ng_rollup_module_mappings_aspect_impl,\n attr_aspects = [\"deps\"],\n)\n\n_NG_ROLLUP_BUNDLE_DEPS_ASPECTS = [esm5_outputs_aspect, ng_rollup_module_mappings_aspect, node_modules_aspect]\n\n_NG_ROLLUP_BUNDLE_ATTRS = {\n \"build_optimizer\": attr.bool(\n doc = \"\"\"Use build optimizer plugin\n\n Only used if sources are esm5 which depends on value of esm5_sources.\"\"\",\n default = True,\n ),\n \"esm5_sources\": attr.bool(\n doc = \"\"\"Use esm5 input sources\"\"\",\n default = True,\n ),\n \"srcs\": attr.label_list(\n doc = \"\"\"JavaScript source files from the workspace.\n These can use ES2015 syntax and ES Modules (import/export)\"\"\",\n allow_files = True,\n ),\n \"entry_point\": attr.label(\n doc = \"\"\"The starting point of the application, passed as the `--input` flag to rollup.\n\n If the entry JavaScript file belongs to the same package (as the BUILD file),\n you can simply reference it by its relative name to the package directory:\n\n ```\n ng_rollup_bundle(\n name = \"bundle\",\n entry_point = \":main.js\",\n )\n ```\n\n You can specify the entry point as a typescript file so long as you also include\n the ts_library target in deps:\n\n ```\n ts_library(\n name = \"main\",\n srcs = [\"main.ts\"],\n )\n\n ng_rollup_bundle(\n name = \"bundle\",\n deps = [\":main\"]\n entry_point = \":main.ts\",\n )\n ```\n\n The rule will use the corresponding `.js` output of the ts_library rule as the entry point.\n\n If the entry point target is a rule, it should produce a single JavaScript entry file that will be passed to the nodejs_binary rule.\n For example:\n\n ```\n filegroup(\n name = \"entry_file\",\n srcs = [\"main.js\"],\n )\n\n ng_rollup_bundle(\n name = \"bundle\",\n entry_point = \":entry_file\",\n )\n ```\n \"\"\",\n mandatory = True,\n allow_single_file = True,\n ),\n \"deps\": attr.label_list(\n doc = \"\"\"Other targets that provide JavaScript files.\n Typically this will be `ts_library` or `ng_module` targets.\"\"\",\n aspects = _NG_ROLLUP_BUNDLE_DEPS_ASPECTS,\n ),\n \"format\": attr.string(\n doc = \"\"\"\"Specifies the format of the generated bundle. One of the following:\n\n- `amd`: Asynchronous Module Definition, used with module loaders like RequireJS\n- `cjs`: CommonJS, suitable for Node and other bundlers\n- `esm`: Keep the bundle as an ES module file, suitable for other bundlers and inclusion as a `